Wednesday 12 December 2012

how to use pdb

Simple way to debug python programs using pdb

python -m pdb <python script.py>

Sunday 9 September 2012

dedications

A post as a dedication to all the teachers who teach programming and to my teachers who have thought me to program. PSM sir, Mohan Sir, KVB, Lalitha Kumari , Thaygraj sir,  Julie Zelenski, Neelesh , David Evans and my friends. I thank them for teaching me programming in class , through the videos or at home.

Search a sorted array for first occurance of K


Find the first occurrence of a given element in the sorted list.

Search + sorted  the way  to go ahead is with binary search. Binary search my default doesn't guarantee to return the first occurrence of the element in case of duplicates. So what to do? search for the element using binary search, check if the element at index-1 is equal to search element if yes rerun binary search from 0 to index-1 else we have our answer.

#------------------------------------------------------------------------------- # Name: fristKInSortedList # Purpose: Find the first occurace of an element in the sorted list # # Created: 10/09/2012 #------------------------------------------------------------------------------- def main(): sortedlist = [1,2,3,4,5,5,5,5,5,5,6,6,6,7,8,9,9,9,11,12,12,12,12,12,12,14,14,14,15,15,15,16] element=9 print(fristKInSortedList(sortedlist,element)) def fristKInSortedList(inlist,element): flag = True index = len(inlist) if inlist[0] == element: return 0 while flag or inlist[index-1] == element:#second part of or never executes the first time flag = False index = binarySearchRecursive(inlist,element,0,index-1) if index == -1: return index return index def binarySearchRecursive(slist,element,begin,end): if len(slist) <= 0: print("invalid list! Empty List!") return -1 if begin > end: return -1 mid=int((begin+end)/2) if slist[mid] > element: return binarySearchRecursive(slist,element,begin,mid-1) elif slist[mid] < element: return binarySearchRecursive(slist,element,mid+1,end) else: return mid if __name__ == '__main__': main()

Matrices Multiplication algorithm implementation in python

Matrices Multiplication implementation in python.

I always ignored questions on matrices i rather ran away from those never dared to accept them and code them, finally made up my mind. Next one in line is "inplace" transform of matrix.  Ns ran away ow that i have started programming matrices i feel better to have done something which i always ran away from.

#------------------------------------------------------------------------------- # Name: matrixmultiplication # Purpose: # # Created: 08/09/2012 #------------------------------------------------------------------------------- def main(): mat1=[[1,2,3,4],[3,3,3,4],[5,6,7,8],[5,6,7,8]] mat2=[[1,2,3,4],[1,2,3,4],[5,6,7,8],[5,6,7,8]] mat3=[[9,2],[6,2],[9,7],[5,6]] c = matmulti(mat1,mat2) print(c) def zeros(*shape): if len(shape) == 0: return 0 a = shape[0] b = shape[1:] return [zeros(*b) for i in range(a)] def matmulti(a,b): x=len(a) y=len(a[0]) m=len(b) n=len(b[0]) #print(x,y,m,n) if y != m: print("Canot multipy the matrices as the column count of multiplier is not equal to the row count of the multiplicand") return [] i,j,k,c=0,0,0,zeros(x,n) while i < x: j=0 while j < n: k=0 sum=0 while k < y: sum=sum+(a[i][k]*b[k][j]) k=k+1 c[i][j]=sum j=j+1 i=i+1 return c if __name__ == '__main__': main()

Square root of a number upto accurate 6 decimal points

Implement a fast integer square root function that takes in a unsigned integer and returns another unsigned integer that is the square root of the input correct up to 6 decimal places.

