Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Monday 24 November 2014

Change the screen brightness using bash script - xrandr

November 24, 2014 Posted by Dinesh , , ,

In my Ubuntu 14.0 (Dell Inspiron), brightness controls were not working at all. So I started searching for other alternatives to sets the brightness.

finally I found this xrandr.
it is great tool to set the brightness and even to rotate the screen.


--brightness flag can be used to set the brightness (best values: 0 - 1)
--brightness flag cab be used to rotate the screen (possible options : normal, left, right) 

Usage:
          ./brightness_control.sh +      # Increase the brightness by 0.05
          ./brightness_control.sh  -       # Decrease the brightness by 0.05
          ./brightness_control.sh 1       # Set brightness to 1
 
 



Saturday 13 September 2014

Undestanding Generators in Python

September 13, 2014 Posted by Dinesh ,
Before we understand generator we must know Iterator.

Iterator:
Iterator is any object which understands the concept of a for-loop.
Basically this means that it has a next method, when it is called it returns the next item in the sequence.
Everything you can use in "for" is an iterable: lists, strings, files...etc

>>> [x*x for x in range(3)]
[0, 1, 4]


>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
    print i


0
1
4


Generator:
Generators are iterators, but you can only iterate over them once.
It's because they do not store all the values in memory, they generate the values on the fly.

If we try to print the generator we will get the object.

>>> (x*x for x in range(3))
<generator object <genexpr> at 0x000000000268C480>


>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
 print i
0
1
4


Generators can be iterated only once. If we try to iterate over them again we get nothing its because when for loop is running it actually calls next element in the tuple and loop will break when there are no more elements. Once the loop breaks generator is destroyed (object still exist but no more elements to return). So if we try to use the same generator again to print the elements we get nothing.

>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
 print i
0
1
4

>>> for i in mygenerator:
 print i


In short,  if round parentheses are used, then a generator iterator is created.
If rectangular parentheses are used, then we get a list.


Sunday 27 July 2014

Encrypt files using Vim

July 27, 2014 Posted by Dinesh , , , , , No comments

Vim comes with default encryption mechanism refereed as VimCrypt in the documentation. It is capable of writing files encrypted and read them back.

Creating new encrypted file:

vim -x <file>

This will create new file if it is not exist or open an existing file and prompt for password. This password is used as key to encrypt and decrypt the file.

Encrypt the current working file:

:X

You can also encrypt the current working file /open files using :X  option. This will also prompt for password. The typed password is stored in the 'key' option which is used to encrypt the file when it is written.

Disable the encryption:

To disable the encryption reset the 'key' option to empty value. To do this you first need to open the file with proper password.

:set key=




Saturday 26 July 2014

Automate your Vim - The power of autocmd

July 26, 2014 Posted by Dinesh , , , No comments


1. Vim templates


I often used to write sample C++ codes to test the functionality. But it is pain to add default code for every test code that I write. Vim has a brilliant solution for it. that is templates.

Create some template files in any of the directory you wish, here I created ~/.vim/templates/skeleton.cpp that contains default c++ code i.e #include, using namespace std, main,..etc.
Then add the below code to your ~/.vimrc  file. Now try to open a new cpp file and see the magic.


Here we are telling vim that, if I try to open a new cpp file, read the content from ~/.vim/templates/skeleton.cpp file and write to the new file that is opened. Similarly you can have templates for all type of files.

This means, what ever you write in template will be loaded by default for every file you open newly using vim.


2. Auto compile C++ code on saving


We can even compile the code immediately after saving the file without typing any single command.  Add the below code to your vimrc file and try to save the test cpp file. It will create a executable with the name of the file.

1
2
"Auto compile on save
autocmd BufWritePost,FileWritePost *.cpp !g++ -Wall %:p -o %:r 

In vim :p expands to full file name path and :r expands to root of the file name (file extension will be removed)

But this is bad ! every time you try to save your file it tries to compile. So there is alternative, vim has quit event. i.e VimLeave.

1
2
"auto compile on quit - silent: do not report errors
autocmd VimLeave *.cpp !silent g++ -Wall %:p -o %:r

VimLeave event indicates vim to execute the command specified after ! before exiting the vim after writing viminfo file.

3. Abbreviations for faster coding


Abbreviations can save typing when you want to type same text multiple times thorough the document. and abbreviations can be defined to auto correct the typos.
Add the below code to your vimrc file and try to edit the cpp file. when every you type iff this will be auto corrected to if ()  and moves the cursor in between the parenthesis.


abbrev(ab) is used to create abbreviations, this works on normal mode. iabbrev is used to work with abbreviations on insert mode. and <left> is used to move the cursor one character left.

4. Auto comments


Similarly to automate commenting add the below code to vimrc.


Vim will detect the file type using FileType event. And we are mapping the movement ,c to comment lines.
But this will comment only current line.

For commenting a block of text, go to the first line you want to comment, press Ctrl + V, and select until the last line. Second, press I// + Esc (then give it a second), and it will insert a // character on all selected lines.
ctrl+v
drop down using arrow key(select only first character of the each line)
shif+i
shift+//
esc
Un-commenting a block of text is almost the same: Put your cursor on the first # character, press CtrlV and go down until the last commented line and press x, that will delete all the # characters vertically.

