Friday, October 16, 2015

Git commands


Basics:
========
To add files to be committed      
  git add 
To commit a change in the local tree. To be done after the git add.
  git commit -m "comment about the changes"
To push the changes or checkin the changes to main branch    
  git push
To discard all changes done in a branch locally
  git stash save --keep-index
  git stash drop
    
To create a new branch     
  git checkout -b myBranch
 
To create a patch from the local branch
 Before this check out a new branch, do all changes in the branch, verify it. And then commit those changes. Do not push the changes to master.
 git format-patch master --stdout > myPatch.patch

git reset  updates the index for that path so that it matches HEAD (the current commit). 
It doesn't touch the working tree

git rm --cached -r  to remove a directory which was added.
 
GT Diff:
==========
git diff HEAD@{1}
The @{1} means "the previous position of the ref I've specified", so that
evaluates to what you had checked out previously - just before the pull.

git diff HEAD@{1} filename
This is a general thing - if you want to know about the state of a file
in a given commit, you specify the commit and the file, not an ID/hash
specific to the file.

git diff --cached --name-only   
It lists the filenames in the staging area that will be committed to git. Can be used after all the files to be committed are added thru 'git add'  to verify only intended files are being commited

git difftool --cached
the diff of files that are about to be committed against the head will be showed in vimdiff one by one.

git difftool  
the diff of files in the two commits will be shown in vimdiff one by one.

git log --pretty=oneline
compact display of git log

how about 
  • git diff --name-only for changes relative to index
  • git diff --name-only --staged for ... well staged chages :)
  • git diff --name-only HEAD got both
To get the modified files alone:
git status --porcelain|awk '{if($1=="M") {print "basename " $2}}'|sh

To copy the modified files alone to a remote server, as below:
git status --porcelain|awk '{if($1=="M") {print "scp " $2 " account_name@server_ip:~/my_codebase/$(dirname " $2 ")/;"} }'|sh


Global GIT Configuration: ~/.gitconfig

#vi ~/.gitconfig
[alias]
    st = status
    ci = commit
    br = branch
    co = checkout
    df = diff
    dc = diff --cached
    lg = log -p
    who = shortlog -s --
    changes=diff --name-status -r
    diffstat=diff --stat -r
    logtree = log --pretty=format:\"%h %ad | %s%d [%an]\" --graph --date=short
    last = log -1 HEAD
    tree = log --graph --decorate --pretty=oneline --abbrev-commit
     # format %cd with --date=short cuts the timezone in log 
    ll = log --graph --pretty=format:\"%C(yellow)%h %C(green)(%cd)%C(auto)%d %Creset%s [%an]\" --date=short
    logtree = log --pretty=format:\"%h %ad | %s%d [%an]\" --graph --date=short
 
[user]
        email = emailid@email.com
        name = Name S
[color]
        ui = auto
[diff]
        tool = vimdiff



# run
git config --global diff.tool vimdiff  #to defibe difftool
git difftool    # launch vimdiff with changes

This will add alias "tree"
git config --global alias.tree "log --graph --decorate --pretty=oneline --abbrev-commit"

For external file diff usage
[diff]
    external = /bin/git-meld.sh


$ cat /home/<dir>/bin/git-meld.sh
#!/bin/bash

meld $2 $5





vi editor ~/.vimrc



" Run time config for vim editor
set cindent    " for c indentation(correct spacing)
syntax on    "To color the VIM editor
set nu ” line numbers
set ts=4 " –> for tab spaces set to four per tab character
set sw=4 "–> Set the shift width to four spaces
set spell " –> set spellchecking on
 set spl=en "–> Set spelling language to english
set ai "–> Enable auto indentation
set nu "–> Enables line numbers
" To remember last position of open file
if has("autocmd")
  " When editing a file, always jump to the last known cursor position.
  " Don't do it when the position is invalid or when inside an event handler
  " (happens when dropping a file on gvim).
  " Also don't do it when the mark is in the first line, that is the default
  " position when opening a file.
  autocmd BufReadPost *
    \ if line("'\"") > 1 && line("'\"") <= line("$") |
    \   exe "normal! g`\"" |
    \ endif

endif

Thursday, May 21, 2015

Highlight the anchor in HTML




To highlight the anchor use following css style code:

<style type="text/css" >
a{color:orange;text-decoration:none;font:bold} 
a:focus{color:cyan}
</style>
<script>
function FocusOnInput(){
        document.getElementById('text').focus();
}
//Add FocusOnInput() in onload event in the body attribute:
</script>

