The Code Cookbook - Popularhttp://code-cookbook.com/The Code Cookbook - Freshly served code snippets C# String to Byte Array http://code-cookbook.com/entry/78/c-string-to-byte-array Converts a String to a Byte Array and vice versa.

//String to byte array
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] byteArray =  enc.GetBytes(str);

//Byte array to string
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
String str = enc.GetString(byteArr);
2009-03-27 01:38:02 http://code-cookbook.com/entry/78/c-string-to-byte-array
PHP Month Number to Month Name http://code-cookbook.com/entry/80/php-month-number-to-month-name An easy way to convert a month number to a month name without a switch statement.

$monthName = date("F", mktime(0, 0, 0, $monthNum, 10)); 
2009-03-31 03:17:00 http://code-cookbook.com/entry/80/php-month-number-to-month-name
Target iPhone with CSS http://code-cookbook.com/entry/70/target-iphone-with-css The logic of this is that only browsers that understand "screen" understand "only", and of these, only the iphone has a "max-device-width" of 480px. The reason for the anti-IE comments is that some versions of IE render CSS regadless of media type declarations.

<!--[if !IE]>
<link media="only screen and (max-device-width: 480px)"
    href="iPhone.css" type="text/css" rel="stylesheet" />
<![endif]-->
2009-02-27 01:51:22 http://code-cookbook.com/entry/70/target-iphone-with-css
Wordpress Enable Adsense Shortcode http://code-cookbook.com/entry/84/wordpress-enable-adsense-shortcode Wordpress allows developers and theme creators to write functions that allow the user to use shortcode, i.e., [adsense]. This kind of "pseudo" code makes it easy for end users to insert elements where they would like without knowing about coding. Knowing that we can create shortcodes, we can create one to insert a Google Adsense ad anywhere in our theme.

function showads() {  
     	return '<div id="adsense"><script type="text/javascript"><!--  
     	google_ad_client = "pub-XXXXXXXXXXXXXX";  
    	 google_ad_slot = "4668915978";  
    	 google_ad_width = 468;  
    	 google_ad_height = 60;  
    	 //-->  
		 </script>  
 
		 <script type="text/javascript"  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">  
 		 </script></div>';  
 }  
 
 add_shortcode('adsense', 'showads');
2009-04-29 08:37:33 http://code-cookbook.com/entry/84/wordpress-enable-adsense-shortcode
jQuery Browser Detection http://code-cookbook.com/entry/47/jquery-browser-detection Note: This code is deprecated as of jQuery 1.3 (see jQuery.support instead). Available flags are: safari, opera, msie and mozilla

jQuery.each(jQuery.browser, function(i) {
  if($.browser.msie){
     $("#div ul li").css("display","inline");
  }else{
     $("#div ul li").css("display","inline-table");
  }
});
2009-02-19 08:32:11 http://code-cookbook.com/entry/47/jquery-browser-detection
C# Excel Column Number to Name and Vice Versa http://code-cookbook.com/entry/82/c-excel-column-number-to-name-and-vice-versa Convert a column number to a column name and vice versa in an Excel spreadsheet.

private int colNameToNum(final String colName)
{
        int result  = 0;
        String  lcColName   = colName.toLowerCase();
        for (int ctr = 0; ctr < lcColName.length(); ++ ctr)
            result  = (result * 26) + (lcColName.charAt(ctr) - 'a' + 1);
        --result;
        return (result);
}

private String colNumToName(int colNum)
{
        StringBuffer    sb  = new StringBuffer();
        int cycleNum    = colNum / 26;
        int withinNum   = colNum - (cycleNum * 26);
        if (cycleNum > 0)
            sb.append((char) ((cycleNum - 1) + 'a'));
        sb.append((char) (withinNum + 'a'));
        return (sb.toString());
} 
2009-04-27 07:49:24 http://code-cookbook.com/entry/82/c-excel-column-number-to-name-and-vice-versa
Wordpress "Tweet This" Link http://code-cookbook.com/entry/65/wordpress-tweet-this-link

<a href="http://twitter.com/home?status=I just read <?php the_permalink(); ?>" title="Send this page to Twitter!" target="_blank">Tweet This!</a>
2009-02-25 05:37:15 http://code-cookbook.com/entry/65/wordpress-tweet-this-link
Make IE8 Emulate IE7 http://code-cookbook.com/entry/77/make-ie8-emulate-ie7 Put this XHTML in your code to make IE8 render pages like IE7.

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
2009-03-20 06:11:42 http://code-cookbook.com/entry/77/make-ie8-emulate-ie7
Colored Output in Bash Function http://code-cookbook.com/entry/62/colored-output-in-bash-function Simple bash function for adding color to output.

#!/bin/bash
#
# Example usage:
# echo ${RedF}This text will be red!${Reset}
# echo ${BlueF}{$BoldOn}This will be blue and bold!${BoldOff} - and this is just blue!${Reset}
# echo ${RedB}${BlackF}This has a red background and black font!${Reset}and everything after the reset is normal text!

