<?xml version="1.0" encoding="UTF-8"?>
<codes type="array">
  <code>
    <code>        def dedent()
            sRaw    =   self;
            sep     =   "\n";
            aLines  =   [];

            ###
            iMargin = sRaw.split(sep.to_s).map {|line|
                aLines.push(line);
                stest   = line[/^\s*[\S]/]
                if(stest != nil)
                    stest   = stest.length-1
                end
            }
            iMargin =   iMargin.find_all{|vxx| vxx;}.min;
            iMargin =   iMargin.to_i;

            ###
            aLines = aLines.map{|line|
                line    =   line.to_s
                if(line.length &gt;= iMargin)
                    line[iMargin..line.length]
                end
            }
            ###
            return aLines.join("\n")
        end
</code>
    <comment>Remove leading whitespace from a string without removing the relative indentation of content within the string</comment>
    <created-at type="datetime">2010-03-05T16:37:38+00:00</created-at>
    <id type="integer">1206</id>
    <language>Ruby</language>
    <permalink>ruby-dedent-whitespace-in-a-string</permalink>
    <refactors-count type="integer">2</refactors-count>
    <title>ruby dedent whitespace in a string</title>
    <trackback-url></trackback-url>
    <updated-at type="datetime">2010-03-07T14:37:02+00:00</updated-at>
    <user-id type="integer">1871</user-id>
    <user>
      <id type="integer">1871</id>
      <identity-url>http://dreftymac.myopenid.com</identity-url>
      <name>dreftymac.myopenid.com</name>
      <rating type="float">0.0</rating>
      <refactors-count type="integer">1</refactors-count>
      <website nil="true"></website>
    </user>
  </code>
  <code>
    <code>def compress(source)
    source.gsub!(/\s+/, " ") # collapse space
    source.gsub!(/\/\*(.*?)\*\//, "") # remove comments - caution, might want to remove this if using css hacks
    source.gsub!(/;\s+/, ";") #remove extra space after ;
    source.gsub!(/\}\s+/, "}") #remove extra space after }
    source.gsub!(/\{\s+/, "{") #remove extra space after {
    source.gsub!(/\:\s+/, ":") #remove extra space after :
    source.gsub!(/\,\s+/, ",") #remove extra space after ,

    source.gsub!(/\s+;/, ";") #remove extra space before ;
    source.gsub!(/\s+\}/, "}") #remove extra space before }
    source.gsub!(/\s+\{/, "{") #remove extra space before {
    source.gsub!(/\s+\:/, ":") #remove extra space before :
    source.gsub!(/\s+\,/, ",") #remove extra space before ,

    source.strip!
  end</code>
    <comment>There is a lot of repetition here. But I don't know how to trim it up. </comment>
    <created-at type="datetime">2008-10-31T09:44:53+00:00</created-at>
    <id type="integer">571</id>
    <language>Ruby</language>
    <permalink>gsubing</permalink>
    <refactors-count type="integer">2</refactors-count>
    <title>Gsubing</title>
    <trackback-url></trackback-url>
    <updated-at type="datetime">2008-10-31T14:16:58+00:00</updated-at>
    <user-id type="integer">1135</user-id>
    <user>
      <id type="integer">1135</id>
      <identity-url>http://oid.marko.myopenid.com</identity-url>
      <name>marko.z</name>
      <rating type="float">0.0</rating>
      <refactors-count type="integer">1</refactors-count>
      <website></website>
    </user>
  </code>
  <code>
    <code>namespace Utilities
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;

    public static class StringExt
    {

        public static bool IsEmail(this string inputstr)
        {
            // exit if the string is null or empty
            if (inputstr.IsEmpty())
                return false;

            string strRegex = @"^([a-zA-Z0-9_\-\.\+]+)@((\[[0-9]{1,3}" +
                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            return inputstr.MatchRegex(strRegex);
        }

        public static bool IsZip(this string inputstr)
        {
            // exit if the string is null or empty
            if (inputstr.IsEmpty())
                return false;

            string strRegex = @"^\d{5}$|^\d{5}-\d{4}$";

            return inputstr.MatchRegex(strRegex);
        }

        public static bool IsStateAbbrv(this string inputstr)
        {
            return inputstr.IsStateAbbrv(false);
        }


        public static bool IsStateAbbrv(this string inputstr, bool CaseSensitive)
        {
            // exit if the string is null or empty
            if (inputstr.IsEmpty())
                return false;

            string strRegex = @"^((AL)|(AK)|(AS)|(AZ)|(AR)|(CA)|(CO)|(CT)|(DE)|(DC)|(FM)|(FL)|" +
                @"(GA)|(GU)|(HI)|(ID)|(IL)|(IN)|(IA)|(KS)|(KY)|(LA)|(ME)|(MH)|(MD)|(MA)|(MI)|" +
                @"(MN)|(MS)|(MO)|(MT)|(NE)|(NV)|(NH)|(NJ)|(NM)|(NY)|(NC)|(ND)|(MP)|(OH)|(OK)|" +
                @"(OR)|(PW)|(PA)|(PR)|(RI)|(SC)|(SD)|(TN)|(TX)|(UT)|(VT)|(VI)|(VA)|(WA)|(WV)|" +
                @"(WI)|(WY))$";

            return inputstr.MatchRegex(strRegex, CaseSensitive);
        }

        public static bool IsStateName(this string inputstr)
        {
            return inputstr.IsStateName(false);
        }

        public static bool IsStateName(this string inputstr, bool CaseSensitive)
        {
            // exit if the string is null or empty
            if (inputstr.IsEmpty())
                return false;

            string strRegex = @"^((Alabama)|(Alaska)|(AmericanSamoa)|(Arizona)|(Arkansas)|(California)|" +
                @"(Colorado)|(Connecticut)|(Delaware)|(DistrictofColumbia)|(Florida)|(Georgia)|(Guam)|" +
                @"(Hawaii)|(Idaho)|(Illinois)|(Indiana)|(Iowa)|(Kansas)|(Kentucky)|(Louisiana)|(Maine)|" +
                @"(Maryland)|(Massachusetts)|(Michigan)|(Minnesota)|(Mississippi)|(Missouri)|(Montana)|" +
                @"(Nebraska)|(Nevada)|(NewHampshire)|(NewJersey)|(NewMexico)|(NewYork)|(NorthCarolina)|" +
                @"(NorthDakota)|(NorthernMarianasIslands)|(Ohio)|(Oklahoma)|(Oregon)|(Pennsylvania)|" +
                @"(PuertoRico)|(RhodeIsland)|(SouthCarolina)|(SouthDakota)|(Tennessee)|(Texas)|(Utah)|" +
                @"(Vermont)|(Virginia)|(VirginIslands)|(Washington)|(WestVirginia)|(Wisconsin)|(Wyoming))$";

            return inputstr.MatchRegex(strRegex, CaseSensitive);
        }

        public static bool IsEmpty(this string inputstr)
        {
            if (inputstr == null || inputstr.Trim().Length == 0)
            {
                return true;
            }
            return false;
        }

        public static bool IsPhone(this string inputstr)
        {
            // exit if the string is null or empty
            if (inputstr.IsEmpty())
                return false;

            string strRegex = @"^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$";
            return inputstr.MatchRegex(strRegex);
        }

        public static bool MatchRegex(this string inputstr, string regex)
        {
            return inputstr.MatchRegex(regex, false);
        }


        public static bool MatchRegex(this string inputstr, string regex, bool CaseSensitive)
        {
            var IsCaseSensitive = RegexOptions.IgnoreCase;
            if (CaseSensitive)
            {
                IsCaseSensitive = RegexOptions.None;
            }

            return System.Text.RegularExpressions.Regex.IsMatch(inputstr, regex, IsCaseSensitive);
        }

        public static bool EqualsIgnoreCase(this string s, string value)
        {
            return s.ToLowerInvariant() == value.ToLowerInvariant();
        }
        
        // be nice to VB &amp; CF devlopers
        public static string Left(this string s, int position)
        {
            return s.Substring(0, position);
        }

        // be nice to VB &amp; CF devlopers
        public static string Right(this string s, int position)
        {
            return s.Substring(s.Length - position);
        }

        public static string Reverse(this string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }

        public static string FormatTitleCase(this string s)
        {
            string[] words = s.Split(' ');

            string result = string.Empty;
            string temp = string.Empty;

            foreach (string i in words)
            {
                temp = i.ToLower();
                result = result + i.Substring(0, 1).ToUpper() + i.Substring(1) + " ";
            }

            result = result.Substring(0, result.Length - 1);

            return result;
        }

        /// &lt;summary&gt;
        /// convert a string that is CSV formated into a List
        /// credit goes to www.usualdosage.com where I got most of this code
        /// &lt;/summary&gt;
        /// &lt;param name="s"&gt;&lt;/param&gt;
        /// &lt;returns&gt;List&lt;/returns&gt;
        public static List&lt;string&gt; CSVToList(this string s)
        {
            char CHAR_COMMA = Convert.ToChar(44);
            char CHAR_QUOTE = Convert.ToChar(34);
            char CHAR_PIPE = Convert.ToChar(124);
            char CHAR_BACKQUOTE = Convert.ToChar(96);
            // Create a new array to contain the return values
       
            string strCurrent = s;
            string[] arrTokens = null;
            
            // Replace any instance of double quotes with a back quote
            strCurrent = strCurrent.Replace("\"\"", "`");
            
            if (!strCurrent.Contains(CHAR_QUOTE.ToString())) // No quotes, so just split on commas
            {
                arrTokens = strCurrent.Split(CHAR_COMMA);
            }
            else // Contains quotes, so more detailed parsing needed
            {
                bool bQuote = false;
                bool bEscape = false;
            
                // Convert temp to a char array to make it easier to check each char
                char[] arrTempChars = strCurrent.ToCharArray();
                for (int i = 0; i &lt; arrTempChars.Length; i++)
                {
                    // Loop through until we find a quote. If found, flip the bool value
                    if (arrTempChars[i] == CHAR_QUOTE)
                    {
                        if (!bEscape)
                        bQuote = !bQuote;
                    }

                    // If we&#8217;re in a quote group and find a comma, change it to a temp char for the moment
                    if (bQuote &amp;&amp; (arrTempChars[i] == CHAR_COMMA))
                    {
                        arrTempChars[i] = CHAR_PIPE;
                    }
                }
               // Parse out the modified character array into a string
               string strReassemble = string.Empty;
               
               for (int j = 0; j &lt; arrTempChars.Length; j++)
               {
                   strReassemble = strReassemble + arrTempChars[j].ToString();
               }
               
               // Remove the quotes, which will leave just commas, and split
               strReassemble = strReassemble.Replace(CHAR_QUOTE.ToString(), string.Empty);
               arrTokens = strReassemble.Split(CHAR_COMMA);
               
               // Loop through the array, and reset the temp chars back to
               // commas, and replace the back quotes with double quotes
               for (int k = 0; k &lt; arrTokens.Length; k++)
               {
                   arrTokens[k] = arrTokens[k].Replace(CHAR_PIPE, CHAR_COMMA);
                   arrTokens[k] = arrTokens[k].Replace(CHAR_BACKQUOTE, CHAR_QUOTE);
               }
            }

            List&lt;string&gt; rtrnList = new List&lt;string&gt;();
            foreach (string entry in arrTokens)
            {
                rtrnList.Add(entry);
            }

            return rtrnList;
        }

        /// &lt;summary&gt;
        /// convert a string that is CSV formated into a List
        /// credit goes to www.usualdosage.com where I got most of this code
        /// &lt;/summary&gt;
        /// &lt;param name="s"&gt;&lt;/param&gt;
        /// &lt;returns&gt;List&lt;/returns&gt;
        public static string[] CSVToArray(this string s)
        {
            return s.CSVToList().ToArray();
        }

        /// &lt;summary&gt;
        /// Convert a string[] into a single string that is seperated by a 
        /// delimiter
        /// &lt;/summary&gt;
        /// &lt;param name="s"&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static string ToDelimitedString(this string[] s)
        {
            return s.ToDelimitedString(",", false);
        }

        public static string ToDelimitedString(this string[] s, string vDelimeter)
        {
            return s.ToDelimitedString(vDelimeter, false);
        }
        public static string ToDelimitedString(this string[] s, bool QuoteEachEntry)
        {
            return s.ToDelimitedString(",", QuoteEachEntry);
        }

        public static string ToDelimitedString(this string[] s, string Delimeter, bool QuoteEachEntry)
        {
            string result = string.Empty;
            string vDelim = string.Empty;

            foreach (string element in s)
            {
                if(QuoteEachEntry)
                    result += vDelim + "\"" + element + "\"";
                else
                    result += vDelim + element;
                vDelim = Delimeter;
            }
            return result;
        }
    }
}
</code>
    <comment>Ok take it easy on me, I just started c# and I'd love everyone's feed back on the following extension I made. I'd love to hear about best practices, speed improvements, or just better ways to code what I did.  I came from a coldfusion background so I was trying to code in some of the methods I missed in cf as well as a few nice shortcut methods.</comment>
    <created-at type="datetime">2008-08-06T16:46:43+00:00</created-at>
    <id type="integer">422</id>
    <language>C#</language>
    <permalink>stringext-cs-string-extension</permalink>
    <refactors-count type="integer">6</refactors-count>
    <title>StringExt.cs (String Extension)</title>
    <trackback-url></trackback-url>
    <updated-at type="datetime">2008-10-24T14:22:12+00:00</updated-at>
    <user-id type="integer">912</user-id>
    <user>
      <id type="integer">912</id>
      <identity-url>http://proe.myopenid.com</identity-url>
      <name>snafu918</name>
      <rating type="float">0.0</rating>
      <refactors-count type="integer">1</refactors-count>
      <website nil="true"></website>
    </user>
  </code>
  <code>
    <code>## Model