< body onload="FocusOnInput()" >

use id="text"   # highlighthe first componenet

Eg:
<a  id="text" href="http://google.com"> </a>


Note:  DOM Level 2 HTML
only elements that have a focus() method are 
HTMLInputElement, 
HTMLSelectElement, 
HTMLTextAreaElement and 
HTMLAnchorElement.       eg: <a  id='text' hreaf= ... >
And this notably omits HTMLButtonElement and HTMLAreaElement.

Logging on condition:
function logt(msg) 
{
  if(navigator.appName == "Netscape") {
    console.log("[DBG]: " + msg);
    }  else {
   alert(msg); }
}

Monday, November 18, 2013

How to make the tmp file system volatile


mount -t tmpfs -o size=65536 tmpfs /tmp
With size restricted /tmp dir created .
 For this you need enable temp file system in Linux kernel.

 mount -t tmpfs -o size=$((192 * 1024)) tmpfs /var

 For example in nfs create a temporary fs to hold core files alone:

 #update the core file pattern
echo "/var/core/core.%e.%p" > /proc/sys/kernel/core_pattern
mkdir -p /var/core
mount -t tmpfs -o size=$((32 * 1024)) tmpfs /var/core

PHP example


HTML Client :  demo.html

<!DOCTYPE html>
<html>
<head>
<script src="javascript/jquery/jquery-1.9.1.min.js"></script>
<script>
http_post = function(){
var data = $.ajax({
        type: "POST",
        async: false,
        url: 'http://10.30.130.125/demo.php',
        data: ({request : {ID:"hello world"} }) 
        }).responseText;
         //return eval('(' +data +')');
//eval('(' +data +')');
//alert (data);
document.getElementById("demo").innerHTML=data ;
<!---document.getElementById("demo").innerHTML="Hello World";  -->
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="http_post()">Click me</button>
<p id="demo"></p>
</body>
</html>


PHP File: demo.php

<?php
error_reporting(E_ALL);
$in_str = "None" ;
if ($_POST) { 
//var_dump($_POST['request']) ;

$in_str = '{"demo":"'.$_POST["request"]['ID'].'"}' ;
//$in_str = $_POST["request"] ;
}

$service_port = '5000' ; 
$address = '10.30.130.170' ;

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

$result = socket_connect($socket, $address, $service_port);

echo $in_str ;

/* write into TCP/IP socket.*/
socket_write($socket, $in_str, strlen($in_str)); 

/* read from TCP/IP socket. */
$out = socket_read($socket, 4096);

/* Closing socket... */
socket_close($socket);

//$out = "{\"a\":1 }" ; 
header('Access-Control-Allow-Origin: *');
echo $out;
//echo '{"hi": 1 }';

/*echo "{\"a\":1 }" ;*/

?>

C Server Socket code below:

#include < sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include <sys/types.h>

int main(int argc, char *argv[])
{
    int listenfd = 0, connfd = 0;
    struct sockaddr_in serv_addr;
        char recvBuff[1024];
    int data = 65;
        int  n  ;
    time_t ticks;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, '0', sizeof(serv_addr));
    memset(&recvBuff, '0', sizeof(recvBuff));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(5000);

    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    listen(listenfd, 10);

    while(1)
    {
        connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
        n = read(connfd, recvBuff, sizeof(recvBuff)) ;
        recvBuff[n] = 0;
        printf("Recieved Client request.\n") ;
        printf("%s\n" , recvBuff) ;  // Received string will be ID => {"demo":"hello world"} 
        if(strstr(recvBuff, "hello world")== 0) 
        {
         write(connfd, &data, sizeof(data));
         close(connfd);
        }
        else
        {
          printf("%s\n" , recvBuff) ;
        }
        data++ ;
     }

}

Thursday, February 16, 2012

TT Specifications

Specs:

1.Blades
1.1.Handles
The Shakehand Models
AN - Anatomic Handle
FL- Flare Handle
ST -Staright handle
The penhold models
(It has rubber on only one side, hence to reduce weight, Asian use to hold
like a pen and drives the all shots in one side.)
CS-Chinese penhold
Jp- Japanese penhold
2.Rubber

Click here to search local butterfly rackets

Read b before you buy

Sunday, December 4, 2011

Look at a String literals



