DZone 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
  • submit to reddit
        // i can't get this to work.  This seems to be the problem portion of the code.

//import random
# choose from a list
adam = random.choice([1,2])
print adam
input('press enter to continue');
if adam = 1:
    print 'you loose'
raw_input('press enter to exit')
if adam = 2:
    print 'you WIN!!'
raw_input('press enter to exit')
    
        In some test cases I need all my fixtures to be loaded.  To make this easier, add the following to test/test_helper.rb:

class Test::Unit::TestCase
  def self.all_fixtures
    Dir[File.dirname(__FILE__) + "/fixtures/*.yml"].each do |f|
      fixtures File.basename(f, '.yml')
    end
  end

  ..
end

and in your tests use it as follows:

class FooTest < Test::Unit::TestCase
  all_fixtures

  ..
end

Happy testing!    
        // ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone
//
// SureRemoveDir('EmptyMe', false);
// SureRemoveDir('RemoveMe', true);

<?php
function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }

    closedir($dh);
    if ($DeleteMe){
        @rmdir($dir);
    }
}
?>
    
        
class String
  def is_numeric?
    Float self rescue false
  end
end
    
        More lovely alias commands... this time to kill/restart Rail's script/server from any Terminal session or login on your box... (as long as your the same user).

alias dierails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -KILL $1'
alias resetrails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -HUP $1'
    
        This lil Ruby-OSA script will allow you to import your "Flagged Items" in NetNewsWire as Web Archive Items in Yojimbo. Thus allowing you to save RSS articles for off-line viewing/storage.

#!/usr/local/bin/ruby
['rubygems', 'rbosa'].each {|lib| require lib}
nnw = OSA.app('NetNewsWire')
yojimbo = OSA.app('Yojimbo')

nnw.subscriptions.find { |s| s if s.display_name == 'Flagged Items' }.headlines.each do |article|
  unless yojimbo.web_archive_items.map { |f| f.source_url }.include?(article.url)
    archived = yojimbo.make(OSA::Yojimbo::WebArchiveItem, 
                            article.url, 
                            :name => article.title)
    # Adjust this for slower/faster bandwidth connections (or your feeling lucky, punk)
    sleep(5)
    # Uncomment below to remove the flagged items upon successfully archiving
    # if archived.name == 'untitled' && archived.source_url.empty?
    #   puts "!!! #{article.title} does not look to be imported !!!"
    # else
    #   article.delete
    # end
  end
end
    
        // It's not necessarily the cleanest, but it got the job done on an internal transfer we were doing. Your mileage may vary by quite a bit. 

