What I learned today ?

Ramblings of a programming aficianado

Compile Ruby Script To Exe (MS DOS or Windows)

leave a comment »

Today I spent some time compiling a small ruby script of mine into an executable. Why? well, I don’t have concerns of hiding the code but this was a requirement of one of the users of my script.

I started with a Google search on such compilers. RubyScript2Exe is what I used. After installing it as a gem I got an error. I downloaded the script RubyScript2Exe.RB and tried again. But fate had it – the same error.

C:\Users\mawasthi\Desktop>ruby rubyscript2exe.rb theboringstuff.rb
rubyscript2exe.rb:621:in `replace’: can’t modify frozen string (RuntimeError)
from rubyscript2exe.rb:577:in `block in newlocation’
from rubyscript2exe.rb:505:in `block in newlocation’
from rubyscript2exe.rb:472:in `newlocation’
from rubyscript2exe.rb:505:in `newlocation’
from rubyscript2exe.rb:577:in `newlocation’
from rubyscript2exe.rb:619:in `<main>’

I read about solutions on forums. None helped. Problem was clear (some change in Ruby updated version in which program name will be a frozen string).

Then I got from one of the forums a link to another “less SEO’ed” compiler “ocra”. I installed it -

C:\Users\mawasthi\Desktop>gem install ocra
Fetching: ocra-1.3.0.gem (100%)
Successfully installed ocra-1.3.0
1 gem installed
Installing ri documentation for ocra-1.3.0…
Installing RDoc documentation for ocra-1.3.0…

Worked like charm:

C:\Users\mawasthi\Desktop>ocra theboringstuff.rb
=== Loading script to check dependencies
:: === Including 52 encoding support files (2741248 bytes, use –no-enc to exclude)
=== Building theboringstuff.exe
=== Adding user-supplied source files
=== Adding ruby executable ruby.exe
=== Adding library files
=== Compressing 5678626 bytes
=== Finished building theboringstuff.exe (1391140 bytes)

Written by awmanoj

December 14, 2011 at 8:01 pm

Posted in Ruby

Is it possible that I call function with NULL object without segfaulting?

leave a comment »

Oh yes it is!

While debugging my project at work I came across this interesting piece. Inspector (watch or expressions in visual studio) showed me the variable with which the function was being called was NULL (0×0) i.e. considered invalid and still the function call went fine. This variable was initialized later. I thought this should be one of the weird things that compilers and IDEs do sometimes but no it was not like that and i observed the same behavior with restarting the IDE and changing the compiler.

If your class does not have data associated with it (member variables) then its functions can be called without allocating any memory to it.

e.g. following class and example:

class A
{
public:
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();
}

Then for MS compiler cl.exe, you can call a function from a NULL object as far as you don’t access the variable even if you have defined it.

class A
{
int i;
public:
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();
}

This will SEGFAULT.

class A
{
int i;
public:
void printA() { cout << “A\n” << i; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();

and yes, you can do this in C++ and not Java.

Written by awmanoj

September 18, 2011 at 5:41 pm

Posted in C++, technical

Blank Page on install page of wordpress & resetting the forgotten root password for MySQL

leave a comment »

WordPress installation has been painless for me always but today it got me into trouble. Well, it was not wordpress it was mysql. Well, well not even mysql me myself. I forgot the root password. Whole story here -

I was setting up wordpress. It showed me a blank page while accessing wp-admin/install.php page for installation. I was left wondering!

Then I added in wp-config.php the following line:

define('WP_DEBUG', true); // debugging mode: 'true' = enable; 'false' = disable

This enabled debugging logs and I was able to get away from the “blank page” problem. It showed the error due to which the blank page was coming. WordPress could not connect to Database.

This got me to look into phpmyadmin and that gave the issue:

#1045 – Access denied for user ‘root’@'localhost’ (using password: YES)

I had put a blank password in the configuration file and hence this error was encountered. I forgot the root password. Following solved the issue:

1. Stop the mysqld service.

2. Start the mysqld service in safe mode  and without reading grant tables

mysqld --safe-mode --skip-grant-tables &

3. Now use the mysql client to connect with the daemon and change the password

MYSQL>UPDATE mysql.user SET Password=PASSWORD(‘MyNewPass’) WHERE User=’root’;

MYSQL>FLUSH PRIVILEGES;

4. Stop the safe mode daemon

5. Start the service normally.

Written by awmanoj

March 2, 2011 at 4:34 pm

Posted in technical

Flex: Storing custom user strings in controls

leave a comment »

Few days back while I was programming on Flex this cool problem came through. Problem was that I created buttons dynamically in the code based on some parameters passed to the function. These parameters would decide the label, id and color of the button. In addition to this there was an information called category which had a contextual meaning to the project I was working on. So it went something like this - 

private function InitializeAndDisplayButton(id:String, label:String, category:String)
{
var b:Button = new Button(); 
b.id = id; 
b.label = label; 
b.addEventListener(MouseEvent.CLICK, buttonHandler);
}

private function buttonHandler(event:Event):void
{
var id:String = event.currentTarget.id; 
/* how do I access “category” here */

Now the problem, how do you store the category for each button so that in the button handler you access it through the event? 

Solution I

A naive solution came to mind that I can keep a private map (flash.utils.Dictionary) between id and the category and add an entry corresponding to each id in the function InitializeAndDisplayButton and access it in buttonHandler after extracting “id”. 

Solution II – (topic of this post) 

Another solution is a cool one certainly. Function “SetStyle” takes two parameters and stores them as key-value pairs. We can use this to store any custom user strings (data) in controls. e.g. we can add following line in InitializeAndDisplayButton - 

b.setStyle(“ButtonCategory”, category); 

and access it with following code in function buttonHandler

var id:String = event.currentTarget.getStyle(“ButtonCategory”); 

This looks cool to me! :D  

_

Written by awmanoj

April 7, 2009 at 4:29 am

Posted in Uncategorized

Desktop Twitter – twitter out of the browser

leave a comment »

Desktop Twitter is an Adobe AIR desktop application written in Flex (Actionscript) which I wrote up few days back. It is an attempt to bring the twitter experience out of the browser. Current version of the application that am giving out so it contains minimal features. A screenshot is shown at left. Twitter Rest APIs are quite simple to use and developing any such application becomes painless using them.

 

 

Current set of features include -

1. On entering the user name of the user whose desk twitter page you wish to see, you get the list of thumbnails of friends of this user near the bottom.

2. On selecting any thumbnail you get to see the details of that user. Account information is shown in the right top box, twitter updates are shown in the left big box and thumbnails of the friends of the selected user are shown in the right bottom box. 

Issue Known – On scrolling the list of thumbnails fast, thumbs disappear. This is a bug with Flex and am looking around to fix this ASAP. You can workaround by scrolling really slow. :D

Missing – Help is missing for now but will be available in next release (soon) (Details of the different panels are intended to be clear by the labels provided. ). No caching of thumbnails is done and hence sometimes there may be some delay in loading of images.

Application can be downloaded from here. You will need to install Adobe AIR runtime (takes not more than few seconds) to install (again, not more than a few seconds) and use this application. Please download the application, try it out and report any bugs, suggestions, features at awasthi.manoj@gmail.com.

Written by awmanoj

October 16, 2008 at 7:23 am

Posted in Uncategorized

Extracting full path while uploading a file to server in Flex

leave a comment »

In my free prototyping time I decided writing a simple uploader in AIR (what else?). I could create a working application in minutes using FileReference class and its method browse() (for opening a File Selection Dialog) and upload() method to upload the file.

But something looked odd. I wished to show the user the filepath he has selected in a disabled text box (the good old way..) but FileReference does not have the full path information. Googling helped. It said that “for security reasons full path of a file won’t be available in flash”. Valid. But then it clicked in my mind that I’m developing an AIR application. I talked to a friend, asked him for resolution. And that helped -

Use File intead of FileReference while developing AIR application. It is an extension to FileReference with more functionality (including a getter/setter to the private variable nativepath). Cool!

Thanks Raghu.

Written by awmanoj

January 31, 2008 at 12:03 pm

Posted in Uncategorized

Tagged with , , , ,

A generic binary search implementation in C – thoughts

with 4 comments

Wish you a very happy new year!

This is an attempt to discuss a problem I’ve come across. Some common things that I would like to suggest people going for computer science interviews are -

  • listen to the question with full concentration on every word; avoid wandering for the similar questions that your friend discussed this morning
  • do not assume anything (even if this means asking the dumbest questions, don’t hesistate)
  • if you know the problem and the solution (or you’ve been asked the same or similar question in a previous round of interview), tell them. don’t waste your and their time.
  • break the problem into small tangible subsets; things that you are more comfortable working with (say a problem with million users telephone directory, think of a 50 or 10 users telephone directory or say a problem on a variation of tower of hanoi, think of the implementation of simple tower of hanoi and then move towards the special treatment) or things that are more do-able.
  • think aloud; most interviewers love loud thinking
  • think out of box when you cannot remember (or you do not know) a standard solution (which you are sure exists although). Everyone loves innovative ideas and believe me, they do come.
  • do not make an obvious mistake while writing code. code defensively. check success of every memory allocation or file read.
  • make sure you understand the Big-O notation for algorithmic time-space metric. I’ve seen that computer scientists’ are happy when you come up with more accurate O-notation understanding.
  • think of design issues like portability of code, reentrancy of the code, bottleneck portions of the code (and any trade offs) etc. and discuss these with the interviewer
  • if you can think of more than one solution for a problem, tell them.

Write a program to implement a binary search for generic array whose elements are sorted.

Problem is to write n implementation of binary search algorithm and twist is “generic”. The term generic itself is enough for giving you a clue into the direction of thoughts. Without the “generic” requirement, suppose a binary search algorithm is to be implemented for an array of integers, then signature is:

int binsearch(int a[], int x, int n)

If you are going to implement the algorithm in C, think “void *” and if you are going to implement the algorithm in C++, think templates. Now I discuss here an implementation in C. Well my function should have an array (which will be a ‘void *’ to accommodate an array of any data type), the item to search for (again a void *), the number of elements in the array. What else?

  • We do not have an idea of how to dereference the pointer available to us.
  • we do not have a way to base our comparison on (e.g. this may be an array of structures sorted on an element of the structure (which obviously our algorithm is blind to)).

So we require two more arguments, size of the data structure so that we can do a typecast of ‘void * arr’ to ‘char *’ and for an index ‘i’, jump using the expression ((char*)arr + i*size) to get to the item of interest and a pointer to a function, compare, which will take two ‘void *’ and return -1, 0, 1 just like any compare function. so signature is:

int binsearch(void *arr, void *x, int n, size_t size, int (*func)(void *, void*));

Algorithm itself is not much a problem I think. It works like calculating the “mid” (for 0 to n), and then comparing the mid value with x by:

int p = compare(((char *)arr + mid*size), x);

If p == 1, search in [mid+1, n], if p == -1, search in [0, mid-1] and if p == 0, you happy, go lucky got it!

You can actually edo away with the argument “size” if you make the function signature a bit uglier by pushing the responsibility of dereferencing the arr (void *) to the user. so now your function signature code will be -

int compare(void * /* arr */, int index /* index */, void * /* tosearch */);

But this is dirtier since humans normally are in habit of a ‘compare’ with two parameters. In this new avatar your binsearch becomes -

int binsearch(void *arr, void *x, int n, int (*func)(void *, int i, void*) );

Happy implementation!

Written by awmanoj

January 6, 2008 at 1:01 pm

Posted in Uncategorized

Power of plain text, the power of being simple

leave a comment »

As we see the convergence of technologies through web, I think plain text is going to play a crucial role in delivering a standard cross platform solution for communication. It has already taken the center stage in form of XML. Debate on simplicity (or human side of technology) and performance will, I think, have a positive shift towards the former (people love faster development and simpler use more these days I think.. Rubyist view)

why plain text?

pragmatic programmers answer it with bullets – insurance against obsolescence, leverage (lot of tools available for talking to plain text) and easier testing. and I as always agree.

The concern is there although. Concern is that in addition to being human readable, the text should be human understandable as well. Using names which are semantically correct and contextually relevant is going to act as a substantial catalyst in helping dealing with these plain text files (whether it is a database or configuration file or data-transfer format).

Being always biased towards keeping configuration and databases (good old unix way) I am going to take care of this as a specification in almost all (not everything is driven by me!) development I do. You should also do the same so that your database outlasts your application!

Written by awmanoj

December 22, 2007 at 10:50 am

Posted in linux, Technology

Tagged with , , , ,

Orthogonality and its importance in software development

leave a comment »

I’ve been lately reading The Pragmatic Programmer by Andrew Hunt & David Thomas. Been onto a chapter about decoupling requirement in the development of software, I thought of putting few lines on the weblog. Orthogonality is derived originally from Geometry where it is meant to illustrate two lines which meet at right angles and hence are mutually independent moving in all directions. In software, orthogonality refers to the independence between the modules of the software. e.g. user interface of a software should not have any dependence on Database schema. Decoupling, if not met properly while designing software, can lead to disaster in code maintenance. A decoupled code is better for maintenance because of numerous reasons -

1. Changes are localized and hence development and testing time (and cost) are reduced. Quality also improves since better division of work is possible.

2. Problems are also localized. An issue in one module does not affect other modules and hence fix requires to be done their only (or whole module can be replaced by another implementation altogether).

3. There is more possibility of smaller independent teams (which is ideal for a better coordination)

An interesting introduction into orthogonality is the advent of Aspect Oriented Programming (AOP), a research project at Xerox Parc. As Object oriented programming focusses on the objects and their interaction, Aspect oriented programming focusses on aspects (concerns). AOP lets you express a behavior which would otherwise be distributed throughout the source code. The most obvious example would be logging. Log messages are normally generated by sprinkling explicit calls to some log function throughout the code. With AOP, you implement logging orthogonally to the things being logged. Using the AOP for Java, you could write a log message while entering any method of Class Fred by coding the aspect -

aspect Trace {
advise * Fred.*(..) {
static before {
Log.write(” -> Entering ” + thisJointPoint.methodname);
}
}
}

If you weave this aspect in your code then log messages will be generated and if you don’t, they won’t. Either way, your original source is unchanged.

Towards the end of the discussion is a challenge: Consider large GUI-oriented tools typically available on Windows and small but combinable command line tools used on shell prompts. Which do you think are more orthogonal in design?

What do you think?

Written by awmanoj

December 20, 2007 at 3:16 pm

Building Strings in Ruby

leave a comment »

If efficiency is important to you, don’t build a new string when you can append items onto an existing string. Constructs like str << ‘a’ + ‘b’ or  str << “#{var1} #{var2}” create new strings that are immediately subsumed into the larger string. This is exactly the thing to avoid. Use str << var1 << ” ” << var2; instead.

Written by awmanoj

December 2, 2007 at 5:49 pm

Posted in Ruby

Tagged with , ,

Follow

Get every new post delivered to your Inbox.