Feeds:
Posts
Comments

Posts Tagged ‘Python’

While i was working on the project onspot_v2, i came across with a specific need. onspot_v2 makes use of the django admin interface for data entry. When employees are entering data, ‘branch’ field in the form will get populated automatically as per the branch of the employee. When a manager is entering data using the form, an extra field should appear to select the ‘branch’ instead of automatically populating. Googling didn’t help much. Finally i thought of overriding the ModelAdmin.add_view() method which is invoked when you try to add an entry using the admin. I changed the editable property of the field ‘branch’ inside after checking the request.user and it worked out. Part of my code in admin.py

from django.contrib import admin
from books.models import Agent, PolicyIssue

class PolicyIssueAdmin(admin.ModelAdmin):
 
    def add_view(self, request, form_url='', extra_context=None):
        if request.user.get_profile().is_employee:
            self.model.branch.field.editable = False
        else:
            self.model.branch.field.editable = True
        return super(PolicyIssueAdmin, self).add_view(request, form_url)

admin.site.register(PolicyIssue, PolicyIssueAdmin)
Advertisements

Read Full Post »

Actually this is a sample question appeared in codejam contest conducted by mobme wireless. Imdbpy python module is used to retrieve movie informations from imdb.

For those who don’t know about this event : http://codejam.mobme.in/

Sample Question :

Write a program that ranks Hollywood actors based on the number of their appearances in a list of top 100 movies. There are a number of top movie lists on the Internet and it’s up to you to choose one. We’d prefer you choose one that has an open API.

Solution in Python :

#!/usr/bin/env python

__author__ = "Rag Sagar.V"
__email__ = '@'.join(['ragsagar','.'.join([_ for _ in ['gmail','com']])])


from twisted.internet import reactor, threads
import re,imdb,itertools


actors_rating = {} #actors_rating['actor name'] = rank
rank = 0
count = 1
current_rank = 0
concurrent = 5
finished = itertools.count(1)
reactor.suggestThreadPoolSize(concurrent)


try:
	imdb_access = imdb.IMDb()
except imdb.IMDbError, err:
	print err
		
top_100 = imdb_access.get_top250_movies()[:100]


def populate_actors(mid):
	movie = imdb_access.get_movie(int(mid))
	#print movie
	for i in (0,1):
		actor_name =  movie['cast'][i]['name']
		if actors_rating.has_key(actor_name):
			actors_rating[actor_name] = actors_rating[actor_name] + 1
		else:
			actors_rating[actor_name] = 1
	if finished.next()==added:
		reactor.stop()
	
added = 0
for movie in top_100:
	added += 1	
	req = threads.deferToThread(populate_actors, movie.getID())

try:
	reactor.run()
except KeyboardInterrupt:
	reactor.stop()	

   
for actor in sorted(actors_rating, key=actors_rating.get, reverse=True):
	previous_rank = current_rank
	current_rank = actors_rating[actor]
	if previous_rank !=  current_rank :
		rank += count
		count = 1
	else:
		count += 1	
	print rank,actor   
    
    

Dependency :
imdbpy

Read Full Post »

Here is a python script to wish you Good Morning or Good Evening according to the time of the day.

#!/usr/bin/python
import time

current_hour = time.strptime(time.ctime(time.time())).tm_hour

if current_hour < 12 :
	print "Good Morning!"
elif current_hour == 12 :
	print "Good Noon!"
elif current_hour > 12 and current_hour < 18 :
	print "Good AfterNoon!"
elif current_hour >= 18 :
	print "Good Evening!"

Now if you want to display it when you open the console add the following line to your ~/.bashrc file.

python /path/to/the/script.py

Happy Hacking! 🙂

Read Full Post »

This time its the script to fetch the malayalam meanings of english words from malayalam wiktionary.

#!/usr/bin/python
#-*- coding: utf-8 -*-
# https://ragsagar.wordpress.com

from HTMLParser import HTMLParser
import urllib2,sys


class Parser(HTMLParser):
	
	def __init__(self):
		self.in_header = False
		self.in_definition = False
		HTMLParser.__init__(self)
	
	def handle_starttag(self, tag, attrs):
		if tag == 'li':
			self.in_header = True
		if tag == 'a' and self.in_header :
			self.in_definition = True
	
	def handle_endtag(self, tag):
	    	if tag == 'li':
			self.in_header = False
		if tag == 'a' :
			self.in_defintion = False
			
	def handle_data(self, data):
		if self.in_definition:
			print data 
			exit(0)
					