def convert_from_twiki_to_mediawiki(old_page_text)
  new_page_text = ""
  
  # shifting the tables over
  while (true)
    if (old_page_text.index(/\n\|/).nil?)
      new_page_text += old_page_text
      break
    end
        
    # table extraction
    table_index = old_page_text.index("\n|")
    first_chunk = old_page_text.slice!(0..table_index)
    table_chunk = ""
    old_page_text.each_line do |line|
      if line[0..0] == '|'
        table_chunk += line
      else
        break
      end
    end
    old_page_text.slice!(table_chunk)
    
    # table conversion
    table_chunk.gsub!(/\|/, "||")
    table_chunk.gsub!(/\|\|\s*$/, "\n|-")
    table_chunk.gsub!(/^\|\|/, "|")
    table_chunk.gsub!(/\|-\s*\Z/, "|}")
    table_chunk.gsub!(/\A\|/, "{|class=\"wikitable sortable\"\n|")
    
    # process new table looking for headings
    new_table_chunk = ""
    table_chunk.each_line do |line|
      if line.match(/\*\s.*\s\*/)
        line.gsub!(/\|\|/, "!!")
        line.gsub!(/^\|/, "!")
        line.gsub!("*", '')
      end
      
      new_table_chunk += line
    end
    
    new_page_text += first_chunk + new_table_chunk
  end
  
  # bold
  new_page_text.gsub!(/(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/, "\\1'''\\2'''\\3")
  # italic bold
  new_page_text.gsub!(/(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/, "\\1''<b>\\2<\/b>''\\3") 
  # italic
  new_page_text.gsub!(/(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/, "\\1''\\2''\\3")
  # monospaced bold
  new_page_text.gsub!(/(^|[\s\(])==([^ ].*?[^ ])==([\s\)\.\,\:\;\!\?]|$)/, "\\1'''<tt>\\2<\/tt>'''\\3")
  # monospaced
  new_page_text.gsub!(/(^|[\s\(])=([^ ].*?[^ ])=([\s\)\.\,\:\;\!\?]|$)/, "\\1<tt>\\2<\/tt>\\3")
  # H6
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+\+\+\+([^\n\r]*)/, "\\1======\\2 ======")
  # H5
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+\+\+([^\n\r]*)/, "\\1=====\\2 =====")
  # H4
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+\+([^\n\r]*)/, "\\1====\\2 ====")
  # H3
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+([^\n\r]*)/, "\\1===\\2 ===")
  # H2
  new_page_text.gsub!(/(^|[\n\r])---\+\+([^\n\r]*)/, "\\1==\\2 ==")
  # H1
  new_page_text.gsub!(/(^|[\n\r])---\+([^\n\r]*)/, "\\1=\\2 =")
  # external link
  new_page_text.gsub!(/\[\[(https?\:.*?)\]\[(.*?)\]\]/, "\[\\1 \\2\]")
  # internal link [[WikiWord][WikiWord]]
  new_page_text.gsub!(/\[\[([^\]]*)\]\]/, "\[\[\\1\|\\1\]\]")
  # internal lnk [[WikiWord][label]]
  new_page_text.gsub!(/\[\[([^\]]*)\]\[(.*?)\]\]/, "\[\[\\1\|\\2\]\]")
  # level 1 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{3}\* /, "\\1*")
  # level 2 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{6}\* /, "\\1**")
  # level 3 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{9}\* /, "\\1***")
  # level 4 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{12}\* /, "\\1****")
  # level 5 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{15}\* /, "\\1*****")
  # level 6 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{18}\* /, "\\1******")
  # level 7 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{21}\* /, "\\1*******")
  # level 8 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{24}\* /, "\\1********")
  # level 9 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{27}\* /, "\\1*********")
  # level 10 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{30}\* /, "\\1**********")
  # level 1 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{3}[0-9]\.? /, "\\1#")
  # level 2 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{6}[0-9]\.? /, "\\1##")
  # level 3 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{9}[0-9]\.? /, "\\1###")
  # level 4 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{12}[0-9]\.? /, "\\1####")
  # level 5 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{15}[0-9]\.? /, "\\1#####")
  # level 6 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{18}[0-9]\.? /, "\\1######")
  # level 7 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{21}[0-9]\.? /, "\\1#######")
  # level 8 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{24}[0-9]\.? /, "\\1########")
  # level 9 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{27}[0-9]\.? /, "\\1#########")
  # level 10 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{30}[0-9]\.? /, "\\1##########")
    
  
  new_page_text
end
    
        Get PHP parsing errors on command line. Useful for those extreme cases where you can't get them to print to the browser.

find . -name \*.php \! -exec php -l {} \;
    
        // description of your code here

SELECT serverproperty ('engineedition')
SELECT serverproperty ('productlevel')
SELECT serverproperty ('edition')
    
        Demonstrates a way of speeding up the O(n<sup>2</sup>) version of Dijkstra's Algorithm by about 4x.

Here, dist[][] is the adjacency matrix representing the graph and n is the number of nodes. d2[] is where the lengths of the shortest paths are saved.

For a full explanation, see <a href="http://compprog.wordpress.com/2008/01/17/speeding-up-dijkstras-algorithm-1/">this</a>.

