Thursday, December 25, 2008

Ruby Ternary Search Tree

Simple Ruby Ternary Search Tree Implementation.

Currently supports:


  • Insertion (insert)

  • Search (search, node)

  • Printing (to_s)



git clone at: http://github.com/giancarlo/algorithms.git

Wednesday, December 10, 2008

Ruby 1.9 C Api Extensions Guide

I am writing a guide on the Ruby (SVN) C API. You can see it here: http://coaxialhost.com/tutorials/writing_ruby_extensions.html.

Expect more stuff to be added later.

New Mirror Blog and Theme

I have created a wordpress blog in my own server which will eventually replace this site. The blog is at http://cpb.coaxialhost.com.

This new blog has a better format and will implement new features in the future.

Friday, November 21, 2008

Embed Fonts in HTML document using PHP and Javascript

I wrote a php + js script to replace HTML markup with formatted text in the form of images. The script is called PHPJSFont and it is available at http://code.google.com/p/phpjsfont.

What it does is simple: the Javascript code replaces the text inside HTML tags with an image generated by the PHP script.

Currently it depends on JQuery and PHP 4+ compiled with the GD extension and TTF support.

It should be fairly simple to use, as in:


PJF.replace("h2");
PJF.replace("#topmenu UL > LI");
PJF.replace("h1", { size: 20, color: [255, 0, 0] });

Saturday, November 15, 2008

Install Intel Compiler(icc) in Ubuntu 8.10

To install icc in Ubuntu:

  1. Download icc from Intel website

  2. tar -zxvf the file.

  3. Run 'install.sh'.

  4. Follow the installer instructions.

  5. When it is done add this line to your ~/.bashrc (or initialization script):
    source /opt/intel/Compiler/11.0/069/bin/iccvars.sh ia32
    Replace ia32 with your platform: (ia32, intel64, ia64)

  6. Log off and log in and that is it. You can test it with icc -v

  7. To use icc with a configure script use ./configure CC=icc


NOTE: If you get a libimf.so error like "file does not exists" while using sudo, you will need to write a bash script adding "source /opt/intel/Compiler/11.0/069/bin/iccvars.sh" and the program you are trying to run.

Wednesday, October 1, 2008

Ruby 1.9 Blocks Notes



  • Every function can accept a block.

  • Kernel.block_given? will tell you if a block was passed.


  • def test
    a = 42
    yield(a) if block_given?
    end

  • To assign the block to an argument, you add an ampersand (&) in front of the last argument of your function. This will affect performance.

  • You can call the block inside the function using yield or Proc.call like this:


  • def test(&block)
    a = 42
    yield(a) # or block.call(a,b)
    end

  • yield calls and passes the arguments to the block.

  • block.arity will tell you the number of arguments a block can accept

  • If you have a recursive function accepting a block, you can pass the block to it using '&'.


  • def recursive_function(&block)
    # Do stuff
    recursive_function(&block)
    # pass to other functions accepting blocks
    10.times &block # will run block 10 times
    end

  • If you use the return keyword inside a block, it will return the value and exit the function binded to the block, which is the one that created it.


  • def bl(&block)
    yield
    end

    def test
    bl { return }
    puts "Hello" # this will not be executed.
    end

  • You can use break to return a value inside a block and stop iterating.


  • def bl(&block)
    (0..10).each &block
    end

    def test
    # This block will stop iterating at 5 and return true.
    bl { |x| (break true) if (x == 5); false }
    end

Thursday, September 4, 2008

Using SyntaxHighlighter with Blogger or Blogspot

I added Syntax Highlighting capabilities to this blog and here it is how i did it. You might need another server where to put your files:

  1. Download SyntaxHighlighter from http://code.google.com/p/syntaxhighlighter/downloads/list.

  2. Add this to your Edit HTML code in Layout:

  3. <script language='javascript' src='http://www.url.com/Scripts/shCore.js'></script>
    <script language='javascript'>
    window.onload = function() {
    dp.SyntaxHighlighter.ClipboardSwf = 'http://www.url.com/Scripts/clipboard.swf';
    dp.SyntaxHighlighter.BloggerMode();
    dp.SyntaxHighlighter.HighlightAll('code');
    }
    </script>
    <link href='http://www.url.com/Styles/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/>

  4. Put the code you want to highlight inside a <pre> tag like this:

  5. <pre name='code' class='language'>
    code;
    </pre>

  6. Make sure you replace the url and also '<' with &lt; if you are using HTML code

  7. Add this to the top of your post:

  8. <script language='javascript' src='http://www.url.com/Scripts/shBrushXml.js'></script>

  9. Replace the script name with the one used for your language.



