Skip to content
Jul 7 10

Ubuntu “Mac” Dock

by Code Dude

Recently, I’ve been looking around for a good program that replicates the Mac OSX dock.

The first thing I found was a program called Avant Window Navigator. I installed this and although I was reasonably pleased with it, it lacked some important features. These included easy drag and drop onto and off of the dock and also a quick responding intellihide which hides the bar when a window is over it and then shows it again when you move your mouse to the bottom of the screen. Avant Window Navigator was some reason had buggy support for drag and drop and I also had to wait a second or two for the dock to appear when in intellihide mode-rather annoying.

Then I found Docky which promotes itself as “The finest dock no money can buy.” Simply open the Ubuntu Software Center and search for “Docky”. Once you have located it click install and you’re on your way to a better dock.

Unlike AWN (Avant Window Navigator), Docky has seamless drag and drop support and their intellihide feature is perfect. The instant you hover over the bottom of your screen, up pops Docky…very time saving.

Docky allows you to customize the dock by giving 6 theme options, 4 dock hiding modes, variable icon sizes and the option to use “3D Mode”.

It also comes with what it calls “Docklet”-little apps that run in the dock and perform certain tasks such as email alerts, battery moniter, and CPU moniter, among others.

Another thing I found interesting was the ability to add multiple docks with the click of a button. I’m not sure I’d ever use that, but an interesting feature none the less.

VN:F [1.4.8_745]
Rating: 10.0/10 (1 vote cast)
Apr 7 10

Where are you?

by admin
javascript:(function(){var d,s,a,h,gc;d=document;s=function(){gc=google.loader.ClientLocation.address;alert('You\'re in '+gc.city+' '+ gc.region+', '+gc.country+'.'); };if(typeof(google)!==undefined){h=d.getElementsByTagName('head')[0];a=d.createElement('script');a.src='http://www.google.com/jsapi';a.onload=s;h.appendChild(a);}else{s();}})();



Click here to copy the code / bookmarklet.


Copy and paste the above code into your addressbar, then press enter, and it’ll tell you where you are.
Try it!
It’s a fun prank to scare anyone if you give it to them.

VN:F [1.4.8_745]
Rating: 8.5/10 (6 votes cast)
Mar 11 10

nil.

by admin
hi i'm nil
and not .
but also
not lots
chillnil?
but not
dill nil?
i'm just
nil.
VN:F [1.4.8_745]
Rating: 10.0/10 (4 votes cast)
Feb 24 10

Flashcards – Linux

by Iain

Here is a small program to help study Spanish words, by iterating them through a screen using a very simple memorization algorithm. (Repeating the 2nd to last seen card)

It will work with any short word-definition memorization.

VN:F [1.4.8_745]
Rating: 10.0/10 (1 vote cast)
Feb 14 10

Upcoming Changes

by Iain

I’m considering migrating this single blog into two seperate blogs.

One personal, with more essays, pictures, art, etc., while this one will have more code, technical stuff, ramblings about Google, and the such.

What are your thoughts? I’ll setup redirects, don’t worry!

VN:F [1.4.8_745]
Rating: 9.7/10 (3 votes cast)
Feb 14 10

Very Basic PHP ORM

by Iain

Recently, I’ve needed to go back to PHP, and decided to forgo an full ORM engine instead to use PHP PDO functions, and a little class trickery.

I wanted something that’s easy to call, and allows me to setup the database, setup variables, and return an array -> object result.

PHP 5 introduced quite a bit of OOP methods, tricks, and functions. Although PHP still largely is a functional, procedural based programming language, its support for objects is getting slowly better.

Regarding the ORM, I decided to make two classes, (which could be expanded to more, I might end up with two in the final process). One contains a bunch of functions which build SQL queries from a $args array, and class variables. That way, the queries can be changed in one central place, and can be formulated with the database.

The other class, the database class, takes care of connecting to the database, calling the method within the other class to build the query, execute the query, and return the result as objects in an array.

Pretty simple– but it took some time to remember all the functions and work around the class structure, Ruby is so much nicer to manipulate classes. PHP lambdas are very poor.

Here is the code for the Database Controller:

class DBRunner {
    public $db = array('name'=>'dbname', 'user'=>null, 'password'=>null);
    public $dbdriver = null;
 
    public function __construct(){
        if (!$this->dbdriver){
            $this->connect($this->db);
        }
    }
 
    private function connect($db){
        try {
             $this->dbdriver = new PDO('mysql:host=localhost;dbname='.$db['name'],$db['user'], $db['password']);
        } catch(PDOException $e){
             echo('Error Connecting to DB: '+$e); //Please use for development ONLY. Handle properly in production.
        }
    }
 
    public function __destruct(){
        $this->dbdriver = null; //Closes the PDO Connection
    }
 