void dijkstra2(int s) {
	int queue[GRAPHSIZE];
	char inQueue[GRAPHSIZE];
	int begq = 0,
	    endq = 0;
	int i, mini;
	int visited[GRAPHSIZE];

	for (i = 1; i <= n; ++i) {
		d2[i] = INFINITY;
		visited[i] = 0; /* the i-th element has not yet been visited */
		inQueue[i] = 0;
	}

	d2[s] = 0;
	queue[endq] = s;
	endq = (endq + 1) % GRAPHSIZE;


	while (begq != endq) {
		mini = queue[begq];
		begq = (begq + 1) % GRAPHSIZE;
		inQueue[mini] = 0;

		visited[mini] = 1;

		for (i = 1; i <= n; ++i)
			if (dist[mini][i])
				if (d2[mini] + dist[mini][i] < d2[i]) { 
					d2[i] = d2[mini] + dist[mini][i];
					if (!inQueue[i]) {
						queue[endq] = i;
						endq = (endq + 1) % GRAPHSIZE;
						inQueue[i] = 1;
					}
				}
	}
}
    
        // Tests if site is down/server is offline by trying to connect in specified time

import socket
import urllib2

def timeout(site, timeout):
  save = socket.getdefaulttimeout() 
  try:
    response = urllib2.urlopen(site)
    socket.setdefaulttimeout(save)
  except urllib2.URLError, err:
    socket.setdefaulttimeout(save)
    if err.__class__.__name__ == "URLError":
      if isinstance(err[0], socket.timeout):
        return True
  return False


if timeout("http://www.dummy-site.com/test_timeout.html", 10):
  print "Timeout detected"
    
        Just a really quick and easy shell alias for my preferred defaults for Git's repository and branch viewer, Gitk.

This runs "gitk"...
...including all branches,
...outputting errors to the black hole,
...and any extra command-line arguments.

# Run like this
# gitk --since="2 days ago" &

alias gitk="gitk --all $1 2>/dev/null"
    
        Assume you have a table of locations with Latitude and Longitude for each one. In my case the table is "station" and the primary key is "LocID".