For more information and language list visit http://code.google.com/p/syntaxhighlighter/w/list.

Wednesday, September 3, 2008

CSS Sprites



What a wonderful idea, simple and easy. A great way to reduce HTTP GET's.

How to use it in your application:


  1. Find/Buy a good icon set (like tango), try to find a transparent one.

  2. Place a div where the icon would be located and set its onclick event to whatever you want it to do.

  3. create a css class for the icon:


  4. .icon-name {
    display: block; height: 32px; width: 32px;
    background: transparent url(icon.png) -(x)px -(y)px no-repeat;
    cursor: pointer;
    }

  5. Change height, width and (x) and (y) position with the respective values.

  6. assign the class to your div.


Pretty easy.

Ruby on V8



What a great idea, someone put together a hacked version of ruby for the v8 engine based on hotruby.js. It is not a real compiler but it works.

Now, Who is going to make a real port of Ruby to the v8 engine? Sounds like an interesting project. Just what we need, another ruby virtual machine/interpreter!!

Tuesday, September 2, 2008

Chrome


Chrome is fast. Even though I had problems installing it on my laptop win xp sp3, I managed to get a copy of the exe file from http://cache.googlevideo.com/chrome/install/149.27/chrome_installer.exe. I run it and it installed fine. Not sure what the problem was because other people with sp3 could install it just fine. It was probably a disabled service.

Cool things to try in the address bar:

about:network - Network Tools
about:stats - Shhh! This page is secret!
about:cache - Cache.
about:histograms - Data about chrome features.
about:plugins - Installed Plug-ins.
about:dns - DNS records.
about:version - Google Chrome browser version.
https://gmail.com - This one is pretty bad actually... No one is perfect.

To access google's task manager: right click in the blue space at the top and click Task Manager.

Bad news: still doesn't work on linux(nor wine) or macs.

Friday, August 29, 2008

Understanding a Crazy Programmer



Found this on the net. If you have any problems with a programmer in your team, this article/blog might help.

Learning Lisp - Do you know any programmers that exhibit these personality traits?

Tuesday, August 5, 2008

Catching Ctrl+C in Ruby 1.9

Ctrl+C sends a SIGINT signal to the kernel.
To catch it and execute code we use:
Kernel.trap('INT') { code }
Remember to call Kernel.exit if you want to terminate the execution of your ruby script. Kernel.trap can also catch other signals. For more information visit: Kernel.trap

Saturday, August 2, 2008

Storing Passwords securely


The best way to store a password: Salt it then Hash it.

To salt it add random characters to the password entered by the user. Remember we are going to need those random characters later so save them somewhere you can retrieve them later. I would say insert them in fixed locations in the hash. To hash it use the md5 or sha1 function. You can find these functions in the encode ruby extension.

To authenticate the user, you will need to pull the hash associated with the username, retrieve the salt characters, apply them to the password entered by the user, hash it and compare.

Is there a better way?

Tuesday, July 29, 2008

Terminal Awesomeness


The best way to make your desktop look nice is to add true transparency to your terminals. I got urxvt with true transparency enabled working with xcompmgr and it looks wonderful.

xcompmgr is a lightweight composite window manager.
urxvt is an xterm-like terminal lightweight and fast.

I'm using openbox as a window manager and hsetroot to set my desktop wallpaper. These are the contents of my ~/.config/openbox/autostart.sh :

hsetroot -fill ~/Desktop/desktop.jpg &
xcompmgr &
rxvt &
docker &


"docker" takes care of the system tray.