#include <stdio.h>
#include <string.h>
char *ap1="char *ap1";
static char *ap2="static char *ap2";
int ii;
main()
{
int i;
char a[] ="char a[]";
char a1[] ="char a1[]";
static char a2[32] ="static char a2[10] ";
const char a3[32] ="const char a3[10] ";
char *ap ="char *ap";
static char *aptr ="static *aptr";

printf("strlen a[] %d \n",strlen(a));
printf("sizeof a[] %d \n",sizeof(a));
printf("a[sizeof] %d \n",a[strlen(a)]);

char help[20]="a b c d e ";

printf("local:\n&i %p %d \n",&i,i);
printf("a1 %p %s \n",a1,a1);
printf("a2 %p %s \n",a2,a2);
printf("a3 %p %s \n",a3,a3);
printf("*ap %p %s \n",ap,ap);
printf("*aptr %p %s \n",aptr,aptr);
printf("global:\n*ap1 %p %s \n",ap1,ap1);
printf("*ap2 %p %s \n",ap2,ap2);
printf("&ii %p %s \n",&ii,ii);

}

[output]: ./a.out

strlen a[] 8
sizeof a[] 9
a[sizeof] 0
local:
&i 0xbff103f8 -1074723816 < stack
a1 0xbff103e5 char a1[]
a2 0x8049940 static char a2[10]
a3 0xbff103c5 const char a3[10]
*ap 0x80486d8 char *ap
*aptr 0x80486cb static *aptr
global:
*ap1 0x80486b0 char *ap1
*ap2 0x80486ba static char *ap2
&ii 0x8049968 (null)

NULL in stdio is ((void*)0)

Tuesday, November 29, 2011

Quick Makefile


CC=gcc
S = file1.c file2.c

O = $(S:%.c=%.o)


exe: ${O}
     $(CC) ${LIBS} -o $<



# pull in dependency info for *existing* .o files
-include $(OBJS:.o=.d)

%.o: %.c 

 $(CC) ${INCLUDES} $(CFLAGS) -MMD -o $@ -c $<
 gcc -MM $(CFLAGS) $*.c > $*.d


.PHONY clean
clean:
     \rm -rf *.o exe


Note: Green highlighted stuff optional or use -MMD, are used to create dependencies

Another Example:
--------------------
ERR = $(error found an error!)
.PHONY: err

err: ; $(ERR)

Thursday, October 27, 2011

Vi Tips - QuickFix


See
:help :compiler
:help :make

(the latter without a preceding exclamation mark) which will
automagically display the first error (if any) as soon as the make job
terminates. (Not sure if you'll get to the first _warning_ or _error_),
and a few other useful commands for use after that:

:cfir[st]
:cla[st]
:cn[ext]
:cp[revious]
:cnf[ile]
:cpf[ile]

for navigating the error list, and

:cope[n]
:ccl[ose]

to see it in its own window (the "quickfix" window), where hitting Enter
on an error moves to that line in the source. Of course, these commands
can be mapped for ease of use; for instance I have the following in my
vimrc:

:map :cnext
:map :cprev

which I use not so much for compiling but for the ":helpgrep" and
":vimgrep" commands (whose results also come in a quickfix window).

See also ":help quickfix.txt"



====================Vimdiff ==================
# vimdiff
Most of what you asked for is folding: vim user manual chapter on folding. Outside of diffs I sometime use:
   * zo -> open fold.
   * zc -> close fold.
But you wll probably be better served by:
   * zr -> reducing folding level.
   * zm -> one more folding level, please.
or even:

   * zR -> Reduce completely the folding, I said!.
   * zM -> fold Most!.
   
]c - Jump to the next change.
[c - Jump to the previous change.
:diffupdate :diffu -> recalculate the diff,

Sunday, August 21, 2011

Good Technical Books

1. Computer Architecture and Organization by John P. Hayes
Publisher: McGraw-Hill Companies; 3rd edition (December 1, 1997)
ISBN-10: 0070273553
ISBN-13: 978-0070273559http://www.blogger.com/img/blank.gif

2. Solid State Pulse Circuits by Bell David A
ISBN: 8120307445,
ISBN-13: 9788120307445
Publisher: Prentice Hall PTR

3. THREADTIME: Multithreaded programming guide by Scott J. Norton, Mark D. Dispasquale
Publisher: Prentice Hall PTR (November 1, 1996)
Language: Englishhttp://www.blogger.com/img/blank.gif
ISBN-10: 0131900676
ISBN-13: 978-0131900677
Link1: Google.books

4.The Magic Garden Explained: the Internals of Unix System V Release 4: an Open Systems Design By Berny Goodheart James Cox.
Publisher: Prentice Hall
Author: Berny Goodheart James Cox
ISBN: 0130981389
EAN: 9780130981387

Thursday, July 7, 2011

Step to extract a specific file from tar ball

1) zcat compressed.tar.Z | tar xvf - file1 file2
2) cat compressed.tar | tar xvf - file1 file2
3) tar -xf filename.tar file1 file2