Colors() {
  Escape="\033";

  BlackF="${Escape}[30m";   RedF="${Escape}[31m";   GreenF="${Escape}[32m";
  YellowF="${Escape}[33m";  BlueF="${Escape}[34m";    Purplef="${Escape}[35m";
  CyanF="${Escape}[36m";    WhiteF="${Escape}[37m";

  BlackB="${Escape}[40m";     RedB="${Escape}[41m";     GreenB="${Escape}[42m";
  YellowB="${Escape}[43m";    BlueB="${Escape}[44m";    PurpleB="${Escape}[45m";
  CyanB="${Escape}[46m";      WhiteB="${Escape}[47m";

  BoldOn="${Escape}[1m";      BoldOff="${Escape}[22m";
  ItalicsOn="${Escape}[3m";   ItalicsOff="${Escape}[23m";
  UnderlineOn="${Escape}[4m";     UnderlineOff="${Escape}[24m";
  BlinkOn="${Escape}[5m";   BlinkOff="${Escape}[25m";
  InvertOn="${Escape}[7m";  InvertOff="${Escape}[27m";

  Reset="${Escape}[0m";
}
2009-02-24 22:45:56 http://code-cookbook.com/entry/62/colored-output-in-bash-function
PHP Limit File Download Speed http://code-cookbook.com/entry/57/php-limit-file-download-speed This snippet shows you how to limit the download rate of a file download.

// local file that should be send to the client
$local_file = 'test-file.zip';
// filename that the user gets as default
$download_file = 'your-download-name.zip';
 
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5; 
if(file_exists($local_file) && is_file($local_file)) {
    // send headers
    header('Cache-control: private');
    header('Content-Type: application/octet-stream'); 
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);
 
    // flush content
    flush();    
    // open file stream
    $file = fopen($local_file, "r");    
    while(!feof($file)) {
 
        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));    
 
        // flush the content to the browser
        flush();
 
        // sleep one second
        sleep(1);    
    }    
 
    // close file stream
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}
2009-02-23 06:51:16 http://code-cookbook.com/entry/57/php-limit-file-download-speed
Htaccess Clean URL's http://code-cookbook.com/entry/48/htaccess-clean-urls A basic example of how to use .htaccess to create clean urls on your website.

#.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ index.php?page=$1 [L]
</IfModule>

# http://www.example.com/contact -> 
# http://www.example.com/index.php?page=contact
#
# <?php
# // Get the data from the url
# $url_segments = explode("/", $HTTP_SERVER_VARS['PATH_INFO']);
# ?>
2009-02-23 02:56:40 http://code-cookbook.com/entry/48/htaccess-clean-urls
Bash Script to Post to Twitter http://code-cookbook.com/entry/75/bash-script-to-post-to-twitter Here is a quick/easy way to post to twitter from the command line interface. Put the script in /usr/local/bin/ Then it is as easy as: user@river:~$ twitter Your Message Here

#!/bin/bash

# Login information.
USERNAME="email address"
PASSWORD="password"
URL=http://twitter.com/statuses/update.xml

# Check message length.
if [ ! -n "$1" ]; then
        echo "Message not long enough"
        exit
fi

# Check message length again.
message="$@"
maxlen=140;
len=`echo ${#message}`

if [ $len -gt $maxlen ]; then
        echo "Your message was longer than 140 characters...";
fi

# Post to Twitter.
result=`curl -u $USERNAME:$PASSWORD -d status="$message" $URL`
2009-03-06 17:03:51 http://code-cookbook.com/entry/75/bash-script-to-post-to-twitter
Wordpress Separate Trackbacks / Pingbacks from Comments http://code-cookbook.com/entry/66/wordpress-separate-trackbacks-pingbacks-from-comments This is a neat little Wordpress trick to separate real comments from trackbacks and pingbacks.

<?php if ( $comments ) : ?>
<?php foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type == 'comment') { ?>
 
<!-- It's a comment -->
<!-- Comment content goes here -->
 
<?php } else { $trackback = true; }?> 
<?php endforeach; ?>
<?php if ($trackback == true) { ?>
 
<!-- It's a trackback -->
  <ol id="trackbacks-ol">
	  <?php foreach ($comments as $comment) : ?>
	  <?php $comment_type = get_comment_type(); ?>
	  <?php if($comment_type != 'comment') { ?>
	  <li>
		<?php comment_author_link() ?>
	</li>
	  <?php } ?>
	  <?php endforeach; ?>
  </ol>
 
<?php } ?>
<?php else : ?>
<?php endif; ?>
2009-02-25 05:41:08 http://code-cookbook.com/entry/66/wordpress-separate-trackbacks-pingbacks-from-comments
Display Error Messages in WordPress http://code-cookbook.com/entry/81/-display-error-messages-in-wordpress Add the line of code below to the top of your .htaccess file in the root directory of your WordPress website. Remember to only use this technique to help troubleshoot errors and remove it as soon as you are done.

php_flag display_errors on 
2009-04-14 04:04:44 http://code-cookbook.com/entry/81/-display-error-messages-in-wordpress
[RUBY] Print a Fibonacci series http://code-cookbook.com/entry/85/ruby-print-a-fibonacci-series- Simple Fibonacci sequence printer, enjoy!

def fib_max(max)
     num1, num2 = 1, 1
     while num1 <= max
          yield num1
          num1, num2 = num2, num1 + num2
     end
end
puts "What number would you like the Fibonacci sequence to go up to?"
fib_max(gets.chomp.to_i) {|f| print f, " "}
2009-06-17 16:52:17 http://code-cookbook.com/entry/85/ruby-print-a-fibonacci-series-