To enable transparency in urxvt you need to add these lines to your ~/.Xresources file:
URxvt*depth: 32
urxvt*background: rgba:0000/0000/0000/cccc
URxvt*background: rgba:0000/0000/0000/cccc
URxvt*foreground: green


Change the background and foreground to whatever color you want.

I believe desktop managers like kde or gnome are overrated. Openbox is great and doesn't consume your precious resources so u can use them for more important things like compiling code.

Friday, July 25, 2008

More VIM stuff


Set tab size:
set tabstop=2
Quick Write and quit
:wq
If you press Ctrl+S while on a terminal and it freezes then press the following to unfreeze:
Ctrl+Q
Working with tabs
:tabe file # Opens File
:tabn # goes to next tab
:tabp # goes to previous tab
:q # closes current tab
gt # will take you to the next tab
gT # will take you to the previous tab

Auto completion
Ctrl+N Ctrl+P
You can also invoke make and grep within vim
:grep args
:make

If you work on windows (gvim.exe) place your vimrc file in the VIM exe directory. You might need to set the environment variable VIM to the path where gvim.exe. Name your vimrc file as _vimrc

Moving to VIM


I decided to make vim my default text editor. Here are a couple of tips:

To get syntax highlighting in vim, add the following to your ~/.vimrc file or enter while editing (command mode, remember to press ':' before entering):
set background=dark # if your console background is dark..
syntax on

To get line numbers:
set nu
To split the screen in 2
split
vsplit # Vertical Split

To Move from split windows
Ctrl+W+(direction)
Open a file
open file
Close a file
close
Search Reg Ex
/regex
Goto Line Number
:number
Search word under cursor
*

I will post more eventually... vim kicks emacs butt by the way.

Friday, July 18, 2008

Ruby 1.9 C API - Object Instances


To Create a new instance of an object with class Class we will do this:

VALUE obj;

obj = rb_obj_alloc(Class); // Allocate space and create new instance
rb_obj_call_init(obj, 0, 0); // We call the initialize method for the object

Remember rb_obj_alloc() does not initialize the object and will seg fault if you use any custom data types in the object.

The 2nd and 3rd parameters of rb_obj_call_init() are the argument count (argc) and the constructor parameters array ( VALUE* ).

Friday, July 11, 2008

Ruby C API - Classes I


To create a class:


VALUE rb_define_class("name", parent_class);
VALUE rb_define_class_under(module_or_class, "name", parent_class);


To create a method:

rb_define_method(class, "name", c_function, argc)

argc is the number of arguments of the function, not including the first parameter of the c_function which would be the instance variable. Default Parameters can be implemented by setting this number to negative. (-1 would mean variable number of parameters, -2 would create an array to store the arguments)

"name" is the name of the method in ruby, for setter methods you would add the = to the name just like in ruby ( ie "name=" ). The same with operator for the [] operator you will use the string "[]" or "[]=".

The format of a ruby function accepting a variable number of arguments (argc = -1) would be like this:


VALUE function( int argc, VALUE* args, VALUE instance );


argc is the number of arguments passed.
args is an array containing the arguments.
instance is the instance of the object.

The format for a ruby function accepting an array of arguments (argc = -2) :


VALUE function( VALUE instance, VALUE array_of_arguments);


To access instance variables you will use this two methods:


rb_iv_get(instance, "variable");
rb_iv_set(instance, "variable", new_value);


stay tuned for part II.

Thursday, July 10, 2008

Firefox Download Antivirus??


