Archive

Posts Tagged ‘code’

Generating Combinations with Ruby and Recursion

September 16th, 2009

Hello fellow Rubyists :)

The following code is a recursive combination generator written in Ruby. Given an array of objecs/numbers/..etc, it will return an array of all possible combinations . This originally started out using two functions that contained looping logic in them. It worked well, however I just wanted to stretch myself a bit and try my hand at doing it recursively. Below is the result of my efforts. I hope this helps with anything you may be working on… enjoy!

#javazquez.com

#tail is a clone because of Ruby's passing by reference and shift

#returns an unsorted array

def combination(ary,head=[])
  return ary if(ary==[] )
  head << ary.shift
  tail = ary.clone
  tmp=[]
 if(tail.length>=1)
    tmp+= combination(tail[1..(tail.length)],head.flatten)+
                       combination(Array(tail[-1]),head.flatten)
    tmp+=combination(tail[2..(tail.length)],head.flatten) if(tail[2])
  else
    tmp += combination(tail,Array(head[0]))
  end
  tmp += combination(tail, []) +combination(ary,head.flatten)
  return (tmp << head).uniq
end

combination([1,2,3,4]).sort.each{|it| puts it.inspect  }
#  combination(['A','B','C','D','E','F','G','H','I','J']).sort.each{|it|  puts it.inspect}
#  combination(['A','B','C','D']).sort.each{|row| puts row.inspect}

----output--

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 4]
[1, 3]
[1, 3, 4]
[1, 4]
[2]
[2, 3]
[2, 3, 4]
[2, 4]
[3]
[3, 4]
[4]

Ruby, code , , , , , , , , , ,

Ruby’s variable variables

August 31st, 2009

Hello everyone,

This is a quick post that should help developers new to Ruby. It may also help out those that have been away from the language for a while. Its just a quick reference to Ruby’s variables and their respective scopes. I know I had a chart to keep it all straight when I first encountered the language.

  1. @ An instance variable
  2. [a-z] or _ A local variable
  3. [A-Z] A constant
  4. @@ A class variable
  5. $ A global variable

This information is easily found on the net if you know what you are looking for. I just posted it to help make it even easier to find for those that are new to Ruby, or new to code writing :) .

Ruby, code , , ,

Windows GUI File Parser using Groovy

April 18th, 2009

I find myself doing a lot of file parsing on my Windows XP machine lately. I decide to write a quick utility that would allow me to drag and drop files and search for the key words that I have identified. The utility doesn’t have the logic for searching using regex’s yet, but it should be really easy to add this functionality.

I hacked some Groovy Code with some Java Code and came up with the following script. Hope it is useful.

DISCLAIMER:

As the title suggests, I have only been able to get this to work on my Windows XP machine, OS X didn’t like the javax.swing.TransferHandler and it appears some other operating systems have a hard time with this also.


import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.TransferHandler.*;

