Generate thumbnail in ubuntu

sudo apt-get install imagemagick

for i in $(ls *.png); do convert -scale 400 $i th-$i; done

Mar31

Code is like poetry

Code is like poetry

difficult to understand and often has other meaning than intended.

Code is like poetry.

Delightful to read
a pleasure to understand
a lifetime to master.

Dec28

Handle Uploaded file using post in django

def receive(request):
   assert request.method=="POST"
   print "receive.META.SERVER_PORT", request.META["SERVER_PORT"], request.POST
   files = []
   for multipart_name in request.FILES.keys():
      multipart_obj = request.FILES[multipart_name]
      content_type  = multipart_obj['content-type']
      filename      = multipart_obj['filename']  
      content       = multipart_obj['content']  
      files.append((filename, content_type, content))
      import datetime
      # write file to the system - add timestamp in the name
      file("c:\\tmp\\%s_%s" % (datetime.datetime.now().isoformat().replace(":", "-"), filename), "wb").write(content)
 
   fnames = ",".join([fname for fname, ct, c in files])
   return HttpResponse("me-%s-RECEIVE-OK[POST=%s,files=%s]" % (request.META["SERVER_PORT"], request.POST.values(), fnames ))
def write_tmp_file(self,request):
        # open a new file to write the contents into
        new_file_name = TEMP_FILE_PATH + request.FILES['file'].name 
 
        destination = open(new_file_name, 'wb+')
        destination.write(request.FILES['file'].read())
        destination.close()
 
        return str(new_file_name)

Jun27

Upload file using urllib,pycurl and requests in python

 
url = "http://example.com/"
filename = "/home/yash/sample.dat"
 
import urllib
 
f=open(filename, 'rb')
filebody = f.read()
f.close()
data = {'name':'file','file': filebody}
u = urllib.urlopen(url,urllib.urlencode(data))
print u.read()
 
 
import cStringIO
import pycurl
 
response = cStringIO.StringIO()
c = pycurl.Curl()
 
c.setopt(c.POST, 1)
c.setopt(c.URL, url)
c.setopt(c.HTTPPOST, [("file", (c.FORM_FILE, filename))])
# c.setopt(pycurl.HTTPPOST, [('file', (pycurl.FORM_FILE, file_path, pycurl.FORM_FILENAME, filename))])
c.setopt(c.VERBOSE, 1)
c.setopt(c.WRITEFUNCTION, response.write)
c.perform()
c.close() 
print response.getvalue()    
 
import requests
 
 
f = open (filename)
r = requests.post(url = url, data =  {'data':'data'},  files =  {'file':f})
print r.status_code
print r.headers   
print r.text

Jun27

Python datetime

import datetime
 
now = datetime.datetime.now()
 
print
print "Current date and time using str method of datetime object:"
print str(now)
 
print
print "Current date and time using instance attributes:"
print "Current year: %d" % now.year
print "Current month: %d" % now.month
print "Current day: %d" % now.day
print "Current hour: %d" % now.hour
print "Current minute: %d" % now.minute
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond
 
print
print "Current date and time using strftime:"
print now.strftime("%Y-%m-%d %H:%M")

Jun26

On remote running command and fetching file using paramiko

ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
            ssh.connect(hostname=hostname, username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(ssh.get_transport())
            stdin, stdout, stderr = ssh.exec_command(cmd)
            channel = stdout.channel
            while True:
                if channel.exit_status_ready():
                    break
 
            #OTHER way  
            #transport = paramiko.Transport((hostname, ports))
            #transport.start_client()
            #transport.connect(username = username, password = password)
            #rfile = sftp.open(remoteD)
            #sftp.unlink(remoteD)
 
            if not sftp.stat(remoteD) :
                raise Exception("remote wav file not found")
 
            #to copy file from remote to local
            sftp.get(remotepath=remoteD, localpath=localD)

References :

http://www.minvolai.com/blog/2009/09/how-to-ssh-in-python-using-paramiko/

Jun26

Wave python module usage

Converting a wav into 16bit mono format

#Modifying sound file according to below requirement:
#    BitRate 128kbs 
#    16 bit
#    8 KHz    
#    Audio format PCM
# Author : Yash
 
import wav
 
f = wave.open(filename)
# read in entire wav file
nFrames = f.getnframes()
wdata = f.readframes(nFrames) 
params = f.getparams()
 
f.close()
 
n= list(params)
#MONO
n[0] = 1
#8000 hz
n[2] = 8000
 
params = tuple(n)
 
 
f = wave.open(filename,'wb')
f.setparams(params) 
f.writeframes(wdata)
f.close()

Reference:

http://codingmess.blogspot.in/2008/07/how-to-make-simple-wav-file-with-python.html

http://stackoverflow.com/questions/9779416/faster-way-to-convert-from-24-bit-wav-pcm-format-to-float

Jun26

Python list to tuple and tuple to list

 
In [34]: list1 = ['1','2','3','4']
 
In [35]: list1
Out[35]: ['1', '2', '3', '4']
 
In [36]: tup = tuple(list1)
 
In [37]: tup
Out[37]: ('1', '2', '3', '4')
 
In [38]: backlist = list(tup)
 
In [39]: backlist
Out[39]: ['1', '2', '3', '4']

Jun26

SOX usages

sox samples

-c 2  : Number of channels
-b : 16 bit
-r 8000 sampling rate
-t u16(ulaw) / gsm shows type

pad 1000s   : for adding gaps in the begining

Increase sound in wav
sox -v 2.0 file.wav

Adding Silence in the beggining of wav file
sox voice.wav pad 1000s

Converting MP3 to PCM based WAV
sox r.mp3 -r 8000 -c 1 tt1.wav

Converting MP3 to ulaw based WAV file
sox -v 2 -V /home/yash/dumps/r.mp3 -r 8000 -U -b 1 -c 1 -t u16 /home/yash/dumps/infile.ulaw resample -ql

lame -b 128 -m m –resample 8

Reference links:

http://sox.sourceforge.net/sox.html

http://www.thegeekstuff.com/2009/05/sound-exchange-sox-15-examples-to-manipulate-audio-files/

http://sox.sourceforge.net/soxformat.html

http://sox.sourceforge.net/Docs/FAQ

For missing types in SOX
sudo apt-get install libsox-fmt-all

Jun26

Environment variable CentOS

The easiest way to set an environment variable in CentOS is to use export as in

<pre>$> export JAVA_HOME=/usr/java/jdk.1.5.0_12

$> export PATH=$PATH:$JAVA_HOME</pre>

However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots.

In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile.

For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case:

Create a new file called java.sh

vim /etc/profile.d/java.sh

Within this file, initialize the necessary environment variables

export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin

export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME

export PATH=$PATH:$JAVA_HOME/bin

Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded) .

PS: If you want to load the environment variables within java.sh without having to restart the machine, you can use the source command as in:

$> source java.sh

Jun26