    public function __call($method_name, $args){
        if (method_exists(Model, $method_name)){ //If our method exists in the Model class
            foreach ($args as $arg){ //Simple Escaping
                if (is_string($arg)){
                    $args[$arg] = mysql_escape_string($arg);
                }
            }
            $model = new Model; //Make a new 'model' class
            $model->args = $args; //Set the args
            $sql_string = $model->$method_name(); //Call the method to get the query
            if ($this->statement = $this->dbdriver->query($sql_string)){
                $this->result = array(); //Build Results
                foreach($this->statement->fetch(PDO::FETCH_OBJ) as $object){
                    array_push($this->result, $object);
                }
                return $this->result; //Return Results
            } else {
                echo('Database Error - '); //Error Debugging - Development
                print_r($this->dbdriver->errorInfo());
            }
        } else {
            throw new Exception('Database Method Not Found');
        }
    }
}

And example code for the Model class:

class Model{
    public $args;
    function getAllPeople(){
         $ids = implode(',',$args['ids']);
         return "SELECT name, email, pic FROM people WHERE id IN ({$ids});"
    }
}
VN:F [1.4.8_745]
Rating: 10.0/10 (3 votes cast)
Feb 6 10

Wordpress Quick Tip

by Code Dude

There are times when you might want to display your blog posts on a page other than the blog page in Wordpress. To successfully do this, requires a short piece of PHP code. For example, you could show your latest work on the homepage on your website. Here’s the code I used to show my latest work on a portfolio I was building for myself.

There is however, something else that made this extra hard. I wanted to integrate it with the Jquery Fancybox plugin. To do required some extra code that didn’t make things simpler.

The basic code outline for using Fancybox for your images is this:

<a href="the url to the normal sized version of the image" title="The name of the imageā€ class="zoom">
<img src="the url to thumbnail sizes version of the image" />
</a>

This presents some problems with integrating this into Wordpress. Here how I changed it to work with Wordpress posts.

<?php $postslist = get_posts('numberposts=3&order=ASC&orderby=title'); 
	foreach ($postslist as $post) : 
	setup_postdata($post); ?> 
	<div class="project">
		<a class="zoom" 
                      rel="group"
                      title="<?php the_title(); ?>"
                      href="wp-content/themes/starkers/style/images/<?php the_title(); ?>.png">
		<?php the_content(); ?>
	        </a>
	<h4><?php the_title(); ?></h4> 
	</div>			
<?php endforeach; ?>

The first 4 lines are the php that grab the posts. (Note I set it to show the 3 latest posts.)
In the 5th line I enclose each post in a div with an id of “project”.
In the 6th line, there are the basic Fancybox classes that make it work in this particular image.
On the 7th line, I set the name of the image to the title of the post
On the 8th line, I set the url of the normal sized version of the image, in this case it was an image in the theme’s image folder. Notice how I used “the_title();” in the url to make it dynamic for each post.
On the 9th line I just set it to grab the content of the post
10th line-closing out the link
On the 11th line I grab the title of the post
And then close the div and end the foreach statement.

There is one thing you have to do manually to make this work. Set a unique category for the posts to be used here. In this case I used the category “1″

Also, the body of the post must only have the small version of the image in it.

Pretty cool, heh?

VN:F [1.4.8_745]
Rating: 9.3/10 (4 votes cast)
Feb 4 10

The Evolution of a Programmer

by Iain

The Original Python Version

In some ways, it shows the differences between the methods and reasons of different programmers.
Personally, I like

def fact(x):
    return x > 1 and x * fact(x - 1) or 1
print fact(6)

out of them all. (or would write).
The Lambda version sacrifices clarity in variable names, and understood logic.

The Ruby Version

# The evolution of a Ruby programmer
 
def sum(list)
  total = 0
  for i in 0..list.size-1
    total = total + list[i]
  end
  total
end
 
def sum(list)
  total = 0
  list.each do |item|
    total += item
  end
  total
end
 
def sum(list)
  total = 0
  list.each{|i| total += i}
  total
end
 
def sum(list)
  list.inject(0){|a,b| a+b}
end
 
class Array
  def sum
    inject{|a,b| a+b}
  end
end
 
def sum(list)
  list.reduce(:+)
end

And, of course, there’s always using StackOverflow to find a good technique and build upon it.
For ruby, also, the rubydocs are invaluable for refactoring. Lots of great built-in stuff.

VN:F [1.4.8_745]
Rating: 10.0/10 (2 votes cast)
Feb 3 10

Ruby DSL – Fetching a Table

by Iain

Why Ruby Rocks

Ruby is a great programming language for writing DSL languages. It allows for core modifications, and, notably, supports blocks of code to be passed into methods as parameters. This, along with a loose and intuitive syntax, makes it easier to write a clean and easy-to-use interface for a class.

The problem with Tables