I recently noticed that firefox stopped responding for a couple of seconds every time i downloaded a file. The cause was the new virus scan feature. To disable this ( I tried Tools/Options but couln't find anything ) go to about:config and search for browser.download.manager.scanWhenDone then set it to false.

Sunday, July 6, 2008

Ruby 1.9 C API - Exceptions I


rb_raise(exception_object, string_message);
rb_raise will try to call exception_object.new and display string-message as the exception error message.

Some of the built-in exceptions that can be raised are:
rb_eArgError
rb_eEOFError
rb_eException
rb_eFatal
rb_eFloatDomainError
rb_eIndexError
rb_eInterrupt
rb_eIOError
rb_eKeyError
rb_eLoadError
rb_eLocalJumpError
rb_eNameError
rb_eNoMemError
rb_eNoMethodError
rb_eNotImpError
rb_eRangeError
rb_eRegexpError
rb_eRuntimeError
rb_eScriptError
rb_eSecurityError
rb_eSignal
rb_eStandardError
rb_eStopIteration
rb_eSyntaxError
rb_eSysStackError
rb_eSystemCallError
rb_eSystemExit
rb_eThreadError
rb_eTypeError
rb_eZeroDivError

Saturday, July 5, 2008

Listing RSS items with PHP in 3 lines



$rss = simplexml_load_file("rss feed url");
foreach ($rss->channel->item as $k)
echo $k->title . "\n";

In 4 lines with HTML formatting!!

$rss = simplexml_load_file("blog rss url!");
foreach ($rss->channel->item as $k)
$rss_list .= "<li>" . $k->title . "</li>\n";

$index_rss = "<ul>$rss_list</ul>";

Ruby 1.9 C API - Accepting Blocks


Executing the Block
rb_yield(Qnil);
Replace Qnil with the parameters you wish to pass to the block. The Result of the block is returned.
rb_block_given_p();
This function will tell you if a block was passed. Blocks are not counted as parameters so if your function only accepts a block then you need to specify 0 as the number of parameters.

Friday, July 4, 2008

Ruby 1.9 C API !! - Internal Structures


To access the internal structure of any Ruby object, 'ruby.h' defines the following macros:
#define RBASIC(obj) (R_CAST(RBasic)(obj))
#define ROBJECT(obj) (R_CAST(RObject)(obj))
#define RCLASS(obj) (R_CAST(RClass)(obj))
#define RMODULE(obj) RCLASS(obj)
#define RFLOAT(obj) (R_CAST(RFloat)(obj))
#define RSTRING(obj) (R_CAST(RString)(obj))
#define RREGEXP(obj) (R_CAST(RRegexp)(obj))
#define RARRAY(obj) (R_CAST(RArray)(obj))
#define RHASH(obj) (R_CAST(RHash)(obj))
#define RDATA(obj) (R_CAST(RData)(obj))
#define RSTRUCT(obj) (R_CAST(RStruct)(obj))
#define RBIGNUM(obj) (R_CAST(RBignum)(obj))
#define RFILE(obj) (R_CAST(RFile)(obj))
#define RRATIONAL(obj) (R_CAST(RRational)(obj))
#define RCOMPLEX(obj) (R_CAST(RComplex)(obj))


The most important are:
struct RFloat {
struct RBasic basic;
double float_value;
};

struct RBignum {
struct RBasic basic;
union {
struct {
long len;
BDIGIT *digits;
} heap;
BDIGIT ary[RBIGNUM_EMBED_LEN_MAX];
} as;
};

struct RBasic basic;
union {
struct {
long len;
char *ptr;
union {
long capa;
VALUE shared;
} aux;
} heap;
char ary[RSTRING_EMBED_LEN_MAX];
} as;

To Access the value of a float number you will call:

RFLOAT(ruby_value)->double_value;


Fixnum's (Integers) are stored differently:

10 in Ruby => (10 >> 1) in C
10 in C => (10 << 1 | 1) in Ruby
-10 in Ruby => (10 >> 1) in C
-10 in C => (10 >> 1 | 1) in Ruby (0xffffffed)

Bignums are usually 8 bytes (long long).

Friday, June 27, 2008

Finish What You Start


As usual we will go straight to the point.

Three Ways to finish things:
  • Throw it away. Put an end to it. Example: Your sudoku game. Seriously is not that important.

  • Do it yourself. But really, do it.

  • Delegate it. Find someone to do it for you, your friend, or that developer from india. Make sure that you find someone who you can trust.


Why is it important?
Sense of accomplishment and tranquility. Yes, now you can get that out of your mind. As embarrassing or ridiculous you may think it is; it is now out of your head.

How is it relevant to programming?
Finish that project you started a couple of days ago and gave up because it turned too complicated. Spend an entire night finding the solution. It will be more rewarding than what you think and you will probably learn more than what you intended.

Crazy Googled Internet Quote
"The way to achieve inner peace is to finish all the things you've started."

Monday, June 23, 2008

PHP Segmentation Fault

I ran around this problem a couple of times, and recently i spent more than 20 mins trying to figure out why my php page was seg faulting. Well now I'm going to document it.

To make it simple, this code will give you a seg fault:

class A
{
function __construct()
{
new B;
}
}

class B extends A
{

}

new A;


Don't create new objects from classes that inherit from the class you are creating the object. Yes sounds confusing, and probably it makes no sense but i think the code above is enough to explain it.

Monday, June 9, 2008

New Company Website


My new website is up at : http://coaxialhost.com Handcoded HTML, JS and CSS. Fun to make but is it Google friendly? I hope it is.

Saturday, June 7, 2008

Validating (X)HTML using Ruby


This function returns validation messages from the w3c website (http://validator.w3.org)

require 'net/http'
require 'uri'

class XHTML

VALIDATOR_URL = 'http://validator.w3.org/check'
XHTML_STRICT = 'XHTML 1.0 Strict'
XHTML_TRANSITIONAL = 'XHTML 1.0 Transitional'
XHTML_FRAMESET = 'XHTML 1.0 Frameset'

# Returns validation messages
def XHTML.validate(what, xhtml_version=XHTML_STRICT)
post_data = {
'fragment' => what,
'doctype' => xhtml_version
}

r = Net::HTTP.post_form(URI.parse(VALIDATOR_URL), post_data)

return r.body
end

end



We could try to parse the results into an array... maybe in the future.

Friday, June 6, 2008

Creating Custom Ruby Accessors

Built In Ruby Accessors

attr_reader :a # Generates a reader/get function:
#def a
# @a
#end

attr_writer :a # Generates a writer/set function
#def a= (value)
# @a = value
#end

attr_accessor :a # Generates Both get/set functions



Creating Custom Accessors

We need to define a function in the main Module class:

class Module
def custom_accessor(*symbols)
symbols.each do |symbol|
class_eval "
# Here we would insert the code that we want to generate.
"
end
end
end


And this is it. Now we can use our custom accessor like this:

custom_accessor :accessor

Friday, May 30, 2008

Ruby Predefined Constants/Variables

Constants
ENV # Hash of environment variables
STDIN # IO stream for standard input
STDOUT # IO stream for standard output, most cases the console
STDERR # IO stream for standard error output
RUBY_VERSION # String containing current ruby version
RUBY_RELEASE_DATE # String containing the date in which ruby was compiled
RUBY_PLATFORM # String containing the platform and compiler used to build ruby
ARGV # Array of arguments used to run the ruby file. ARGV[0] is the first argument, not the name of the file.


Variables
$: # Ruby Include Path
$> # STDOUT
$. # Current Line
$! # Latest error message
$@ # location of error
$_ # string last read by gets
$. # line number last read by interpreter
$& # string last matched by regexp
$~ # the last regexp match, as an array of subexpressions
$n # the nth subexpression in the last match (same as $~[n])
$= # case-insensitivity flag
$/ # input record separator
$\ # output record separator
$0 # the name of the ruby script file
$* # the command line arguments
$$ # interpreter's process ID
$? # exit status of last executed child process
$SAFE # safe level (0-4)
$" # Loaded modules, extensions (also $LOADED_FEATURES)

Sunday, May 25, 2008

Mysql Ruby Extension

Installing in Windows

Download mysql dev files from : http://dev.mysql.com/downloads/mysql/5.0.html
Install them in your hard drive. We only need the include and lib files, not the server. Download the zip package.

Download last mysql-ruby extension from http://tmtm.org/downloads/mysql/ruby/ and extract it.

we run extconf.rb with the following parameters:

ruby extconf.rb --with-mysql-include=/path/to/mysql/include --with-mysql-lib=/path/to/libs

By default the mysql installer saves the lib files in the lib/opt.

To compile the extension:

nmake

Now we should have a valid mysql.so file. We need to get the libmysql.dll from the bin folder of the mysql distribution, you can grab it from the zip version.

To test it:

ruby test.rb [hostname [user [passwd [dbname [port [socket [flag]]]]]]]

Saturday, May 24, 2008

Ruby 1.9 C API - Data Conversion

Ruby -> C


char* RSTRING_PTR(VALUE); /* Ruby String to char* */
int RSTRING_LEN(VALUE); /* String length */
char* StringValuePtr(VALUE); /* Returns string representation of any object */
RSTRING StringValue(VALUE); /* Returns Ruby string representation of any object */
int NUM2INT(VALUE); /* Number to Int */
double NUM2DBL(VALUE); /* Double to Int */
VALUE* RARRAY_PTR(RARRAY); /*Returns the pointer to values of a Ruby Array */
int RARRAY_LEN(RARRAY); /* Returns length of Array */


C -> Ruby

/* Integer to Ruby Number*/
INT2NUM(number);
UINT2NUM(number);
DOUBLE2NUM(double); /* Or rb_float_new(double) */
RSTRING rb_str_new(char*, len); /* Returns ruby string from char* and length*/
RSTRING rb_str_new2(char*); /* Returns ruby string from null terminated char* */


Generating Arrays

VALUE array = rb_ary_new(); /* Create the array */
rb_ary_push(array, VALUE); /* Push data into the array */


Generating a Hash

VALUE hash = rb_hash_new();
rb_hash_aset(hash, VALUE key, VALUE);


Get the type of a Ruby VALUE object
rb_type(VALUE);
Possible Types:

#define T_NONE RUBY_T_NONE
#define T_NIL RUBY_T_NIL
#define T_OBJECT RUBY_T_OBJECT
#define T_CLASS RUBY_T_CLASS
#define T_ICLASS RUBY_T_ICLASS
#define T_MODULE RUBY_T_MODULE
#define T_FLOAT RUBY_T_FLOAT
#define T_STRING RUBY_T_STRING
#define T_REGEXP RUBY_T_REGEXP
#define T_ARRAY RUBY_T_ARRAY
#define T_HASH RUBY_T_HASH
#define T_STRUCT RUBY_T_STRUCT
#define T_BIGNUM RUBY_T_BIGNUM
#define T_FILE RUBY_T_FILE
#define T_FIXNUM RUBY_T_FIXNUM
#define T_TRUE RUBY_T_TRUE
#define T_FALSE RUBY_T_FALSE
#define T_DATA RUBY_T_DATA
#define T_MATCH RUBY_T_MATCH
#define T_SYMBOL RUBY_T_SYMBOL
#define T_RATIONAL RUBY_T_RATIONAL
#define T_COMPLEX RUBY_T_COMPLEX
#define T_VALUES RUBY_T_VALUES
#define T_UNDEF RUBY_T_UNDEF
#define T_NODE RUBY_T_NODE
#define T_MASK RUBY_T_MASK


Iterate through a Ruby Hash
We iterate with the function
rb_hash_foreach(hash, iterator_c_function, extra_value);
iterator_c_function is of the form:
int iterator(VALUE key, VALUE value, VALUE extra);
Remeber VALUE is the same size as a void*, this means we can typecast it into whatever we want.
To tell the rb_ruby_foreach() function to continue we return a ST_CONTINUE in the iterator function. We can also return a ST_STOP, ST_DELETE, or ST_CHECK.

Ruby 1.9 C API - Modules

Creating a module:

VALUE module = rb_define_module("name");

Add methods/functions to a module:

rb_define_method_function(module, "name", c_function, argc);

Now the tricky part is that ruby adds a reference to the module when calling the function. c_function would look like this if it were to accept 1 parameter:

VALUE c_function(VALUE module, VALUE arg);

In this case the argc parameter in the rb_define function should be 1 not 2 as you would expect.

Define a constant:

rb_define_const(module_or_class, "NAME", value);

value is a VALUE.

Friday, May 23, 2008

HOW TO specify GCC binary in configure script

Ubuntu installs gcc 4.2 as gcc-4.2 binary. To tell configure to use gcc-4.2 instead of gcc we use the following parameter

./configure CC=gcc-4.2