Archive for the ‘Software’ Category

Get a path from a node.

August 30th, 2009


This snippet of code lets you get a TreePath from a nodeview when you only know the ending node. This seems to be a problem I run into rather often where I want to manipulate the tree by expanding a path but I only have the node I want to expand to. The is a GetPath function in the NodeStore class however it is marked as internal with no easy access, so this provides a work around for that.

In order to use this you will need to change out the Node class used here with whatever TreeNode based class your using in your NodeView.

So nifty code in mono/c#:

public Gtk.TreePath GetPath (Node target)
{
	int Count = 0;
	foreach(Node n in view.NodeStore)
	{

		ArrayList path = RecursiveIndexSearch(target,n);

		if (path != null)
		{
			path.Insert(0,Count);
			if(path.Count == 1 && target != n)
			{
				return null;
			}
			else
			{
				return new Gtk.TreePath((int[])path.ToArray(typeof(int)));
			}
		}
		Count++;
	}
	return null;
}
public ArrayList RecursiveIndexSearch(Node target, Node Start)
{
	if(Start.ChildCount > 0)
	{
		for (int i = 0; i < Start.ChildCount; i++)
		{
			ArrayList Path = RecursiveIndexSearch(target,Start[i] as Node);
			if (Path != null)
			{
				Path.Insert(0,i);
				return Path;
			}
		}
	}
	if(Start.ChildCount == 0)
	{
		if (Start == target)
		{
			return new ArrayList();
		}
	}
	return null;
}

Tags: , , ,
Posted in Software | Comments (0)

Nifty Gtk Snippets.

August 20th, 2009


So in my recent works with Gtk I’ve come across (and written) some useful snippets so I thought I’d post a few of them.

The first comes from this site (its in Spanish), this snippet allows you to take a System.Drawing.Image to a Gdk.Pixbuf and it looks like this (slightly modified to fix an ambiguous reference in my project).

static Gdk.Pixbuf ImageToPixbuf( System.Drawing.Image image )
{
  using ( MemoryStream stream = new MemoryStream() )
  {
    image.Save( stream, System.Drawing.Imaging.ImageFormat.Png );
    stream.Position = 0;
    return new Gdk.Pixbuf( stream );
  }
}


So, we can take this first function and we can use it in this second snippet which takes an list of images and makes a single pixbuf that contains all of the images. This allows us to take a group of icon files and string them into a single image to be used in a gtk nodeview so that it only requires one column to show a variety of status icons, which is what I’m using it for maybe you can find something more interesting for it to do. Any ways the second snippet I share with you today looks like this.

public Gdk.Pixbuf GenerateIconImage(List<System.Drawing.Image> images)
{

	if(images != null && images.Count> 0)
	{
		Gdk.Pixbuf Composite = ImageToPixbuf(images[0]).Clone() as Gdk.Pixbuf;
		images.RemoveAt(0);

		foreach (System.Drawing.Image i in images)
		{
			Composite = CreateComposite(Composite,ImageToPixbuf(i).Clone() as Gdk.Pixbuf);
		}
		return Composite;
	}
	else
	{
		Gdk.Pixbuf Composite = new Gdk.Pixbuf(Gdk.Colorspace.Rgb,true,8,16,16);
		Composite.Fill(0);
		return Composite;
	}

}

public Gdk.Pixbuf CreateComposite(Gdk.Pixbuf p1, Gdk.Pixbuf p2)
{
	Gdk.Pixbuf composite = new Gdk.Pixbuf(Gdk.Colorspace.Rgb,true,8,p1.Width+ p2.Width,p1.Height);
	p1.Composite(composite,0,0,p1.Width,p1.Height,0,0,1,1,Gdk.InterpType.Hyper,255);
	p2.Composite(composite,p1.Width,0,p2.Width,p2.Height,p1.Width,0,1,1,Gdk.InterpType.Hyper,255);
	return composite;
}

Tags: , , , ,
Posted in Software | Comments (0)

Python URL grabber!

April 27th, 2009

I’m experimenting with building a web crawler in python (maybe even a small search engine bot) and I thought I would post what I have so far. Basically you give it a starting url (in the PendingURL array) and it goes to that site, uses regular expressions (some of the expressions might not be the best ones to use but they work for now) to find html links then extracts the url and adds them to the PendingURL array. The provided sample stops when its checked 10 urls but its very easy to change.

