Archive | python RSS feed for this section

Remove python2.7 and rollback to python2.6

21 Oct
sudo ln -f /usr/bin/python2.6 /usr/local/bin/python





Use different Python version with virtualenv

18 Oct

virtualenv -p /usr/bin/python2.6 /provide/path/to/new/virtualenv/

Where python2.6 is the python version which can be changed to anything and virtualenv path is the folder created by you to install virtualenv in it

Calculate n-gram in python

12 Oct
def ngrams(sequence, n, pad_left=False, pad_right=False, pad_symbol=None): 
	if pad_left: 
		sequence = chain((pad_symbol,) * (n-1), sequence) 
	if pad_right: 
		sequence = chain(sequence, (pad_symbol,) * (n-1)) 
	sequence = list(sequence)     
    count = max(0, len(sequence) - n + 1) 
    return [tuple(sequence[i:i+n]) for i in range(count)] 


Now lets get Started:

1) Bigrams:
sequence = [1,2,3,4,5]
n=2
ngrams(sequence,n)
[(1,2),(2,3),(3,4),(4,5)]

For Trigrams n=3 and so on..
If you want a left or right padding when the numbers are odd then mention the left Padding or right padding variable

Enjoy.

Decoding http response with gzip encoding in python

7 Aug

Here is the function to use:

import gzip
import StringIO
import zlib

def decode (page):
    encoding = page.info().get("Content-Encoding")    
    if encoding in ('gzip', 'x-gzip', 'deflate'):
        content = page.read()
        if encoding == 'deflate':
            data = StringIO.StringIO(zlib.decompress(content))
        else:
            data = gzip.GzipFile('', 'rb', 9, StringIO.StringIO(content))
        page = data.read()

    return page

Twitter oauth2 application only using python

7 Aug

Here is the first method using urllib library

import urllib
import base64
import httplib&lt;/code&gt;</pre>

CONSUMER_KEY = 'my_key'
CONSUMER_SECRET = 'my_secret'
encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)

concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET

host = 'api.twitter.com'
url = '/oauth2/token/'
params = urllib.urlencode({'grant_type' : 'client_credentials'})
req = httplib.HTTPSConnection(host)
req.putrequest("POST", url)
req.putheader("Host", host)
req.putheader("User-Agent", "My Twitter 1.1")
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
req.putheader("Content-Length", "29")
req.putheader("Accept-Encoding", "utf-8")

req.endheaders()
req.send(params)
resp = req.getresponse()

print resp.status, resp.reason
print resp.read()

This is the Second Method using pycurl

import sys # used for the storage class
import pycurl # used for curling
import base64 # used for encoding string
import urllib # used for enconding
import cStringIO # used for curl buffer grabbing
import json # used for decoding json token
import time # used for stuff to do with the rate limiting
from time import sleep # used for rate limiting
from time import gmtime, strftime # used for gathering time

def get_bearer_token(consumer_key,consumer_secret):
	# enconde consumer key
	consumer_key = urllib.quote(consumer_key)
	# encode consumer secret
	consumer_secret = urllib.quote(consumer_secret)
	# create bearer token
	bearer_token = consumer_key+':'+consumer_secret
	# base64 encode the token
	base64_encoded_bearer_token = base64.b64encode(bearer_token)
	# set headers
	headers = [
	"POST /oauth2/token HTTP/1.1",
	"Host: api.twitter.com",
	"User-Agent: shobhit Twitter Application-only OAuth App Python v.1",
	"Authorization: Basic "+base64_encoded_bearer_token+"",
	"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
	"Content-Length: 29"]
	token_url = "https://api.twitter.com/oauth2/token"
	buf = cStringIO.StringIO()
	access_token = ''
	pycurl_connect = pycurl.Curl()
	pycurl_connect.setopt(pycurl_connect.URL, token_url) # used to tell which url to go to
	pycurl_connect.setopt(pycurl_connect.WRITEFUNCTION, buf.write) # used for generating output
	pycurl_connect.setopt(pycurl_connect.HTTPHEADER, headers) # sends the customer headers above
	pycurl_connect.setopt(pycurl_connect.POSTFIELDS, 'grant_type=client_credentials')
        pycurl_connect.perform() # perform the curl
	access_token = buf.getvalue() # grab the data
	pycurl_connect.close() # stop the curl
	x = json.loads(access_token)
	bearer = x['access_token']
	return bearer