Wednesday, May 18, 2011

JDBC Applications with MySQL


$cat Connect.java
import java.sql.*;

public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
//String query = "Select * FROM mysql.user";
String query = "Show databases";
String dbtime;
try
{
String userName = "root";
String password = "mysql";
String url = "jdbc:mysql://10.255.6.58/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);

System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
System.err.println ("Message :"+e.getMessage());
System.err.println ("Error message: " + e);

e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
dbtime = rs.getString(1);
System.out.println(dbtime);
} //end while

conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}


Compile Connect.java to produce a class file Connect.class that contains executable Java code:

% javac Connect.java

Then invoke the class file as follows and it should connect to and disconnect from your MySQL server:

% java -classpath .:/path/mysql-connectorJ-5.jar Connect
Database connection established
mysql
test
userdb
Database connection terminated


http://www.kitebird.com/articles/jdbc.html
http://download.oracle.com/javase/tutorial/jdbc/basics/connecting.html
http://www.java-samples.com/showtutorial.php?tutorialid=9

Tuesday, November 23, 2010

Auto Login using expect script


#!/bin/expect -f
# Parse argument Variables
set user [lrange $argv 0 0]
set ipaddress [lrange $argv 1 1]

spawn ssh -l user ipaddress
match_max 100000
# Look for passwod prompt
set timeout 2
expect "*(yes/no)?" {
send "yes\r"
}
expect "*?assword:*"
send "password\r"
interact
expect eof


---End---

./test user 192.1.1.1

Enablling traces in Bash script


#!/bin/bash

# require that all variables be set, otherwise the bash script will abort
set -o nounset

# pltTrace=2 # uncomment pltTrace to enable trace

export nodeType=""
export BaseProgName=`basename $0`
export ProgName=${BaseProgName}.$$

# if pltTrace is not already defined, define it
# this will allow individual programs to be
# debugged without turning on debugging for
# all scritps that source this file
if ! [ ${pltTrace:+1} ]
then
declare -x pltTrace=0
#change pltTrace to 1 to turn on debug for
# all scripts that haven't defined pltTrace
fi

if [ $pltTrace -ge 2 ]
then
PS4='${ProgName}:$LINENO: pltTrace-> '
set -o xtrace
fi

echo `date '+%Y%m%d.%H%M.%S'` ${BaseProgName} ": ENTER: Echoing here ..."

echo hello
if [ ! : ]; then
echo hello 2
fi
echo hello 3

---END---
Execute:
export pltTrace=2
./test

ttest.16898:37: pltTrace-> date +%Y%m%d.%H%M.%S
test.16898:37: pltTrace-> echo 20101124.0558.51 test ': ENTER: creating ZFS pools and files systems ... starting'
20101124.0558.51 test : ENTER: creating ZFS pools and files systems ... starting
test.16898:40: pltTrace-> echo hello
hello
test.16898:42: pltTrace-> '[' '!' : ']'
test.16898:47: pltTrace-> echo hello 3
hello 3

Monday, May 31, 2010

How to Use Purify

To use purify, you must create an instrumented executable file. For example, if your program consists of two files named main.C and List.C, you could created an instrumented executable named a.out by typing:

purify g++ -g main.C List.C

(As usual, use the -o flag to produce an executable named something other than a.out.)

Once you have produced an instrumented executable, just run it in the usual way (by typing its name, and, if your program is designed to use them, the appropriate command-line arguments).

Don't be surprised if the instrumented executable runs much more slowly than the non-instrumented version; it may also be much larger than the non-instrumented version.

And Run the executable automatically purify window will get opened along with the your executable.

Visit Following link for example
http://pages.cs.wisc.edu/~cs368-1/handouts/purify.html#example

Thursday, April 23, 2009

How to Create Stored Procedures and Functions in a MySQL Database

Over the past few years one major advantage that some databases, such as Oracle and Microsoft SQL Server, have had over MySQL is their ability to use stored functions and stored procedures. Well, that was before MySQL 5; with MySQL 5 a database developer can start adding in their own bespoke functionality.
What are Stored Procedures and Stored Functions?

