Monday, December 25, 2006

Krugle - Code Search for Developers

This is a nice site for code stealing

Read more at www.krugle.com/

Friday, December 22, 2006

Crystal clear Bangalore on google map

Check this out

Now the map is much more detailed and expressive than the satellite based imagery.

Thursday, October 19, 2006

How to list only directories in Unix

Well this may seem a very simple problem, but its not. So it deserves a thread for sure

Traditional method

ls -l|grep ^d

But u get the other unwanted details, incase u are automating

Slightly Sophisticated

find . -type d

But on execution u will dicern that find is recursive, so "just the" folders of the current directory are not displayed

If its getting slightly complicated try this simpler solution.

ls -l|grep ^d|awk '{print $9}'

Pretty neat.
This command works almost fine. But just in case the folder has a "space", the command fails to get the exact name of the folder.

Here is a solution which "WORKS" and is very simple

ls -p |grep /

Just an indicator of the power of the raw tools invented ages ago. KISS(Keep it Simple S......)

Friday, October 13, 2006

Must Read....

No Silver Bullet

If u write code...read it!

Saturday, October 07, 2006

Google does it again

Check this out. Its out and open for people to use.

Now here are the interesting issues with it.
1) Be prepared for spams. Just try this, you will know.
2) Emotions the poor developers go through :-X . Just pick your slang, google does the rest.I just hope openSolaris is clean!!!!!!!!!!!!!!
3) Some programmers put the default password in sourcecode and Most lazy users never change the default password.This makes it easy to get the default password which can be exploited. Try this

Actually this is not a great innovation in itself. Krugle, Koders, and Codease are into this. But a gaint entering will have its own advatages.

"Good programmers write good code. Great programmers find it on Google!"

Tuesday, September 26, 2006

PHP sucks big time

I was trying to integrate Apache--PHP--mysql for a HR project at janagraha.

The problem is that the php documentation is very old...or I should say it works for lower versions of php and apache.

So here is a small TO-DO on how to go about integrating
1) Download Apache here. Apply your user friendly GUI knowledge of windows and get it installed.
2)Download php here.
3)Unzip in d:\php5.
4)Rename php.ini-recommended to php.ini
5)Add these lines to the top of httpd.conf
# PHP 5 Support
LoadModule php5_module "d:/php5/php5apache2_2_filter.dll"
LoadFile "d:/php5/php5ts.dll"
AddOutputFilter PHP php
PHPIniDir "d:/php5"

***Please note the locations used.
6) Finally process is over. Create a test.php.
Having say

copy to htdocs folder of apache.

7)RESTART APACHE. (hopefully no errors).
Run http://localhost/test.php

Worth a try though

Thursday, September 07, 2006

Google Releases Tesseract as Open Source

Google recently released Tesseract as open source. Originally developed at the HP Labs from 1985-1995, it has been vouched as one of the most accurate Optical Character Recognition (OCR) programs available. You can download Tesseract here.

Checkout one possible use of this technology here

Leaving the rest to imagination....

Monday, August 28, 2006

Does machine have JAVA

My friend can up with a curious problem.

To run an applet a prerequiste is to actually check whether JRE(or JVM) is actually present on the machine. Although applet inherits the intelligence to actually point the browser to the web location.

However if the application has to be in total control then how??????

In short for Non-IE browsers then navigator.mimeTypes gets the registry values for the installed runtimes.
But alas IE does not implement mimetypes. So an activeX document to implement the same.


Here is a small snippet of the code written in javascript.