try :
	search_item = sys.argv[1]
except IndexError:
	print " syntax : %s <definiton> " % sys.argv[0]
	exit(1)
search_link = "http://ml.wiktionary.org/w/index.php?title=%s&printable=yes" % (urllib2.quote(search_item.encode('utf-8')))


request = urllib2.Request(search_link)
request.add_header('User-agent', 'Mozilla/5.0 (hb)')
try :
	response = urllib2.urlopen(request)
except urllib2.HTTPError :
	print "No definition found "
except urllib2.URLError :
	print "Unable to connect to internet "
else :
	parser = Parser()
	data = response.read()
	parser.feed(data)
			

Output in my terminal

malayalam meaning

Read Full Post »

Here is a script i wrote last night.It finds imdb rating of a movie.

#ragsagar[at]gmail.com
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import sys,re

if len(sys.argv) != 2:
	print "\nSyntax: python %s 'Movie title'" % (sys.argv[0])
	exit()
else :
	movie = '+'.join(sys.argv[1].split())

br = Browser()
br.open("http://www.imdb.com/find?s=tt&q="+movie)
link = br.find_link(url_regex = re.compile(r"/title/tt*"))
res = br.follow_link(link)
soup = BeautifulSoup(res.read())
try :
	title = soup.find('h1').contents[0].strip()
	rating = soup.find('span',attrs='rating-rating').contents[0]
	print "Movie : ",title
	print "Rating: ",rating,"/ 10.0"
except :
	print "Not Found!"	

Here is the screenshot of output.

Output of the script

Read Full Post »

Atlast i came up with a real rhythmbox plugin for setting the status message in pidgin as the current song title playing in Rhythmbox music player .I wrote it a few month before and was using it. Thought of sharing it before but didnt get time. Actually i forgot about my blog when i started microblogging. From now onwards i will be updating this blog regularly.( this is what i wanted to do always 😀 )

Download the plugin from here : http://ragsagar.freehostia.com/rb-nowplaying.tar.gz
To install it.
1) Extract the tarball.
2) Copy it to ~/.gnome2/rhythmbox/plugins/ (if no such directories exists, create them)
3) Open rhythmbox. Edit -> Plugins
4) Check ‘Now Playing Pidgin’

That’s it. If you are facing any problems do comment.

Read Full Post »

About Infix and Postfix

In an expression if the operators are placed between the operands, it is known as infix notation ( eg A+B) . On the other hand if the operators are placed after the operands then the expression is in postfix notation .( eg AB+)

Infix Notation                            Postfix Notation

(A-C)*B                                              AC-B*

A+(B*C)                                            ABC*+

(A+B)/(C-D)                                      AB+CD-/

Code

#!/usr/bin/python
#https://ragsagar.wordpress.com

postfix = []
temp = []
operator = -10
operand = -20
leftparentheses = -30
rightparentheses = -40
empty = -50

def precedence(s):
	if s is '(':
		return 0
	elif s is '+' or '-':
		return 1
	elif s is '*' or '/' or '%':
		return 2
	else:
		return 99 
				
def typeof(s):
	if s is '(':
		return leftparentheses
	elif s is ')':
		return rightparentheses
	elif s is '+' or s is '-' or s is '*' or s is '%' or s is '/':
		return operator
	elif s is ' ':
		return empty	
	else :
		return operand							


infix = raw_input("Enter the infix notation : ")
for i in infix :
	type = typeof(i)
	if type is leftparentheses :
		temp.append(i)
	elif type is rightparentheses :
		next = temp.pop()
		while next is not '(':
			postfix.append(next)
			next = temp.pop()
	elif type is operand:
		postfix.append(i)
	elif type is operator:
		p = precedence(i)
		while len(temp) is not 0 and p <= precedence(temp[-1]) :
			postfix.append(temp.pop())
		temp.append(i)
	elif type is empty:
		continue 
				
while len(temp) > 0 :
	postfix.append(temp.pop())
	
print "It's postfix notation is ",''.join(postfix)		

Code Explanation

Above code converts infix notation in variable infix into postfix notation and stores in postfix list. This algorithm makes use of list temp to hold operators and left parantheses in the infix notation. The postfix list will be constructed from left to right using operands from infix and operators which are removed from temp.

output

output

Read Full Post »

Older Posts »

%d bloggers like this: