List methods from a source file

Sometimes source files can become quite large. This is common mostly in C. But this may happen in other languages too. It makes working with these files particularly hard. Off-course there are IDEs which lists method and properties and what not. But there is a fun way to do the same stuff using python. The regex for the signature of Java methods is, (public|protected|private|static|\s) +[\w\\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;]) You can use this regex in python and have some fun summarizing your Java source files. Here is the script: on Github and via Gist, Cheers!


Advertisements

Read_file_bytes

Yesterday, I needed a tool for reading files as bytes. Hexdump programs generally do some formatting and stuff. I did not want that. I wanted to have a straight forward, simple sweet tool, that simply reads a file and prints it’s bytes. Time required for searching such a tool is indeed greater than the amount of time you can simply write a tool by yourself. I wrote the following:

/* read passed file and show bytes in hex val, consicutive each byte */
/* Released in Public domain by nafSadh.khan */
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
	FILE * pFile;
	int c;
	int n = 0;
	if (argc < 2) return 0;
	if (strlen(argv[1]) < 1) return 0;

	pFile = fopen(argv[1], "r");
	if (pFile == NULL) perror("Error opening file");
	else {
		while ((c = fgetc(pFile)) != EOF){
			printf("%02x",c);
			n++;
			if (n % 32 == 0) printf("\n");
		};
		fclose(pFile);
		printf("\n");
	}
	return 0;
}

Next time, I am not re-writing this same program though.

PostgreSQL as Object Database

This is a live blog (i.e. I’d be updating this post time by time.

I am starting to use PostgreSQL as Object Database, mainly as a part of my course project. Object oriented extension of SQL is quite interesting – I, kinda, am loving it. However, all object oriented extensions are not yet implemented by vendors. PostgreSQL lacks a lot of them. Here, in this post, I am going to put notes about what I encounter.

I am using PostgreSQL v9.3.0.

No type inheritance

I tried to use the cool feature of SQL with the keyword under, which was supposed work like extend keyword for type inheritance. e.g.:

CREATE TYPE StudentType UNDER PersonType AS (
    Id INTEGER,
    Level CHAR(2)
)

However, table inheritance is still available, e.g.:

CREATE TABLE Students(
    Id INTEGER,
    Level CHAR(2)
) INHERITS (Persons);

List all tables

select * from information_schema.tables

glut in MS Visual Studio 2010 (MSVS10)


One of my earlier blogs, OpenGL and glut in C++ with MS Visual Studio 2008 (MSVS9) described how to set up your Visual Studio and Computer to work with glut, as well as OpenGL. Now with the new edition, Microsoft Visual Studio 2010, as the version shifted from v6.0A to v7.0A, we need to change some path.So, here goes, what we need to do for using glut in MSVS10:

  • Download the original GLUT library from Nate Robins’ site
  • Unzip the download and copy files as instructed below,
    • glut.h to the folder C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl\
    • glut32.lib to the folder C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib\
    • glut32.dll to the folder C:\Windows\System32\
  • You are now ready to use GLUT!

All other things remain same as described on http://wp.me/puVgg-j

happy gluting, nJoy!

OpenGL, Tree as a fractal, trigonometric Approach

Our goal is to,

  • Draw a tree using fractals with recursion
  • Take user input for:
    • Depth of tree/sub-trees
    • Angle between leftmost and rightmost branch in same depth

Fractals are useful way of approaching to infinity and for drawing some real life like objects where same pattern recurs. To do so, we are drawing single line and then recurring sub trees.

Recursive definition of such trees might be,

A tree is a line from root point to tree top point followed by two sub-trees, each having the root at the top of parent tree and own top at new calculated point.

The idea of Fractal tree is to build it from two initial points,

  • Root of tree p1(x1,y1)
  • Tree top p2(x2,y2)

1

Fig 1: Draw the basis of tree

We draw this part by,

glBegin(GL_LINE_STRIP);
glVertex2f(x1,y1);// root of tree glVertex2f(x2,y2);//tree top glEnd();

 

Now, we should find the two points for each of the sub-trees. To do so, let us first find a point p3 on the line p1p2. This will be done by changing the co-ordinate by placing new origin at p1 and multiplying x2 and y2 by the same multiplication factor. Hence, if the distance between p1 and p2 be l12 and if the multiplication factor is m then we need to get p3 at l23 distant from p1 such that

It is depicted below in figure 2

2 copy

Fig 2: Find point 3

This is done by the code segment shown below,

x3=(x2-x1)*treeRatio+x1, y3=(y2-y1)*treeRatio+y1;

 

After that, we can find the tree top points of the sub-trees, p’3right and p’3left by rotating p3 in y-axis with respect to p2 by θ angle (right sub-tree) and – θ angle (left sub-tree) as done by figure 3 and the pseudo code below,

3 copy Fig 3: Find the recurring points

x3=x3-x2; y3-=y2;
X’3right =  x3 * cos(angle) + y3 * sin(angle) + x2;
Y’3right = -x3 * sin(angle) + y3 * cos(angle) + y2;
X’3left =  x3 * cos(-angle) + y3 * sin(-angle) + x2;
Y’3left = -x3 * sin(-angle) + y3 * cos(-angle) + y2;

 

Now, we can recursively call the function for drawing sub-trees, by decreasing depth by one.

Figure 4 below depicts a right sub-tree being called4 copy

Fig 4: Recursive call to draw right sub-tree

The code segment below, includes the definition of this recursive function in action,

Listing A

 

void tree(GLfloat x1, GLfloat y1,        //root of tree GLfloat x2, GLfloat y2,    //tree top GLfloat angle,//angle/2 between outermost branches of same level GLint n                //depth of subtree )
{

    glBegin(GL_LINE_STRIP);
    glVertex2f(x1,y1);// root of tree glVertex2f(x2,y2);//tree top glEnd();
    if(n<1)return ;        //stop criteria of recursion int nn = n-1;        //decrement GLfloat        //find P3 by x3=(x2-x1)*treeRatio+x1-x2, //translating co-ordinate system to p1 y3=(y2-y1)*treeRatio+y1-y2; //then multiplying p2 by the factor //and position it back to real co-ord //right subtree tree(x2,        y2,
         x3 * cos(angle) + y3 * sin(angle) + x2,// P'3 -x3 * sin(angle) + y3 * cos(angle) + y2,// angle,nn,branchCount);
    //left subtree tree(x2,        y2,
         x3 * cos(-angle) + y3 * sin(-angle) + x2,// P'3 -x3 * sin(-angle) + y3 * cos(-angle) + y2,
        angle,nn,branchCount);
}

 

Enhanced Branches

If we want to use more than two sub-trees, we can do it by enhancing the function from listing A, as depicted in listing B. (Changes are highlighted)

Listing B
void tree(GLfloat x1, GLfloat y1,        //root of tree GLfloat x2, GLfloat y2,    //tree top GLfloat angle,//angle/2 between outermost branches of same level GLint n,        //depth of subtree GLint branchCount)        //number of sub-trees per level {

    glBegin(GL_LINE_STRIP);
    glVertex2f(x1,y1);// root of tree glVertex2f(x2,y2);//tree top glEnd();
    if(n<1)return ;        //stop criteria of recursion int nn = n-1;        //decrement GLfloat            //find P3 by x3=(x2-x1)*treeRatio+x1-x2, //translating co-ordinate system to p1 y3=(y2-y1)*treeRatio+y1-y2; //and then multiplying p2 by the factor //and position it back to real co-ord if(branchCount==2){
        //right subtree tree(x2,        y2,
             x3 * cos(angle) + y3 * sin(angle) + x2,// P'3 -x3 * sin(angle) + y3 * cos(angle) + y2,// angle,nn,branchCount);
        //left subtree tree(x2,        y2,
             x3 * cos(-angle) + y3 * sin(-angle) + x2,// P'3 -x3 * sin(-angle) + y3 * cos(-angle) + y2,
            angle,nn,branchCount);
    }
 else { GLfloat nowAngle = -angle; GLfloat angleTone = angle/(branchCount-1)*2; for(int i=0;i<branchCount;i++,nowAngle+=angleTone){ tree(x2, y2, x3 * cos(nowAngle) + y3 * sin(nowAngle) + x2, -x3 * sin(nowAngle) + y3 * cos(nowAngle) + y2, angle,nn,branchCount); } }
}

