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
        This function will resize any input file restricting the width and height to be no more than the specified pixels, and output a binary stream.

<pre>function resize_jpg($inputFilename, $new_side){
	$imagedata = getimagesize($inputFilename);
	$w = $imagedata[0];
	$h = $imagedata[1];
	
	if ($h > $w) {
		$new_w = ($new_side / $h) * $w;
		$new_h = $new_side;	
	} else {
		$new_h = ($new_side / $w) * $h;
		$new_w = $new_side;
	}
	
	$im2 = ImageCreateTrueColor($new_w, $new_h);
	$image = ImageCreateFromJpeg($inputFilename);
	imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $imagedata[0], $imagedata[1]);
	return $im2;
}</pre>    
        
import ctypes

SPI_SETDESKWALLPAPER = 20 # According to http://support.microsoft.com/default.aspx?scid=97142

ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "myimage.jpg" , 0)
See here for more detail
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435877
    
        If you need to be sure that a user can view an object, you need to check the View permission not only on the object but also all of its parents.  To do this, I slightly modified the script at http://zopelabs.com/cookbook/1018022911 so that it uses the context object and specified the View permission.

Create a Python script in your acquisition path (I used portal_skins/custom) named can_view and paste in this code:
permission = "View"
try:
  object=context
  if not object.acquiredRolesAreUsedBy( permission ):
    for p in object.rolesOfPermission( permission ):
      if p['selected']:
        if p['name'] in user.getRoles():
          return 1
  else:
   return 1
except:
    pass
return 0
Then you can check the permission in TAL like this:

<div tal:condition="some_object/can_view">
  ...
</div>    
        you can use this function to convert an integer into any number system upto base36 (e.g. for TinyURL generation coupled with a global ID counter)

function int2baseX($val,$base=16) {
  if (0==$val) return 0;
  $symbols='0123456789abcdefgihjklmnopqrstuvwxyz';
  $result='';
  $exp=$oldpow=1;
  while($val>0 && $exp<10) {
    $pow=pow($base,$exp++);
    $mod=($val % $pow);
    $result=substr($symbols,$mod/$oldpow,1).$result;
    $val-=$mod;
    $oldpow=$pow;
  }
  return $result;
}
    
        A minimal example to let you choose from you mobile phonebook.
import contacts, appuifw
db = contacts.open()
names = []
numbers = []
for i in db:
  names.append(db[i].title)
  num = db[i].find('mobile_number')
  if num:
    numbers.append(num[0].value) # first mobile
  else:
    numbers.append(None)

i = appuifw.selection_list(names)
print 'number =', numbers[i]
    
        Go to /home/virtual and run:

find -type l -maxdepth 1 -name '*.*' | xargs -n 1 basename | xargs -i find /home/virtual/{}/var/www -type f -size +8192k -ls
    
        You can confirm that your database YAML file is being parsed properly with this one line shell command.

ruby -ryaml -e "File.open('config/database.yml') { |f| puts YAML.load(f).inspect }"
    
        Use this objects:

java.util.Stack (LIFO)
java.util.LinkedList (FIFO)
    
        
# put this in lib/active_record/json.rb
require 'json/lexer'
require 'json/objects'
module ActiveRecord
  module Json # :nodoc:
    DEFAULT_CONVERSIONS = { Time => [:to_s, :db] }
    def to_json(conversions = {})
      conversions = DEFAULT_CONVERSIONS.merge(conversions)
      self.attributes.keys.inject({}) do |hsh, key|
        value = self.send(key)
        hsh.merge(key => conversions[value.class] ? value.send(*conversions[value.class]) : value.to_s)
      end.to_json
    end
  end
end
 
# in environment.rb do
#require "#{RAILS_ROOT}/lib/active_record/json"
#ActiveRecord::Base.class_eval { include ActiveRecord::Json }

Doing something like 
<%= var post = @post.to_json %>
 in a javascript snippet should allow you to use the basic AR attributes such as post.title, post.summary (using the Weblog analogy).  You could also pass the json bits to a javascript function.    
        
//simple general rand function 
float randBetween(float min, float max)
{
    return llFrand(max - min) + min;
}

//uses randBetween to generate a random colour vector
//maybe a bit of overkill, but can be repurposed.

vector randColour()
{   
    vector r_colour = <randbetween 0,1), randBetween(0,1), randBetween(0,1)>;
    return r_colour;    
}
    
        The R FAQ states:
 
par(mar = c(7, 4, 4, 2) + 0.1)
plot(1 : 30, xaxt = "n",  xlab = "")
labels <- paste("Label", 1:30, sep = " ")
text(1:30, par("usr")[3] - 0.25, srt = 90, adj = 1,labels = labels, xpd = TRUE)
mtext(1, text = "X Axis Label", line = 6)

Also see Figure 1 and associated code in Paul Murrell (2003), “Integrating grid Graphics Output with Base Graphics Output�, R News, 3/2, 7–12.    
        At the prompt, type this:

defaults write com.apple.screencapture type image_format

Replace "image_format" with a file format name, like pdf, png, tiff, etc. Then to take screenshots, Cmd+Shift+4, then drag around the area you want to capture.    
        
data <- sort.data.frame(data, key = "LOC")

where the function "sort.data.frame" is as follows:

sort.data.frame <- function(x, key, ...) {
    if (missing(key)) {
        rn <- rownames(x)
        if (all(rn %in% 1:nrow(x))) rn <- as.numeric(rn)
        x[order(rn, ...), , drop=FALSE]
    } else {
        x[do.call("order", c(x[key], ...)), , drop=FALSE]
    }
}
    
        The CSV file "loc.csv" contains the following:

Module LOC
a.rb 100
b.rb 120
c.rb 54

The following R code creates the barplot image "loc.png":

data <- read.csv(file="loc.csv", sep = " ", header = TRUE, row.names = "Module")
png("loc.png", width = 640, height = 480)
barplot(data$LOC, names = rownames(data), ylim = c(0, 250), main = "Lines of code by module", ylab = "Lines of code", xlab = "Module")
dev.off()
    
        This lets you load ActionView helpers globally.

RAILS_ROOT/lib/action_view/helpers/widget_helper.rb:
module ActionView
  module Helpers
    module WidgetHelper
      # define helper methods
    end
  end
end

RAILS_ROOT/config/environment.rb:
require "#{RAILS_ROOT}/lib/action_view/helpers/widget_helper.rb"
ActionView::Base.class_eval do
  include ActionView::Helpers::WidgetHelper
end