text:
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;

namespace System
{
    /// <summary>
    /// A collection of convenient span helpers, exposed as extension methods.
    /// </summary>
    public static partial class SpanExtensions
    {
        // span creation helpers:

        /// <summary>
        /// Creates a new slice over the portion of the target array.
        /// </summary>
        /// <param name="array">The target array.</param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if the 'array' parameter is null.
        /// </exception>
        public static Span<T> Slice<T>(this T[] array)
        {
            return new Span<T>(array);
        }

        /// <summary>
        /// Creates a new slice over the portion of the target array beginning
        /// at 'start' index.
        /// </summary>
        /// <param name="array">The target array.</param>
        /// <param name="start">The index at which to begin the slice.</param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if the 'array' parameter is null.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Thrown when the specified start index is not in range (<0 or >&eq;length).
        /// </exception>
        public static Span<T> Slice<T>(this T[] array, int start)
        {
            return new Span<T>(array, start);
        }

        /// <summary>
        /// Creates a new slice over the portion of the target array beginning
        /// at 'start' index and ending at 'end' index (exclusive).
        /// </summary>
        /// <param name="array">The target array.</param>
        /// <param name="start">The index at which to begin the slice.</param>
        /// <param name="length">The number of items in the new slice.</param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if the 'array' parameter is null.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Thrown when the specified start or end index is not in range (<0 or >&eq;length).
        /// </exception>
        public static Span<T> Slice<T>(this T[] array, int start, int length)
        {
            return new Span<T>(array, start, length);
        }

        /// <summary>
        /// Creates a new slice over the portion of the target array segment.
        /// </summary>
        /// <param name="arraySegment">The target array segment.</param>
        /// </exception>
        public static Span<T> Slice<T>(this ArraySegment<T> arraySegment)
        {
            return new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
        }

        /// <summary>
        /// Creates a new slice over the portion of the target string.
        /// </summary>
        /// <param name="str">The target string.</param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if the 'str' parameter is null.
        /// </exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<char> Slice(this string str)
        {
            Contract.Requires(str != null);
            return new ReadOnlySpan<char>(
                str,
                new UIntPtr((uint)SpanHelpers.OffsetToStringData),
                str.Length
            );
        }

        /// <summary>
        /// Creates a new slice over the portion of the target string beginning
        /// at 'start' index.
        /// </summary>
        /// <param name="str">The target string.</param>
        /// <param name="start">The index at which to begin the slice.</param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if the 'str' parameter is null.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Thrown when the specified start index is not in range (<0 or >&eq;length).
        /// </exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<char> Slice(this string str, int start)
        {
            Contract.Requires(str != null);
            Contract.RequiresInInclusiveRange(start, (uint)str.Length);

            return new ReadOnlySpan<char>(
                str,
                new UIntPtr((uint)(SpanHelpers.OffsetToStringData + (start * sizeof(char)))),
                str.Length - start
            );
        }

        /// <summary>
        /// Creates a new slice over the portion of the target string beginning
        /// at 'start' index and ending at 'end' index (exclusive).
        /// </summary>
        /// <param name="str">The target string.</param>
        /// <param name="start">The index at which to begin the slice.</param>
        /// <param name="end">The index at which to end the slice (exclusive).</param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if the 'start' parameter is null.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Thrown when the specified start or end index is not in range (<0 or >&eq;length).
        /// </exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<char> Slice(this string str, int start, int length)
        {
            Contract.Requires(str != null);
            Contract.RequiresInInclusiveRange(start, length, (uint)str.Length);
            return new ReadOnlySpan<char>(
                str,
                new UIntPtr((uint)(SpanHelpers.OffsetToStringData + (start * sizeof(char)))),
                length
            );
        }

        // Some handy byte manipulation helpers:

        /// <summary>
        /// Casts a Slice of one primitive type (T) to another primitive type (U).
        /// These types may not contain managed objects, in order to preserve type
        /// safety.  This is checked statically by a Roslyn analyzer.
        /// </summary>
        /// <param name="slice">The source slice, of type T.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<U> Cast<[Primitive]T, [Primitive]U>(this Span<T> slice)
            where T : struct
            where U : struct
        {
            int countOfU;

            // This comparison is a jittime constant
            if (Unsafe.SizeOf<T>() > Unsafe.SizeOf<U>())
            {
                IntPtr count = UnsafeUtilities.CountOfU<T, U>((uint)slice.Length);
                unsafe
                {
                    // We can't compare IntPtrs, so have to resort to pointer comparison
                    bool fits = (byte*)count <= (byte*)int.MaxValue;
                    Contract.Requires(fits);
                    countOfU = (int)count.ToPointer();
                }
            }
            else
            {
                countOfU = (int)(((ulong)slice.Length * (ulong)Unsafe.SizeOf<T>()) / (ulong)Unsafe.SizeOf<U>());
            }

            object obj = slice.Object;
            UIntPtr offset = slice.Offset;

            if (countOfU == 0)
            {
                obj = null;
                offset = (UIntPtr)0;
            }

            return new Span<U>(obj, offset, countOfU);
        }

        /// <summary>
        /// Casts a Slice of one primitive type (T) to another primitive type (U).
        /// These types may not contain managed objects, in order to preserve type
        /// safety.  This is checked statically by a Roslyn analyzer.
        /// </summary>
        /// <param name="slice">The source slice, of type T.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<U> Cast<[Primitive]T, [Primitive]U>(this ReadOnlySpan<T> slice)
            where T : struct
            where U : struct
        {
            int countOfU;

            // This comparison is a jittime constant
            if (Unsafe.SizeOf<T>() > Unsafe.SizeOf<U>())
            {
                IntPtr count = UnsafeUtilities.CountOfU<T, U>((uint)slice.Length);
                unsafe
                {
                    // We can't compare IntPtrs, so have to resort to pointer comparison
                    bool fits = (byte*)count <= (byte*)int.MaxValue;
                    Contract.Requires(fits);
                    countOfU = (int)count.ToPointer();
                }
            }
            else
            {
                countOfU = (int)(((ulong)slice.Length * (ulong)Unsafe.SizeOf<T>()) / (ulong)Unsafe.SizeOf<U>());
            }

            object obj = slice.Object;
            UIntPtr offset = slice.Offset;

            if (countOfU == 0)
            {
                obj = null;
                offset = (UIntPtr)0;
            }

            return new ReadOnlySpan<U>(obj, offset, countOfU);
        }

        /// <summary>
        /// Reads a structure of type T out of a slice of bytes.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static T Read<[Primitive]T>(this Span<byte> slice)
            where T : struct
        {
            Contract.RequiresInInclusiveRange(Unsafe.SizeOf<T>(), (uint)slice.Length);
            return UnsafeUtilities.Get<T>(slice.Object, slice.Offset, (UIntPtr)0);
        }

        /// <summary>
        /// Reads a structure of type T out of a slice of bytes.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static T Read<[Primitive]T>(this ReadOnlySpan<byte> slice)
            where T : struct
        {
            Contract.RequiresInInclusiveRange(Unsafe.SizeOf<T>(), (uint)slice.Length);
            return UnsafeUtilities.Get<T>(slice.Object, slice.Offset, (UIntPtr)0);
        }

        /// <summary>
        /// Writes a structure of type T into a slice of bytes.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void Write<[Primitive]T>(this Span<byte> slice, T value)
            where T : struct
        {
            Contract.RequiresInInclusiveRange(Unsafe.SizeOf<T>(), (uint)slice.Length);
            UnsafeUtilities.Set(slice.Object, slice.Offset, (UIntPtr)0, value);
        }