Any programmers reading this should already be comfortable with the concept of subroutines and functions: encapsulated pieces of code that can be called by programs - often used to carry out repetative or complicated tasks.

Subroutines and functions can be made available to a single program or many; and that, of course, is what stored procedures and stored functions are - they are procedures (or subroutines) and functions stored in the database.
What's the Difference Between a Stored Procedure and a Stored Function?

The difference between a stored procedures and stored functions is the same as the difference between a subroutine and a function:

* a stored procedure runs some code
* a stored function runs some code and then returns a result

Why Use Stored Procedures and Stored Functions?

The real advantage to using stored procedures and stored functions is that they provide functionality which is platform and application independant. For example, a team of developers may provide:

* a Visual Basic application on Windows
* a Gambas application on Linux
* a PHP application on a web server

Without stored procedures and stored functions then the functionality would have to be developed independently for each application, but with stored procedures and stored functions the functionality only has to be developed once.

1. Creating MySQL Stored Procedures


A stored procedure is the same as a subroutine in that it cannot directly return a result, however it can receive variables that can be modified by the procedure; these variables are defined as:

* in - the variable can only be used as an input to the procedure
* out - the variable can only be used as an output from the procedure
* inout - this is both an input to, and an output from, the procedure

Procedures are always declared in the same way:

* define the procedure name
* define the procedure inputs and outputs
* define the the body of the procedure (enclosed within a BEGIN ... END statement)

One other (rather imporant) thing to bear in mind is that semicolons are used as part of the definition of the procedure. For this reason the end of line delimiter must be redefined to something that won't be used in the definition. For example:

delimiter //
create procedure circle_area (in r double, out a double)
begin
set a = r * r * pi();
end
//
delimiter ;

Running MySQL Stored Procedures

A MySQL stored procedure is run by using the call method:

call circle_area(22, @a);
select @a;


In this example 1520.5308443375 would be displayed on the screen.

2. Creating MySQL Stored Functions


Unlike stored procedures stored functions always return a result, they will also be one of two types:

* not deterministic - may produce different results for the same inputs (for instance random numbers or dates)
* deterministic - will always produce the same result for any given inputs

Like procedures, all functions are created the same way:

* define the function name
* declare any inputs
* define the data type to be returned by the function
* state whether or not the function is deterministic
* define the body of the function (again within a BEGIN ... END statement)

For example:

delimiter //
create function circumference (r double) returns double
deterministic
begin
declare c double;
set c = 2 * r * pi();
return c;
end
//
delimiter ;



Running MySQL Stored Functions

Unlike stored procedures stored functions are used as part of a select statement:

select circumference(22);