Sublime 3 Licensed version

28 Jun

Installing on MacOS

  • Download the file from this link:
  • http://d.pr/f/QE3d
  • MD5: 59bab8f71f8c096cd3f72cd73851515d
  • Rename it to: Sublime Text
  • Make it executable with: chmod u+x Sublime\ Text
  • Replace it with: Sublime Text.app => Contents => MacOS => "Sublime Text"
  • Enjoy

Flipkart Discount

Installing on Windows x64

  • Download from here:
  • http://d.pr/f/60RQ
  • MD5: 6ddaa1fb63c6d7d4eae9ec39f1fa5d76
  • Rename it to: sublime_text.exe
  • Replace it with the one in your installation folder: e.g. [Installation Folder]/sublime_text.exe
  • Enjoy

Flipkart Discount

Installing on Windows x86

  • Download from here:
  • http://d.pr/f/1HIj
  • MD5: 8569b2cfa26677d72f322c8358f349c0
  • Rename it to: sublime_text.exe
  • Replace it with the one in your installation folder: e.g. [Installation Folder]/sublime_text.exe
  • You will paste a license key for this something like:
---BEGIN LICENSE---
Love Science
Unlimited User License
EA7E-18848
........................
.._____.................
.|  __ \      | |       
.| |  | | __ _| |_ __ _ 
.| |  | |/ _` | __/ _` |
.| |__| | (_| | || (_| |
.|_____/ \__,_|\__\__,_|
........................
---END LICENSE---

or write your own key.

Enjoy

Installing on Linux x64

  • Download from here:
  • http://d.pr/f/VCta
  • MD5: 552726c06917c711f9950e2eda6c928f
  • Rename it to: sublime_text
  • Make it executable with: chmod u+x sublime_text
  • Replace it with the one in your installation folder: e.g. [Installation Folder]/sublime_text
  • DONE
  • Installing on Linux x86
  • Download from here:
  • http://d.pr/f/x3B6
  • MD5: 98dbbcf51e7768f973f0afaf4424cfef
  • Rename it to: sublime_text
  • Make it executable with: chmod u+x sublime_text
  • Replace it with the one in your installation folder: e.g. [Installation Folder]/sublime_text
  • DONE

Alternative Link

This is alternative link due to droplr limitations: http://cl.ly/3H2O2E3v233t

 

 

Flipkart Discount
Donate Button

The os module python (Part 1)

26 Jun

Hi,Today i will give you some information about OS Module in python which provides method to perform various operating system functions.

This module can be imported like this

import os

To check the methods inside the os module do this:-

dir(os)

It will give you an idea that what all you can perform via OS module.

Using OS.rename and OS.path.exists

OS.Rename is Used to RENAME files and OS.path.exists is used to Check if the file is present at path or not.

Renaming shobhit.txt to mygola.txt
First Check if the file exists on the path

os.path.exists('shobhit.txt') # Will either return true or False
>>>true

os.rename('shobhit.txt','mygola.txt')

##Checking Again##
os.path.exists('shobhit.txt') # Will either return true or False
>>>false

os.path.exists('mygola.txt') # Will either return true or False
>>>true

Working with directories
The os module also contains a number of functions that work on entire directories.
The listdir function returns a list of all filenames in a given directory. The current and parent directory
markers used on Unix and Windows (. and ..) are not included in this list. Example: Using the os module to list the files in a directory

import os
for file in os.listdir("Documents"):
    print file

## OR just list everything on the current path ##
os.listdir('./')    #It will return array of files on that current path

The getcwd and chdir functions are used to get and set the current directory:
Using the os module to change the working directory

import os
cwd = os.getcwd() #Current Path
os.chdir("Documents") #Change the Directory to Documents/
os.chdir(os.pardir) #Going back to parent Directory

The makedirs and removedirs functions are used to create and remove directory hierarchies.
Using the os module to create and remove multiple directory levels

import os
os.makedirs("shobhit/mygola/developer") #Making Nested Directories
fp = open("shobhit/mygola/developer/test", "w") #Opening a File in Nested folder
fp.write("Hello world") #Writing a text to the file
fp.close() #Closing the file handle
os.remove("shobhit/mygola/developer/test") #remove the file</pre>
os.removedirs("shobhit/mygola/developer") # Will remove all these directories

Cheers 🙂

If you guys find this post useful .Please make this poll.