        /// <summary>
        /// Determines whether two spans are equal by comparing the elements by using generic Equals method
        /// </summary>
        /// <param name="first">A span of type T to compare to second.</param>
        /// <param name="second">A span of type T to compare to first.</param>
        [ILSub(@"
            .maxstack 4
            .locals([0] uint8 & baseAddr1,
                    [1] uint8 & baseAddr2,
                    [2] native uint i,
                    [3] native uint length)
            ldarg.0
            ldfld      int32 valuetype System.Span`1<!!T>::Length
            dup
            stloc.3
            ldarg.1
            ldfld      int32 valuetype System.Span`1<!!T>::Length
            ceq
            brfalse.s  NOT_EQUAL

            ldloc.3
            brzero.s  EQUAL

            ldarg.0
            ldfld      object valuetype System.Span`1<!!T>::Object
            stloc.0
            ldloc.0
            ldarg.0
            ldfld      native uint valuetype System.Span`1<!!T>::Offset
            add
            stloc.0

            ldarg.1
            ldfld      object valuetype System.Span`1<!!T>::Object
            stloc.1
            ldloc.1
            ldarg.1
            ldfld      native uint valuetype System.Span`1<!!T>::Offset
            add
            stloc.1

            ldc.i4.0
            stloc.2

        LOOP_START:
            ldloc.0
            ldloc.2
            sizeof !!T
            mul
            add

            ldloc.1
            ldloc.2
            sizeof !!T
            mul
            add
            ldobj  !!T

            constrained. !!T
            callvirt   instance bool class [System.Runtime]System.IEquatable`1<!!T>::Equals(!0)
            brfalse.s  NOT_EQUAL
            ldloc.2
            ldc.i4.1
            add
            stloc.2
            ldloc.2
            ldloc.3
            blt.s      LOOP_START

        EQUAL:
            ldc.i4.1
            ret
        NOT_EQUAL:
            ldc.i4.0
            ret ")]
        public static bool SequenceEqual<T>(this Span<T> first, Span<T> second)
            where T : struct, IEquatable<T>
        {
            return false;
        }

        /// <summary>
        /// Determines whether two spans are equal by comparing the elements by using generic Equals method
        /// </summary>
        /// <param name="first">A span of type T to compare to second.</param>
        /// <param name="second">A span of type T to compare to first.</param>
        [ILSub(@"
            .maxstack 4
            .locals([0] uint8 & baseAddr1,
                    [1] uint8 & baseAddr2,
                    [2] native uint i,
                    [3] native uint length)
            ldarg.0
            ldfld      int32 valuetype System.ReadOnlySpan`1<!!T>::Length
            dup
            stloc.3
            ldarg.1
            ldfld      int32 valuetype System.ReadOnlySpan`1<!!T>::Length
            ceq
            brfalse.s  NOT_EQUAL

            ldloc.3
            brzero.s  EQUAL

            ldarg.0
            ldfld      object valuetype System.ReadOnlySpan`1<!!T>::Object
            stloc.0
            ldloc.0
            ldarg.0
            ldfld      native uint valuetype System.ReadOnlySpan`1<!!T>::Offset
            add
            stloc.0

            ldarg.1
            ldfld      object valuetype System.ReadOnlySpan`1<!!T>::Object
            stloc.1
            ldloc.1
            ldarg.1
            ldfld      native uint valuetype System.ReadOnlySpan`1<!!T>::Offset
            add
            stloc.1

            ldc.i4.0
            stloc.2

        LOOP_START:
            ldloc.0
            ldloc.2
            sizeof !!T
            mul
            add

            ldloc.1
            ldloc.2
            sizeof !!T
            mul
            add
            ldobj  !!T

            constrained. !!T
            callvirt   instance bool class [System.Runtime]System.IEquatable`1<!!T>::Equals(!0)
            brfalse.s  NOT_EQUAL
            ldloc.2
            ldc.i4.1
            add
            stloc.2
            ldloc.2
            ldloc.3
            blt.s      LOOP_START

        EQUAL:
            ldc.i4.1
            ret
        NOT_EQUAL:
            ldc.i4.0
            ret ")]
        public static bool SequenceEqual<T>(this ReadOnlySpan<T> first, ReadOnlySpan<T> second)
            where T : struct, IEquatable<T>
        {
            return false;
        }

        /// <summary>
        /// Determines whether two spans are equal by comparing the elements by using generic Equals method
        /// </summary>
        /// <param name="first">A span of type T to compare to second.</param>
        /// <param name="second">A span of type T to compare to first.</param>
        public static bool SequenceEqual<T>(this Span<T> first, ReadOnlySpan<T> second)
            where T : struct, IEquatable<T>
        {
            return SequenceEqual((ReadOnlySpan<T>)first, second);
        }

        public static bool StartsWith<T>(this ReadOnlySpan<T> items, ReadOnlySpan<T> slice)
            where T : struct, IEquatable<T>
        {
            if (slice.Length > items.Length) return false;
            return items.Slice(0, slice.Length).SequenceEqual(slice);
        }

        /// <summary>
        /// Determines whether two spans are structurally (byte-wise) equal by comparing the elements by using memcmp
        /// </summary>
        /// <param name="first">A span, of type T to compare to second.</param>
        /// <param name="second">A span, of type U to compare to first.</param>
        public static bool BlockEquals<[Primitive]T, [Primitive]U>(this Span<T> first, Span<U> second)
            where T : struct
            where U : struct
        {
            var bytesCount = (ulong)first.Length * (ulong)Unsafe.SizeOf<T>();
            if (bytesCount != (ulong)second.Length * (ulong)Unsafe.SizeOf<U>())
            {
                return false;
            }

            // perf: it is cheaper to compare 'n' long elements than 'n*8' bytes (in a loop)
            if ((bytesCount & 0x00000007) == 0) // fast % sizeof(long)
            {
                return SequenceEqual(Cast<T, long>(first), Cast<U, long>(second));
            }
            if ((bytesCount & 0x00000003) == 0) // fast % sizeof(int)
            {
                return SequenceEqual(Cast<T, int>(first), Cast<U, int>(second));
            }
            if ((bytesCount & 0x00000001) == 0) // fast % sizeof(short)
            {
                return SequenceEqual(Cast<T, short>(first), Cast<U, short>(second));
            }

            return SequenceEqual(Cast<T, byte>(first), Cast<U, byte>(second));
        }

        /// <summary>
        /// Determines whether two spans are structurally (byte-wise) equal by comparing the elements by using memcmp
        /// </summary>
        /// <param name="first">A span, of type T to compare to second.</param>
        /// <param name="second">A span, of type U to compare to first.</param>
        public static bool BlockEquals<[Primitive]T, [Primitive]U>(this ReadOnlySpan<T> first, ReadOnlySpan<U> second)
            where T : struct
            where U : struct
        {
            var bytesCount = (ulong)first.Length * (ulong)Unsafe.SizeOf<T>();
            if (bytesCount != (ulong)second.Length * (ulong)Unsafe.SizeOf<U>())
            {
                return false;
            }

            // perf: it is cheaper to compare 'n' long elements than 'n*8' bytes (in a loop)
            if ((bytesCount & 0x00000007) == 0) // fast % sizeof(long)
            {
                return SequenceEqual(Cast<T, long>(first), Cast<U, long>(second));
            }
            if ((bytesCount & 0x00000003) == 0) // fast % sizeof(int)
            {
                return SequenceEqual(Cast<T, int>(first), Cast<U, int>(second));
            }
            if ((bytesCount & 0x00000001) == 0) // fast % sizeof(short)
            {
                return SequenceEqual(Cast<T, short>(first), Cast<U, short>(second));
            }

            return SequenceEqual(Cast<T, byte>(first), Cast<U, byte>(second));
        }

        /// <summary>Searches for the specified value and returns the index of the first occurrence within the entire <see cref="T:System.Span" />.</summary>
        /// <returns>The zero-based index of the first occurrence of <paramref name="value" /> within the entire <paramref name="slice" />, if found; otherwise, –1.</returns>
        /// <param name="slice">The <see cref="T:System.Span" /> to search.</param>
        /// <param name="value">The value to locate in <paramref name="slice" />.</param>
        /// <typeparam name="T">The type of the elements of the slice.</typeparam>
        [ILSub(@"
            .maxstack 3
            .locals([0] uint8 & addr,
                    [1] native uint i,
                    [2] native uint length)
            ldarg.0
            ldfld      int32 valuetype System.ReadOnlySpan`1<!!T>::Length
            dup
            stloc.2
            brfalse.s  EMPTY_SPAN

            ldarg.0
            ldfld      object valuetype System.ReadOnlySpan`1<!!T>::Object
            stloc.0
            ldloc.0
            ldarg.0
            ldfld      native uint valuetype System.ReadOnlySpan`1<!!T>::Offset

            add
            stloc.0

            ldc.i4.0
            stloc.1

        LOOP_START:
            ldloc.0
            ldloc.1
            sizeof !!T
            conv.u
            mul
            add
            ldarg.1
            constrained. !!T
            callvirt   instance bool class [System.Runtime]System.IEquatable`1<!!T>::Equals(!0)
            brfalse.s   NOT_EQUAL
            ldloc.1
            ret

        NOT_EQUAL:
            ldloc.1
            ldc.i4.1
            add
            stloc.1
            ldloc.1
            ldloc.2
            blt.s       LOOP_START
        EMPTY_SPAN:
            ldc.i4.m1
            ret")]
        public static int IndexOf<T>(this ReadOnlySpan<T> slice, T value)
           where T : struct, IEquatable<T>
        {
            return 0;
        }

        // Helper methods similar to System.ArrayExtension:

        // String helper methods, offering methods like String on Slice<char>:
        // TODO(joe): culture-sensitive comparisons.
        // TODO: should these move to string/text related assembly

        public static bool Contains(this ReadOnlySpan<char> str, ReadOnlySpan<char> value)
        {
            if (value.Length > str.Length)
            {
                return false;
            }
            return str.IndexOf(value) >= 0;
        }

        public static bool EndsWith(this ReadOnlySpan<char> str, ReadOnlySpan<char> value)
        {
            if (value.Length > str.Length)
            {
                return false;
            }

            int j = str.Length - value.Length;
            foreach (var c in value)
            {
                if (str[j] != c)
                {
                    return false;
                }
                j++;
            }

            return true;
        }

        public static int IndexOf(this ReadOnlySpan<char> str, string value)
        {
            return IndexOf(str, value.Slice());
        }

        public static int IndexOf(this ReadOnlySpan<char> str, ReadOnlySpan<char> value)
        {
            throw new NotImplementedException();
        }

        public static int IndexOfAny(this ReadOnlySpan<char> str, params char[] values)
        {
            throw new NotImplementedException();
        }

        public static int IndexOfAny(this ReadOnlySpan<char> str, params string[] values)
        {
            throw new NotImplementedException();
        }

        public static int IndexOfAny(this ReadOnlySpan<char> str, params ReadOnlySpan<char>[] values)
        {
            throw new NotImplementedException();
        }

        public static int LastIndexOf(this ReadOnlySpan<char> str, char value)
        {
            throw new NotImplementedException();
        }

        public static int LastIndexOf(this ReadOnlySpan<char> str, string value)
        {
            return LastIndexOf(str, value.Slice());
        }

        public static int LastIndexOf(this ReadOnlySpan<char> str, ReadOnlySpan<char> value)
        {
            throw new NotImplementedException();
        }

        public static int LastIndexOfAny(this ReadOnlySpan<char> str, params char[] values)
        {
            throw new NotImplementedException();
        }

        public static int LastIndexOfAny(this ReadOnlySpan<char> str, params string[] values)
        {
            throw new NotImplementedException();
        }

        public static int LastIndexOfAny(this ReadOnlySpan<char> str, params ReadOnlySpan<char>[] values)
        {
            throw new NotImplementedException();
        }

        public static SplitEnumerator Split(this ReadOnlySpan<char> str, params char[] separator)
        {
            throw new NotImplementedException();
        }

        public struct SplitEnumerator
        {
        }

        public static bool StartsWith(this ReadOnlySpan<char> str, ReadOnlySpan<char> value)
        {
            if (value.Length > str.Length)
            {
                return false;
            }

            for (int i = 0; i < value.Length; i++)
            {
                if (str[i] != value[i])
                {
                    return false;
                }
            }

            return true;
        }

        public static bool StartsWith(this ReadOnlySpan<byte> bytes, ReadOnlySpan<byte> slice)
        {
            if (slice.Length > bytes.Length) {
                return false;
            }

            for (int i = 0; i < slice.Length; i++) {
                if (bytes[i] != slice[i]) {
                    return false;
                }
            }

            return true;
        }

        public unsafe static void Set(this Span<byte> bytes, byte* values, int length)
        {
            var valuesSpan = new Span<byte>(values, length);
            valuesSpan.CopyTo(bytes);
        }
    }
}


text:
package com.sadofftext.jobapplication;

/**
* The class Address stores someone's address.
* While the class might seem trivial,
* it is simpler to have a class for addresses
* than to have many constructors for Applicant.
*
* @since 1.0.0
* @author Eli Sadoff
*/
public class Address {
  /* Stores the first line of an address */
  private String addressLine1;
  /* Stores the optional second line of an address */
  private String addressLine2;
  /* Stores the city */
  private String city;
  /* Stores the state */
  private String state;
  /* Stores the zip code */
  private String zipcode;

  /**
  * This is the full constructor for Address.
  * This is to be used by people with a multi-line address.
  * @param addressLine1 the first address line to set
  * @param addressLine2 the second address line to set
  * @param city the city to set
  * @param state the state to set
  * @param zipcode the zip code to set
  */
  public Address(String addressLine1, String addressLine2, String city, String state,
                 String zipcode) {
    this.addressLine1 = addressLine1;
    this.addressLine2 = addressLine2;
    this.city = city;
    this.state = state;
    this.zipcode = zipcode;
  }

  /**
  * This is the abbreviated constructor for Address.
  * This is to be used by people with a single line address.
  * @param address the address line to set
  * @param city the city to set
  * @param state the state to set
  * @param zipcode the zip code to set
  */
  public Address(String address, String city, String state, String zipcode) {
    this.addressLine1 = address;
    this.addressLine2 = "";
    this.city = city;
    this.state = state;
    this.zipcode = zipcode;
  }

  /**
  * This gets the first address line
  * @return the first address line
  */
  public String getAddressLine1() {
    return addressLine1;
  }

  /**
  * This sets the first address line
  * @param addressLine1 the first address line to set
  */
  public void setAddressLine1(String addressLine1) {
    this.addressLine1 = addressLine1;
  }

  /**
  * This gets the optional second address line
  * @return the optional second address line
  */
  public String getAddressLine2() {
    return addressLine2;
  }

  /**
  * This sets the option second address line
  * @param addressLine2 the optional second address line to set
  */
  public void setAddressLine2(String addressLine2) {
    this.addressLine2 = addressLine2;
  }

  /**
  * This gets the city
  * @return the city
  */
  public String getCity() {
    return city;
  }

  /**
  * This sets the city
  * @param city the city to set
  */
  public void setCity(String city) {
    this.city = city;
  }

  /**
  * This gets the state
  * @return the state
  */
  public String getState() {
    return state;
  }

  /**
  * This sets the state
  * @param state the state to set
  */
  public void setState(String state) {
    this.state = state;
  }

  /**
  * This gets the zip code
  * @return the zip code
  */
  public String getZipcode() {
    return zipcode;
  }

  /**
  * This sets the zip code
  * @param zipcode the zip code to set
  */
  public void setZipcode(String zipcode) {
    this.zipcode = zipcode;
  }

  /**
  * This override's Object's
  * toString method.
  * @return string representation of an
  * address in the format:

  * ADDRESS LINE 1

  * ADDRESS LINE 2 (If exists)

  * CITY, STATE

  * ZIPCODE
  */
  @Override
  public String toString() {
    String addressLine;
    if(getAddressLine2().equals("")) {
      addressLine = getAddressLine1();
    } else{
      addressLine = getAddressLine1() + "\n" + getAddressLine2();
    }
    return addressLine + "\n" + getCity() + ", " + getState() + "\n" + getZipcode();
  }

  @Override
  public boolean equals(Object o){
    if(o instanceof Address){
      Address a = (Address) o;
      boolean al1 = getAddressLine1().equals(a.getAddressLine1());
      boolean al2 = getAddressLine2().equals(a.getAddressLine2());
      boolean cy = getCity().equals(a.getCity());
      boolean st = getState().equals(a.getState());
      boolean zc = getZipcode().equals(a.getZipcode());
      return al1 && al2 && cy && st && zc;
    }
    return false;
  }

  public static String getState(String stateAbbr) {
    switch (stateAbbr) {
      case "AK":
        return "Alaska";
      case "AL":
        return "Alabama";
      case "AR":
        return "Arkansas";
      case "AZ":
        return "Arizona";
      case "CA":
        return "California";
      case "CO":
        return "Colorado";
      case "CT":
        return "Connecticut";
      case "DC":
        return "Washington, DC";
      case "DE":
        return "Delaware";
      case "FL":
        return "Florida";
      case "GA":
        return "Georgia";
      case "GU":
        return "Guam";
      case "HI":
        return "Hawai'i";
      case "IA":
        return "Iowa";
      case "IL":
        return "Illinois";
      case "IN":
        return "Indiana";
      case "KS":
        return "Kansas";
      case "KY":
        return "Kentucky";
      case "LA":
        return "Louisiana";
      case "MA":
        return "Massachusetts";
      case "MD":
        return "Maryland";
      case "ME":
        return "Maine";
      case "MI":
        return "Michigan";
      case "MN":
        return "Minnesota";
      case "MO":
        return "Missouri";
      case "MS":
        return "Mississippi";
      case "MT":
        return "Montana";
      case "NC":
        return "North Carolina";
      case "ND":
        return "North Dakota";
      case "NE":
        return "Nebraska";
      case "NH":
        return "New Hampshire";
      case "NJ":
        return "New Jersey";
      case "NM":
        return "New Mexico";
      case "NV":
        return "Nevada";
      case "NY":
        return "New York";
      case "OH":
        return "Ohio";
      case "OK":
        return "Oklahoma";
      case "OR":
        return "Oregon";
      case "PA":
        return "Pennsylvania";
      case "PR":
        return "Puerto Rico";
      case "RI":
        return "Rhode Island";
      case "SC":
        return "South Carolina";
      case "SD":
        return "South Dakota";
      case "TN":
        return "Tennessee";
      case "TX":
        return "Texas";
      case "UT":
        return "Utah";
      case "VA":
        return "Virginia";
      case "VI":
        return "Virgin Islands";
      case "VT":
        return "Vermont";
      case "WA":
        return "Washington";
      case "WI":
        return "Wisconsin";
      case "WV":
        return "West Virginia";
      case "WY":
        return "Wyoming";
      default:
        return "";
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

{% extends 'base.html' %}
{% load static %}

    <title>{% block title %}write up{% endblock %}</title>
    {% block linking %}
    {% endblock %}

{% block body %}
    {% if  writeup.aproved %}

write up by {{ writeup.author }}

{{ writeup.content }}

    {% else %}

the write up you look for is not approved by the admin yet!

    {% endif %}
{% endblock %}
{% block scripts %}
{% endblock %}


text:
// Generated by TinyPG v1.3 available at www.codeproject.com

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Threading;

namespace <%Namespace%>
{
    // Summary:
    //     System.EventArgs is the base class for classes containing event data.
    [Serializable]
    [ComVisible(true)]
    public class ContextSwitchEventArgs : EventArgs
    {
        public readonly ParseNode PreviousContext;
        public readonly ParseNode NewContext;

        // Summary:
        //     Initializes a new instance of the System.EventArgs class.
        public ContextSwitchEventArgs(ParseNode prevContext, ParseNode nextContext)
        {
            PreviousContext = prevContext;
            NewContext = nextContext;
        }
    }

    // delegate for firing context switch events
    public delegate void ContextSwitchEventHandler(object sender, ContextSwitchEventArgs e);

    /// <summary>
    /// Takes control over the RichTextBox and will color the text accoording to the rules of the parser and the scanner
    /// this control extender will also support Undo/Redo functionality.
    /// </summary>
    public class TextHighlighter : IDisposable
    {
        private class UndoItem
        {
            /// <summary>
            /// contains the information for an undo/redo action
            /// </summary>
            /// <param name="text">the full text to be undone/redone</param>
            /// <param name="position">position of the caret after the un/redo action</param>
            /// <param name="scroll">position of the scrollbars after un/redo action</param>
            public UndoItem(string text, int position, Point scroll)
            {
                Text = text;
                Position = position;
                ScrollPosition = scroll;
            }

            public string Text;
            public int Position;
            public Point ScrollPosition;
        }

        // some winapís required
        [DllImport("user32", CharSet = CharSet.Auto)]
        private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        private static extern bool PostMessageA(IntPtr hWnd, int nBar, int wParam, int lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int GetScrollPos(int hWnd, int nBar);

        [DllImport("user32.dll")]
        private static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

        private const int WM_SETREDRAW = 0x000B;
        private const int WM_USER = 0x400;
        private const int EM_GETEVENTMASK = (WM_USER + 59);
        private const int EM_SETEVENTMASK = (WM_USER + 69);
        private const int SB_HORZ = 0x0;
        private const int SB_VERT = 0x1;
        private const int WM_HSCROLL = 0x114;
        private const int WM_VSCROLL = 0x115;
        private const int SB_THUMBPOSITION = 4;
        private const int UNDO_BUFFER = 100;

        private int HScrollPos
        {
            get { return GetScrollPos((int)Textbox.Handle, SB_HORZ); }
            set
            {
                SetScrollPos((IntPtr)Textbox.Handle, SB_HORZ, value, true);
                PostMessageA((IntPtr)Textbox.Handle, WM_HSCROLL, SB_THUMBPOSITION + 0x10000 * value, 0);
            }
        }

        private int VScrollPos
        {
            get { return GetScrollPos((int)Textbox.Handle, SB_VERT); }
            set
            {
                SetScrollPos((IntPtr)Textbox.Handle, SB_VERT, value, true);
                PostMessageA((IntPtr)Textbox.Handle, WM_VSCROLL, SB_THUMBPOSITION + 0x10000 * value, 0);
            }
        }

        // public shared members
        public ParseTree Tree;
        public readonly RichTextBox Textbox;

        // private members
        private Parser Parser;
        private Scanner Scanner;
        private IntPtr stateLocked = IntPtr.Zero;

        private int UndoIndex = -1;
        private List<UndoItem> UndoList;

        private ParseNode currentContext;
        public event ContextSwitchEventHandler SwitchContext;

        private Thread threadAutoHighlight;

        private void Do(string text, int position)
        {

            if (stateLocked != IntPtr.Zero) return;

            UndoItem ua = new UndoItem(text, position, new Point(HScrollPos, VScrollPos));
            UndoList.RemoveRange(UndoIndex, UndoList.Count - UndoIndex);
            UndoList.Add(ua);
            if (UndoList.Count > UNDO_BUFFER)
                UndoList.RemoveAt(0);

            // make undo/redo a little smarter, remove single strokes
            // reducing nr of undo states
            if (UndoList.Count > 7)
            {
                bool canRemove = true;
                UndoItem nextItem = ua;
                for (int i = 0; i < 6; i++)
                {
                    UndoItem prevItem = UndoList[UndoList.Count - 2 - i];
                    canRemove &= (Math.Abs(prevItem.Text.Length - nextItem.Text.Length) <= 1 && Math.Abs(prevItem.Position - nextItem.Position) <= 1);
                    nextItem = prevItem;
                }
                if (canRemove)
                {
                    UndoList.RemoveRange(UndoList.Count - 6, 5);
                }
            }
            UndoIndex = UndoList.Count;
        }

        public void ClearUndo()
        {
            UndoList = new List<UndoItem>();
            UndoIndex = 0;
        }

        public void Undo()
        {
            if (!CanUndo) return;

            UndoIndex--;
            if (UndoIndex < 1)
                UndoIndex = 1;

            // implement undo action here
            UndoItem ua = UndoList[UndoIndex-1];
            RestoreState(ua);
        }

        public void Redo()
        {
            if (!CanRedo) return;

            UndoIndex++;
            if (UndoIndex > UndoList.Count)
                UndoIndex = UndoList.Count;

            UndoItem ua = UndoList[UndoIndex-1];
            RestoreState(ua);

        }

        private void RestoreState(UndoItem item)
        {
            Lock();
            // restore state
            Textbox.Rtf = item.Text;
            Textbox.Select(item.Position, 0);
            HScrollPos = item.ScrollPosition.X;
            VScrollPos = item.ScrollPosition.Y;

            Unlock();
        }

        public bool CanUndo
        {
            get { return UndoIndex > 0; }
        }

        public bool CanRedo
        {
            get { return UndoIndex < UndoList.Count; }
        }

        public TextHighlighter(RichTextBox textbox, Scanner scanner, Parser parser)
        {
            Textbox = textbox;
            Scanner = scanner;
            Parser = parser;

            ClearUndo();

            //Tree = Parser.Parse(Textbox.Text);
            Textbox.TextChanged += new EventHandler(Textbox_TextChanged);
            textbox.KeyDown += new KeyEventHandler(textbox_KeyDown);
            Textbox.SelectionChanged += new EventHandler(Textbox_SelectionChanged);
            Textbox.Disposed += new EventHandler(Textbox_Disposed);

            SwitchContext = null;
            currentContext = Tree;

            threadAutoHighlight = new Thread(AutoHighlightStart);
            threadAutoHighlight.Start();
        }

        public void Lock()
        {
            // Stop redrawing:
            SendMessage(Textbox.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
            // Stop sending of events:
            stateLocked = SendMessage(Textbox.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
            // change colors and stuff in the RichTextBox
        }

        public void Unlock()
        {
            // turn on events
            SendMessage(Textbox.Handle, EM_SETEVENTMASK, 0, stateLocked);
            // turn on redrawing
            SendMessage(Textbox.Handle, WM_SETREDRAW, 1, IntPtr.Zero);

            stateLocked = IntPtr.Zero;
            Textbox.Invalidate();
        }

        void textbox_KeyDown(object sender, KeyEventArgs e)
        {
            // undo/redo
            if (e.KeyValue == 89 && e.Control) // CTRL-Y
                Redo();
            if (e.KeyValue == 90 && e.Control) // CTRL-Z
                Undo();
        }

        void Textbox_TextChanged(object sender, EventArgs e)
        {
            if (stateLocked != IntPtr.Zero) return;

            Do(Textbox.Rtf, Textbox.SelectionStart);

            HighlightText();
        }

        void Textbox_SelectionChanged(object sender, EventArgs e)
        {
            if (stateLocked != IntPtr.Zero) return;

            if (SwitchContext == null) return;
            ParseNode newContext = GetCurrentContext();

            if (currentContext == null)
                currentContext = newContext;
            if (newContext == null) return;

            if (newContext.Token.Type != currentContext.Token.Type)
            {
                SwitchContext.Invoke(this, new ContextSwitchEventArgs(currentContext, newContext));
                currentContext = newContext;
            }

        }

        /// <summary>
        /// this handy function returns the section in which the user is editing currently
        /// </summary>
        /// <returns></returns>
        public ParseNode GetCurrentContext()
        {
            ParseNode node = FindNode(Tree, Textbox.SelectionStart);
            return node;
        }

        private ParseNode FindNode(ParseNode node, int posstart)
        {
            if (node == null) return null;

            if (node.Token.StartPos <= posstart && (node.Token.StartPos + node.Token.Length) >= posstart)
            {
                foreach (ParseNode n in node.Nodes)
                {
                    if (n.Token.StartPos <= posstart && (n.Token.StartPos + n.Token.Length) >= posstart)
                        return FindNode(n, posstart);
                }
                return node;
            }
            else
                return null;
        }

        /// <summary>
        /// use HighlighText to start the text highlight process from the caller's thread.
        /// this method is not used internally.
        /// </summary>
        public void HighlightText()
        {
            lock (treelock)
            {
                textChanged = true;
                currentText = Textbox.Text;
            }
        }

        // highlight the text (used internally only)
        private void HighlightTextInternal()
        {
            Lock();

            int hscroll = HScrollPos;
            int vscroll = VScrollPos;

            int selstart = Textbox.SelectionStart;

            HighlighTextCore();

            Textbox.Select(selstart,0);

            HScrollPos = hscroll;
            VScrollPos = vscroll;

            Unlock();
        }

        /// <summary>
        /// this method should be used only by HighlightText or RestoreState methods
        /// </summary>
        private void HighlighTextCore()
        {
            //Tree = Parser.Parse(Textbox.Text);
            StringBuilder sb = new StringBuilder();
            if (Tree == null) return;

            ParseNode start = Tree.Nodes[0];
            HightlightNode(start, sb);

            // append any trailing skipped tokens that were scanned
            foreach (Token skiptoken in Scanner.Skipped)
            {
                HighlightToken(skiptoken, sb);
                sb.Append(skiptoken.Text.Replace(@"\", @"\\").Replace("{", @"\{").Replace("}", @"\}").Replace("\n", "\\par\n"));
            }

            // NOTE: if you do not need unicode characters and you need a little bit more performance
            // you can comment out the following line:
            sb = Unicode(sb);     // <--- without this, unicode characters will be garbled after highlighting

            AddRtfHeader(sb);
            AddRtfEnd(sb);

            Textbox.Rtf = sb.ToString();

        }

                /// <summary>
        /// added function to convert unicode characters in the stringbuilder to rtf unicode escapes
        /// </summary>
        public StringBuilder Unicode(StringBuilder sb)
        {
            int i = 0;
            StringBuilder uc = new StringBuilder();
            for (i = 0; i <= sb.Length - 1; i++)
            {
                char c = sb[i];

                if ((int)c < 127)
                {
                    uc.Append(c);
                }
                else
                {
                    uc.Append("\\u" + ((int)c).ToString() + "?");
                }
            }
            return uc;
        }

        // thread start for the automatic highlighting
        private static object treelock = new object();
        private bool isDisposing;
        private bool textChanged;
        private string currentText;

        private void AutoHighlightStart()
        {
            ParseTree _tree;
            string _currenttext = "";
            while (!isDisposing)
            {
                bool _textchanged;
                lock (treelock)
                {
                    _textchanged = textChanged;
                    if (textChanged)
                    {
                        textChanged = false;
                        _currenttext = currentText;
                    }
                }
                if (!_textchanged)
                {
                    Thread.Sleep(200);
                    continue;
                }

                _tree = (ParseTree)Parser.Parse(_currenttext);
                lock (treelock)
                {
                    if (textChanged)
                        continue;
                    else
                        Tree = _tree; // assign new tree
                }

                Textbox.Invoke(new MethodInvoker(HighlightTextInternal));

            }
        }

        /// <summary>
        /// inserts the RTF codes to highlight text blocks
        /// </summary>
        /// <param name="node">the node to highlight, will be appended to sb</param>
        /// <param name="sb">the final output string</param>
        private void HightlightNode(ParseNode node, StringBuilder sb)
        {
            if (node.Nodes.Count == 0)
            {
                if (node.Token.Skipped != null)
                {
                    foreach(Token skiptoken in node.Token.Skipped)
                    {
                        HighlightToken(skiptoken, sb);
                        sb.Append(skiptoken.Text.Replace(@"\", @"\\").Replace("{", @"\{").Replace("}", @"\}").Replace("\n", "\\par\n"));
                    }
                }
                HighlightToken(node.Token, sb);
                sb.Append(node.Token.Text.Replace(@"\", @"\\").Replace("{", @"\{").Replace("}", @"\}").Replace("\n", "\\par\n"));
                sb.Append(@"}");
            }

            foreach (ParseNode n in node.Nodes)
            {
                HightlightNode(n, sb);
            }
        }

                /// <summary>
        /// inserts the RTF codes to highlight text blocks
        /// </summary>
        /// <param name="token">the token to highlight, will be appended to sb</param>
        /// <param name="sb">the final output string</param>
        private void HighlightToken(Token token, StringBuilder sb)
        {
            switch (token.Type)
            {
<%HightlightTokens%>
                default:
                    sb.Append(@"{{\cf0 ");
                    break;
            }
        }

        // define the color palette to be used here
        private void AddRtfHeader(StringBuilder sb)
        {
            sb.Insert(0, @"{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Consolas;}}{\colortbl;<%RtfColorPalette%>}\viewkind4\uc1\pard\lang1033\f0\fs20");
        }

        private void AddRtfEnd(StringBuilder sb)
        {
            sb.Append("}");
        }

        void Textbox_Disposed(object sender, EventArgs e)
        {
            Dispose();
        }

        #region IDisposable Members

        public void Dispose()
        {
            isDisposing = true;
            threadAutoHighlight.Join(1000);
            if (threadAutoHighlight.IsAlive)
                threadAutoHighlight.Abort();
        }

        #endregion
    }
}


text:
using Newtonsoft.Json.Linq;

namespace GenericListener.Adapters.MessageMappers
{
    public static class MapperHelpers
    {
        public static bool HasProperty(this JObject jsonObject, string propertyName)
        {
            return jsonObject.Property(propertyName) != null;
        }

        public static bool HasProperty(this JToken jsonObject, string propertyName)
        {
            return ((JObject)jsonObject).Property(propertyName) != null;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Harvest.Api
{
    public class TasksResponse : PagedList
    {
        public Task[] Tasks { get; set; }
    }
}


text:
require File.expand_path("../spec_helper", __FILE__)

describe MerchantSidekick::Addressable::Address, "should handle default columns" do
  it "should have default class attr columns assigned" do
    MerchantSidekick::Addressable::Address.street_address_column.should == :street
    MerchantSidekick::Addressable::Address.city_column.should == :city
    MerchantSidekick::Addressable::Address.postal_code_column.should == :postal_code
    MerchantSidekick::Addressable::Address.province_column.should  == :province
    MerchantSidekick::Addressable::Address.province_code_column.should == :province_code
    MerchantSidekick::Addressable::Address.country_column.should == :country
    MerchantSidekick::Addressable::Address.country_code_column.should  == :country_code
    MerchantSidekick::Addressable::Address.gender_column.should == :gender
    MerchantSidekick::Addressable::Address.first_name_column.should == :first_name
    MerchantSidekick::Addressable::Address.middle_name_column.should == false
    MerchantSidekick::Addressable::Address.last_name_column.should == :last_name
  end
end

describe MerchantSidekick::Addressable::Address, "with address members" do

  before(:each) do
    @address = MerchantSidekick::Addressable::Address.new(valid_address_attributes(:addressable => Addressable.create))
  end

  it "should create an address" do
    @address.should_not == nil
    @address.first_name.should == "George"
    @address.firstname.should == "George"
    @address.middle_name.should == "W." if @address.middle_name?
    @address.last_name.should == "Bush"
    @address.lastname.should == "Bush"
  end

  it "should handle street and address_line" do
    @address.street.should == "100 Washington St."
    @address.address_line_1.should == "100 Washington St."
  end

  it "should add address_line_2 properly" do
    @address.street.should == "100 Washington St."
    @address.address_line_2 = "Suite 1234"
    @address.address_line_2.should == "Suite 1234"
    @address.street.should == "100 Washington St.\nSuite 1234"
  end

  it "should address_line_1 and address_line_2 properly" do
    @address.street = ''
    @address.address_line_1 = "100 Enterprise Way"
    @address.address_line_2 = "Office Square 15"

    @address.address_line_1.should == "100 Enterprise Way"
    @address.address_line_2.should == "Office Square 15"
    @address.street.should == "100 Enterprise Way\nOffice Square 15"
  end

  it "should have a valid name" do
    if @address.middle_name?
      @address.name.should == "George W. Bush"
    else
      @address.name.should == "George Bush"
    end
  end

  it "should have a valid salutation and name" do
    if @address.middle_name?
      @address.salutation_and_name.should  == "Mr George W. Bush"
    else
      @address.salutation_and_name.should == "Mr George Bush"
    end
  end

  it "should stringify address fields" do
    # full
    @address.to_s.should == "George Bush, 100 Washington St., Santa Cruz, California, 95065, United States of America"

    # sparse
    @address = MerchantSidekick::Addressable::Address.new(
      :street        => "100 Sunshine Blvd.",
      :postal_code   => '95066',
      :city          => 'Scotts Valley',
      :province_code => 'CA',
      :country_code  => 'US'
    )
    @address.to_s.should == "100 Sunshine Blvd., Scotts Valley, CA, 95066, US"
  end

  it "should return a name" do
    @address.name.should == 'George Bush'
  end

  it "should return nil if names are nil" do
    @address = MerchantSidekick::Addressable::Address.new
    @address.name.should be_nil
  end

  it "should convert to active merchant address attributes" do
    @address = MerchantSidekick::Addressable::Address.new(valid_address_attributes(
      :addressable => Addressable.create,
      :street => "100 Sunshine Blvd.\nSuite 7"
    ))
    merchant = @address.to_merchant_attributes
    merchant[:name].should == "George Bush"
    merchant[:address1].should == "100 Sunshine Blvd."
    merchant[:address2].should == "Suite 7"
    merchant[:city].should == "Santa Cruz"
    merchant[:state].should == "CA"
    merchant[:country].should == "US"
    merchant[:zip].should == "95065"
    merchant[:phone].should == "+1 831 123-4567"
  end

  it "should work with gender" do
    @address.should be_gender  # funny :-)
    @address.gender = :male
    @address.gender.should == 'm'
    @address.should be_is_gender_male
    @address.gender = :female
    @address.gender.should == 'f'
    @address.gender = 'm'
    @address.gender.should == 'm'
    @address.gender = 'f'
    @address.gender.should == 'f'
  end

  it "should return a province or a province code" do
    address = MerchantSidekick::Addressable::Address.new(:province => "California", :province_code => "CA" )
    address.province_or_province_code.should == "California"

    address = MerchantSidekick::Addressable::Address.new(:province_code => "CA" )
    address.province_or_province_code.should == "CA"

    address = MerchantSidekick::Addressable::Address.new(:province => "", :province_code => "CA" )
    address.province_or_province_code.should == "CA"

    address = MerchantSidekick::Addressable::Address.new
    address.province_or_province_code.should be_nil
  end

  it "should return a country or a country code" do
    address = MerchantSidekick::Addressable::Address.new(:country => 'Germany', :country_code => 'DE')
    address.country_or_country_code.should == "Germany"

    address = MerchantSidekick::Addressable::Address.new(:country_code => 'DE')
    address.country_or_country_code.should == "DE"

    address = MerchantSidekick::Addressable::Address.new(:country => '', :country_code => 'DE')
    address.country_or_country_code.should == "DE"

    address = MerchantSidekick::Addressable::Address.new
    address.country_or_country_code.should be_nil
  end

end


text:
module.exports = function(context, fns, callback) {
    // if context isn't given
    if ( Array.isArray(context) ) {
        callback = fns;
        fns = context;
        context = {};
    }

    if ( typeof callback !== 'function' ) {
        callback = context;
        context = {};
    }

    // call each function (of length 1 or 2) in turn
    var upToIndex = -1;
    var err = null;

    function doNext() {
        // incremement to the next function
        upToIndex = upToIndex + 1;

        // we're finished since there are no more fns
        if ( upToIndex === fns.length ) {
            return callback(err, context);
        }

        // if this is an error function, just skip to the next one
        // since we're not in an error state
        if ( fns[upToIndex].length > 2 ) {
            return process.nextTick(function() {
                doNext();
            });
        }

        // call this function with the context
        fns[upToIndex](context, function(thisErr) {
            if (thisErr) {
                err = thisErr;
                return doNextError();
            }

            // no error, so continue back on the regular chain and clear the error
            err = null;
            doNext();
        });
    }

    function doNextError() {
        // incremement to the next function
        upToIndex = upToIndex + 1;

        // we're finished since there are no more fns
        if ( upToIndex === fns.length ) {
            return callback(err, context);
        }

        // if this is a normal function, just skip to the next one
        // since we're currently in an error state
        if ( fns[upToIndex].length < 3 ) {
            return process.nextTick(function() {
                doNextError();
            });
        }

        // call this function with the err and the context
        fns[upToIndex](err, context, function(thisErr) {
            if (thisErr) {
                err = thisErr;
                return doNextError();
            }
            // no error, so continue back on the regular chain and clear the error
            err = null;
            doNext();
        });
    }

    // kick things off
    doNext();
};

// ----------------------------------------------------------------------------


text:
layout: tag
section-type: tag
title: welcome
---
## Tag


text:
package com.tle.beans.item.cal.request;

import com.tle.beans.entity.BaseEntity;
import com.tle.beans.item.VersionSelection;
import com.tle.common.NameValue;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.Index;

@Entity
@AccessType("field")
// No can do as it's across 2 tables... we need some enforcement though...
// @Table(uniqueConstraints = {@UniqueConstraint(columnNames =
// {"institution_id", "code"})})
public class CourseInfo extends BaseEntity {
  private static final long serialVersionUID = 1L;

  // Keep Sonar happy with a final immutable List
  // @formatter:off
  @SuppressWarnings("nls")
  public static final List<NameValue> COURSE_TYPES =
      Collections.unmodifiableList(
          Arrays.asList(
              new NameValue("Internal", "i"),
              new NameValue("External", "e"),
              new NameValue("Staff", "s")));
  // @formatter:on

  private int students;
  private Date from;

  @Index(name = "courseInfoUntilIndex")
  private Date until;

  private String citation;
  private String lmsid;

  @Column(length = 512)
  private String departmentName;

  private Character courseType;

  @Index(name = "courseCodeIndex")
  @Column(length = 128)
  private String code;

  @Column(length = 30)
  @Enumerated(EnumType.STRING)
  private VersionSelection versionSelection;

  public CourseInfo() {
    super();
  }

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public Date getFrom() {
    return from;
  }

  public void setFrom(Date from) {
    this.from = from;
  }

  public int getStudents() {
    return students;
  }

  public void setStudents(int students) {
    this.students = students;
  }

  public Date getUntil() {
    return until;
  }

  public void setUntil(Date until) {
    this.until = until;
  }

  public String getCitation() {
    return citation;
  }

  public void setCitation(String citation) {
    this.citation = citation;
  }

  public String getLmsid() {
    return lmsid;
  }

  public void setLmsid(String lmsid) {
    this.lmsid = lmsid;
  }

  public String getDepartmentName() {
    return departmentName;
  }

  public void setDepartmentName(String departmentName) {
    if (departmentName != null && departmentName.length() > 512) {
      departmentName = departmentName.substring(0, 512);
    }
    this.departmentName = departmentName;
  }

  public char getCourseType() {
    if (courseType == null) {
      return 'i';
    }
    return courseType;
  }

  public void setCourseType(char courseType) {
    this.courseType = courseType;
  }

  public VersionSelection getVersionSelection() {
    return versionSelection;
  }

  public void setVersionSelection(VersionSelection versionSelection) {
    this.versionSelection = versionSelection;
  }

  /**
   * From static List, get the name string corresponding to primitive char.
   *
   * @param ch
   * @return name String if matched, otherwise null
   */
  public static String getTypeStringFromChar(char ch) {
    String val = null;
    Iterator<NameValue> iter = CourseInfo.COURSE_TYPES.iterator();
    while (iter.hasNext()) {
      NameValue nameValue = iter.next();
      if (nameValue.getValue().charAt(0) == ch) {
        return nameValue.getName();
      }
    }
    return val;
  }
}


text:
<?php

return [

    /*
     * Application Name
     *
     * Name of your project in `https://console.developers.google.com/`.
     */
    'applicationName' => 'MyProject',

    /*
     * Json Auth File Path
     *
     * After creating a project, go to `APIs & auth` and choose `Credentials` section.
     *
     * Click `Create new Client ID` and select `Service Account` choose `P12` as the `Key Type`.
     *
     * After downloading the `p12` file copy and paste it in the `storage` directory.
     *      Example:
     *          storage/MyProject-2a4d6aaa4413.p12
     *
     */
    'jsonFilePath' => 'MyProject-2a4d6aaa4413.p12',

    /*
     * Here you should pass an array of needed scopes depending on what service you will be using.
     *
     *      Example:
     *          For analytics service:
     *
     *              'scopes' => [
     *                  'https://www.googleapis.com/auth/analytics.readonly',
     *              ],
     */
    'scopes' => [
        //
    ],

];


text:
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
    <aspects>
        <aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
    </aspects>
</aspectj>


text:
package hierarchicalclustering.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;

import br.ufpe.cin.AmountDependencies;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class AmountDependenciesHandler extends AbstractHandler {

	public Object execute(ExecutionEvent event) throws ExecutionException {
		AmountDependencies amountDependencies = new AmountDependencies();
		amountDependencies.main();
		return null;
	}

}


text:
<?php
    require __DIR__.'/includes/form-messages.inc.php';
    renderResultMessagesHtml(new Dto_FormResult());

    // is form voor het toevoegen van een groep ipv wijzigen van een
    $isNew = (isset($data['isnew']));

    // vraag de opgegeven securitygroup op
    if (!$isNew) {
        $securitygroup = $tplHelper->getSecGroup($data['groupid']);
    } else {
        $securitygroup = ['name' => ''];
    }// if

?>

	<fieldset>
		<form class="editsecgroupform" name="editsecgroupform" action="<?php echo $tplHelper->makeEditSecGroupAction(); ?>" method="post">
			<input type="hidden" name="editsecgroupform[xsrfid]" value="<?php echo $tplHelper->generateXsrfCookie('editsecgroupform'); ?>">
<?php if (!$isNew) { ?>
			<input type="hidden" name="groupid" value="<?php echo $securitygroup['id']; ?>">
<?php } else {  ?>
			<input type="hidden" name="groupid" value="9999">
<?php } ?>

<?php echo _('Name'); ?>

				<input type="text" name="editsecgroupform[name]" value="<?php echo htmlspecialchars($securitygroup['name']); ?>" />

<?php if ($isNew) { ?>
				<input class="smallGreyButton" type="submit" name="editsecgroupform[submitaddgroup]" value="<?php echo _('Add'); ?>">
<?php } else { ?>
				<input class="smallGreyButton" type="submit" name="editsecgroupform[submitchangename]" value="<?php echo _('Change'); ?>">
<?php } ?>

		</form>
	</fieldset>


text:
layout: project
title: "Wireless Electricity"
description: "Light an LED without wires"
modified:
tags: [Circuits]
categories: [Circuits]
excerpt:
image:
  feature:
  teaser: wireless.png
  thumb: https://www.youtube.com/embed/eiCe56eSl8E
report: WirelessElectricity.pdf
ads: false
---

<!-- more -->
A short video showing my group's free lab project for Circuits II.  We were allowed to use any of the equipment within the lab.

<figure>
  <iframe width="560" height="315" src="https://www.youtube.com/embed/eiCe56eSl8E" frameborder="1" allowfullscreen></iframe>
</figure>

<!-- more -->
Voltage is connected to a sending circuit at the circuit's harmonic frequency.  The harmonic frequency creates a magnetic field around the circuit's inductor.  An inductor from a second circuit is placed within the field and power is transferred, turning on the LED.  The extra wires connected to the receiving circuit were for the oscilloscope to measure the voltage received.


text:
'use strict'
const path = require('path')
const arrayify = require('array-back')
const fs = require('fs-then-native')

/**
 * A memoisation solution intended to cache the output of expensive operations, speeding up future invocations with the same input.
 * @module cache-point
 * @example
 * const Cache = require('cache-point')
 * const cache = new Cache({ dir: 'tmp/example' })
 *
 * // The first invocation will take 3s, the rest instantaneous.
 * // outputs: 'result'
 * getData('some input')
 *   .then(console.log)
 *
 * // check the cache for output generated with this input.
 * // cache.read() will resolve on hit, reject on miss.
 * function getData (input) {
 *   return cache
 *     .read(input)
 *     .catch(() => expensiveOperation(input))
 * }
 *
 * // The expensive operation we're aiming to avoid,
 * // (3 second cost per invocation)
 * function expensiveOperation (input) {
 *   return new Promise((resolve, reject) => {
 *     setTimeout(() => {
 *       const output = 'result'
 *       cache.write(input, output)
 *       resolve(output)
 *     }, 3000)
 *   })
 * }
 */

/**
 * @alias module:cache-point
 * @typicalname cache
 */
class Cache {
  /**
   * @param [options] {object}
   * @param [options.dir] {string}
   */
  constructor (options) {
    options = options || {}
    if (!options.dir) {
      var os = require('os')
      options.dir = path.resolve(os.tmpdir(), 'cachePoint')
    }
    /**
     * Current cache directory. Can be changed at any time.
     * @type {string}
     */
    this.dir = options.dir
  }

  get dir () {
    return this._dir
  }
  set dir (val) {
    this._dir = val
    const mkdirp = require('mkdirp')
    mkdirp.sync(this.dir)
  }

  /**
   * A cache hit resolves with the stored value, a miss rejects.
   * @param {*} - One or more values to uniquely identify the data. Can be any value, or an array of values of any type.
   * @returns {Promise}
   */
  read (keys) {
    const blobPath = path.resolve(this._dir, this.getChecksum(keys))
    return fs.readFile(blobPath).then(JSON.parse)
  }

  /**
   * A cache hit returns the stored value, a miss returns `null`.
   * @param {*} - One or more values to uniquely identify the data. Can be any value, or an array of values of any type.
   * @returns {string?}
   */
  readSync (keys) {
    const blobPath = path.resolve(this._dir, this.getChecksum(keys))
    try {
      const data = fs.readFileSync(blobPath, 'utf8')
      return JSON.parse(data)
    } catch (err) {
      return null
    }
  }

  /**
   * Write some data to the cache. Returns a promise which resolves when the write is complete.
   * @param {*} - One or more values to index the data, e.g. a request object or set of function args.
   * @param {*} - the data to store
   * @returns {Promise}
   */
  write (keys, content) {
    const blobPath = path.resolve(this._dir, this.getChecksum(keys))
    return fs.writeFile(blobPath, JSON.stringify(content))
  }

  /**
   * Write some data to the cache with a key.
   * @param {*} - One or more values to index the data, e.g. a request object or set of function args.
   * @param {*} - the data to store
   */
  writeSync (keys, content) {
    const blobPath = path.resolve(this._dir, this.getChecksum(keys))
    fs.writeFileSync(blobPath, JSON.stringify(content))
  }

  /**
   * Used internally to convert a key value into a hex checksum. Override if for some reason you need a different hashing strategy.
   * @param {*} - One or more values to index the data, e.g. a request object or set of function args.
   * @returns {string}
   */
  getChecksum (keys) {
    const crypto = require('crypto')
    const hash = crypto.createHash('sha1')
    arrayify(keys).forEach(key => hash.update(JSON.stringify(key)))
    return hash.digest('hex')
  }

  /**
   * Clears the cache. Returns a promise which resolves once the cache is clear.
   * @returns {Promise}
   */
  clear () {
    return fs.readdir(this._dir)
      .then(files => {
        const promises = files.map(file => fs.unlink(path.resolve(this._dir, file)))
        return Promise.all(promises)
      })
  }

  /**
   * Clears and removes the cache directory. Returns a promise which resolves once the remove is complete.
   * @returns {Promise}
   */
  remove () {
    return this.clear().then(() => {
      return fs.rmdir(this._dir)
    })
  }
}

module.exports = Cache


text:
package org.spockframework.compiler;

import java.io.File;

import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.*;

import org.spockframework.compiler.model.*;
import org.spockframework.runtime.model.*;

/**
 * Puts all spec information required at runtime into annotations
 * attached to class members.
 *
 * @author Peter Niederwieser
 */
public class SpecAnnotator extends AbstractSpecVisitor {
  private final AstNodeCache nodeCache;
  private ListExpression blockAnnElems;

  public SpecAnnotator(AstNodeCache nodeCache) {
    this.nodeCache = nodeCache;
  }

  @Override
  public void visitSpec(Spec spec) throws Exception {
    addSpecMetadata(spec);
  }

  private void addSpecMetadata(Spec spec) {
    AnnotationNode ann = new AnnotationNode(nodeCache.SpecMetadata);
    String pathname = spec.getAst().getModule().getContext().getName();
    String filename = new File(pathname).getName();
    ann.setMember(SpecMetadata.FILENAME, new ConstantExpression(filename));
    ann.setMember(SpecMetadata.LINE, new ConstantExpression(spec.getAst().getLineNumber()));
    spec.getAst().addAnnotation(ann);
  }

  @Override
  public void visitField(Field field) throws Exception {
    addFieldMetadata(field);
  }

  private void addFieldMetadata(Field field) {
    AnnotationNode ann = new AnnotationNode(nodeCache.FieldMetadata);
    ann.setMember(FieldMetadata.NAME, new ConstantExpression(field.getName()));
    ann.setMember(FieldMetadata.ORDINAL, new ConstantExpression(field.getOrdinal()));
    ann.setMember(FieldMetadata.LINE, new ConstantExpression(field.getAst().getLineNumber()));
    field.getAst().addAnnotation(ann);
  }

  @Override
  public void visitMethod(Method method) throws Exception {
    if (method instanceof FeatureMethod)
      addFeatureMetadata((FeatureMethod)method);
  }

  private void addFeatureMetadata(FeatureMethod feature) {
    AnnotationNode ann = new AnnotationNode(nodeCache.FeatureMetadata);
    ann.setMember(FeatureMetadata.NAME, new ConstantExpression(feature.getName()));
    ann.setMember(FeatureMetadata.ORDINAL, new ConstantExpression(feature.getOrdinal()));
    ann.setMember(FeatureMetadata.LINE, new ConstantExpression(feature.getAst().getLineNumber()));
    ann.setMember(FeatureMetadata.BLOCKS, blockAnnElems = new ListExpression());

    ListExpression paramNames = new ListExpression();
    for (Parameter param : feature.getAst().getParameters())
      paramNames.addExpression(new ConstantExpression(param.getName()));
    ann.setMember(FeatureMetadata.PARAMETER_NAMES, paramNames);

    feature.getAst().addAnnotation(ann);
  }

  private void addBlockMetadata(Block block, BlockKind kind) {
    AnnotationNode blockAnn = new AnnotationNode(nodeCache.BlockMetadata);
    blockAnn.setMember(BlockMetadata.KIND, new PropertyExpression(
        new ClassExpression(nodeCache.BlockKind), kind.name()));
    ListExpression textExprs = new ListExpression();
    for (String text : block.getDescriptions())
      textExprs.addExpression(new ConstantExpression(text));
    blockAnn.setMember(BlockMetadata.TEXTS, textExprs);
    blockAnnElems.addExpression(new AnnotationConstantExpression(blockAnn));
  }

  @Override
  public void visitSetupBlock(SetupBlock block) throws Exception {
    addBlockMetadata(block, BlockKind.SETUP);
  }

  @Override
  public void visitExpectBlock(ExpectBlock block) throws Exception {
    addBlockMetadata(block, BlockKind.EXPECT);
  }

  @Override
  public void visitWhenBlock(WhenBlock block) throws Exception {
    addBlockMetadata(block, BlockKind.WHEN);
  }

  @Override
  public void visitThenBlock(ThenBlock block) throws Exception {
    addBlockMetadata(block, BlockKind.THEN);
  }

  @Override
  public void visitCleanupBlock(CleanupBlock block) throws Exception {
    addBlockMetadata(block, BlockKind.CLEANUP);
  }

  @Override
  public void visitWhereBlock(WhereBlock block) throws Exception {
    addBlockMetadata(block, BlockKind.WHERE);
  }
}


text:
require 'ixtlan/babel/serializer'
module Ixtlan
  module UserManagement
    class UserSerializer < Ixtlan::Babel::Serializer

      add_context( :session ) do
        only( :login,
              :name,
              :groups => only( :name,
                               :associations ) )
      end
    end
  end
end


text:
Jupytext works well with the [pre-commit](https://pre-commit.com/) framework. You can add the following to your `.pre-commit-config.yaml` file to sync all staged notebooks:

```yaml
repos:
-   repo: https://github.com/mwouts/jupytext
    rev: v1.14.0  # CURRENT_TAG/COMMIT_HASH
    hooks:
    - id: jupytext
      args: [--sync]
```

You can provide almost all command line arguments to Jupytext in pre-commit, for example to produce several kinds of output files:

```yaml
repos:
-   repo: https://github.com/mwouts/jupytext
    rev: v1.14.0  # CURRENT_TAG/COMMIT_HASH
    hooks:
    - id: jupytext
      args: [--from, ipynb, --to, "py:percent"]
```

If you are combining Jupytext with other pre-commit hooks, you must ensure that all hooks will pass on any files you generate. For example, if you have a hook for using `black` to format all your python code, then you should use Jupytext's `--pipe` option to also format newly generated Python scripts before writing them:

```yaml
repos:
-   repo: https://github.com/mwouts/jupytext
    rev: v1.14.0  # CURRENT_TAG/COMMIT_HASH
    hooks:
    - id: jupytext
      args: [--sync, --pipe, black]
      additional_dependencies:
        - black==22.3.0 # Matches hook

-   repo: https://github.com/psf/black
    rev: 22.3.0
    hooks:
    - id: black
      language_version: python3
```

Tested examples of how to use the pre-commit hook are available in
our [tests](https://github.com/mwouts/jupytext/tree/main/tests) -
see for instance
[test_pre_commit_1_sync_with_config.py](https://github.com/mwouts/jupytext/blob/main/tests/test_pre_commit_1_sync_with_config.py).


text:
<project>

	<taskdef resource="org/gridkit/lab/gridant/gridant.properties"/>

	<target name="local-twin-server">
		<cluster type="local">
			<server id="server1"/>
			<server id="server2"/>
		</cluster>
	</target>

	<target name="local-base1">
		<cluster type="local">
			<basepath>target/base1</basepath>
			<server id="server1"/>
		</cluster>
	</target>

	<target name="local-base2">
		<cluster type="local">
			<basepath>target/base2</basepath>
			<server id="server2"/>
		</cluster>
	</target>

    <target name="grid-echo" depends="local-twin-server">
        <echo>This is master</echo>
        <remotely servers="server*">
            <echo>This is slave ${slave.id}</echo>
        </remotely>
    </target>

    <target name="grid-touch" depends="local-base1, local-base2">
        <echo>This is master</echo>
        <remotely servers="server*">
            <touch file="${slave.id}.txt"/>
        </remotely>
    </target>

	<target name="grid-touch2" depends="local-base1, local-base2">
        <echo>This is master</echo>
        <remotely servers="server*">
            <antcall target="remote-touch" inheritrefs="true"/>
        </remotely>
    </target>

	<target name="grid-touch3" depends="local-base1, local-base2">
        <echo>This is master</echo>
        <remotely servers="server*">
            <remote-touch-macro/>
        </remotely>
    </target>

	<target name="remote-touch">
	    <touch file="${slave.id}-2.txt"/>
	</target>

	<macrodef name="remote-touch-macro">
		<sequential>
	        <touch file="${slave.id}-3.txt"/>
	    </sequential>
	</macrodef>

</project>


text:
package org.multibit.hd.ui.languages;

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import org.multibit.hd.core.config.Configurations;
import org.multibit.hd.core.dto.CoreMessageKey;

import java.awt.*;
import java.net.URI;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 *
Utility to provide the following to Views:

 *

 *
Access to internationalised text strings

 *

 *
 * @since 0.0.1
 */
public class Languages {

  public static final String BASE_NAME = "languages.language";

  /**
   * The Crowdin.com  MultiBit HD translate site (HTTPS)
   */
  public static final URI MBHD_TRANSLATION_WEBSITE_URI = URI.create("https://crowdin.com/project/multibit-hd");

  /**
   * Utilities have private constructors
   */
  private Languages() {
  }

  /**
   *
Provide an array of the available amount separators. A hard space '\u00a0' is needed to
   * ensure that values do not wrap.

   *
   * @return The array
   */
  public static String[] getCurrencySeparators(boolean forGrouping) {

    if (forGrouping) {
      // Groups can be separated by comma, point and space
      return new String[]{
        Languages.safeText(MessageKey.DECIMAL_COMMA),
        Languages.safeText(MessageKey.DECIMAL_POINT),
        Languages.safeText(MessageKey.DECIMAL_SPACE)
      };
    } else {
      // Decimals can be separated by comma and point only
      return new String[]{
        Languages.safeText(MessageKey.DECIMAL_COMMA),
        Languages.safeText(MessageKey.DECIMAL_POINT)
      };

    }
  }

  /**
   * @return Current locale from configuration
   */
  public static Locale currentLocale() {

    Preconditions.checkNotNull(Configurations.currentConfiguration, "'currentConfiguration' must be present");

    return Configurations.currentConfiguration.getLocale();
  }

  /**
   * @param value The encoding of the locale (e.g. "ll", "ll_rr", "ll_rr_vv")
   *
   * @return A new resource bundle based on the locale
   */
  public static Locale newLocaleFromCode(String value) {

    Preconditions.checkNotNull(value, "'value' must be present");

    String[] parameters = value.split("_");

    Preconditions.checkState(parameters.length > 0, "'value' must not be empty");

    final Locale newLocale;

    switch (parameters.length) {
      case 1:
        newLocale = new Locale(parameters[0]);
        break;
      case 2:
        newLocale = new Locale(parameters[0], parameters[1]);
        break;
      case 3:
        newLocale = new Locale(parameters[0], parameters[1], parameters[2]);
        break;
      default:
        throw new IllegalArgumentException("Unknown locale descriptor: " + value);
    }

    return newLocale;

  }

  /**
   * @param key    The key (treated as a direct format string if not present)
   * @param values An optional collection of value substitutions for {@link MessageFormat}
   *
   * @return The localised text with any substitutions made
   */
  public static String safeText(MessageKey key, Object... values) {

    // Simplifies processing of empty text
    if (key == null) {
      return "";
    }

    ResourceBundle rb = currentResourceBundle();

    String message;

    if (!rb.containsKey(key.getKey())) {
      // If no key is present then use it direct
      message = key.getKey();
    } else {
      // Must have the key to be here
      message = rb.getString(key.getKey());
    }
    message = escapeSingleQuote(message);

    return MessageFormat.format(message, values);
  }

  /**
   * @param key    The key (treated as a direct format string if not present)
   * @param values An optional collection of value substitutions for {@link MessageFormat}
   *
   * @return The localised text with any substitutions made
   */
  public static String safeText(CoreMessageKey key, Object... values) {

    ResourceBundle rb = currentResourceBundle();

    String message;

    if (!rb.containsKey(key.getKey())) {
      // If no key is present then use it direct
      message = key.getKey();
    } else {
      // Must have the key to be here
      message = rb.getString(key.getKey());
    }
    message = escapeSingleQuote(message);

    return MessageFormat.format(message, values);
  }

  /**
   * @param key    The key (must be present in the bundle)
   * @param values An optional collection of value substitutions for {@link MessageFormat}
   *
   * @return The localised text with any substitutions made
   */
  public static String safeText(String key, Object... values) {

    ResourceBundle rb = currentResourceBundle();

    String message;

    if (!rb.containsKey(key)) {
      // If no key is present then use it direct
      message = "Key '" + key + "' is not localised!";
    } else {
      // Must have the key to be here
      message = rb.getString(key);
    }
    message = escapeSingleQuote(message);

    return MessageFormat.format(message, values);
  }

  /**
   * @param contents  The contents to join into a localised comma-separated list
   * @param maxLength The maximum length of the result single string
   *
   * @return The localised comma-separated list with ellipsis appended if truncated
   */
  public static String truncatedList(Collection<String> contents, int maxLength) {

    Preconditions.checkNotNull(contents, "'contents' must be present");
    Preconditions.checkState(maxLength > 0 && maxLength < 4096, "'maxLength' must be [1,4096]");

    String joinedContents = Joiner
      .on(Languages.safeText(MessageKey.LIST_COMMA) + " ")
      .join(contents);

    String ellipsis = Languages.safeText(MessageKey.LIST_ELLIPSIS);

    // Determine the truncation point (if required)
    int maxIndex = Math.min(joinedContents.length() - 1, maxLength - ellipsis.length() - 1);

    if (maxIndex == joinedContents.length() - 1) {
      // No truncation
      return joinedContents;
    } else {
      // Apply truncation (with ellipsis)
      return joinedContents.substring(0, maxIndex) + ellipsis;
    }

  }

  /**
   *
Package access only - external consumers should use safeText()

   *
   * @return The resource bundle based on the current locale
   */
  static ResourceBundle currentResourceBundle() {

    return ResourceBundle.getBundle(BASE_NAME, currentLocale());
  }

  /**
   * @return The component orientation based on the current locale
   */
  public static ComponentOrientation currentComponentOrientation() {
    return ComponentOrientation.getOrientation(Languages.currentLocale());
  }

  /**
   * @return True if text is to be placed left to right (standard Western language presentation)
   */
  public static boolean isLeftToRight() {
    return ComponentOrientation.getOrientation(currentLocale()).isLeftToRight();
  }

  /**
   * Note: This approach is currently limited to English to support Trezor
   *
   * @param value The value represented as a simple string
   *
   * @return The value with its ordinal in the idiom for the language (e.g. English "1st", "2nd", "3rd", "4th" etc)
   */
  public static String getOrdinalFor(int value) {

    String ordinal = String.valueOf(value);
    if (ordinal.endsWith("11") || ordinal.endsWith("12") || ordinal.endsWith("13")) {
      ordinal = ordinal + "th";
    } else if (ordinal.endsWith("1")) {
      ordinal = ordinal + "st";
    } else if (ordinal.endsWith("2")) {
      ordinal = ordinal + "nd";
    } else if (ordinal.endsWith("3")) {
      ordinal = ordinal + "rd";
    } else {
      ordinal = ordinal + "th";
    }
    return ordinal;
  }

  /**
   * Capitalise the first letter of a phrase
   *
   * @param phrase The phrase to capitalise
   *
   * @return the phrase, with the first letter capitalised
   */

  public static String toCapitalCase(String phrase) {
    if (phrase == null) {
      return null;
    }
    if (phrase.length() == 0) {
      return "";
    }
    if (phrase.length() == 1) {
      return phrase.toUpperCase();
    }
    return Character.toString(phrase.charAt(0)).toUpperCase() + phrase.substring(1);
  }

  /**
   *
Automatically escape single quotes
   * This is done to avoid confusion with translators having to do this
   * We check for complex formatting first and avoid auto-escape if present
   *

   *
   * @param message The original message
   *
   * @return The escaped message (unchanged if auto-escape is not possible)
   */
  public static String escapeSingleQuote(String message) {

    if (!message.contains("'{") && !message.contains("''")) {
      // OK to auto-escape
      message = message.replace("'", "''");
    }

    return message;

  }
}


text:
<?php

namespace ZendTest\Db\Sql\Ddl\Column;

use Zend\Db\Sql\Ddl\Column\Blob;

class BlobTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Zend\Db\Sql\Ddl\Column\Blob::setLength
     */
    public function testSetLength()
    {
        $blob = new Blob('foo', 55);
        $this->assertEquals(55, $blob->getLength());
        $this->assertSame($blob, $blob->setLength(20));
        $this->assertEquals(20, $blob->getLength());
    }

    /**
     * @covers Zend\Db\Sql\Ddl\Column\Blob::getLength
     */
    public function testGetLength()
    {
        $blob = new Blob('foo', 55);
        $this->assertEquals(55, $blob->getLength());
    }

    /**
     * @covers Zend\Db\Sql\Ddl\Column\Blob::getExpressionData
     */
    public function testGetExpressionData()
    {
        $column = new Blob('foo', 10000000);
        $this->assertEquals(
            array(array('%s %s', array('foo', 'BLOB 10000000 NOT NULL'), array($column::TYPE_IDENTIFIER, $column::TYPE_LITERAL))),
            $column->getExpressionData()
        );
    }

}