Tables are often used to show large amounts of information in HTML, but they aren’t easily searchable, combinable, and querable. Tables in a database are all of the above. If a table online could easily be converted to a database table, then it would be easier to analyze, and view over time. Copying the table by hand is impractical, but tables can be parsed by a number of libraries.

Why Nokogiri Rocks

Nokogiri is Ruby library that parses XML-based formats, including html, quite well.
It allows for xpath expressions, and css expressions. For this implementation of a table parser, I chose to use xpath. It is a more powerful parent of css, and it allows for more complex queries, which make dealing with unmarked and messy html easier. If you don’t know xpath, a good walk-through can be found at W3schools.

So, gimme the code

Here’s the library code for the parser:
(Download)

#!/usr/bin/ruby
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'time'
require 'pp'
 
class TableParser
  attr_accessor :rows
  alias :to_s :rows
  def initialize(doc)
    @doc = doc
    @cond = []
  end
  def go(&block)
    self.instance_eval(&block)
    @output = get_rows
    run_after_hook
    @output
  end
  def to_s
    @output
  end
  def save!(*args)
    @db = has_db(*args)
  end
  def run_after_hook
    @db.insert(@output) if @db
  end
  def has_db(db, collection) 
    require 'mongo'
    Mongo::Connection.new.db(db)[collection]
  end
  def get_rows
      @rows.collect do |row|
       row_levels = {}
       flag = false
       @cond.collect do |name, xpath, block|
         unless ((xpath.nil? || xpath.empty?) && !!block)
          column = row.at_xpath(xpath+'/text()').to_s.strip
          flag = true if column.empty?
        end
        column = convert_column(block, column) if block 
        row_levels[name] = column
       end
       next if flag
       row_levels
     end.compact!
  end
  def convert_column(block, column)
    if block.is_a? String
     column.instance_eval(block)
    elsif block.is_a? Proc
       block.call column
    else
      case block
        when :int
          column.gsub!(/[^0-9]/, '')
          column.to_i
        when :float
          column.gsub!(/[^0-9\.]/, '')
          column.to_f
        else
          column
      end
    end
  end
  def using_table(xpath)
    @rows = @doc.xpath(xpath)
  end
  def fetch(name, location, block = nil)
    @cond.push [name, location, block]
  end
  def reject(xpath, no = true)
    eval "@rows.reject{|tr|#{no ? '!' : '!!'}tr.at(xpath)"
  end
end
 
class TableFetcher
  attr_accessor :table, :doc
  def get_page(uri)
    @table = []
    page = open(uri)
    @doc = Nokogiri::HTML(page)
  end
  def get_table(&block)
    table_parser = TableParser.new(@doc)
    @table.push table_parser
    table_parser.go(&block)
  end
end
 
if __FILE__ == $0
  unless File.exists? ARGV[0]
    puts 'Usage: Use another file to specify rules.'
    puts 'You can use an argument to include a file.'
  else
    load ARGV[0]
  end
end

It’s the library that takes your instructions, and provides an interface to Nokogiri, suited to mongodb and HTML tables.

Sample Usage:

Say, I needed to capture an HTML table to a mongodb database for quick searching, I could use the following code:

require 'get-table.rb'
 
fetcher = TableFetcher.new
fetcher.get_page('http://www.science.co.il/PTelements.asp')
elements = fetcher.get_table do
  fetch :number, 'td[1]', :int
  fetch :weight, 'td[3]', :float
  fetch :name, 'td[4]'
  fetch :symbol, 'td[5]'
  fetch :electron_configuration, 'td[12]'
  fetch :ionization_energy, 'td[13]', :float
  using_table '//table[@class="tabint8"]/tr[td[13]]'
  save! 'chemistry', 'periodic_elements'
end
pp elements

What does this do?

The first line requires the beforementioned get-table.rb library.
The second line is grabs the webpage, and the third and remaining calls the actual parser.
The lines after the get_table do block specify the table, in xpath, and provide types for conversion.

There is some hidden power in the third argument. If you pass the symbols: :float, :int, it’ll format the database row, or your returned hash, to that format. If it’s a strong, it’ll eval that string in the current context. Therefore, providing chomp will result in column.chomp, and leading and trailing whitespace will be removed. If you want to use a block instead, pass a lambda { |column| Time.parse(column) } or a Proc.new { |col| col.split(',') } into the parameter, to format that row.

And that’s all! I’ll be posting a more detailed overview on how to write a DSL in ruby at a later date. I hope you liked it.

VN:F [1.4.8_745]
Rating: 10.0/10 (3 votes cast)
Jan 8 10

Photos of the Snow

by admin

Picture of the Majestic Snow:

To not bother you with more than necessary….

Snow falling between the trees.

The wonderful beautiful blanket of snow showered atop the mountain today and yesterday, bringing an exuberant delight to those there.

Here are the remains of the dwaning fall.

VN:F [1.4.8_745]
Rating: 7.5/10 (4 votes cast)