Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

« Newer Snippets
Older Snippets »
Showing 1-10 of 4847 total  RSS 

ASP.NET Permanent Redirect (301)

Response.Redirect normally returns a 302 Object moved HTTP response. However a 301 permanent redirect is often better for search engine spiders:

Response.StatusCode = 301;
Response.AddHeader("Location", "New.aspx");
Response.Write("<html><body>Page moved permanently to <a href="New.aspx">New</a></body></html>");
Response.End();

ASP.NET Web.config TIP

Register controls for pages in Web.config:

<system.web>
    <pages>
        <controls>
            <add tagPrefix="mycontrol" src="~/Controls/Header.ascx" tagName="header"/>
            <add tagPrefix="mycontrol" src="~/Controls/Footer.ascx" tagName="footer"/>
        </controls>
    </pages>
</system.web>

C#: One-line SHA1 or MD5 crypto-hash

Perform a hash and base64-encode:

// SHA1 hash:
string h1 = Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes("one two")));

// MD5 hash:
string h2 = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes("one two")))

Ctrl-A shortcut to select all text (Windows.Forms.TextBox)

Set this event handler for your textbox to enable Ctrl-A shortcut and select all text:


private void anyTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
	if (e.KeyChar == '\x1')
	{
		((TextBox)sender).SelectAll();
		e.Handled = true;
	}
}

Terribly useful regex to run before committing code

// I use this regex/replace before I commit locally and before creating patches for Mozilla
// Will trim out random spaces/tabs at end of lines or if they take up the whole line.

s/^[ \t]+$|[ \t]+$//

Eight queens problem

// python script to solve the 8 queens problem

def allowedMoves(usedCol, usedDiagL, usedDiagR):
    allowed = ~(usedCol | usedDiagL | usedDiagR)
    for col in (1,2,4,8,16,32,64,128):
        if col & allowed:
            yield usedCol | col, (usedDiagL | col) << 1, (usedDiagR | col) >> 1

def eightQueensSolutions():
    for q0 in allowedMoves(0, 0, 0):
     for q1 in allowedMoves(*q0):
      for q2 in allowedMoves(*q1):
       for q3 in allowedMoves(*q2):
        for q4 in allowedMoves(*q3):
         for q5 in allowedMoves(*q4):
          for q6 in allowedMoves(*q5):
           for q7 in allowedMoves(*q6):
               yield (0,0,0),q0,q1,q2,q3,q4,q5,q6,q7

def solve8queens():
    ''' Solves the problem of placing 8 queens on a chess board with no queen 
        under attack. Queens are placed row by row, with the respective columns
        encoded by setting bit after bit in the qN variables for fast generation
        of allowed moves. The printboard() function decodes these to show the 
        final board.

        My goal was a fast program that is easy to read. The code is a concise
        combination of a generator for allowed moves and a deeply nested loop to
        traverse the search tree. Most assignments are accomplished by function
        calls and loops. Speed is achieved by not using recursion, by limiting
        data carried through the search to three integers, and through testing
        for allowed moves by a single bitwise operation. For diagonal attacks,
        two integers (usedDiagL and usedDiagR) keep track of queens placed, and
        are shifted left or right bitwise as the search proceeds from row to
        row. On my machine, it takes 7 ms to find all 92 solutions.

        Because the number of queens to be placed is hardcoded (by the giant
        nested loop), there is no need to have branching code deciding whether
        the final queen was just placed (in which case you have a solution).
        It is not possible to parameterize the dimensions of the chess board
        using this approach in a way that would keep the program lean and mean.
    '''
    solutions = [i for i in eightQueensSolutions()]
    for s in solutions:
        print ''
        printboard(s)
    print len(solutions), "solutions found"

def printboard(s):
    b = '_Q'
    for i,j in zip(s[:-1],s[1:]):
        n = i[0] ^ j[0]
        print " ".join([b[(n >> y) & 1] for y in range(8-1, -1, -1)])

if __name__ == "__main__": solve8queens()

Generating YAML hashes sorted by key

I needed to store YAML structures in version control, so I wanted the YAML output of hashes to be sorted by the key name (this way, when using "diff" between two versions, you'll get a minimal changeset).

Of course a Hash object in Ruby doesn't have any ordering on its keys, which is fine. I just want to make sure that when I output the YAML serialization of a Hash object, it will serialize the keys in alphabetic order.

Put this code somewhere before you actually serialize your hashes:

require 'yaml'
 
class Hash
  # Replacing the to_yaml function so it'll serialize hashes sorted (by their keys)
  #
  # Original function is in /usr/lib/ruby/1.8/yaml/rubytypes.rb
  def to_yaml( opts = {} )
    YAML::quick_emit( object_id, opts ) do |out|
      out.map( taguri, to_yaml_style ) do |map|
        sort.each do |k, v|   # <-- here's my addition (the 'sort')
          map.add( k, v )
        end
      end
    end
  end
end


Now simply use "to_yaml" or "y" on your hash object. For example, this code:

my_hash = { "aaa" => "should be first", "zzz" => "I'm last", "mmm" => "middle", "bbb" => "near beginning" }
puts my_hash.to_yaml


will always output this:

---
aaa: should be first
bbb: near beginning
mmm: middle
zzz: I'm last

Sharing has_many extensions

Sometimes you extend an ActiveRecord association this way:

has_many :things do
  def active
    find :all, :conditions => ['active = ?', true]
  end
end


You can share the same extensions using a lambda:


extensions = lambda {
  def active
    find :all, :conditions => ['active = ?', true]
  end
}

has_many :things, &extensions
has_many :more_things, &extensions


Fill text with javascript

// description of your code here

<script type="text/javascript">
/*** Temporary text filler function. Remove when deploying template. ***/
var gibberish=["This is just some filler text", "Another some text here", "Demo content nothing to read here"]
function filltext(words){
for (var i=0; i<words; i++)
document.write(gibberish[Math.floor(Math.random()*3)]+" ")
}
</script>
<script type="text/javascript">filltext(255)</script>

XML-RPC request

Here's an example of an XML-RPC request:

POST /RPC2 HTTP/1.0
User-Agent: Frontier/5.1.2 (WinNT)
Host: betty.userland.com
Content-Type: text/xml
Content-length: 181

<?xml version="1.0"?>
<methodCall>
   <methodName>examples.getStateName</methodName>
   <params>
		<param>
			<value>APIKEY</value>
		</param>
		<param>
			<value><i4>41</i4></value>
		</param>
	</params>
</methodCall>
« Newer Snippets
Older Snippets »
Showing 1-10 of 4847 total  RSS