if(navigator.mimeTypes) {
//For non-IE browsers
for (i=0; i < navigator.mimeTypes.length; i++) {
if( (navigator.mimeTypes[ i].type != null)
&& (navigator.mimeTypes[ i].type.indexOf(
"application/x-java-applet;jpi-version=1.5") != -1) ) {
pluginDetected = true;
break;
}

}
}
} else if (is_ie5up) {
var javaVersion;
var shell;
try {
// Create WSH(WindowsScriptHost) shell, available on Windows only
shell = new ActiveXObject("WScript.Shell");

if (shell != null) {
// Read JRE version from Window Registry
try {
javaVersion = shell.regRead("HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\Java Runtime Environment\\CurrentVersion");
} catch(e) {
// handle exceptions raised by 'shell.regRead(...)' here
// so that the outer try-catch block would receive only
// exceptions raised by 'shell = new ActiveXObject(...)'
}
}
} catch(e) {
}
My friend can up with a curious problem.

To run an applet a prerequiste is to actually check whether JRE(or JVM) is actually present on the machine. Although applet inherits the intelligence to actually point the browser to the web location.

However if the application has to be in total control then how??????

In short for Non-IE browsers then navigator.mimeTypes gets the registry values for the installed runtimes.
But alas IE does not implement mimetypes. So an activeX document to implement the same.


Here is a small snippet of the code written in javascript.


if(navigator.mimeTypes) {
//For non-IE browsers
for (i=0; i < navigator.mimeTypes.length; i++) {
if( (navigator.mimeTypes[ i].type != null)
&& (navigator.mimeTypes[ i].type.indexOf(
"application/x-java-applet;jpi-version=1.5") != -1) ) {
pluginDetected = true;
break;
}

}
}
} else if (is_ie5up) {
var javaVersion;
var shell;
try {
// Create WSH(WindowsScriptHost) shell, available on Windows only
shell = new ActiveXObject("WScript.Shell");

if (shell != null) {
// Read JRE version from Window Registry
try {
javaVersion = shell.regRead("HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\Java Runtime Environment\\CurrentVersion");
} catch(e) {
// handle exceptions raised by 'shell.regRead(...)' here
// so that the outer try-catch block would receive only
// exceptions raised by 'shell = new ActiveXObject(...)'
}
}
} catch(e) {
}

Tuesday, August 22, 2006

Extract Windows Product Key !

Just came across this while searching something on "Google", looked very interesting.
Everyone will be wondering how to get this product key if not mentioned it on the CD label.
But I haven't tried this yet, cause am not a windows programmer ;)
Let me know the results about this!

BSTR GetProductKey()
/*
Window Product Key Extract

*/
{
CString strResult; //Return a Window Product Key

HKEY hRegistryKey; //Registry Handler
BYTE *DigitalProductID; //Digital Product Key Value
DWORD DataLength; //Digital Product Key Length

BYTE ProductKeyExtract [15]; //Extract Key

char sCDKey [256]; //Temp, adding a Window Product Key

long ByteCounter; //Counter
long ByteConvert; //Convert

int nCur; //XOR calculate


char *KeyChars[] = {
"B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y",
"2","3","4","6","7","8","9",NULL
};

// HKLM\\SOFTWARE\\MICROSOFT\\Windows NT\\CurrentVersion 열기
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, NT_CURRENT,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, &hRegistryKey) == ERROR_SUCCESS)
{

DataLength = 164;

//Allocate Memory
DigitalProductID = (BYTE *)malloc(DataLength);

//Memory Initializationd
memset(DigitalProductID, 0, DataLength);

//Digital Product Key Open

if(RegQueryValueEx(hRegistryKey, "DigitalProductId",
NULL, NULL, DigitalProductID, &DataLength) == ERROR_SUCCESS)
{
//reading a value start position 52, by 66
for(ByteCounter=52; ByteCounter<=66; ByteCounter++)
{
ProductKeyExtract[ByteCounter - 52] = DigitalProductID[ByteCounter];
}

//Last Indexer
ProductKeyExtract[sizeof(ProductKeyExtract)] = NULL;
}
}

//Start Converting job, Next Step

memset(sCDKey, 0, sizeof(sCDKey));