In this case (for anyone that's interested) the result would be 138.23007675795.
Conclusion

Stored procedures and stored functions are important tools for any database developer, and thankfully, those tools are now available to MySQL users - provided, of course, that they're using MySQL 5.

Read more: "MySQL Stored Procedures and Functions: How to Create Stored Procedures and Functions in a MySQL Database" -
http://database-programming.suite101.com/article.cfm/mysql_stored_procedures_and_functions#ixzz0DVzBNS5i&A

How to Access MySQL Stored Functions from a C++ Program

http://www.atlasindia.com/sql.htm

One of the most powerful combinations that any programmer can use is the combination of C++ and MySQL - a flexible programming language with a multi-platform and stable database; but this may seem an intimidating task to the new software developer.

It's not. This article will show just how easy it is for a programmer to use C++ to:

* set up a connection to a MySQL database
* use the C++ code to access an MySQL stored function
* display the results returned by the MySQL stored function
* and (perhaps most importantly) handle any errors

Setting up Test Data in a MySQL Database

Before a programmer can use a database that database must, of course, exist; or, at very least, a test database must exist. Fortunately creating a database in MySQL is very simple and consists of three steps:

1. log on to MySQL
2. use SQL to create the MySQL database and any tables
3. populate the tables with appropriate data

The first step (logging on to MySQL) can be done from the command line:

mysql -p -u user mysql
&nbsp or create new user from root login
mysql -u root -p
GRANT ALL ON cpp_data TO 'user1'@'localhost' IDENTIFIED BY 'password';
exit
mysql -p -u user cpp_data

Next, simple SQL can be used to the database and tables for the database:

Read more: "Using a MySQL Database with C++: How to Access MySQL Stored Functions from a C++ Program"

create database cpp_data;
use cpp_data;
create table users(id int, fname varchar(25), sname varchar(25), active bool);
insert into users values (1, 'Fred', 'Smith', True);
insert into users values (2, 'Jane', 'Jones', True);

With this done, it's time to start thinking about doing some actual programming.
Creating a Stored Procedure in a MySQL Database

One of the new additions to MySQL is one that Oracle users will already know - the stored function. The great advantage to using stored functions is that programming code can be built into the database rather than into an application - meaning that multiple applications can use the same piece of code:

delimiter //
create function user_count () returns int
deterministic
begin
declare c int;
select count(*) into c from users where active = True;
return c;
end
//
delimiter ;
select user_count ();

This code simply returns the number of active users (from the table users).
Loading the MySQL Header File into C++

When using MySQL with C++ the programmer needs to know absolutely nothing about the actual mechanics of the process - all the programmer has to do is to load the MySQL header file:

#include &lt iostream &gt
#include &lt mysql.h &gt
using namespace std;
MYSQL *connection, mysql;
MYSQL_RES *result;
MYSQL_ROW row;
int query_state;
int main() {
return 0;
}

C++ Code for Connecting to a Database

This example code above will compile and run, but doesn't actually do anything - first the C++ code must make a connection to the MySQL database:

mysql_init(&mysql);
//mysql_real_connect(&mysql,"localhost","User","Password","databaseName",0,0,0);
connection = mysql_real_connect(&mysql,"localhost","user1","password","cpp_data",0,0,0);
if (connection == NULL) {
cout << mysql_error(&mysql) << endl;
return 1;
}

The above code:

* initialises the MySQL connection
* makes the connection to the MySQL database (for which the programmer needs to define the host, user name, password and database)
* displays an error message if the connection is rejected for any reason

C++ Code for Running a Query on a MySQL Database

Having made a successful connection to the MySQL database the C++ code may be used to send s SQL query - in this case to run the stored procedure created earlier:

query_state = mysql_query(connection, "select user_count()");
if (query_state !=0) {
cout << mysql_error(connection) << endl;
return 1;
}

This time the C++ code sends the SQL and then displays another error message if any problem is encountered.
C++ Code for Processing the Results of a MySQL Query

If the connection is successful and the query returns a result (otherwise known as a recordset) then the next step is to display those results:

result = mysql_store_result(connection);
while ( ( row = mysql_fetch_row(result)) != NULL ) {
cout << row[0] << endl;
}

C++ Code for Disconnecting from a MySQL Database

The final step is to free up any memory used by the recordset and to close the connection:

mysql_free_result(result);
mysql_close(connection);

Compiling and Running the C++ Code

How the code is compiled will depend on the operating system being used and the local set up - in the case of Debian Linux the code would be compiled by using the command:

g++ -o db db.cc -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql

Assuming, of course, that the code is stored in a file named db.cc.
Conclusion

Both the MySQL database and the C++ programming language are powerful tools in their own right; and combined they are an incredibly important tool for the software developer - an important tool and one which is very easy to use, and very, very effective.
Further Reading

MySQL Stored Procedures and Functions

Read more: "Using a MySQL Database with C++: How to Access MySQL Stored Functions from a C++ Program" - http://c-programming.suite101.com/article.cfm/using_a_mysql_databases_with_c#ixzz0DVt7ShLb&A

Tuesday, November 11, 2008

Windows CMD prompt profile for Linux users

rem Set PATH to current working directory

mkdir profile
rem --- create ls command ---
echo @echo off > profile/ls.bat
echo dir >> profile/ls.bat
rem --- create pwd command ---
echo @echo off > profile/pwd.bat
echo cd >> profile/pwd.bat

Wednesday, October 22, 2008

Makefile Tips and Tricks - GNU Make


http://www.gnu.org/software/make/manual/make.html



Index of Concepts


append '-' before command to ignore error in makefile and
--silent with make or '@' before every command to echo off
eg:
  -rm foo
  -include Makefile_vars inc.mk
  @echo " Only once printed ";

Implicit variables
MAKELEVEL - Gives level of the make recursive subdir entries


Appendix A Quick Reference



Function Call Syntax

A function call resembles a variable reference.
It looks like this:
$(function arguments)
or like this:
${function arguments}


Functions for Transforming Text


1.Test Functions for String Substitution and Analysis

$(subst from,to,text)
$(patsubst pattern,replacement,text)
$(strip string)
.........and so on
example : override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))