Many objects have self-similarity. A fractal is a rough or fragmented geometric shape that can be subdivided in parts, each of which is (at least approximately) a smaller copy of the whole. These fractals can be utilized to model such self-similar objects in computer graphics. Recursive functions can be nicely used to design fractals with its self-similar parts. Design of such objects depends on devising a recursion and thus care should be taken to limit the bound and base criteria should be evaluated nicely.

Thanks for your time with me 🙂

Randomizing the C++ Random function

In programming, we often need to use the random number generator. C++ also provide us with one function for the purpose, the rand(). Alright, it functions properly, I have nothing to blame it about, but one thing you might have noticed, it always generates the same sequence of random numbers, i.e. these are not really random numbers! This is because, any random function generates the random number using a function and based upon a seed, this seed for C++ is fixed. (Oh NO!, you are doomed, how could you get real random numbers!?)

Don’t get frustrated, you can seed the seed using srand(). Now, all you need to do is, just seed it right, (definitely, you shall chose the seed randomly).

I guess, the only thing surely be randomly chosen every time you execute the program is current time. So I prefer to use the time here.

Now, having the theory posed, let me post a code demonstrating the use of real random function generator…

#include <iostream>
#include <ctime>
using namespace std;

int random(int a_seed = 0){
  //type to hold calender time 
  time_t sysTime;
  //Structure to hold time 
  struct tm *timeBox;
  //Read System 
  time sysTime= time(NULL);
  //Convert calender time to tm structure 
  timeBox = gmtime(&sysTime);
  //Generate the seed 
  unsigned seed = timeBox->tm_sec 
                  + timeBox->tm_min
                  + timeBox->tm_hour;
  //feed the seed 
  srand(seed+a_seed);
  return rand();
}