for(ByteCounter=24; ByteCounter>=0; ByteCounter--)
{
nCur = 0;

for(ByteConvert=14; ByteConvert>=0; ByteConvert--)
{

nCur = (nCur * 256) ^ ProductKeyExtract[ByteConvert]; //XOR계산
ProductKeyExtract[ByteConvert] = nCur / 24;
nCur = nCur % 24;
}

strrev(sCDKey);
strcat(sCDKey, KeyChars[nCur]);
strrev(sCDKey);

//Insert "-"

if(!(ByteCounter % 5) && (ByteCounter))
{
strrev(sCDKey);

strcat(sCDKey, "-");

strrev(sCDKey);
}
}

//Insert Product Key into Return value

strResult.Format("%s", sCDKey);

//Close Registry
RegCloseKey(hRegistryKey);

//Relese Memory
if(DigitalProductID) free(DigitalProductID);

return strResult.AllocSysString();
}

Note: Please mention the results in the comments section.

Thursday, August 17, 2006

Richard Stallman @IISc

Title: Free Software: current status and challenges

Time: 19 Aug (Sat) 11am
Place: Faculty Hall

Speaker: Richard Stallman,
Founder of GNU project and FSF (Free Software Foundation)


Abstract:
Richard Stallman will give a talk on free software and current status on
aspects such as GPLv3, DRM (digital rights mgmt), DMCA, etc.

Bio:
Richard Stallman is the founder of the GNU Project, launched in 1984 to
develop the free software operating system GNU. The name ``GNU'' is a
recursive acronym for ``GNU's Not Unix''.

Stallman graduated from Harvard in 1974 with a BA in physics. During his
college years, he also worked as a staff hacker at the MIT Artificial
Intelligence Lab, learning operating system development by doing it. He
wrote the first extensible Emacs text editor there in 1975. He also
developed the AI technique of dependency-directed backtracking, also
known as truth maintenance. In January 1984 he resigned from MIT to
start the GNU project.

Stallman received the Grace Hopper award for 1991 from the Association
for Computing Machinery, for his development of the first Emacs editor.
In 1990 he was awarded a Macarthur foundation fellowship, and in 1996 an
honorary doctorate from the Royal Institute of Technology in Sweden. In
1998 he received the Electronic Frontier Foundation's pioneer award
along with Linus Torvalds. In 1999 he received the Yuri Rubinski award.
In 2001 he received a second honorary doctorate, from the University of
Glasgow, and shared the Takeda award for social/economic betterment with
Torvalds and Ken Sakamura. In 2002 he was elected to the US National
Academy of Engineering, and in 2003 to the American Academy of Arts and
Sciences. In 2003 he was named an honorary professor of the Universidad
Nacional de Ingenieria in Peru, and received an honorary doctorate from
the Free University of Brussels. In 2004 he received an honorary
doctorate from the Universidad Nacional de Salta, in Argentina.

About GNU:

GNU is free software: everyone is free to copy it and redistribute it,
as well as to make changes either large or small. Non-free software
keeps users divided and helpless, forbidden to share it and unable to
change it. A free operating system is essential for people to be able to
use computers in freedom.

Today, Linux-based variants of the GNU system, based on the kernel Linux
developed by Linus Torvalds, are in widespread use. There are estimated
to be some 20 million users of GNU/Linux systems today.

Richard Stallman is the principal author of the GNU Compiler Collection,
a portable optimizing compiler which was designed to support diverse
architectures and multiple languages. The compiler now supports over 30
different architectures and 7 programming languages.

Stallman also wrote the GNU symbolic debugger (gdb), GNU Emacs, and
various other programs for the GNU operating system.

Monday, August 07, 2006

Is this methods fool proof?

Does this method make a valid check for even numbers?

public static boolean isEven(int i) {
return i % 2 == 1;
}

Thursday, August 03, 2006

http://localhost/Wiki/

Imagine finding yourself in the middle of nowhere wanting to browse wiki :))

Wikipedia offers whole of their content as a huge xml dump file, which you can download and host wikipedia on your local machine. There are filters such as WikiFilter available which can read this XML dump and render html dynamically. It also provides indexing and search features, So virtually you won't find any diffrerence when you are browsing the local version, except that you wont be seeing the images on the wiki page. (actually you can get a dump of even the image links, just that you got to have a 100 GB hard disk! ).

