All posts by admin

About admin

I am a Computer Scientist and an Artist. I have a strong desire to combine my two areas of study to make something useful.

Ruby to Python Primer

If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It’s not Ruby 😀 , but it can get the job done. Here is a quick list of similarities between the two languages. I hope it helps… don’t forget to this list in the comments section 😉

#-----find object methods-----
s="hello, I am a string"

#ruby
puts s.methods

#python
print dir(s)

#find out more about a method using python
help(s.split)

#-----view object's class-----
#ruby
s.class

#python
s.__class__

#------Iterate hashes-------

#ruby
h.each{|key,value| puts "#{key}, #{value}"}

#python
for key,value in h.iteritems():
print key, value

#---ternary operators

#ruby
condition ? var = x : var = y

#python.. not exactly an operator, but you get the meaning
#---- var = y if condition is false
var = x if condition else y

#----lengths------
#ruby
s="hello, I am a string"
puts "Length of string is #{s.length} or #{s.size}"

h={:one=>2,:three=>4}
puts "Length of hash is same as string, #{h.length} or #{h.size} "

#python
print("This is the length of a string %s" % len("string"))
print("number of key/value pair= %d" % len({'one':1,'two':2}))

#---slicing lists/arrays
l=[1,2,3,4,5]

#ruby
l[1..3] #=>[2,3]

#python
l[1:3] #=>[2,3]

#--print string multiple times-----

#ruby
4.times{print "hello"} #=> hellohellohellohello

#python
print("hello" * 4) #=> hellohellohellohello

Ruby HTTPS POST’ing

So for my own geeky pleasure, I decided to try writing cgi scripts with Ruby, Python, PHP, and Perl.  All had readily accessible documentation on how to POST to a https URL but ruby. My first thought was to look at the Net:HTTP documentation found HERE.

The one example I wanted was not listed. I did some searching around and pieced together the following code. I hope this is as big a help to you as it was to me. Looking at it, It seems pretty intuitive….but if your like me, sometimes you need it spelled out 😀

As a side note, setting path to path = ‘/../’ is my work-around for a script that is mapped to www.mysite.com rather than ‘/some_POST_handling_script.rb’


#Juan Vazquez ->javazquez.com
require 'net/http'
require 'net/https'
http = Net::HTTP.new('www.mysite.com', 443)
http.use_ssl = true
#path(a.k.a) ->www.mysite.com/some_POST_handling_script.rb'
path = '/some_POST_handling_script.rb'
data = 'badguy=Gargamel'

headers = {'Content-Type'=> 'application/x-www-form-urlencoded'}

resp, data = http.post(path, data, headers)

puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data

Recursive Directory Search with Ruby and Groovy

A while back I was bored and decided I need to brush up on my Ruby chops. I had been wanting to play with threads for quite some time and couldn’t think of anything that would be a fun project to do…until this crazy idea hit me.  Wouldn’t it be cool if could generate multiple threads to search different servers for any file of my choosing?” The code I wrote doesn’t directly do this, but with some minor tweaks it could be done.

I took that idea and ran with it using Ruby. After I finished coding, I thought I would try writing it from scratch using my second favorite language, Groovy (Ruby is my first).  I have to admit, writing the Groovy code was more intuitive because of the baked in file/directory iterators. I refactored my Ruby code a few times and ended up using the find module to maximize performance. Below is the code, and as always, I am open to suggestions on other ways of doing it 😀

Ruby code
 