2. So on.. Please click link for further details



.PHONY Target


Automatic Variables

$< $@ $? $*


Defining and Redefining Pattern Rules

Here are some examples of pattern rules actually predefined in make. First, the rule that compiles `.c' files into `.o' files:

%.o : %.c
        $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@

defines a rule that can make any file x.o from x.c. The command uses the automatic variables `$@' and `$<' to substitute the names of the target file and the source file in each case where the rule applies (see Automatic Variables).

Bash Script Tips

http://www.hsrl.rutgers.edu/ug/shell_help.html

Command line arguments to shell scripts are positional variables:
$0, $1, ... - The command and arguments.
   With $0 the command and the rest the arguments.

$# - The number of arguments.
$*, $@ - All the arguments as a blank separated string.
  Watch out for "$*" vs. "$@".
  And, some commands: shift

$$ - Current process id.
$? - The exit status of the last command. and return result of last function

Conditional Reference
${variable-word} - If the variable has been set, use it's value, else use word.

POSTSCRIPT=first;
echo POSTSCRIPT
POSTSCRIPT=${POSTSCRIPT-second};
export POSTSCRIPT
echo POSTSCRIPT

${variable:-word} - If the variable has been set and is not null, use it's value, else use word.

These are useful constructions for honoring the user environment.
Ie. the user of the script can override variable assignments. Cf. programs like lpr(1) honor the PRINTER environment variable, you can do the same trick with your shell scripts.

${variable:?word} -If variable is set use it's value, else print out word and exit. Useful for bailing out.

String concatenation
The braces are required for concatenation constructs.
$p_01 - The value of the variable "p_01".
${p}_01 - The value of the variable "p" with "_01" pasted onto the end.

Include configuration
. command

This runs the shell script from within the current shell script. For example:
# Read in configuration information
. /etc/hostconfig

Debugging
The shell has a number of flags that make debugging easier:
sh -n command -

Read the shell script but don't execute the commands. IE. check syntax.
sh -x command
Display commands and arguments as they're executed. In a lot of my shell scripts you'll see
# Uncomment the next line for testing
# set -x

Makefile Options

http://www.hsrl.rutgers.edu/ug/make_help.html

dependecy1: dependencyA dependencyB ... dependencyN
[tab] command for dependency1

That is probably one of the simplest makefiles that could be made. When you type make, it automatically knows you want to compile the 'myprogram' dependency (because it is the first dependency it found in the makefile). It then looks at mainprog.cc and sees when the last time you changed it, if it has been updated since last you typed 'make' then it will run the 'gcc mainprog.cc ..." line. If not, then it will look at myclass.cc, if it has been edited then it will execute the 'gcc mainprog.cc ..." line, otherwise it will not do anything for this rule.

Before issuing any command in a target rule set there are certain special macros predefined.

1. $@ is the name of the file to be made.
2. $? is the names of the changed dependents.

So, for example, we could use a rule

printenv: printenv.c
[tab] $(CC) $(CFLAGS) $? $(LDFLAGS) -o $@

alternatively:

printenv: printenv.c
[tab] $(CC) $(CFLAGS) $@.c $(LDFLAGS) -o $@

There are two more special macros used in implicit rules. They are:

3. $< the name of the related file that caused the action.
4. $* the prefix shared by target and dependent files.

Example Target Rules
INC=../misc
OTHERS=../misc/lib.a

$(OTHERS):
[tab] cd $(INC); make lib.a