class Race &lt; ActiveRecord::Base
  
  before_validation :set_abbreviation
  
  # Associations
  has_one :employee
  
  # Validatioins
  validates_presence_of :name, :abbreviation
  validates_uniqueness_of :name, :abbreviation
  
  protected

  # The method will generate an unambiguous abbreviatioin from the model's name attribute and assign it to the models abbreviation attribute
  def set_abbreviation
    
    name = self.name.to_s
    strnlength = name.size
    
    while strnlength &gt;= 3 do
      chop.name
      strnlength = name.size
    end

    if name.size == 3
      self.abbreviation = name.capitalize
    else
      raise "While loop failed to produce a viable abbreviation"
    end

  end
  
end</code>
    <comment>Hi all,

I am attempting to utilize Rails' callback hooks to run a custom function on an instance of a model.  Originally I had the abbreviation assigned to the model through a form (i.e. the user would assign an abbreviation and the time of creation); however I'd like to just generate one automatically before validations occur so that I can control the format.  here is what I have so far, but from the console I get a "TypeError: $_ value need to be String (nil given)" for chop.  Any ideas or recommendations would be greatly appreciated.</comment>
    <created-at type="datetime">2008-04-06T16:16:01+00:00</created-at>
    <id type="integer">277</id>
    <language>Ruby</language>
    <permalink>help-generating-abbreviation-from-string</permalink>
    <refactors-count type="integer">3</refactors-count>
    <title>Help generating abbreviation from string</title>
    <trackback-url></trackback-url>
    <updated-at type="datetime">2010-03-07T19:46:14+00:00</updated-at>
    <user-id type="integer">509</user-id>
    <user>
      <id type="integer">509</id>
      <identity-url>http://mpfilbin.myopenid.com</identity-url>
      <name>Michael Filbin</name>
      <rating type="float">0.0</rating>
      <refactors-count type="integer">0</refactors-count>
      <website></website>
    </user>
  </code>
  <code>
    <code>## Actionscript [actionscript]