The whole xml dump file is just about 1.4 gb (compressed ver) and came to about 6.4 gb after decompressing.You can also get a sql dump which you can host using mysql which will obviously take less hard disk space, but I couldn't get anything which renders dynamic html out of it and can also provide search capabilities.

Aha...Its information about anything under the sun literally at your fingertips. All for free . Screw internet. Screw Encarta. Happy Wiki'ing !

Wednesday, August 02, 2006

Nice Article on troublshooting

Check this out

I liked the following points discussed

1)Use of strings for printing the strings of printable characters in files.

2)Apt examples of gdb,strace & ldd

Also this very useful tip. I ran into this , for finding out what is used of "OR-ing" in javascript.

"Google normally removes common words like 'and', 'or', 'when' etc from the search patten. To forcefully include them in the search, use a '+' just before the word. ( +word_to_be_included)"

Monday, July 31, 2006

IBM is legacy, Infosys is the future

These are the exact words of euphemism used by our FM P Chidambaram.
I think its time for Indian companies and Indians to be globally competetive. I would love to see a day when a fresh college grad rejects a MNC's offer for an Indian company for a more financially as well as technically satisfying career. I know the day is not quite far, its in the air- can sense it .
Well Infosys has all it takes to kick butt out of IBM.


Happy birthday Infy( btw its Arnold's Birthday today as well, 1 more astrological reason to be gr8)

And congratulations to all the Infy mates, u are in for a treat. Enjoy madi

Wednesday, July 26, 2006

YouOS Online OS!!!!!!!!

Are we seeing the beginning of the end of Microsoft days, finally? It may be too soon to say but YouOS looks pretty functional to me. “YouOS strives to bring the web and traditional operating systems together to form a shared virtual computer.” It is a wonderful concept. There are gotchas today, not to mention crumbling under digg/slash effect, but first, what in the hell is YouOS?

YouOS is a web operating system that lets you run diverse applications within a web browser. Small applications like sticky notes or clocks. Large applications like word processing, mp3 players, and instant messaging. Even better, it’s very easy to tweak an existing application or write your own.

The idea is very captivating. Imagine a giant computer which everyone across the internet can share and work on. You can share your desktop, work equally well from any computer. “Your desktop, applications, and data travel with you from cafe to cafe, session to session. And tedious things like data backups and archiving? We’ll take care of them for you.” And yet you control your data.

Rapid application development and management is central to YouOS. You can also clone an existing application to start yours. Here is a subset of the sample apps developed by the YouOS team:
* RichTextWarrior - a rich text editor.
* Wshell - a shell program, like in Linux. Try running “ps” or “ls” or javascript.
* FlickRSS - want to have new pictures every time you log on? Use this.
* Mersenne Prime Search - help search for special prime numbers.
* goohoo - a not-so elegant way to search yahoo and google at the same time.
* Penguin - an animated gif for your desktop
* ChatWarrior - a chat room application

YouOS exposes its functionality through open RESTful server APIs. That means you can easily write applications which consumes them or builds upon them. You can easily provide a customized version of YouOS for mobile for example or a desktop client which uses YouOS API’s to provide services.


In short - wonderful concept and nice implementation (in Python). I wish this project success. It is very likely that it will soon be gobbled by the likes or Microsoft, Yahoo or Google.

Thursday, July 06, 2006

Wiki --How can we create ONE

Just finished with my wiki creation. My machine is the server for the internal wiki which can be put to use.

It turned out to be much simpler than I expected.

Just go to http://www.jspwiki.org/wiki/JSPWikiDownload .....download

Tomcat is required as a container for the above generated war file.

Just place the JSP WIKI war file in the tomcat HOME directory. Tomcat does everything all by itself.

Thats it WIKI is up

Wednesday, June 21, 2006

Microchip@500GHz speed

Check this news out.

This is truly out of the world.... If IBM achieves it then boy it will be the company everyone will be after. If I may recall correctly Intel is struggling to get a 5 GHz processor out.

When I purchased my PC way back in 2002, I was proud to say that my intel processor is the fastest with 1.7Gig. Well Moore's law set in thereafter. But hey this is voilation of the law to the core.

I wholeheartdly doubt such high speeds being pragmatic.Nevertheless in case it clicks, then the entire world will be changed.

This processor at 451 degrees below zero is certailnly SUPER COOL!!!!!!!!!

Monday, May 15, 2006

Recursive Fun

I was browsing through orkut and found community on Recursive Programming, and saw below piece of code .. Its cool ..

node* Reverse(node* ptr)
{
if(ptr->next == NULL)
{
Head = ptr;
return ptr;
}

Reverse(ptr->next)->next = ptr;

return ptr;
}



Did anyone get it :-) ....