First we create a view to help with the 3D geometry (6378 = Earth's radius in km):
CREATE VIEW gpsGlb AS
    SELECT 
        LocID
        ,6378 * COS(RADIANS(Latitude)) * COS(RADIANS(Longitude)) AS x
        ,6378 * COS(RADIANS(Latitude)) * SIN(RADIANS(Longitude)) AS y
        ,6378 * SIN(RADIANS(Latitude)) AS z
    FROM station;

Here I query for distances to all my locations that are NOT LocID = 405 (rounded miles in my case):
SELECT 
    LocID
    ,ROUND((2 * 6378 * ASIN(d / 2 / 6378)) * 0.621371192) AS dist_mi
FROM
    (SELECT
        SQRT(dx * dx + dy * dy + dz * dz) AS d
        ,LocID
     FROM
        (SELECT
            p1.x - p2.x AS dx
            ,p1.y - p2.y AS dy
            ,p1.z - p2.z AS dz
            ,p2.LocID
        FROM gpsGlb p1
        JOIN gpsGlb p2 ON (p1.LocID = 405 AND p2.LocID != 405)
       ) t1
    ) t2
ORDER BY dist_mi

Here I get the initial bearing to the locations. The "boxed" calculation will come in handy later.
SELECT
    LocID
    ,(360 + DEGREES(ATAN2(y, x))) % 360 AS initBearing_deg
    ,ROUND(((360 + DEGREES(ATAN2(y, x))) % 360) / 22.5) * 22.5 
     AS initBearingBoxed_deg
FROM
    (SELECT
        SIN(RADIANS(s2.Longitude - s1.Longitude)) * COS(RADIANS(s2.Latitude)) 
        AS y
        ,COS(RADIANS(s1.Latitude)) * SIN(RADIANS(s2.Latitude))
            - SIN(RADIANS(s1.Latitude)) * COS(RADIANS(s2.Latitude))
               * COS(RADIANS(s2.Longitude - s1.Longitude)) 
        AS x
        ,s2.LocID
    FROM station s1
    JOIN station s2 ON (s1.LocID = 405 AND s2.LocID != 405)
    ) q1

Here's the combined query plus boxed degrees converted to 'NNE', etc. I've also added a limit for the distance in the qq1 subquery.
SELECT
    qq2.LocID
    ,dist_mi
    ,CASE initBearingBoxed_deg
        WHEN 22.5 THEN 'NNE'   WHEN 45 THEN 'NE'
        WHEN 67.5 THEN 'ENE'   WHEN 90 THEN 'E'
        WHEN 112.5 THEN 'ESE'  WHEN 135 THEN 'SE'
        WHEN 157.5 THEN 'SSE'  WHEN 180 THEN 'S'
        WHEN 202.5 THEN 'SSW'  WHEN 225 THEN 'SW'
        WHEN 247.5 THEN 'WSW'  WHEN 270 THEN 'W'
        WHEN 292.5 THEN 'WNW'  WHEN 315 THEN 'NW'
        WHEN 337.5 THEN 'NNW'  ELSE 'N'
     END AS bearing
FROM (
    SELECT 
        LocID
        ,ROUND((2 * 6378 * ASIN(d / 2 / 6378)) * 0.621371192) AS dist_mi
    FROM
        (SELECT
            SQRT(dx * dx + dy * dy + dz * dz) AS d
            ,LocID
         FROM
            (SELECT
                p1.x - p2.x AS dx
                ,p1.y - p2.y AS dy
                ,p1.z - p2.z AS dz
                ,p2.LocID
            FROM gpsGlb p1
            JOIN gpsGlb p2 ON (p1.LocID = 405 AND p2.LocID != 405)
           ) t1
        ) t2
    ) qq1
JOIN (
    SELECT
        LocID
        ,(360 + DEGREES(ATAN2(y, x))) % 360 AS initBearing_deg
        ,(360 + ROUND((DEGREES(ATAN2(y, x))) / 22.5) * 22.5) % 360 
         AS initBearingBoxed_deg
    FROM
        (SELECT
            SIN(RADIANS(s2.Longitude - s1.Longitude)) * COS(RADIANS(s2.Latitude)) 
             AS y
            ,COS(RADIANS(s1.Latitude)) * SIN(RADIANS(s2.Latitude))
                - SIN(RADIANS(s1.Latitude)) * COS(RADIANS(s2.Latitude))
                   * COS(RADIANS(s2.Longitude - s1.Longitude)) 
             AS x
            ,s2.LocID
        FROM station s1
        JOIN station s2 ON (s1.LocID = 405 AND s2.LocID != 405)
        ) q1
    ) qq2 ON (qq1.LocID = qq2.LocID
              AND qq1.dist_mi <= 60)
ORDER BY dist_mi
    
        Here's the forms authentication code that I always seem to forget.  

Blatantly stolen from http://www.4guysfromrolla.com/webtech/110701-1.2.shtml and http://support.microsoft.com/kb/316871

Sub Submit_OnClick(sender as Object, e as EventArgs)
  If MyCustomMethod (txtUserName.Text, txtPassword.Text) Then    
      FormsAuthentication.RedirectFromLoginPage (txtUserName.Text, False)
  Else
      ' Invalid credentials supplied, display message
      lblMessage.Text = "Invalid login credentials"
  End If
End Sub

<configuration>
	<system.web>
		<authentication mode="Forms" >
			<forms loginUrl="login.aspx" name=".ASPNETAUTH" protection="None" path="/" timeout="20" >
			</forms>
		</authentication>
<!-- This section denies access to all files in this application except for those that you have not explicitly specified by using another setting. -->
		<authorization>
			<deny users="?" /> 
		</authorization>
	</system.web>
<!-- This section gives the unauthenticated user access to the Default1.aspx page only. It is located in the same folder as this configuration file. -->
		<location path="default1.aspx">
		<system.web>
		<authorization>
			<allow users ="*" />
		</authorization>
		</system.web>
		</location>
<!-- This section gives the unauthenticated user access to all of the files that are stored in the Subdir1 folder.  -->
		<location path="subdir1">
		<system.web>
		<authorization>
			<allow users ="*" />
		</authorization>
		</system.web>
		</location>
</configuration>
    
        A basic implementation of response caching in camping.

Camping.goes :MyCampingApp

module MyCampingApp
  module Controller
    class View < R '/'
      def get
        cache('root') do
          'Expensive operation!'
        end
      end
    end
  end
  
  def flush(id)
    f = File.dirname(__FILE__) + "/cache/#{id}"
    File.delete(f) if File.exists?(f)
  end
  
  def cache(id, timeout = 1.hour)
    f = File.dirname(__FILE__) + "/cache/#{id}"
    
    if File.exists?(f) && (Time.now - File.stat(f).mtime) < timeout
      File.read(f)
    else
      r = yield
      open(f, 'w'){|wr| wr.write(r)}
      r
    end
  end

  def self.create
    cache_dir = File.dirname(__FILE__) + "/cache"
    Dir.mkdir(cache_dir) unless File.directory?(cache_dir)
  end
end
    
        
SELECT -5 - CAST(REPLACE(TIMEDIFF(NOW(), UTC_TIMESTAMP()), ':00:00', '') AS SIGNED) AS isDst
To test in other timezones, replace -5 with your local standard time GMT offset.    
        Recently, I saw a this snippet :
alias rmdsstores='find ./ -type f | grep .DS_Store | xargs rm'
But this one is not very optimized, because you have two pipes with command call.

You can do exactly the same, with only the 'find' command, here the code :
alias rmdsstores='find . -name *.DS_Store -type f -exec rm {} \;'
    
        http://ourworld.cs.com/tcmits1/javascript/papers/pause/pause.html

<script type = "text/javascript"language = "JavaScript">
 
/*	constructor 
	duration integer seconds
	<optional> function to run while waiting.
*/
function Pause(duration, busy) {
	this.duration = duration * 1000;
	this.busywork = null;
    // function to call while waiting.
    this.runner = 0;

    if (arguments.length == 2) {
        this.busywork = busy;

    }
    this.pause(this.duration);
}/* Pause class*/

/* pause method 
      duration: integer in seconds 
*/
  
Pause.prototype.pause = function(duration) {
    if ((duration == null) || (duration < 0)) {
        return;
    }

    var later = (new Date()).getTime() + duration;

    while (true) {
        if ((new Date()).getTime() > later) {
            break;

        }
        this.runner++;

        if (this.busywork != null) {
            this.busywork(this.runner);
        }
    }/* while*/
}/*pause method*/

 </script>
    
        This shell alias will recursively remove all .DS_Store files from the current directory up.

alias rmdsstores='find ./ -type f | grep .DS_Store | xargs rm'
    
        Create many users in a Debian system using a text file as argument

#!/bin/bash

#******************************************************************************#
# AddManyUsers-deb.sh - Create many users in a Debian system using a text file #
# 			as argument					       #
#   Copyright (C) 2008 - written by flynets - <flynets<at>autistici<dot>org>   # 
#   AddManyUsers-deb is free software: you can redistribute it and/or modify   #
#   it under the terms of the GNU General Public License as published by       #
#   the Free Software Foundation, either version 3 of the License, or          #
#   any later version.							       #
#									       #
#   AddManyUsers-deb is distributed in the hope that it will be useful,	       #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of             #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the	       #
#   GNU General Public License for more details.			       #
#									       #
#   You should have received a copy of the GNU General Public License	       #
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.      #
#******************************************************************************#

# Checks if you have the right privileges
if [ "$USER" = "root" ]
then

# CHANGE THIS PARAMETERS FOR A PARTICULAR USE
PERS_HOME="/home/"
PERS_SH="/bin/bash"

   # Checks if there is an argument
   [ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
   # checks if there a regular file
   [ -f "$1" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
   TMPIN=$(mktemp)
   # Remove blank lines and delete duplicates 
   sed '/^$/d' "$1"| sort -g | uniq > "$TMPIN"
   
   NOW=$(date +"%Y-%m-%d-%X")
   LOGFILE="AMU-log-$NOW.log"
   
   for user in $(more "$TMPIN"); do
      # Checks if the user already exists.
      cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
      OUT=$?
      if [ $OUT -eq 0 ];then
   	 echo >&2 "ERROR: User account: \"$user\" already exists."
	 echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
      else
	 # Create a new user
         /usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
	 # gpw must be installed on debian system
	 pass=$(gpw 1 8)
         echo $user:$pass | chpasswd
	 # save user and password in a file
	 echo -e $user"\t"$pass >> "$LOGFILE"
	 echo "The user \"$user\" has been created and has the password: $pass"
      fi
   done
   rm -f "$TMPIN"
   exit 0
else
   echo >&2 "ERROR: You must be a root user to execute this script."
   exit 1
fi