Solution:
Classic application of Binary search Algorithm to solve the square root problem. A question asked in FB interview. Coded in python one of my fav programming language cant believe i ditched C++ :(. I'm still novice in python but would love to code more and more in python.

I need a better solution to stop at after 6 places after the decimal point, one other obvious solution is to run the while loop six times, but i need a mathematical rule which controls the loop.

#------------------------------------------------------------------------------- # Name: SquareRoot.py # Purpose: Implement a fast integer square root function that # takes in a unsigned integer and returns another unsigned integer that is # the square root of the input correct upto 6 decimal places. # # Created: 09/09/2012 #------------------------------------------------------------------------------- def main(): number=334567 sqroot=findsqroot(number) print(sqroot) def findsqroot(number): i=0 for i in range(number+1):# for 1 and 2 special cases input we need number+1 product=i*i if product > number: break; elif product == number: return i print(i) rootbase=i-1 begin,end=rootbase,i mid=(begin+end)/2 product=mid*mid while ((mid-rootbase)*1000000%10) == 0: if product > number: end=mid elif product < number: begin=mid else: return mid mid=(begin+end)/2 product=mid*mid return mid if __name__ == '__main__': main()

Thursday 12 July 2012

Export MySQL tables into CSV/PSV/TSV format


CSV:
mysql my_db -e "SELECT * FROM my_table" | sed 's/\t/","/g;s/^/"/;s/$/"/;' > my_db.my_table.csv
 
PSV:
mysql my_db -e "SELECT * FROM my_table" | sed 's/\t/|/g' > my_db.my_table.psv
 
TSV:
mysql my_db -e "SELECT * FROM my_table" > my_db.my_table.tsv 

Wednesday 11 July 2012

kill -9 , A bad idea!

[Source]:http://web.archive.org/web/20080801151452/http://speculation.org/garrick/kill-9.html

Most programs require some sort of cleanup when it exits. These programs setup a signal handler to perform these cleanup duties as a result of SIGTERM and SIGINT. They would setup a signal handler for SIGKILL if they could, but SIGKILL is untrappable.
If a program decided to trap the TERM or INT signals, then it would most likely delete any temporary files, shutdown sockets, remove shared memory segments, close open files, or some other task. For instance, MySQL needs to flush data to disk and close its database files. Killing MySQL with -9 will corrupt your databases. Most user apps that work on some binary formatted data files require temporary files, using kill -9 on these apps would leave around these temporary files. Network daemons need to flush their logs and properly shutdown Internet sockets so that clients aren't left hanging. Killing your web browser can corrupt your bookmarks file, cache files, leave temp files in /tmp (remember that 20MB mpeg you clicked on? yah, it's still sitting in /tmp)
Using kill -9 on a process is like just hitting the power button on your running PC. You already know that powering off a running PC can damage your filesystem because of run-time inconsistent data, why would you do the same thing to your applications? You risk the _exact same_ data corruption.

Therefore, so that your important applications may close themselves, it is very important you follow this procedure when killing them:
kill pid (sends a TERM, wait 5 seconds)
kill pid (yes, try again, wait 5 seconds)
kill -INT pid  (wait for it)
kill -INT pid  (damn, still not dead?)
kill -KILL pid (same thing as -9)
kill -KILL pid (something is wrong)
If the process is still running, then stop sending it signals. It's either stuck in I/O wait or it's Defunct. 'ps auxw | grep processname', if you see it's in state D, then kill its parent process (the 3rd column of 'ps -ef' is the parent pid). If it's in I/O wait, then you have a deeper system problem. Most home users will never have this problem.

Wednesday 27 June 2012

Issue:- ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Issue:- ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Solution:- Follow the below steps.

[root@server ~]# /etc/init.d/mysql stop

Stopping MySQL: [ OK ]

[root@servert1 ~]# mysqld_safe --skip-grant-tables &

[root@servert1 ~]# Starting mysqld daemon with databases from /var/lib/mysql



[root@servert1 ~]# mysql -u root

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 1

Server version: 5.0.77 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.


mysql> show databases;

+--------------------+

| Database |

+--------------------+

| mysql | 

+--------------------+

1 rows in set (0.13 sec)



mysql> use mysql; 

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A



Database changed

mysql> show tables;

+---------------------------+

| Tables_in_mysql |

+---------------------------+

| columns_priv | 

| db | 

| func | 

| help_category | 

| help_keyword | 

| help_relation | 

| help_topic | 

| host | 

| proc | 

| procs_priv | 

| tables_priv | 

| time_zone | 

| time_zone_leap_second | 

| time_zone_name | 

| time_zone_transition | 

| time_zone_transition_type | 

| user | 

+---------------------------+

17 rows in set (0.00 sec)



mysql> update user set password=PASSWORD("testpass") where User='root';

Query OK, 3 rows affected (0.05 sec)

Rows matched: 3 Changed: 3 Warnings: 0



mysql> flush privileges; 

Query OK, 0 rows affected (0.04 sec)



mysql> quit



[root@server ~]# /etc/init.d/mysql restart

STOPPING server from pid file /var/run/mysqld/mysqld.pid

101120 04:17:15 mysqld ended

Stopping MySQL: [ OK ]

Starting MySQL: [ OK ]

[1]+ Done mysqld_safe --skip-grant-tables

[root@servert1 ~]# mysql -u root -p

Enter password: 

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 2

Server version: 5.0.77 Source distribution



Type 'help;' or '\h' for help. Type '\c' to clear the buffer.



mysql>