Sunday, April 30, 2006

Pick Up Javascript code for bookmark

Bookmark this site here
Tested on Firefox and IE. Please comment if you face any run-time or javascript errors with your favourite browser.

Friday, April 14, 2006

Online tutorial to learn Web Services in Java

http://java.sun.com/webservices/docs/1.5/tutorial/doc/index.html

The above is a guide to developing Web applications with the Java Web Services Developer Pack (Java WSDP).

Sun's Application Server needs to be used in here to implement the examples.

The tutorials covers various things like
-The Java API for XML Processing (JAXP)
-The Java API for XML-based RPC (JAX-RPC)
-SOAP with Attachments API for Java (SAAJ)
-The Java API for XML Registries (JAXR)

Best part of this is -- all examples are available for download . Hardly any work is needed to get the simple examples working.

Worst part is --various jargons are in place like SAX(Simple API for XML), DCOM(Document Object Model) . These are XML processing models.

This link is a good starting point to parse XML documents using a SAX parser in Java.

Friday, April 07, 2006

Pick up code for sending mail in Java

////Use Java 1.3 and above

import javax.mail.*;
import javax.mail.internet.*;

import java.util.*;

/**
* A simple email sender class.
*/
public class SimpleSender
{

public static void main(String args[])
{
try
{
*************Change the smtpServer name ***************************
String smtpServer="mySMTP";//Use the respective smtpServer name
String to="shantanu.gg@gmail.com";
String from="shantanu.gg@gmail.com";
String subject="Please work";
String body="Consider urself lucky";

send(smtpServer, to, from, subject, body);
}
catch (Exception ex)
{
System.out.println("Usage:"
+" smtpServer toAddress fromAddress subjectText bodyText");
}

System.exit(0);
}
public static void send(String smtpServer, String to, String from
, String subject, String body)
{
try
{
Properties props = System.getProperties();

// -- Attaching to default Session, or we could start a new one --

props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);

// -- Create a new message --
Message msg = new MimeMessage(session);

// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));

// -- We could include CC recipients too --
// if (cc != null)
// msg.setRecipients(Message.RecipientType.CC
// ,InternetAddress.parse(cc, false));

// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(body);

// -- Set some other header information --
msg.setHeader("X-Mailer", "MyMail");
msg.setSentDate(new Date());

// -- Send the message --
Transport.send(msg);

System.out.println("Message sent OK.");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Thursday, March 16, 2006

Just got Geekie

There is a hairline difference between techie/geekie and posts like this will transcend into the geeky category.
Here is a small,lazy-- time saving tip for the readers who just can get the article on their systems as and when they are created.

Here is the RSS feed link for this blog

http://puretechie.blogspot.com/atom.xml

Use this feed with your favourite RSS reader and be the first to view the articles....(Now u know what geeky really means ). I use Mozilla thunderbird --real good for such geeky things.

Stay Updated................

Monday, February 27, 2006

New features in Java 1.5

The For-Each loop
A task that is done often is to iterate through a collection, and do something with each element. For example, this shows all the elements in a list :

public void Show(List l) {
for (int i = 0; i < l.size(); i++) {
System.out.println (l.get(i));
}
}

This code seems right; however it could be very inefficient.
The in-efficiency can be attributed to the sequential manner - the
above progresses,resulting in an algorithm of order O(n^2)
whereas an algorithm O(n) is easily obtained.

O(n) can be got with the use of iterators (similar to c++)

public static void ShowFast(List l) {
for (Iterator it = l.iterator(); it.hasNext();) {
System.out.println (it.next());
}
}

When you ask for an iterator of the collection using the method
iterator(), a reference to the beginning of the list is retrieved.
Then, the hasNext() method returns whether there are still more
elements to come, and it.next() does two things: it advances the
reference to the next element in the collection and retrieves the
current element. This gives the LinkedList the opportunity to iterate
through the list in O(n). For the moment, all that can be done in
earlier versions of Java. Even if the above code works, it's not nice
and quite error prone. For example, if in the hurry you call again to
it.next() in the for block in order to retrieve again the element,
you'll get half the list in one place and half in another. Of course
that this can be solved storing the value of it.next() in a local
variable, but Java 1.5 brings a nicer and safer way to do the same: the
for-each loop.


public static void ShowFastAndNice(List l) {
for (Object o : l) {
System.out.println (o);
}

}


You can read the for sentence as "for each Object o in l"

With New features--- have to come their share of new problems.
Not everything is rosy here .....

The following bombs
Object o;
for (o : l) {
System.out.println (o);
}

Sun documents this as "these kinds of practices are not very clear and robust,
so the compiler is making you to write better code, even if it might require
an additional flag."(not verbatim but on similar lines).



Friday, February 24, 2006

A bit off track , nevertheless useful

Spent a hell lot of time getting this

How do you find the OS your DB is running on ???????

As Simple as

select dbms_utility.port_string from dual;

Now I am posting it so that I myself dont forget it .....

Tuesday, February 14, 2006

How does it work

int main()
{
return(mycmp("a"));
}
int mycmp(char * a1,char *a2)
{
printf("mycmp called");
return(1);
}


$>cc mystring.c
$>./a.out
mycmp called
$>

How is mycmp called when the parameters are different.

Wednesday, January 25, 2006

Fore-warned is fore-armed

Many of the networking or related applications have to marshal/unmarshal packets to/from structures. And its not uncommon to have more than one field within a byte of a packet. So, what's the best way to construct a packet before sending it over the wire? Say, a SCSI CDB (command descriptor block - similar to an SNMP packet) has to be sent to a device target. Lets simplify the whole thing and say that just 1 byte consisting of 8 1-bit flags is to be sent over the wire. What's the best way to represent such a byte? The first solution that comes to anyone's mind would be bitfields. So, let's go ahead with that.

typedef struct CDB_Byte {
  unsigned char a:1;
  unsigned char b:1;
  unsigned char c:1;
  unsigned char d:1;
  unsigned char e:1;
  unsigned char f:1;
  unsigned char g:1;
  unsigned char h:1;
} CDB_Byte;

Now I want to set only the LSB(least significant bit) and the one next to it. Okay, that's simple.

CDB_Byte byte;
byte.h = 1;
byte.g = 1;

But, I have a question. Is this the correct way to do it? The answer is NO. Let me illustrate why this is'nt the correct way with a simple example.

unsigned char c = 0x01; // LSB set
CDB_Byte byte;
std::memcpy(&byte, &c, 1); //copy the bits
// to change the value of 'c' to 0x03
byte.g = 1; // set the bit next to the LSB
std::memcpy(&c, &amp;byte, 1); // copy the bits back
std::cout << (unsigned)c;

Will this print '3'? The answer is 'depends'. The language standard does not say anything about the allocation of bitfields. The compilers are free to implement them as they deem fit. On linux, the gcc compiler allocates the bitfields starting from the LSB. This can be verified - the above piece of code prints '65'.

hgfedcba

However on HP-UX, the aCC compiler allocates bitfields starting from the MSB. The above piece of code prints '3' (as one might have expected in the first place).

abcdefgh

Moral of the story is this: Never use bitfields to construct structures containing sub-byte fields. Always use a void * chunk of memory, extract a byte, and use masks and bitwise operators to set/extract sub-byte fields. At least, if you expect your application to be portable, don't use bitfields! I would say that bitfields should never be used anyway, 'cos there's no guarantee that the same application will run on the same platform if the compiler vendor rolls out a newer version.

Fore-warned is fore-armed!

Monday, January 23, 2006

System Calls

What is a System call? Why do we need system call? These are the few question raise in mind.
Firstly, System Call is a interface between the application and the underlying hardware [managed by kernel, Operating System]. Secondly, ensures security and stability by not allowing direct access to the hardware. The hardware access[system resources] is maintained by the kernel.

Flow of Execution
I will be explaining about how the system call flows.
Consider a printf() call in simple C program, the printf() is an API which inturn call the write system call. System Call are those which are executed in Kernel Mode[or System Mode] in Process context. What I meant was, the system call is only visible to kernel, and it is executed on behalf of the process which calls it, because as I told System Call uses system resources and hardware access, which is managed by Kernel[security issue].

printf() ---> printf() in the C library --->write() in C library --->write() system call in kernel.

The printf() in library and write() in the library indicates the conversion of the printf() in application to make an appropriate call to write() in Kernel. Its usually called "stub". Remember the RPC [Remote Procedure Call] stubs, which is used to convert function call and its arguments to some protocol. The library routine is responsible for invoking the system call.

There is a trap instruction [int 80h - in x86 arch] that is executed which transfers control from user mode to kernel mode to excute the sytem call. The system call is identified in the kernel by the syscall number that is passed by library routine through a register[EAX - in x86 arch]. Further on I will explaining w.r.t x86 arch and w.r.t Linux OS. Once the trap instruction is executed, it generates an interrupt which is handled by syscall_handler(). The interrupts are dealt in kernel mode itself. This handler checks for the sytem call number in the syscall_table, which contain a detailed list of all the system calls present the kernel. There is a numerous other checks that needs to be handled[security issues, takes lot of time to explain].

If the system call is present in the list w.r.t to the syscall number passed in EAX, the system call is invoked with the arguments passed to it. Now, one more question arises, how is the arguments to system call is passed? The answer is through other registers EBX,ECX,EDX, ESI,EDI contain the first 5 arguments passed. If the arguments is more than 5, then a pointer to memory location where it is present in the user mode is passed through register.

In Linux, the return value of each system call is long int so has to be compatible with the 64-bit arch. The return value is stored in EAX register and switched to user mode.

Adding a System Call in Linux. Reusability[of already existing system call] is highly recommended hence think twice before adding a system call.

For any more details or doubts, scratch a comment to this article.

Saturday, January 21, 2006

Floating Point Anamoly

Source:YPK "Test Your C Skills" Ch-4 "Floating Point Issues" 1st question

main()
{
float a=0.7;
if(a <0.7) a="="b" href="http://docs.sun.com/source/806-3568/ncg_goldberg.html">IEEE
and
Why this anamoly

One good practice is

use something like
#include <math.h>

if(fabs(a - b) <= epsilon * fabs(a))

for some suitably-chosen degree of closeness epsilon (as long as a is nonzero!).


Is a[i] = i++; valid?

This is a very basic question, but many intersting concepts emerge out of it.

Answer is "Behaviour is Undefined".A compiler may do anything it likes when faced with undefined behavior (and, within limits, with implementation-defined and unspecified behavior), including doing what you expect.

Briefly: implementation-defined means that an implementation must choose some behavior and document it. Unspecified means that an implementation should choose some behavior, but need not document it. Undefined means that absolutely anything might happen. In no case does the Standard impose requirements; in the first two cases it occasionally suggests (and may require a choice from among) a small set of likely behaviors.

The concept of sequence point can be used to base a discussion on
A sequence point is a point in time (at the end of the evaluation of a full expression, or at the ||, &&, ?:, or comma operators, or just before a function call) at which the dust has settled and all side effects are guaranteed to be complete.The ANSI/ISO C Standard states that
"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored."

The second sentence can be difficult to understand. It says that if an object is written to within a full expression, any and all accesses to it within the same expression must be for the purposes of computing the value to be written. This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification(as above).

Friday, January 13, 2006

C++: Strange name lookup

This is something I never knew and read about it recently in "Exceptional C++". Let me start with a code example...

namespace A {
  class S { };
  void foo(S& parm) { }
}

namespace B {
  void foo(A::S& parm) { }
  void bar(A::S& parm) {
    foo(parm); // Which "foo" does this call?
  }
}

Try this out and to your surprise you'll find that this gives a "call to foo is ambiguous" error. But why?? The only foo visible at the place of call is in namespace B. Why should this result in an error? Okay, now try this out - comment out the "foo" definition in namespace B.

namespace A {
  class S { };
  void foo(S& parm) { }
}

namespace B {
  // void foo(A::S& parm) { }
  void bar(A::S& parm) {
    foo(parm); // Which "foo" does this call?
  }
}

This compiles without errors! Surprised again? When you run the program, it'd have called A::foo. What happened here? Does this not appear to be a namespace violation. Apparently not! This strange behavior is explained by "Koenig lookup" also known as "Argument dependent lookup".

If you supply a function argument of class type (here parm, of type A::S), then to find the function name the compiler considers matching names in the namespace (here A) containing the argument's type.

But still, is'nt this a namespace violation?? NO. Just consider this piece of code...

std::string str("Hello");
std::cout << str;

This works fine right? How? This works because of Koenig lookup. The function in question here is "operator <<" which is found in "namespace std". But we have'nt used any "using" declaration to bring that function into the current scope. Since std::string is going as an argument into that function, the compiler will automatically look into the std namespace and will find that function. Without this kind of lookup, the same function call would have to be written as...

std::operator <<( std::cout, str) ; // ugly! ain't it??

This is the great value that Koenig lookup gets us and we tend to use it every now and then without realising it. Interesting - is'nt it??

Monday, January 09, 2006

cURL -- A tool limited by imagination

A stock ticker is a piece of code which keeps you updated with the latest(as and when) stock quotations of various companies at the stock exchange. Technically to build this one needs the following tools --

  1. XML
  2. RSS
  3. cURL
  4. sed,awk,grep and simple shell scripting knowledge.

1. XML
Need to know just this concepts elements.

2. RSS (Really Simple Syndicate) -- it is really simple.
As I understand this, there is a link like "http://www.xanadb.com/ticker/YHOO" which provides RSS feed for stocks(YHOO- for yahoo, MSFT-microsoft).
Now observe the xml format carefully. All rss feeds essentially have these 3 elements
title,descrption,link.
An RSS reader is one which makes sense of this rss feed.

So to build the stock ticker here is the design
a) Get the contents of "http://www.xanadb.com/ticker/YHOO" in a variable.
b) Just find the “title” tag. Trash the rest.
c) Find the number and thats it.

3. cURL

Now to achieve step (a) mentioned above we have to use a tool which gets us the contents of the page in a variable or a file.

cURL is shipped freely with most of the Linux installations.

Catch hold of one and execute this

curl "http://www.xanadb.com/ticker/YHOO"

Now go through the manual in case you are using proxies, SSL protected site, etc etc etc.

Now the power is all yours. Just think all the stuff possible with this tool and have i told you this. Its a MIT product.

4. sed,grep and other scripting techniques

Here after its child's play and the scripting skills.

curl "http://www.xanadb.com/ticker/YHOO" | grep title | sed s/title//g

I havent tried the above on a machine , but hope you got an idea as to how the attempt is being made to get the stock quote.

Conclusion

No matter how hard web designers may try to force you to surf their sites interactively, there will always be free tools to help automate the process, thus enriching our overall Net experience.
A deliberate attempt has been made only to answer the "How" part of the tools and not the "What" part of them, as they are available in the links suggested.

Next in Line

PODCAST -- what the hell is this

cant use html tags

After writing the article , I just realized that some html tags (like title, link etc in the exact syntax) cant be used in the article. So I could not use the tags correctly.