Learning from http://learnvimscriptthehardway.stevelosh.com/

Saturday 4 January 2014

Python - Thread synchronization - using Thread Events

January 04, 2014 Posted by Dinesh No comments
We may often need to signal the thread to do some special task. Simple solution is to create events.

Definition from python docs:
threading.Event()
    A factory function that returns a new event object. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true 

the event represents an internal flag, and threads can wait for the flag to be set, or set or clear the flag themselves. The methods provided are very much self explanatory: set() clear() isSet() wait(timeout)
This is a simple mechanism. A thread signals an event and the other thread(s) wait for it.

In the following example we are crating an event and a thread,  and passing that event to the thread function. that thread function is waiting on that event. if user press ctrl+c then it is caught in the main program by keyboardInterrup and we are setting the stop event. This even cause the while in the thread function to break and exits the thread.


#!/usr/bin/python
import threading,time

def collectstats(event):
    while not event.is_set():
          event.wait(1)
    print "event set.. thread exiting.."

stop_event = threading.Event()
th = threading.Thread(target=collectstats, args=(stop_event,))
th.start()

while True:
    try:
        time.sleep(100)
    except KeyboardInterrupt as e:
        stop_event.set()
        th.join()
        break;

print "in main: exiting.."

if we run the program, here is the output


# ./even.py 

^Cevent set.. thread exiting..
in main: exiting..

Any number of threads can wait on same event and can set same event. once the even is set it will notify all the threads ( equivalent to notifyall() method )

Friday 3 January 2014

Python - Signal handling and identifying stack frame

January 03, 2014 Posted by Dinesh No comments
Signals are identified by integers and are defined in the operating system C headers. Python exposes the signals appropriate for the platform as symbols in the 'signal' module. 

the signal module in python is used to install your own signal handlers.  When the interpreter sees a signal, the signal handler associated with that signal is executed as soon as possible.

signal handler is a call back function, the arguments to the signal handler are the signal number and the stack frame from the point in your program that was interrupted by the signal. 

First basic example:

import signal,time

def signal_handler(signum, stack):
    print 'Received:', signum

signal.signal(signal.SIGHUP, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(15, signal_handler)
while True: print 'Waiting...try kill using signal 1(SIGHUP) or 2(SIGINT)' time.sleep(3)


Linux Standard signals:
from signal man page:
       Signal     Value     Action   Comment
       -------------------------------------------------------------------------
       SIGHUP        1       Term    Hangup detected on controlling terminal or death of controlling process
       SIGINT        2        Term    Interrupt from keyboard
       SIGQUIT       3      Core    Quit from keyboard
       SIGILL        4        Core    Illegal Instruction
       SIGABRT       6      Core    Abort signal from abort(3)
       SIGFPE        8       Core    Floating point exception
       SIGKILL       9       Term    Kill signal
       SIGSEGV      11     Core    Invalid memory reference
       SIGPIPE      13      Term    Broken pipe: write to pipe with no readers
       SIGALRM      14       Term    Timer signal from alarm(2)
       SIGTERM      15       Term    Termination signal
       SIGUSR1   30,10,16    Term    User-defined signal 1
       SIGUSR2   31,12,17    Term    User-defined signal 2
       SIGCHLD   20,17,18    Ign     Child stopped or terminated
       SIGCONT   19,18,25    Cont    Continue if stopped
       SIGSTOP   17,19,23    Stop    Stop process
       SIGTSTP   18,20,24    Stop    Stop typed at tty
       SIGTTIN   21,21,26    Stop    tty input for background process
       SIGTTOU   22,22,27    Stop    tty output for background process

The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored. 

How to trap all the signals (except few..!!) ??
here is the example: 

#!/usr/bin/python
import signal

def sighandler(signum, frame):
 print "Caough signal :", signum

for x in dir(signal):
  if x.startswith("SIG"):
     try:
        signum = getattr(signal,x)
        signal.signal(signum,sighandler)
     except:
        print "Skipping %s"%x
   
while True:
      pass


Printing stack frames :

The frame argument is the stack frame also known as execution frame. It point to the frame that was interrupted by the signal. to print the stack trace you need to use 'traceback' module. 
this is very useful in multi-threaded program because any thread might be interrupted by a signals and signal is only received by the main program. 


#!/usr/bin/python
import signal,traceback

def sighandler(signum, frame):
 print "Caough signal :", signum
 traceback.print_stack(frame)

for sig in dir(signal):
  if sig.startswith("SIG"):
     try:
        signum = getattr(signal,sig)
        signal.signal(signum,sighandler)
     except:
        print "Skipping %s"%sig
   
while True:
      pass

Ignoring signals:

To ignore a signal, register SIG_IGN as the handler (no call back required). This will ignore the ctr+c signal raised from terminal.

#!/usr/bin/python
import signal

signal.signal(signal.SIGINT,signal.SIG_IGN)

while True:
 pass