Beware:, the following will not work (but you'd think it should)

INC=../misc
OTHERS=../misc/lib.a

$(OTHERS):
[tab] cd $(INC)
[tab] make lib.a

Each command in the target rule is executed in a separate shell. This makes for some interesting constructs and long continuation lines.

Tuesday, October 21, 2008

GCC Options and GDB notes

gcc example.c [options]

-S - Compiles and stops. Output is assembler code (suffix .S).
-o [name] - Gives executable as 'name'.
-E - Preprocess source file only.
    Comments will be discared unless -C is also specified.
    Creates #line directives unless -P is also specified.
-M - The preprocessor outputs one make rule containing the object file name for that source file, a colon, and the names of all the included files,including those coming from -include or -imacros command line options.
-W - Print extra warning messages.
    -Wall print all warnings


Example:
cat > example.c << EOF
#include <stdio.h>
#include <string.h>

int main()
{
printf("Hello world");
}
EOF
#


GDB notes:

Compile C code with -g option and run 'gdb a.out'
In gdb prompt set the break point as 'break main' or any function.
To run 'run '
To watch the particular variable set 'watch ' and if the variable get modified then it will get notified
To see the local variables 'info local'
To proceed next line 'n or next'
list to display the source code

Wednesday, July 23, 2008

Intel hex code Format

The Intel hex record looks like:
:090160001204283119740280E236

Intel hex data record: ':nnaaaattddddddd...dcc'
where:
: == start of data record
nn == number of bytes in record in ascii hex
aaaa == address to load data record at in memory
tt == type of record; 00=data; 01=end of file
ddd...d == data bytes of record in ascii hex (two chars per byte)
cc == checksum of record

checksum is two's complement of eight bit sum of all data from 'nn'
to end of data '...d'
end of file record (00) has zero number of bytes

So the above record would be decoded as :

:090160001204283119740280E236
start of record :
length of record 09
address to store record at 0160
record type 00
actual data of record 1204283119740280E2
checksum of record 36

Wednesday, July 16, 2008

Find error number in C

Refer : http://www.xinotes.net/notes/note/1793/  for getsockopt case

/usr/include/asm/error.h

#ifndef _I386_ERRNO_H
#define _I386_ERRNO_H

#define EPERM 1 /* Operation not permitted */
#define ENOENT 2 /* No such file or directory */
#define ESRCH 3 /* No such process */
#define EINTR 4 /* Interrupted system call */
#define EIO 5 /* I/O error */
#define ENXIO 6 /* No such device or address */
#define E2BIG 7 /* Arg list too long */
#define ENOEXEC 8 /* Exec format error */
#define EBADF 9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */

#define EDEADLOCK EDEADLK

#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define EREMOTEIO 121 /* Remote I/O error */
#define EDQUOT 122 /* Quota exceeded */

#define ENOMEDIUM 123 /* No medium found */
#define EMEDIUMTYPE 124 /* Wrong medium type */

#endif

Monday, June 9, 2008

Telnet command with port number.

Telnet command will helps to peep in to the remote server's application port. And we can have response from the remote server if you sent appropriate packets or data.

Syntax: telnet [IP address] [Application port num]
eg:
#telnet 192.168.1.2 8000
[ type here to send the appropriate data which remote server can recognize ]
Use Crtl + ] to get command mode prompt.
telnet> ? Enter
Gives some commad
telnet>close -->to exit

If you want to send Http response from command ..
Use ethereal to capture the data to be sent.
[Hint Right click the request and select TCP Streams ,You will get the Http response packet , Just Copy and paste it after telnet.]
Procedure
---------

Below packet is the capture of the HTTP get method ,since
assuming httpd is running in the server at port 8080.

#telnet 192.168.1.2 8080



If application is HTTP server below code capture will help full.
---This is what HTTP GET method request packet looks----
GET /index.html HTTP/1.1
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Host: 192.168.1.1:8080
Connection: Keep-Alive
Cache-Control: no-cache
------------------------Ends-----------------

---This is what HTTP POST method request packet looks----
POST /line_sip.htm?l=1 HTTP/1.1
Content-Length: 312
Connection: Keep-Alive

user_moh1=&user_alert_info1=&user_pic1=&user_dp_str1= &user_dp_exp1_0=off&user_dper_expiry1=3600&user_auto_connect1=off &user_descr_contact1=on&user_sipusername_and_local_name1=off& Settings=Save
------------------------Ends-----------------
user_moh1,user_alert_info1 .. are variables getting update values by POST request.

Telephone Recorder Circuit



This is simple telephone Recorder circuit.
T1 = Audio Transformer
(available in old modem or phone set)
R1 = 5.6K ohms
R2 = 10K ohms
R3 = 4.4K ohms
C1 = Disc Capacitor 203
D1 =D2 = 1N4148

Friday, June 6, 2008

Test Operator Usage



Example
[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup <== This check for Exec permision
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources <== this will check exists and a file

Ascii Table

Thursday, April 3, 2008

Linux Commad ctags with find

catgs:
ctags -w `find $(SUBDIRS) include common \( -name CVS -prune \) -o \( -name '*.[ch]' -print \)`

find [options]
-name '*.[ch]' => This option restricts *.c and *.h files only
-prune -o -print => use to display and cut out subdirectories

This will search only .c and .h files with argument as search pattern"
alias f "find . -name '*.[c,h]' -print | xargs grep -n --color $1 "
eg: f pattern