function toUpperCase( str : String ):String {
	var avoid : Array = [ "&#223;" ]; // Characters to avoid uppercasing
	var pattern : RegExp = new RegExp( avoid.join( "|" ) , "gm" );
	var results : Array = new Array();
	var result:Array = pattern.exec(str);
	while (result != null) {
		results.push( result );		
		result = pattern.exec(str);
	}
	str = str.toUpperCase();
	var a : Array = str.split("");
	while( results.length &gt; 0 ) {
		var r : Object = results.shift();
		a[r.index] = r;
	}
	return a.join("");
}</code>
    <comment>I had to do this on my current project, i finally managed to do it, but it doesn't look very good i think and i'm sure it could be made much faster so i thought maybe you guys could help me! :) 

It's in actionscript 3, but it's ecmascript too so...</comment>
    <created-at type="datetime">2007-10-30T18:46:41+00:00</created-at>
    <id type="integer">120</id>
    <language>JavaScript</language>
    <permalink>uppercase-a-string-but-skip-certain-characters</permalink>
    <refactors-count type="integer">2</refactors-count>
    <title>Uppercase a string, but skip certain characters</title>
    <trackback-url></trackback-url>
    <updated-at type="datetime">2007-11-05T07:37:04+00:00</updated-at>
    <user-id type="integer">72</user-id>
    <user>
      <id type="integer">72</id>
      <identity-url>http://slaskis.myopenid.com/</identity-url>
      <name>slaskis</name>
      <rating type="float">3.0</rating>
      <refactors-count type="integer">2</refactors-count>
      <website></website>
    </user>
  </code>
  <code>
    <code>class String 
  def postal?  
    self.match(/[a-zA-Z]{1}\d{1}[a-zA-Z]{1}([\x20-])*\d{1}[a-zA-Z]{1}\d{1}/) ? true : false
  end
end</code>
    <comment>We've had the debate over wether it was a good idea or not to do this.</comment>
    <created-at type="datetime">2007-10-30T15:29:16+00:00</created-at>
    <id type="integer">118</id>
    <language>Ruby</language>
    <permalink>is-this-string-postal</permalink>
    <refactors-count type="integer">6</refactors-count>
    <title>Is This String Postal?</title>
    <trackback-url></trackback-url>
    <updated-at type="datetime">2007-12-02T16:29:55+00:00</updated-at>
    <user-id type="integer">4</user-id>
    <user>
      <id type="integer">4</id>
      <identity-url>http://gary.haran.myopenid.com/</identity-url>
      <name>Gary Haran</name>
      <rating type="float">3.2</rating>
      <refactors-count type="integer">7</refactors-count>
      <website>http://www.garyharan.com/</website>
    </user>
  </code>
</codes>