int main(){
  //use the randomized random cout<<random(11);
  //use either random() or rand() after random() is once called 
  cout<<rand();
  cout<<random();
  return 0;
}

I wrote this code when I was a 2nd year student at university and thought that it might be of help to some guy out there in some end of the earth, staring at his/her pretty monitor for some while. Meanwhile, let me get busy with another movie before I go for sleep, tomorrow I shall have to go to job again. So, good luck reader 🙂

List in Prolog

It is important for any programming tool to have some functionality of handling collections like array, list or something else. Prolog use lists for the very purpose and I must warn C/C++ programmers (or even Java, C# or any other C-like language fan) that lists are not arrays but similar to it.

A list must be declared as list type in domains section or in predicate section, it should be mentioned that we are using list.

In domains section, we do it by declaring a new domain and equaling it to a list type, declared by name of type followed by an asterisk; e.g.:

numList=integer*

if one like to avoid domain section, but use list it should be mentioned in predicate section like this:

somePredicate(integer*)

A list is presented as a comma-separated bracket closed tuple of same type:

[a,b,c,]

[1,15,2,100,11,12,19]

[“Car”,“House”,”pen”,”tree”,”Etc”]

List is not random access container but can be accessed in sequence. First element of a list can be accessed in kind of weird way:

[Head|Tail]

If we pass a list there, Head will contain the first element while Tail contains another list excluding the first elemetn. Hence, we need to write some extra lines of code to access nth element.

I would like to avoid further explanation, which you can find a lot in the internet, but will go forward to placing an example code:

/*nafSadh.org*/
/*Example code on LIST in Prolog*/
domains

numList=integer*
key,index,element,minimum,maximum,sum,count=integer
average=real

predicates

/*Traverse list*/
trav(numList)
/*Search an element in the list*/
search(numList,key,index)
search(numList,key)
/*Get the last element of list*/
last(numList,element)
last(numList)
/*Get nth element of list*/
nth(numList,index)
/*get the minimum valued element out of list*/
min(numList)
min(numList,minimum)
/*get the maximum valued element out of list*/
max(numList,maximum)
max(numList)
/*find the average value of elements in list*/
avg(numList)
avg(numList,average)
avg(numList,sum,count)

clauses

/*TRAV*/
trav([]):-
nl.
trav([H|Tail]):-
write(H,”,”),trav(Tail).

/*SEARCH*/
search(List,Key):-
search(List,Key,1).
search([],_,_):-
write(“Not Found”),nl.

search([H|_],Key,I):-
H=Key,write(“Found at “,I),nl.

search([_|T],Key,I):-
II=I+1,search(T,Key,II).

/*LAST*/
last(List):-
last(List,E),write(E),nl.

last([Head],E):-
E=Head.
last([_|Tail],E):-
last(Tail,E).

/*NTH ELEM*/
nth([],_):-
write(“overflow”),nl.

nth([Head|_],I):-
I=1,write(Head),nl.

nth([_|Tlist],I):-
II=I-1,nth(Tlist,II).

/*MIN*/
min([H|T]):-
min(T,H).
min([],Min):-
write(Min),nl.
min([H|T],Min):-
H<Min,M1n=H,min(T,M1n).
min([_|T],Min):-
min(T,Min).

/*MAX*/
max([H|T]):-
max(T,H).
max([],Max):-
write(Max),nl.
max([H|T],Max):-
H>Max,M4x=H,max(T,M4x).
max([_|T],Max):-
max(T,Max).

/*AVG*/
avg([]):-
write(“Empty List”),nl.
avg(List):-
avg(List,Avg),write(Avg),nl.
avg(List,Avg):-
avg(List,Sum,C),Avg=Sum/C.
avg([H],Sum,C):-
Sum=H,C=1.
avg([H|T],Sum,C):-
avg(T,S,Count),Sum=S+H,C=Count+1.

Happy Prolog!

Unlike some of my fellow bloggers, I hold pure authorship to the codes placed here and these codes have never been cut pasted from some other site or plagiarized from any fellow student. Being frightened by some web publisher, I hereby have to claim my copyright on elements presented here.

All elements published here are published under NS7 Open Content License, which express that,

  • if anyone use the content, partial or full in any context, s/he shall must mention the source and refer to the hyperlink
  • any code under this license must not be published in any media unless modified significantly and that modification executes well enough without harm and credit to actual author is mentioned
  • if anyone need to use code, published under this license,  as example s/he can do it by mentioning actual author and shall not host a source file but refer to the original one, with another hyperlink to content accompanying, if accompanies one, the very code. As this code shall be used as example, content text should be relevant and example code should not be more than 40% of total content.
  • Mentions to authors of codes and contents under this license must be in a good manner. Mention should be in same font of normal text of the content used in, font size should be of same size or larger than normal text of the content but in any case minimum size in electronic media is 12px or 11pt in print media. Normal text is regarded as that kind of text that comprises of a minimum of 70% of total content.
  • contents presented here can be used for personal and academic purpose without any mention but shall not be published without taking proper permission from actual author