#########################
#  Juan Vazquez
#  http://javazquez.com
#########################
require 'find'
class DirectoryWizard
  attr_accessor :root_dir,:exts, :thread_cnt, :thread_tracker, :count
  #initialize with a root , and file extensions
  def initialize(root, t_count,*extensions)
    @root_dir, @exts, @thread_cnt , @thread_tracker, @count = root, extensions, t_count, [], 0
  end

  def start_looking
    begin
      puts Dir.entries(@root_dir).select{|dir_item| is_in_ext(dir_item) }
      list_dirs(@root_dir).each do|di|
        @thread_tracker << Thread.new(@root_dir+di){|directory| 
                                             recursive_file_search(directory) }
        wait_for_running_threads  if(@thread_tracker.size > @thread_cnt)
      end
      wait_for_running_threads
    rescue Exception => e; puts e;
    end
  end
  def recursive_file_search(directory)
    Find.find(directory){|dir_item|
      if(is_in_ext(dir_item))
       @count+=1
       puts dir_item
      end
    }
  end

    #return array of immediate subdirectories excluding . and ..
  def list_dirs(directory)
   Dir.entries(directory).select{|fh|(!is_p_c_directory?(fh) && 
                                          File.directory?(directory+fh))}
  end

  #return an array of all file/directories excluding '.' and '..'
  def list_contents(directory)
    Dir.entries(directory).delete_if{|x| is_p_c_directory?(x)}
  end

  #is Parent or Current Directory
  def is_p_c_directory?(filename);(filename =="." || filename == "..");end
  
#return an array of files that match ext
  def is_in_ext(dir_item); @exts.detect{|ext| dir_item.match(ext)}; end
 
 def wait_for_running_threads
    @thread_tracker.each{|th|th.join}
    @thread_tracker=[]
  end
end #end class


t= DirectoryWizard.new("\\\\server\\e$\\profiles\\",16,'filename')

t.start_looking

puts "Done with Program count is #{t.count}"

Groovy Code

import java.util.regex.*;
class DirWiz{
   def root_dir, exts, thread_max_cnt, thread_tracker, count