class FileDropHandler extends TransferHandler {

private static final long serialVersionUID = 1L;

def wordsToFind =[]
JTextArea output
private JLabel errorMsg;
private String fileText = "";
private boolean test = false;
private boolean same = true;

public boolean canImport(TransferSupport supp) {
/* for the demo, we'll only support drops (not clipboard paste) */
if (!supp.isDrop()) {
return false;
}

/* return false if the drop doesn't contain a list of files */
if (!supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}

boolean copySupported = (COPY & supp.getSourceDropActions()) == COPY;

if (copySupported) {
supp.setDropAction(COPY);
return true;
}

return false;
}

public boolean importData(TransferSupport supp) {
if (!canImport(supp)) {
return false;
}

/* get the Transferable */
Transferable t = supp.getTransferable();

try {

Object data = t.getTransferData(DataFlavor.javaFileListFlavor);

List fileList = (List) data;

for (int j = 0; j < fileList.size(); j++) {

File file = (File) fileList.get(j);
//file.getAbsolutePath()
def tmpfh = new File("FileParser.txt")
println wordsToFind.inspect()
new File(file.getAbsolutePath()).eachLine{line->
wordsToFind.each{ if(line =~ "${it}" ){
println "${line}"
tmpfh.append(line)
tmpfh.append("\n\n")
this.output.setText(this.output.getText()+line+"\n")
}
}
}//end for

tmpfh.close()

}
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return true;
}

public void setOutput(JTextArea jta) {
this.output = jta;
}

public void setOutput(JLabel jta) {
errorMsg = jta;
}

public String getText() {
return fileText;
}

public void clearAll() {
fileText = "";
test = false;
same = true;

}
}

class AL implements ActionListener{
public JTextField jtf
public FileDropHandler dh
public AL(JTextField jtf,FileDropHandler dh){
this.jtf = jtf
this.dh =dh
}
public void actionPerformed(ActionEvent actionEvent){
println "${this.jtf.getText()}"
dh.wordsToFind= this.jtf.getText().split(' ')
}
}

JTextArea dTextArea = new JTextArea("Drop on me");
FileDropHandler dh = new FileDropHandler()
dh.setOutput(dTextArea)
JTextField jta = new JTextField("Enter words seperated by spaces")
dh.wordsToFind= jta.getText().split(' ')
JButton jb =new JButton("Update Word List")
jb.addActionListener( new AL(jta ,dh ))

dh.setOutput(dTextArea);
dTextArea.setDragEnabled(true);
dTextArea.setTransferHandler(dh);

JPanel p =new JPanel(new BorderLayout());
JFrame f = new JFrame()
p.add(jta, BorderLayout.NORTH)
p.add(dTextArea, BorderLayout.CENTER)
p.add(jb, BorderLayout.SOUTH)

f.getContentPane().add(p)
f.setSize(400,400)
f.setVisible(true)

Groovy, Windows, code, java , , , ,

A Groovy Flickr API

March 30th, 2009

A long time ago I wanted to write a desktop GUI interface for Flickr. At the time I had just learned Java and thought it would be really cool to write it using swing. Little did I know how not cool working with swing would be :(

About halfway through the project I heard about a cool new dynamic way to write Java code called Groovy. From that day on Groovy has been making my life a whole lot easier. I didn’t need all the functionality in the flickrj library, so I decide to write a few methods for my app using Groovy. The hardest part of the whole thing was figuring out how to post images to Flickr, for that, I used the flickrj code as a reference. If source code was not available, I don’t think I would have ever figured it out. So a big thanks to all the folks working on that project!

This is not a complete API for Flickr, but should provide enough to get started. Also, here is a link to a text file with the below code for an easier way to view the source.

import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.ArrayList
import java.util.Date
import java.util.Hashtable
import javax.imageio.ImageIO
import org.w3c.dom.Element
import org.w3c.dom.NodeList
import java.io.File;
import java.net.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class FlickrAPI {
String nsid = ""

private String secret = "your secret"

/**
* api key
*/
private String akey = "your key goes here"

private String sig = ""

private String url = ""

String authToken = ""

private String frob = ""

private String restString = "http://flickr.com/services/rest/?method="

public FlickrAPI() {
println("Created FlickerAPI")
}

public void authNewUser() {
constructFrobUrl()
createAuthURL()
getToken()
}
private String constructUrl(String flickrMethod,Map m,boolean authCall =false){
String s= this.restString+flickrMethod+"&api_key="+this.akey
m.each{key,value->
s+=key+value
}
if(authCall){s+="&auth_token=${this.authToken}&api_sig=${this.sig}"}
return s
}
def mapFlickrUser(){

}
//if bool is true then this is a Authenticated call
public void setSig(String method,boolean bool = false){
String sigString="${this.secret}api_key${this.akey}"
try {
if(bool){
sigString +="auth_token${this.authToken}${method}"
println "Sig is true"
}else{sigString+=method}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace()
}
println "sig is " +sigString
this.sig = calcMD5(sigString)
}

def jupload(String filePath,Map parameters=[:]){
println("parameters ${parameters.inspect()}")
def paramMessages=[]
int paramLength=0

if(parameters==[:]){
this.sig = calcMD5("${this.secret}api_key${this.akey}auth_token${this.authToken}")
}else{
//sort them and add them to the signature
String p=""
parameters.keySet().toList().sort().each{key->
//if the key ='tags' make it into space separated string
p+= "${key}${parameters[key]}"
paramMessages.add(addParameter([key,parameters[key]]) )
}
this.sig = calcMD5("${this.secret}api_key${this.akey}auth_token${this.authToken}${p}")
paramMessages.each{stringMsg->paramLength+=stringMsg.length()}
}

File file=new File(filePath)
String CrLf = "\r\n";
def url = new URL("http://api.flickr.com/services/upload/")
//def connection = url.openConnection()
HttpURLConnection conn = url.openConnection()
def is = new FileInputStream(file)
def flength= file.length()
byte[] imgData= new byte[(int)flength]

int offset = 0;
int numRead = 0;
while (offset < imgData.length && (numRead=is.read(imgData, offset, imgData.length-offset)) >= 0) {
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < imgData.length) {
throw new IOException("The file was not completely read: "+file.getName());
}
println "filesize ->${imgData.length}"
// Close the input stream, all file contents are in the bytes variable
is.close();
String message01=addParameter(['api_key',this.akey])
String message02 = addParameter(['auth_token',this.authToken])
String message03 = addParameter(['api_sig',this.sig])

String message1 = "";
message1 += "---------------------------6d72u458s1587" + CrLf;
message1 += "Content-Disposition: form-data; name=\"photo\"; filename=\""+filePath+"\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;

// the image is sent between the messages in the multipart message.

String message2 = "";
message2 += CrLf + "---------------------------6d72u458s1587--" + CrLf;

def totalLength = String.valueOf((message01.length() + message02.length() + message03.length() + message1.length() + message2.length() + imgData.length+ paramLength))
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=-------------------------6d72u458s1587");
conn.setRequestProperty("Host", "api.flickr.com");
conn.setRequestProperty("Content-Length",totalLength );
conn.setDoOutput(true)

System.out.println("open os");
def os = conn.getOutputStream();

System.out.println(message01);
os.write(message01.getBytes());

System.out.println(message02);
os.write(message02.getBytes());
//write the params here before the image
paramMessages.each{msg->os.write(msg.getBytes())}

System.out.println(message03);
os.write(message03.getBytes());

System.out.println(message1);
os.write(message1.getBytes());
os.write(imgData,0 ,imgData.length)

os.write(message2.getBytes());

println "end writing"
os.flush()
os.close()

conn.connect()
conn.disconnect()
println conn.content.text

}
//[name value]
private String addParameter(List para){
String CrLf = "\r\n";
String message01 = "";
message01 += "---------------------------6d72u458s1587" + CrLf;
message01 += "Content-Disposition: form-data; name=\"${para[0]}\"" + CrLf;
message01 += CrLf;
message01 += para[1] + CrLf;
return message01
}

public void constructFrobUrl() {
setSig("methodflickr.auth.getFrob")
this.url = "http://flickr.com/services/rest/?method=flickr.auth.getFrob&api_key=${this.akey}&api_sig=${this.sig}"
println("here is url-> ${this.url}")
def node = new XmlParser().parse(this.url)//dom.parseXML("frob")
this.frob = node['frob'].text().toString()
println("frob =>${this.frob}\n\n")
}

/**
* This function will calculate an MD5 sum of String Signature and return
* the String value of the Hash via strBuildup
*
* @param signature
* @throws NoSuchAlgorithmException
* @returns strBuildup
*/
private String calcMD5(String signature) throws NoSuchAlgorithmException {
// get Instance from Java Security Classes
String strBuildup = ""
MessageDigest md5 = MessageDigest.getInstance("MD5")
byte[] md5summe = md5.digest(signature.getBytes())
for (int k = 0; k < md5summe.length; k++) {
byte b = md5summe[k]
String temp = Integer.toHexString(b & 0xFF)
/*
* toHexString has the side effect of making stuff like 0x0F only
* one char F(when it should be '0F') so I check the length of
* string
*/
if (temp.length() < 2) {
temp = "0" + temp
}
temp = temp.toUpperCase()
strBuildup += temp
}
return strBuildup
}

/**
* get the authentication token
*
* @return
*/
public checkToken(){
setSig("methodflickr.auth.checkToken",true)
this.url=constructUrl('flickr.auth.checkToken',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing check Token INFO ===>${node.children()}")
}
public void getToken() {
println("Entering getToken\n\n")
setSig("frob${this.frob}methodflickr.auth.getToken")
this.url = "${this.restString}flickr.auth.getToken&api_key=${this.akey}&frob=${this.frob}&api_sig=${this.sig}"
//println(this.url)
def node = new XmlParser().parse(this.url)
//need to get the nsid and the authtoken
this.authToken = node['auth']['token'].text()
this.nsid = node['auth']['user'].'@nsid'.text()
println "token is ${this.authToken}"
println("Token =>${node['auth']['token'].text()}")
println("nsid =>${node['auth']['user'].'@nsid'.text()}")
println("perms =>${node['auth']['perms'].text()}")

// set user nsid
println("Exiting GET Token")
}

public void createAuthURL() {
setSig("frob${this.frob}permsdelete")
String cmd = "open http://flickr.com/services/auth/?api_key="+ this.akey + "&perms=delete" + "&frob=" + this.frob + "&api_sig=" + this.sig
try {
Process proc = cmd.execute()
proc.waitForOrKill(10000)
sleep(2000)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}

/***************************************************************************
* AUTH
**************************************************************************/
/***************************************************************************
* ACTIVITIES
**************************************************************************/
//POLL ONLY ONCE AN HOUR!!!!!
public activityGetUserComments(){
setSig("methodflickr.activity.userComments",true)
this.url=constructUrl('flickr.activity.userComments',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing GET user Comments INFO ===>${node.children()}")
}
/***************************************************************************
* BLOGS
**************************************************************************/
/***************************************************************************
* CONTACTS
**************************************************************************/
public void contactsGetList(){
setSig("methodflickr.contacts.getList",true)
this.url=constructUrl('flickr.contacts.getList',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing GET contact List INFO ===>${node.children()}")
}
/***************************************************************************
* FAVORITES
**************************************************************************/
/***************************************************************************
* GROUPS
**************************************************************************/
/***************************************************************************
* GROUP POOLS
**************************************************************************/

/***************************************************************************
* INTERESTINGNESS
**************************************************************************/

/***************************************************************************
* PHOTOS
*what if a return back an array of pictures?
**************************************************************************/
def photosGetNotInSet(){
List piclist=[]
setSig("methodflickr.photos.getNotInSet",true)
this.url=constructUrl('flickr.photos.getNotInSet',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing GET Not in Set INFO ===>${node.children()}\n\n\n")
/* test=f.photosGetNotInSet()
println test.photos.each{it-> it.each{p-> println p}} //list of nodes

test.photos.photo[3].attributes()
test.photos.photo.each{it-> println it.attribute('isfamily')} //gets the individual attr
test.photos.photo.each{it-> picList.push(new Picture(it))} //push a node into picture contructor

*/

return node
}

def photosGetContactsPhotos(){
setSig("methodflickr.photos.getContactsPhotos",true)
this.url=constructUrl('flickr.photos.getContactsPhotos',[:],true)
def node = new XmlParser().parse(this.url)
return node
}

def photosGetRecentlyUploaded() {
setSig("methodflickr.photos.getRecent",true)
//this.url = "flickr.photos.getRecent&api_key",[:],true)
this.url= constructUrl('flickr.photos.getRecent',[:],true)
def node = new XmlParser().parse(this.url)
println("done parsing RecentPhotos ===>${node.children()}")
return node
}
public void photosGetInfo(){

}
/***************************************************************************
* PEOPLE
**************************************************************************/
def contactsGetList(){
setSig("methodflickr.contacts.getList",true)
this.url=constructUrl('flickr.contacts.getList',[:],true)
def node = new XmlParser().parse(this.url)
//println("done parsing GET contact List INFO ===>${node.children()}")
return node
}
def peopleGetUploadStatus(){
setSig("methodflickr.people.getUploadStatus",true)
this.url=constructUrl('flickr.people.getUploadStatus',[:],true)
def node = new XmlParser().parse(this.url)
println("done parsing GET upload Status INFO ===>${node.children()}")
return node
}
def peopleGetPublicPhotos() {
setSig("methodflickr.people.getPublicPhotosuser_id${this.nsid}",true)
this.url=constructUrl('flickr.people.getPublicPhotos',['&user_id=':"${this.nsid}"],true)
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
println("done parsing GET Public Photos ===>${node.children()}")
return node
}
def peopleGetPeopleInfo() {
setSig("methodflickr.people.getInfouser_id${this.nsid}",true)
this.url=constructUrl('flickr.people.getInfo',['&user_id=':"${this.nsid}"],true)
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
return node
}

/********************************************
* photosets
************************/
def photosetsGetList(String uid){
setSig("methodflickr.photosets.getListuser_id${uid}",true)
this.url=constructUrl('flickr.photosets.getList',['&user_id=':"${uid}"],true)
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
return node

}
def photosetsGetPhotos(String setID){
setSig("methodflickr.photosets.getPhotosphotoset_id${setID}",true)
this.url=constructUrl('flickr.photosets.getPhotos',['&photoset_id=':"${setID}"],true)
println this.url
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
return node

}
/**
Upload photos

http://api.flickr.com/services/upload/

*/
//get the picture when supplied the proper args
//http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg

public String getPicture(String farmId, String serverId, String photoid, String secret,String size ="s"){
return "http://farm${farmId}.static.flickr.com/${serverId}/${photoid}_${secret}_${size}.jpg"

}

Groovy, code, java , , , , , , , ,

Adding and Resizing Images with Grails

January 24th, 2009

Here is a quick post on how to upload images within your Grails project to your file system(rather than your database). It seems simple enough, but I ran into a few snags as I was working on one of my projects. Just wanted to provided a working example for those that are entering the Grails territory for the first time. Happy Coding!

I am using the imageTools plugin which you can read more about here

NOTE: The imageTools plugin has been criticized for its low quality of output. ImageMagick may be a better fit for you project(s). My particular project didn’t call for high quality pictures. A quick google search for “imagemagick for grails” should get you started on your way.

I am using version 1.0.3 in the example below

to install, I ran the following command from my grails application’s root directory

grails install-plugin http://www.arquetipos.co.cr/blog/files/grails-image-tools-1.0.3.zip

Domain-Class

class Picture {
byte[] imagefile
//Any other stuff you want to track

}

Controller Code for Saving an image

def save = {

def downloadedfile = request.getFile('imagefile')
def pictureInstance = new Picture(params)
def imageTool = new ImageTool()

if(downloadedfile && pictureInstance.save()){
String imagepath = grailsAttributes.getApplicationContext().getResource("images/").getFile().toString() + File.separatorChar + "${pictureInstance.id}.jpg"
downloadedfile.transferTo(new File(imagepath))

imageTool.load(imagepath)
imageTool.thumbnail(140)

imageTool.writeResult(imagepath, "JPEG")
imageTool.square()
flash.message = "Picture ${pictureInstance.id} created"
redirect(action:show,id:pictureInstance.id)
}
else {
render(view:'create',model:[pictureInstance:pictureInstance])
}
}

Code for displaying the image in both the ’show’ and ‘list’ views

<td><img src="${createLinkTo(dir:'images', file: pictureInstance.id+'.jpg' )}" /> </td>

Grails, Groovy, code , , , , , ,

Mergesort and Quicksort with Dynamic Languages

January 3rd, 2009

The other day I was flipping through an algorithms book and came across a section on sorting. I remembered that I had a blast writing them c++ during my undergrad and thought it would be fun to write them in a couple of different languages. I settled on writing a quicksort, and mergesort.
Interesting notes:
1) Python(2.5) returns a None type when appending a value to an empty list which forced me to use ‘+’
>>> ex= [].append()
>>> print ex
>>>None

2) Groovy gave me a java.util.ConcurrentModificationException when I transcribed my Ruby code to Groovy. Because of the fact that I was deleting items from a list that I would read in later(while loop which checks size of left and right), I got this error. Accounting for that, the groovy code is pretty nasty.(anyone that would like to provide a better example without relying on the built in Collections.sort(list) would be welcome)

Here is my code… enjoy!


# javazquez.com
==========MERGE SORT========

-------------RUBY----------------

def merge_sort(ary)
  return ary if (ary.length <= 1)
  half = ary.length/2
  left = merge_sort(ary[0...half])
  right = merge_sort(ary[half..ary.length-1])
  result =[]
#compare first left and first right
  while left.length > 0 and right.length > 0
    result << (left[0] < right[0] ? left.shift : right.shift)
  end
  result.concat((left.length > 0 ? left : right))
  return result
end

ary=[1,5,14,3,2,45,2,0,01,-1]
p merge_sort(ary)


-----------Python Mergesort-------------

def merg_sort(lst):
    if(len(lst) <= 1):  return lst
    left = merg_sort(lst[:len(lst)/2])
    right = merg_sort(lst[len(lst)/2:len(lst)])
    result = []
    while len(left) > 0 and len(right)> 0:
        if( left[0] > right[0]):
            result.append(right.pop(0))
        else:
            result.append(left.pop(0))

    if(len(left)>0): result.extend(merg_sort(left))
    else: result.extend(merg_sort(right))

    return result

print merg_sort([8,7,43,2,5])


--------Erlang Mergesort-------------
-module(mergesort).
-export([ms/1,msTestSuite/1]).

ms(Lst)->break(Lst).
break([]) -> [];
break([L]) -> [L];
break(List) ->
    {Left, Right} = lists:split(length(List) div 2, List),
    merge(break(Left),break(Right)).

merge(L, []) -> L;
merge([], R) -> R;
merge([Lh|Ltail],[Rh|Rtail])->
	 if
	 Lh < Rh -> [Lh | merge(Ltail,[Rh|Rtail])];
	 Lh >= Rh -> [Rh | merge(Rtail,[Lh|Ltail])]
	 end.

%to test, run mergesort:msTestSuite(run).
msTestSuite(run)->
	[mstest1(run),mstest2(run),
	mstest3(run),mstest4(run),
    mstest5(run)].

mstest1(run)-> ms([3,2,1]).
mstest2(run)-> ms([3,3,3,1]).
mstest3(run)-> ms([]).
mstest4(run)-> ms([1]).
mstest5(run)-> ms([123,0,-1,23,2,34,5,678,7,5,8]).


-------------GROOVY MERGESORT--------
def ms(lst){
    if(lst.size() <= 1){return lst}
    def sz=lst.size()
    int half = (int)(sz/2)
    def l = lst[0..


# javazquez.com
========QUICKSORT========

-----RUBY----------------
def quick_sort(ary)
  return ary if(ary.length <= 1)
  greater,less = [],[]
  pos = rand(ary.length)
  pivot = ary[pos]
  ary.delete_at(pos)
  ary.each{|item|
       (item < pivot) ? less << item :greater << item}
  return (quick_sort(less) << pivot).concat(quick_sort(greater))
end

ary=[1,5,14,3,2,45,2,0,01,-1]
p quick_sort(ary)


----------Python Quicksort--------------

import random
def quickSort(lst):
	if(len(lst) <= 1):return lst
	greater = []
	less = []
	pivot = lst.pop(random.randint(0,len(lst)-1))
	for item in lst:
		if(item < pivot): less.append(item)
		else: greater.append(item)
	return quickSort(less)+[pivot]+quickSort(greater)

ary=[1,5,14,3,2,45,2,0,01,-1]


----------Erlang Quicksort--------------
-module(quicksort).
-export([qsort/1]).

qsort([]) ->[];
qsort([Pivot|T]) ->
		lists:append( [qsort([X || X <- T, X < Pivot]),
		[Pivot], qsort([X || X <- T, X >= Pivot]) ).

-------GROOVY QUICKSORT--------------
def quickSort(lst){
	if(lst.size() <= 1){return lst}
	def greater = []
	def less = []
	def pivot = lst.remove(new  Random().nextInt(lst.size()))
	lst.each{item->
		if(item < pivot){ less.add(item)}
		else{greater.add(item)}
	}
	return quickSort(less)+[pivot]+quickSort(greater)
}
print quickSort([1,5,14,3,2,45,2,0,01,-1])


Erlang, Groovy, Ruby, code, python , , , , , , , , , , ,

Fun with Python and Gmail API

December 24th, 2008

Yesterday I decided to play with Gmail’s API in order to grab my contacts. To my surprise, it was a snap. Google has instructions for python Here, I wrote my example using Python 2.5 on OS X. Once I had unzipped the GData contents, I just changed to the GData directory and ran
sudo python setup.py install
and I was ready to go.

Python Documentation for GDATA

#################################
# javazquez.com
# Google GMAIL API example
##################################
import gdata.contacts.service

user = 'user@gmail.com'
pwd = 'password'
client2 = gdata.contacts.service.ContactsService()
# Authenticate using your Google Docs email address
# and password.
client2.ClientLogin(user, pwd)
contacts_feed = client2.GetContactsFeed()

################################################
# NOTE: The GetContactsFeed does not give back
# all contacts.
# This 'problem' can be solved by looping
# until the contacts_feed.GetNextLink
# returns None.
################################################
l=[]
while(contacts_feed) :
for x in contacts_feed.entry:
l.append([x.title.text, x.email[0].address])
ret = contacts_feed.GetNextLink()
contacts_feed = client2.GetContactsFeed(ret.href) if(ret) else ret

print "here are your %d contacts" % len(l)
for contact in l:
print "%s -> %s" % (contact[0],contact[1])


Output

here are your xxxx contacts
ANDREW -> adrew@somewhere.com
...

code, google, python , ,

Ruby to Python Primer

December 16th, 2008

If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It’s not Ruby :D , 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, Uncategorized, code, python , , , , ,

Ruby HTTPS POST’ing

December 7th, 2008

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 :D

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

Ruby, code , , , , ,

Recursive Directory Search with Ruby and Groovy

November 6th, 2008

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 :D

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}")


 

 

Groovy, Ruby, code , ,