Currently If there is a issue with a link (e.g. cannot connect, cant find server) it just ignores it and moves on. I’ll probably change that later on. But for right now it’s a nifty tool can grab quite a few urls off of just a few pages. When its done running it outputs all of the links to a text file.

This code requires httplib2 and the regular expression modules.

import httplib2
import re

URLList = []
PendingURL = ["STARTING URL"]

RegLinks = "((<a).*?(href).*?(>).*?())"
RegURL = '.*?((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))'
RegLinks = re.compile(RegLinks, re.IGNORECASE|re.DOTALL|re.MULTILINE)
RegURL = re.compile(RegURL, re.IGNORECASE|re.DOTALL|re.MULTILINE)

def LoadHttp (url):
    global URLList
    global PendingURL
    PendingURL.remove(url)
    H = httplib2.Http(".cache")
    resp,  content  = H.request(url, "GET")
    URLList.append(url)
    return RegLinks.findall(content)

def GetUrls (Result):
    global PendingURL
    for R in range(len(Result)):
        URL = RegURL.findall(Result[R][0])
        if URL <> []:
            if URL not in PendingURL:
                PendingURL.append( URL[0])

while (len(URLList) < 10):
    try:
        GetUrls(LoadHttp(PendingURL[0]))
    except:
        print "Something broken, Ignoring it cuse I'm lazy"

for A in PendingURL:
    if A not in PendingURL:
        URLList.append(A)

file = open("urls.txt", "w")
for U in URLList:
    file.write(U+"\r\n")
file.close()

Posted in Software | Comments (0)

Linux foundation says boycott the FAT file system!

April 2nd, 2009

Read it here [non-working link removed] basically Microsoft can’t be trusted to follow up on there promises of openness so we should stop using there technology. That being said I have nothing that uses FAT and would have to wonder at how widespread it really is?

Posted in Software | Comments (0)

Radix Sort revisited.

March 22nd, 2009

Went back and looked at the radix sort and found that it when sorting say 10,000,000 3 digit numbers it can use almost a gig and a half of ram. To try and fix this I changed the ArrayLists to Queues so that an item is only moved to another queue not copied to another queue, I also stopped copying the items to sort into a new variable at the start of the function it was a waste. The old Radix sort used a gig to a gig and a half of ram on average the new version uses 600mb to 800mb on average. Both run in linear time with similar performance.

Not really any point to this yet just seeing if I could make it better. There’s still probably a million improvements to make but this is what I got so far.

Provided in c#/mono once again.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace RadixSort
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Random rand = new Random(System.DateTime.Now.Millisecond);
            int items = Convert.ToInt32(args[0]);

            Queue Items = new Queue();
            int c = 0;
            while (c <= items)
            {
                Items.Enqueue(rand.Next(0, 999));
                c++;
            }
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            Items = RadixSort(Items, 3);
            sw.Stop();
            Console.WriteLine("Sorted in :: " + sw.Elapsed.ToString());
        }
        static Queue RadixSort(Queue Items, int Digits)
        {

            int Digit = Digits - 1;
            while (Digit >= 0)
            {
                Queue Zero = new Queue();
                Queue One = new Queue();
                Queue Two = new Queue();
                Queue Three = new Queue();
                Queue Four = new Queue();
                Queue Five = new Queue();
                Queue Six = new Queue();
                Queue Seven = new Queue();
                Queue Eight = new Queue();
                Queue Nine = new Queue();
                int UpperLimit = Items.Count;
                int counter = 1;
                while (counter < UpperLimit)
                {
                    int i = Convert.ToInt32(Items.Dequeue());
                    counter++;
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '0')
                    {
                        Zero.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '1')
                    {
                        One.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '2')
                    {
                        Two.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '3')
                    {
                        Three.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '4')
                    {
                        Four.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '5')
                    {
                        Five.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '6')
                    {
                        Six.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '7')
                    {
                        Seven.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '8')
                    {
                        Eight.Enqueue(i);
                        continue;
                    }
                    if (i.ToString().PadLeft(Digits, '0')[Digit] == '9')
                    {
                        Nine.Enqueue(i);
                        continue;
                    }
                }
                Items = new Queue();
                foreach (int i in Zero)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in One)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Two)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Three)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Four)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Five)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Six)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Seven)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Eight)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Nine)
                {
                    Items.Enqueue(i);
                }
                Digit--;
            }
            return Items;
        }
    }
}

Posted in Software | Comments (0)