   public DirWiz(String basedir, int t_count, List extensions){
        this.root_dir = basedir
        this.exts = compile_regex(extensions)
        this.thread_max_cnt = t_count
        this.thread_tracker = []
        this.count=0
    }
    def start_looking(){
      try{
          def dir = new File(this.root_dir)
           check_for_files(this.root_dir)
          //recursively search directories
           dir.eachDir{ subDir->
            //thread it off
           if(this.thread_tracker.size() > this.thread_max_cnt){
               this.thread_tracker.each{it->it.join()}
               this.thread_tracker=[]
           }
           this.thread_tracker << Thread.start{
                 subDir.eachFileRecurse{ fh -> 
                    check_using_compiled_regex(fh.canonicalPath)
                 }
           }
        }
      }catch(Exception e){
        println("error ${e}")
      }
      this.thread_tracker.each{it->it.join()}
      println("Done")
    }
   def print_if_match(String file){this.exts.each{ext->
                if(file=~ext){this.count+=1;println(file)}}
   }
   def check_using_compiled_regex(String file){
    try{
	def var = this.exts.find{it.matcher(file).matches()}
	if(var){this.count+=1;println(file)}
    }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def check_for_files(String dir){
      try{ new File(dir).eachFile{ file ->
	        check_using_compiled_regex(file.canonicalPath)
        }
      }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def compile_regex(List list){
    List ret_list=[]
    list.each{ ret_list <<    Pattern.compile(it,Pattern.CASE_INSENSITIVE)}
    return ret_list
   }
}


def t = new DirWiz('c:\\',16,[".*\\.jpg.*"])//look for jpegs
//def t = new DirWiz('\\\\server\\dir\\',16,["filname"])
t.start_looking()

println("Done with the program total number of files is ${t.count}")


 

 

Proxy/ReverseProxy and Apache2

I recently configured Apache2 to be a ReverseProxy/Proxy and thought I would share my experiences while it was still fresh. Having never configured any kind of proxy, I found this webpage very informative. The scenario I would like to use for my example is that I have three internal web servers called

Site Local IP Remote IP Port
www.reallycoolsite.com 192.168.1.102 10.15.22.1 80
www.justcoolsite.com 192.168.1.102 10.15.22.2 80
www.reallylamesite.com 192.168.1.44 10.15.22.3 80

Alright…pretty straight forward right? If you are in a situation that I was when I started, you haven’t done much more than install apache from source and added a few modules here and there occasionally. The way I solved the problem was to create name-based virtual host for each of the servers.
our example would look like


#you can listen on specific ports for requests if you like
#(ex->Listen 192.168.1.102:80)
#I use the below statement to listen on 80 for all requests
Listen *:80
#Because we have multiple names mapped to same ip
NameVirtualHost 192.168.1.102:80

<VirtualHost 192.168.1.102:80 >
ServerName www.reallycoolsite.com
ProxyRequests Off
ProxyPass / http://10.15.22.1/
ProxyReverse / http://www.reallycoolsite.com/
ProxyPreserveHost On
ErrorLog reallycoolsite_error_log
CustomLog reallycoolsite_access_logs
</VirtualHost >

<VirtualHost 192.168.1.102:80 >
ServerName www.justcoolsite.com
ProxyRequests Off
ProxyPass / http://10.15.22.2/
ProxyReverse / http://www.justcoolsite.com/
ProxyPreserveHost On
ErrorLog justcoolsite_error_log
CustomLog justcoolsite_access_logs
</VirtualHost >

<VirtualHost 192.168.1.44:80 >
ServerName www.reallylamesite.com
ProxyRequests Off
ProxyPass / http://10.15.22.3/
ProxyReverse / http://www.reallylamesite.com/
ProxyPreserveHost On
ErrorLog reallylamesite_error_log
CustomLog reallylamesite_access_logs
</VirtualHost >

If you receive errors during the communication of your proxy and your server, it may be a good idea to investigate if you have an http protocol error discussed at the bottom of this page
The following two lines are pulled from the reference and fixed a problem I had with one of my IIS servers using SSL(for more info about the issue, go here

SetEnv force-proxy-request-1.0 1
SetEnv proxy-nokeepalive 1

My apache configuration file(httpd.conf) was the file I used to edit my settings.. Your file may be different depending on how new your apache version is. I found that some implementations called the configuration file apache.conf…. I hope this blog entry is helpful you, Happy Configuring!

Rotating Java Images

I am working on a swing flickr app and thought I would share some code to help those that are new to java gui programming( like me) and get them on their way to making their killer application.

I’ll start off with my first problem,  “How do I show an Image?” After looking through Java forums and going through my Java books, I settled on using Image Icons in JLabels. The next thing I wanted to do was rotate the image 90 degrees. I used Java’s Graphics class to accomplish this. The following groovy code loads 100 JLabels containing a JPEG of Pixar’s Wall-e that I had in the same directory rotated 90 degrees.

import java.awt.image.BufferedImage
import javax.swing.*
import java.awt.*;
import java.util.*;
import java.awt.image.AffineTransformOp
import java.awt.geom.AffineTransform

class ImageButton extends JLabel{
	ImageIcon picture

public ImageButton(ImageIcon icon){
	super(icon)
	this.setBackground(Color.BLACK)
	this.setForeground(Color.BLACK)
	this.picture=icon
	this.setPreferredSize(new Dimension(120,100))
}

public void rotateImage( int angle) {
	int w = this.picture.getImage().getWidth()
	int h = this.picture.getImage().getHeight()
	BufferedImage bi = new BufferedImage(w,h,
                      BufferedImage.TYPE_INT_RGB)
	Graphics bg = bi.createGraphics();
	bg.rotate(Math.toRadians(angle), w/2, h/2);
	bg.drawImage(this.picture.getImage(),0,0,w, h,
			0,0,w, h, null);

	bg.dispose()//cleans up resources
	this.setIcon(new ImageIcon(bi))
	this.setPreferredSize(new Dimension(this.picture.getIconHeight(),
                       this.picture.getIconWidth()))
	}
}

JFrame f= new JFrame()
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
JPanel panel=new JPanel();
def img= new ImageIcon("walle.jpg")
(1..100).each{i->
	def btn=new ImageButton(new ImageIcon(img.getImage()
                        .getScaledInstance(120,100,4)))
	panel.add(btn)
	btn.rotateImage(90)//rotate the image now
	println i
}

panel.setBackground(Color.BLACK)

f.setSize(300,400)
f.getContentPane().add(panel)
f.setVisible(true)

 

My first few attempts at the code gave me out of memory Heap errors. I unknowingly had BufferedImage references hanging around.  Once I realized this, I cleaned up my code and remembered to call dispose() on the graphics bg object and everything came together quite nicely.

BarCamp Omaha

I have just been informed/invited to Omaha’s BarCamp! According to the site, this is a “unconference born from the desire for people to share and learn in an open environment.”

The list of topics that have been submitted thus far are already enough to get any developer’s inner geek super-charged. At this point I am not sure what I will talk about, but here are a few ideas.

  1. uploading/updating multiple models in one form (ROR)
  2. Groovy and flickr
  3. Action Script 3 concepts
  4. Linux Administration
  5. Setting up Twiki

Any suggestions or votes on what I could bring to the BarCamp would be awesome. If you can make it, I suggest checking this event out! After all, you don’t want to be sitting there listening to you fellow IT buddies raving about the great time they had learning at BarCamp…right?

File I/O Part 1

I love to learn and try new languages. Not only is learning a new language fun, many times it teaches me something new about a language that I am already familiar with. The only problem that I have with learning so many languages, is keeping them straight. I decided that I would take a few of the dynamic languages I use most often and compile a list of how to handle File I/O with each of them. If you have a Dynamic language(part 2 of this post will be on static languages) not represented below or have another method of File I/O with the represented languages, please add to the list with its respective File I/O code:D
Without further ado…

//Groovy open file for writing
def target ="filename"
File wf= new File(target)
wf.write( "I am in your file eating your space" )

//Groovy one liner
new File('filename.txt').text = 'First line of text!'

//Groovy open file for appending
def target ="filename"
File af= new File(target)
af.append("I have all of your base")

//Groovy read each line in file
new File("filename").eachLine{line-> println line}

//Groovy read whole document and put into List

List lines = new File("filename").readLines()
//lines contains two lines that we need
println "first line  $lines[0]"
println "second line $lines[1]"

//Groovy reading one line
File rf= new File("filename") //open for reading
//read first line, trim, assign to tmp
rf.withReader { line ->tmp = line.readLine().trim()}

//Groovy test if file exists
File src = new File(srcFile)
if (src.exists() ){ println "I exist"}
else{println "I don't exist"}

#Ruby openfile for reading
fh = File.new(path, "r")  # open file "path" for reading only
fh.close

#Ruby open file for writing
fout   = File.new(path, "w")  # open file "path" for writing only
fout.puts "Up, Up, Down, Down, Left, Right, Left, Right, B, A, Select, Start"
fout.close

#Ruby open file for apending
fa= File.new("DeleteMe.txt","a")
fa.puts "I am at the end of file"
fa.close

#Ruby read eachline in a file
File.open("file").each { |line| p line}

#Ruby read entire file to string
fh = File.new(filename)
str = fh.read

#Ruby read entire file into array(each line is an element in the array)
fh = File.new(filename)
str = fh.readlines

#Python Write a file
fout = open("DeletMe.txt", "w")
fout.write("Writing to fout\nCheck it out!")
fout.close()

#Python Read an entire file
fin = open("ReadingTest.txt", "r")
fin_text =  fin.read()
fin.close()
print fin_text

#Python read entire file into list
fin = open("ReadingTest.txt", "r")
txt= fin.readlines()
fin.close()
print txt[0]

#Python append to a file
fh= open ( 'DeleteMe.txt', 'a' )
fh.write ( '\n\n\nBottom line.' )
fh.close()

#Perl reading a file
open(FILE,  '<', $file) or die "Can't read $file: $!\n";
while(<FILE>)
{
print ;
}

#Perl append to a file
open(FILE, '>>', $file) or    die "Can't append to $file: $!\n";
print FILE "text";
close(FILE);

#Perl read and write to a file
#+< allows reading and writing, and keeps the data that was
#already in the file.  open() will fail if file doesn't exist.
open(FILE, "+<$file" ) or die ("Can't  read|write: $file\n");
close(FILE);

#Perl read and write to a file
#+>allows writing and reading, but replaces/overwrites the
#data in the file if the file exists. Creates it if it doesn't exist.
open(FILE, "+>$file" ) or die ("Can't write or read:$file \n");

close(FILE);

PHP code doesn’t display properly within WordPress, so here is an image of the code

PHP File I/O

Handling Ruby’s String.each_char Iterator

Ahh the joys of iterators. I can’t say enough about how much they make my life easier. They are just so darn handy. Life was good in my Ruby world until I needed to iterate through the characters in a string. Thinking to myself, “there has got to be a method that does this,” I looked up Ruby’s String class and saw just what the doctor ordered… each_char.

Feeling pretty proud that my favorite language had this baked right in, I was only to happy to inject it into my code and test it out. That is until I recieved the dreaded NoMethodError: undefined method `each_char’ . Eeek, what did I do wrong? Did I mispell the method…..Nope, did I call it correctly…..Yep. Well, what the heck is going on?

After multiple attempts to find the answer on Google, I finally posted my problem to the ruby-talk group. I was told that the Ruby 1.8 String implementation that I was using only understood bytes and that I could use require ‘jcode’ to get the iterator to work the way I wanted. I did some looking around and I am not sure this is a great solution, after all, I could have easily used the each_byte{|f| f.chr} to iterate through and convert accordingly. I don’t understand why something that is documented as part of the class, does not work.

It would really help if there was an easy to search area on the net dedicated to language quirks for people trying to get a better grasp of their programming language of choice. Maybe that will be my next ROR project.

As it turns out, my Ruby 1.8.7 installation on my Fedora core 9 works as advertised.

su vs. “su -” The Mystery Revealed

Inquiring minds want to know, what is this su - and why is it different than su? Well, if you are like me, you didn’t even know that su - existed. I ran into this problem when I was trying to add a new user to a new Linux machine. Remote root login was disabled(for obvious reasons:D) and I was logged in with my regular non-privileged user account. Well, normally the story goes like this…

  1. su
  2. Authenticate
  3. useradd account
  4. set password
  5. log out of privileged account
  6. Take coffee break from all the hard work and call it a day

No so today:( . When I attempted to run step three(useradd), I received a command not found error. “That’s weird” I thought. How could a machine not have this basic command. I looked in the bin directory to see if it was some kind of path error I was having. Thinking that this was the case, I was shocked to see that none of the user commands(adduser, usermod, deluser) where there.

After a few minutes of scratching my head, I asked someone more versed in Linux than I what they thought. After walking through each of the steps I had taken, my mistake was easily spotted. I hadn’t added the ‘-‘ to the su command. Thinking that the explanation was weird, I checked with google for the su - command. Sure enough, the link to Wikipedia had this to say about it,

Optionally, you can use a hyphen with su to invoke a login shell and assume the target user’s complete user environment:

I am glad I had someone to point this out to me… It could have been a longer and very frustrating ordeal. It was also a lesson for me to refer more to the man pages(it had the answer there too). I hope this blog entry helps someone else who is confronted with this situation.

Adding Functionality to Ruby Strings

Ok, here is the scoop. I was working on a project using Ruby and needed to grab three characters from a string skipping one character in between.

ex –>  “123456789”    would become 234 and 567

I thought this would be a great opportunity to try out blocks in Ruby and test open classes

class String
   def blocker(sizeOfGroup,offset)
     while(val=self.slice!(0..offset.abs-1))
        break if val.to_s.length < 1
        yield  self.slice!(0..(sizeOfGroup.abs-1))
      end
  end
end


here is the code I used to test with


string = "12345678910" 
ary=[] 
string.blocker(3,-1){|v| ary.push(v)}
ary.each{|i|puts i}
puts "her is ary "+ary.inspect 

And this is the result.

>>> test.rb

234
678
10
her is ary ["234", "678", "10"]

This was definitely a fun experiment and I can't wait to try out more stuff. If you haven't played around with blocks, give it a try...you just might like it.