Custom Search

Tuesday, March 29, 2011

Top 10 Python Django IDEs

Top 10 python Django IDEs

1) Emacs
Various modes for Django development.

2) Pycharm
Its commercial.Good Django integration.

3) Eclipse with Pydev

4) Netbeans with Django Plugin

5) Komodo with Django Komodo Kit

6) Wing

Monday, March 28, 2011

how to python with statement

how to python with statement
====================1

class Test:
def __enter__(self):
print "\n-----in __enter__---self-----", self
return self

def __exit__(self, type, value, traceback):
print "\n-------in __exit__----self, type, value, traceback-----",
self, type, value, traceback

with Test() as thing:
print "\n-----in with------", thing

OUTPUT
======
-----in __enter__---self----- <__main__.Test instance at 0x7f98f1ebfe60>

-----in with------ <__main__.Test instance at 0x7f98f1ebfe60>

-------in __exit__----self, type, value, traceback----- <
__main__.Test instance at 0x7f98f1ebfe60> None None None

====================2

fp = open("my_file", "r")

print "\n------fp--------", fp

fp.__enter__()

print "\n------fp--------", fp

data = fp.readline()

print "\n------data--------", data

fp.__exit__()

print "\n------fp--------", fp

data = fp.readline()

OUTPUT
======

------fp--------

------fp--------

------data-------- hello #data red from file

------fp--------
Traceback (most recent call last):
File "py_with.py", line 23, in
data = fp.readline()
ValueError: I/O operation on closed file

====================3

so to open a file, process its contents, and make sure to close it, you can simply do:

with open("my_file") as fp:
data = fp.read()
do something with data

====================
More

Sunday, March 27, 2011

Python Using Functions as Decorators

Python Using Functions as Decorators

#############Using Functions as Decorators###########
#http://www.python.org/dev/peps/pep-0318/
#http://www.siafoo.net/article/68

def apply(func):
print "\n------func----", func
print "\n------locals()----", locals()
return func()

@apply
def test():
print "\n----in test-----"
return 'hello'

print "----1----", test

"""
Equal to
fun = apply(test)
"""

print "=========A========="

def apply1(t):
print "\n----t------", t
print "\n----locals()------", locals()
def apply2(f):
print "\n----f------", f
print "\n----vars(f)------", vars(f)
print "\n-----locals()-----", locals()
print "\n-----can access t here--------", t
def apply3(x,y):
print "\n----x,y------", x,y
print "\n----- locals()-----", locals()
print "\n-----can access t here--------", t
print "\n-------apply3--------", apply3, vars(apply3)
print "\n-------globals--------", globals()
return apply3
print "\n-------apply2--------", apply2, vars(apply2)
return apply2

t=100
@apply1(t)
def test1(a, b):
print "\n----in test1-----"
return a+b

print "\n----2-----", test1(5,5)

print "\n-------apply1--------", apply1, vars(apply1)
print "\n-------test1--------", test1, vars(test1)

"""
Equal to
fun = apply1(t)(test1)(a,b)

OR

apply2=apply1(t)
apply3=apply2(test1)
fun=apply3(a,b)
"""

print "=========B========="

"""
http://www.python.org/dev/peps/pep-0318/
http://www.siafoo.net/article/68

@dec2
@dec1
def func(arg1, arg2, ...):
pass

This is equivalent to:

def func(arg1, arg2, ...):
pass
func = dec2(dec1(func))

---------------------------------

@decomaker(argA, argB, ...)
def func(arg1, arg2, ...):
pass

This is equivalent to:

func = decomaker(argA, argB, ...)(func)

"""
print "=========C========="

#############Using Class as Decorators###########
#http://www.artima.com/weblogs/viewpost.jsp?thread=240808


OUTPUT
=======

------func----

------locals()---- {'func': }

----in test-----
----1---- hello
=========A=========

----t------ 100

----locals()------ {'t': 100}

-------apply2-------- {}

----f------

----vars(f)------ {}

-----locals()----- {'t': 100, 'f': }

-----can access t here-------- 100

-------apply3-------- {}

-------globals-------- {'apply1': ,
'__builtins__': ,
'__file__': 'deco.py', '__package__': None, 't': 100,
'apply': , 'test': 'hello',
'__name__': '__main__', '__doc__': None}

----2-----
----x,y------ 5 5

----- locals()----- {'y': 5, 'x': 5, 't': 100}

-----can access t here-------- 100
None

-------apply1-------- {}

-------test1-------- {}
=========B=========
=========C=========


introduction python pickle load dump

introduction python pickle load dump

* for serializing and de-serializing a Python object structure.
* Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1] or “flattening”.
* The pickle module can transform a complex object into a byte stream and it can transform the byte stream into an object with the same internal structure. Perhaps the most obvious thing to do with these byte streams is to write them onto a file, but it is also conceivable to send them across a network or store them in a database. The module shelve provides a simple interface to pickle and unpickle objects on DBM-style database files.
* non-Python programs may not be able to reconstruct pickled Python objects.
* http://docs.python.org/library/pickle.html


*******Dumping*******

class A:
g1=100

def __init__(self):
self.name='saju'

def f1(self):
print "----f1--"

import pickle
a1 = A()
pickle.dump(a1, file('pickle_file_1','w'))
print "\n------vars(A)------", vars(A)
print "\n------vars(a1)------", vars(a1)

OUTPUT
======
------vars(A)------ {'f1': ,
'__module__': '__main__',
'__init__': ,
'g1': 100,
'__doc__': None}

------vars(a1)------ {'name': 'saju'}

*******Loading-1*******

class A:
g1=100

def __init__(self):
self.name='saju'

def f1(self):
print "----in f1--"

import pickle
c1 = pickle.load(file('pickle_file_1'))
print "\n------vars(A)------", vars(A)
print "\n------vars(c1)------", vars(c1)
print "\n------c1.name------", c1.name
print "\n------ c1.g1------", c1.g1
print "\n------c1.f1------", c1.f1()

OUTPUT
======
------vars(A)------ {'f1': ,
'__module__': '__main__',
'__init__': ,
'g1': 100,
'__doc__': None}

------vars(c1)------ {'name': 'saju'}

------c1.name------ saju

------ c1.g1------ 100

------c1.f1------ ----in f1--

*******Loading-2*******

#Made some changes in class 'A'.
#Added class variable 'g2' , method 'f2()' and instance variable 'age'.
#We can access new class variable 'g2' , method 'f2()' using loaded object.
#But we can not access instance variable 'age' using loaded object.
# that means pickle only dump __dict__ attribute of object "c1".

class A:
g1=100
g2=200
def __init__(self):
self.age=23
self.name='saju'

def f1(self):
print "----in f1--"

def f2(self):
print "----in f2--"

import pickle
c1 = pickle.load(file('pickle_file_1'))
print "\n------vars(A)------", vars(A)
print "\n------vars(c1)------", vars(c1)
print "\n------c1.name------", c1.name
print "\n------ c1.g1------", c1.g1
print "\n------c1.f1------", c1.f1()
print "\n------ c1.g2------", c1.g2
print "\n------c1.f2------", c1.f2()
print "\n------c1.age------", c1.age

OUTPUT
=====
------vars(A)------ {'f1': ,
'__module__': '__main__',
'g2': 200,
'g1': 100,
'f2': ,
'__doc__': None,
'__init__': }

------vars(c1)------ {'name': 'saju'}

------c1.name------ saju

------ c1.g1------ 100

------c1.f1------ ----in f1--

------ c1.g2------ 200

------c1.f2------ ----in f2--

------c1.age------
Traceback (most recent call last):
File "pickle1.py", line 39, in
print "\n------c1.age------", c1.age
AttributeError: A instance has no attribute 'age'


=========================
python , __dict__ attribute of class and object

More
More

python Simple File Read and Write

python Simple File Read and Write

fp = open("test_file_1", "w")

h1 = "hello1"
h2 = "hello2"
h3 = "hello3"
h4 = "hello4"

fp.write(h1)
#OR
print >> fp, h2, h3
print >> fp, h4
#close file
fp.close()

OUTPUT
======
hello1hello2 hello3
hello4


Note
====
To open a file/file object :

open(filename,mode)

1. filename can be a file or path to a file
2. mode can be any of the following

1. ‘r’ for reading
2. ‘r+’ for reading and writing
3. ‘w’ for writing
4. ‘a’ for appending
5. both read and write modes also have a ‘b’ option for binary reading and writing (‘rb’, or ‘wb’)

s = myFile.read() Will read entire file into a string
s = myFile.read(N) Will read N bytes (1 or more) from file
s = myFile.readline() Will read next line into string until end of line
L = myFile.readlines() Will read entire file into a list of strings

how upload ogv video to youtube

how upload ogv video to youtube

1) Install Handbrake
http://handbrake.fr/

2)Encode(Convert) your .ogv source file to .mkv.

3)Upload that to youtube.

Tuesday, March 22, 2011

python exclude items from list

python Django exclude items from list

---------------------------

>>> k = [2,4,7,5]

>>> k.remove(7)

>>> k
[2, 4, 5]

---------------------------

>>> k = [2,4,7,5]

>>> a = [2,4]

>>> [k.remove(x) for x in a]
[None, None]

>>> k
[7, 5]


---------------------------

Sunday, March 13, 2011

python json examples

python json examples

import json

#list
list_str = '[1,2,3]'

#dict
#dict_str = "{'a':1, 'b':5}" #Not works (do not use single quote inside)
dict_str = '{"a":1, "b":5}'


#tuple
#json does not support typles
tup = (5,6,7,8)
tup_str = json.dumps(tup)
print "\n-------tup_strdd----", tup_str

#dict_list_str = "{'l1':[2,4], 'l2':[6,7], 'd1':{'x':8, 'y':3}, 'name':'my_name'}"
dict_list_str = '{"l1":[2,4], "l2":[6,7], "d1":{"x":8, "y":3}, "name":"my_name"}'


print "\n-------json.loads(list_str)-------", json.loads(list_str)

print "\n-------json.loads(dict_str)-------", json.loads(dict_str)

print "\n-------json.loads(tup_str)-------", json.loads(tup_str)

print "\n-------json.loads(dict_list_str)-------", json.loads(dict_list_str)


OUTPUT
=======
-------tup_strdd---- [5, 6, 7, 8]

-------json.loads(list_str)------- [1, 2, 3]

-------json.loads(dict_str)------- {u'a': 1, u'b': 5}

-------json.loads(tup_str)------- [5, 6, 7, 8]

-------json.loads(dict_list_str)------- {u'd1': {u'y': 3, u'x': 8}, u'l2': [6, 7],
u'name': u'my_name', u'l1': [2, 4]}


============ Notes =========

#http://diveintopython3.org/serializing.html
#http://diveintopython3.org/serializing.html#json-dump
#http://diveintopython3.org/serializing.html#json-types

Json Types
------------
* http://diveintopython3.org/serializing.html#json-types
* JSON does not support Python Tuples & bytes
* JSON has an array type, which the json module maps to a Python list.

python how create read-only Instance attributes examples

python examples how create read-only Instance attributes

class Test(object):

def __init__(self):
self._year = 2011

def get_year(self):
return self._year

#property() only works with new-style classes correctly,
#(classe which are inherited from 'object')
year = property(get_year)

t = Test()
print "------t.year--------", t.year
t.year = 2012
print "------t.year--------", t.year


OUTPUT
=======
------t.year-------- 2011
Traceback (most recent call last):
File "test.py", line 48, in
t.year = 2012
AttributeError: can't set attribute


#====================== OR

class Test(object):
def __init__(self):
self._year = 2011

#property() only works with new-style classes correctly,
#(classe which are inherited from 'object')
@property
def year(self):
return self._year

t = Test()
print "------t.year--------", t.year
t.year = 2012
print "------t.year--------", t.year


OUTPUT
=======
------t.year-------- 2011
Traceback (most recent call last):
File "test.py", line 65, in
t.year = 2012
AttributeError: can't set attribute


----------------------------Note:

# don't use two underscores on the beginning of your attributes
# why ?? any problem ??
# yes, it invokes name mangling
# __ invokes magic
# which is not what you want
# use a single underscore to denote "private"

http://fosshelp.blogspot.com/2010/04/public-and-private-variables-in-python.html

Saturday, March 12, 2011

python attributes of sys module

python attributes of sys module

import sys

attr_list = dir(sys)

for attr in attr_list:
str_data = "sys.%s" %(attr)
print "\n", str_data
print "---------------------"
print eval(str_data)

-----------------------OR

import sys
from pprint import pprint
pprint(vars(sys))


OUTPUT
========


sys.__displayhook__
---------------------


sys.__doc__
---------------------
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
To customize printing in an interactive session or to install a custom
top-level exception handler, assign other functions to replace these.

exitfunc -- if sys.exitfunc exists, this routine is called when Python exits
Assigning to sys.exitfunc is deprecated; use the atexit module instead.

stdin -- standard input file object; used by raw_input() and input()
stdout -- standard output file object; used by the print statement
stderr -- standard error object; used for error messages
By assigning other file objects (or objects that behave like files)
to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
These three are only available in an interactive session after a
traceback has been printed.

exc_type -- type of exception currently being handled
exc_value -- value of exception currently being handled
exc_traceback -- traceback of exception currently being handled
The function exc_info() should be used instead of these three,
because it is thread-safe.

Static objects:

maxint -- the largest supported integer (the smallest is -maxint-1)
maxsize -- the largest supported length of containers.
maxunicode -- the largest supported character
builtin_module_names -- tuple of module names built into this interpreter
version -- the version of this interpreter as a string
version_info -- version information as a tuple
hexversion -- version information encoded as a single integer
copyright -- copyright notice pertaining to this interpreter
platform -- platform identifier
executable -- pathname of this Python interpreter
prefix -- prefix used to find the Python library
exec_prefix -- prefix used to find the machine-specific Python library
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!

Functions:

displayhook() -- print an object to the screen, and save it in __builtin__._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exc_clear() -- clear the exception state for the current thread
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function


sys.__egginsert
---------------------
2

sys.__excepthook__
---------------------


sys.__name__
---------------------
sys

sys.__package__
---------------------
None

sys.__plen
---------------------
13

sys.__stderr__
---------------------
', mode 'w' at 0x7f907428b1e0>

sys.__stdin__
---------------------
', mode 'r' at 0x7f907428b0c0>

sys.__stdout__
---------------------
', mode 'w' at 0x7f907428b150>

sys._clear_type_cache
---------------------


sys._current_frames
---------------------


sys._getframe
---------------------


sys.api_version
---------------------
1013

sys.argv
---------------------
['test.py']

sys.builtin_module_names
---------------------
('__builtin__', '__main__', '_ast', '_bisect', '_codecs', '_collections', '_functools',
'_hashlib', '_locale', '_random', '_socket', '_sre', '_ssl', '_struct', '_symtable',
'_warnings', '_weakref', 'array', 'binascii', 'cPickle', 'cStringIO', 'errno',
'exceptions', 'fcntl', 'gc', 'grp', 'imp', 'itertools', 'marshal', 'math', 'operator',
'posix', 'pwd', 'select', 'signal', 'spwd', 'strop', 'sys', 'syslog', 'thread', 'time',
'unicodedata', 'xxsubtype', 'zipimport', 'zlib')

sys.byteorder
---------------------
little

sys.call_tracing
---------------------


sys.callstats
---------------------


sys.copyright
---------------------
Copyright (c) 2001-2010 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.

sys.displayhook
---------------------


sys.dont_write_bytecode
---------------------
False

sys.exc_clear
---------------------


sys.exc_info
---------------------


sys.exc_type
---------------------
None

sys.excepthook
---------------------


sys.exec_prefix
---------------------
/usr

sys.executable
---------------------
/usr/bin/python

sys.exit
---------------------


sys.flags
---------------------
sys.flags(debug=0, py3k_warning=0, division_warning=0, division_new=0, inspect=0,
interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,
ignore_environment=0, tabcheck=0, verbose=0, unicode=0, bytes_warning=0)

sys.float_info
---------------------
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308,
min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53,
epsilon=2.2204460492503131e-16, radix=2, rounds=1)

sys.getcheckinterval
---------------------


sys.getdefaultencoding
---------------------


sys.getdlopenflags
---------------------


sys.getfilesystemencoding
---------------------


sys.getprofile
---------------------


sys.getrecursionlimit
---------------------


sys.getrefcount
---------------------


sys.getsizeof
---------------------


sys.gettrace
---------------------


sys.hexversion
---------------------
33949168

sys.maxint
---------------------
9223372036854775807

sys.maxsize
---------------------
9223372036854775807

sys.maxunicode
---------------------
1114111

sys.meta_path
---------------------
[]

sys.modules
---------------------
{'copy_reg': , 'encodings': , 'site': , '__builtin__': , '__main__': ,
'encodings.encodings': None, 'abc': , 'posixpath': , 'errno': ,
'encodings.codecs': None, '_abcoll': , 'types': , '_codecs': , '_warnings': ,
'genericpath': , 'stat': , 'zipimport': , 'encodings.__builtin__': None,
'warnings': , 'UserDict': , 'encodings.utf_8': , 'sys': , 'codecs': , 'os.path': ,
'sitecustomize': , 'signal': , 'apport_python_hook': , 'linecache': , 'posix': ,
'encodings.aliases': , 'exceptions': , 'os': }

sys.path
---------------------
['/home/test/Desktop/test',
'/usr/local/lib/python2.6/dist-packages/setuptools-0.6c11-py2.6.egg',
'/usr/local/lib/python2.6/dist-packages/virtualenv-1.5.1-py2.6.egg',
'/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '
/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload',
'/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL',
'/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6',
'/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0',
'/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode',
'/usr/local/lib/python2.6/dist-packages']

sys.path_hooks
---------------------
[]

sys.path_importer_cache
---------------------
{'/usr/lib/python2.6/lib-tk': None,
'/usr/local/lib/python2.6/dist-packages/virtualenv-1.5.1-py2.6.egg': None,
'/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode': None, 'test.py': ,
'/usr/lib/pymodules/python2.6/gtk-2.0': None, '/usr/lib/python2.6/plat-linux2': None,
'/usr/lib/python2.6/lib-old': , '/usr/lib/python2.6/dist-packages/gtk-2.0': None,
'/usr/lib/python2.6/dist-packages/PIL': None, '
/usr/local/lib/python2.6/dist-packages': None, '/usr/lib/python2.6/': None,
'/usr/local/lib/python2.6/dist-packages/setuptools-0.6c11-py2.6.egg': ,
'/usr/lib/python2.6/dist-packages': None,
'/usr/lib/python2.6/dist-packages/gst-0.10': None,
'/usr/lib/pymodules/python2.6': None, '/usr/lib/python2.6': None,
'/usr/lib/python2.6/lib-dynload': None, '/usr/lib/python2.6/encodings': None}

sys.platform
---------------------
linux2

sys.prefix
---------------------
/usr

sys.py3kwarning
---------------------
False

sys.pydebug
---------------------
False

sys.setcheckinterval
---------------------


sys.setdlopenflags
---------------------


sys.setprofile
---------------------


sys.setrecursionlimit
---------------------


sys.settrace
---------------------


sys.stderr
---------------------
', mode 'w' at 0x7f907428b1e0>

sys.stdin
---------------------
', mode 'r' at 0x7f907428b0c0>

sys.stdout
---------------------
', mode 'w' at 0x7f907428b150>

sys.subversion
---------------------
('CPython', 'tags/r265', '79063')

sys.version
---------------------
2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3]

sys.version_info
---------------------
(2, 6, 5, 'final', 0)

sys.warnoptions
---------------------
[]


python find differences between two text files

python find differences between two text files

==================== Example-1

fp1 = open('f1', 'r')
lines1 = fp1.readlines()
fp1.close()
print "-----lines1-----", lines1

fp2 = open('f2', 'r')
lines2 = fp2.readlines()
fp2.close()
print "-----lines2-----", lines2

newlist = []
for i, x in enumerate(lines1):
try:
if x != lines2[i]:
print x
newlist.append(x)
except IndexError, e:
newlist.append(x)

print "----newlist----", newlist


fp3 = open('f3', 'w')
fp3.writelines(newlist)
fp3.close()


OUTPUT
========

$ python test.py

-----lines1----- ['hello\n', 'testing1\n', 'testing3\n', 'hi\n']
-----lines2----- ['hello\n', 'testing2\n', '\n']
testing1

testing3

----newlist---- ['testing1\n', 'testing3\n', 'hi\n']

==================== Example-2

fp1 = open('f1', 'r')
lines1 = fp1.readlines()
fp1.close()
print "-----lines1-----", lines1

fp2 = open('f2', 'r')
lines2 = fp2.readlines()
fp2.close()
print "-----lines2-----", lines2

fp2 = open('f3', 'w')
for x in lines1:
if x not in lines2:
fp2.write(x)

#fp2.writelines([x for x in lines1 if x not in lines2]) # <--- OR fp2.close() ==================== Example-3

# python find differences between two text files
#http://www.daniweb.com/software-development/python/threads/96638

import difflib

fp1 = open('f1', 'r')
lines1 = fp1.readlines()
fp1.close()
print "-----lines1-----\n", lines1

fp2 = open('f2', 'r')
lines2 = fp2.readlines()
fp2.close()
print "-----lines2-----\n", lines2

result_list = list(difflib.Differ().compare(lines1, lines2))

print "-----result_list-------\n", result_list

lines_diff1 = []
lines_diff2 = []
for l in result_list:
if l[0] == '-':
lines_diff1.append(l)
elif l[0] == '+':
lines_diff2.append(l)

print "-----lines which are in lines1 and not in lines2 -----\n", lines_diff1
print "-----lines which are in lines2 and not in lines1 -----\n", lines_diff2


OUTPUT
========

-----lines1-----
['hello\n', 'testing1\n', 'testing3\n', 'hi\n']
-----lines2-----
['hello\n', 'testing2\n']
-----result_list-------
[' hello\n', '- testing1\n', '? ^\n', '+ testing2\n', '? ^\n',
'- testing3\n', '- hi\n']
-----lines which are in lines1 and not in lines2 -----
['- testing1\n', '- testing3\n', '- hi\n']
-----lines which are in lines2 and not in lines1 -----
['+ testing2\n']


Friday, March 11, 2011

python Create date string and convert to datetime object

python Django Create date string and convert to datetime object

>>> from datetime import datetime

>>> today = datetime.utcnow()

>>> uptoDate = today.strftime("%Y-%m-%d %H")

>>> uptoDate <=======date String
'2011-03-11 11'

>>> year = int(uptoDate[:4])

>>> month = int(uptoDate[5:7])

>>> day = int(uptoDate[8:10])

>>> hour = int(uptoDate[11:13])

>>> formatted_uptoDate = datetime(year, month, day, hour)

>>> formatted_uptoDate <=====datetime object
datetime.datetime(2011, 3, 11, 11, 0)

Monday, March 7, 2011

Eucalyptus No route to host when ssh to instance

Eucalyptus No route to host when ssh to a instance

Check your network subnets: I think you are using 192.168.1.x for the MANAGED-NOVLANS but that network is the one your machine are using. Try something different, for example 10.10.x.x. If you do such a change you have to stop all eucalyptus services (and instances) and you have to restart the cc with clean-restart.

**********1**********
* In Cluster Controller
* In /etc/eucalyptus/eucalyptus.local.conf

# network configuration from the input configuration file
VNET_MODE="MANAGED-NOVLAN"
VNET_SUBNET="172.19.0.0"
VNET_NETMASK="255.255.0.0"
VNET_DNS="125.22.47.125"
VNET_ADDRSPERNET="32"
VNET_PUBLICIPS="192.168.1.50-192.168.1.60" <------

--------- change to

# network configuration from the input configuration file
VNET_MODE="MANAGED-NOVLAN"
VNET_SUBNET="172.19.0.0"
VNET_NETMASK="255.255.0.0"
VNET_DNS="125.22.47.125"
VNET_ADDRSPERNET="32"
VNET_PUBLICIPS="10.10.5.1-10.10.5.9" <-------

**********2**********

# restart eucalyptus-cc CLEAN=1

**********3**********

root@cc-host:~# ifconfig
eth0 Link encap:Ethernet HWaddr 00:19:66:1c:4d:8c
inet addr:192.168.1.107 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::219:66ff:fe1c:4d8c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:5478 errors:0 dropped:0 overruns:0 frame:0
TX packets:4483 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1550033 (1.5 MB) TX bytes:1828909 (1.8 MB)
Interrupt:22 Base address:0xb800

eth0:metadata Link encap:Ethernet HWaddr 00:19:66:1c:4d:8c <------------------
inet addr:169.254.169.254 Bcast:0.0.0.0 Mask:255.255.255.255
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Interrupt:22 Base address:0xb800

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:57349 errors:0 dropped:0 overruns:0 frame:0
TX packets:57349 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:27541581 (27.5 MB) TX bytes:27541581 (27.5 MB)


===============================

More

Sunday, March 6, 2011

python tuple comprehension example

python tuple comprehension example

---------------1

>>> dt = (x for x in l1)
>>>
>>> dt
generator object genexpr> at 0x27edaf0>
>>>
>>> dd = tuple(dt)
>>>
>>> dd
('a', 'b', 'c', 'd')
>>>

----------------2

>>> l1 = ['a', 'b', 'c', 'd']
>>>
>>> t = tuple(l1)
>>>
>>> t
('a', 'b', 'c', 'd')
>>>

python dict comprehension example

python dictionary comprehension example

---------------1

>>> l1 = ['a', 'b', 'c', 'd']
>>>
>>> dt = {x:2 for x in l1}
>>>
>>> dt
{'a': 2, 'c': 2, 'b': 2, 'd': 2}
>>>

----------------2

>>> l1 = ['a', 'b', 'c', 'd']
>>>
>>> l2 = [1,2,3,4]
>>>
>>>
>>> dt = {x:y for x,y in zip(l1,l2)}
>>>
>>> dt
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>>

----------------3

>>> dt = {i : chr(65+i) for i in range(4)}
>>>
>>> dt
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}
>>>

----------------4

>>> dt = dict([(i, chr(65+i)) for i in range(4)])
>>>
>>> dt
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}
>>>

Thursday, March 3, 2011

how to Catch Invisible Friends On GTalk using python

The bellow peace of python code get the list of invisible users from your GTalk buddy list. It uses XMPP module for python. You can install this module inUbuntu/Debian via apt. It also requires python dns module.

sudo aptitude install python-xmpp python-dnspython

Now here is our script. Open your favorite text editor and save the
code as ‘gchat.py’. Dont forget to fill your gtalk username and
password in the script.

------------------------------------------------- in gtalk.py



import xmpp

# Google Talk constants
FROM_GMAIL_ID = "username@gmail.com"
GMAIL_PASS = "secret passwd"
GTALK_SERVER = "gmail.com"

jid=xmpp.protocol.JID(FROM_GMAIL_ID)
C=xmpp.Client(jid.getDomain(),debug=[])

if not C.connect((GTALK_SERVER,5222)):
raise IOError('Can not connect to server.')
if not C.auth(jid.getNode(),GMAIL_PASS):
raise IOError('Can not auth with server.')

C.sendInitPresence(requestRoster=1)

def myPresenceHandler(con, event):
if event.getType() == 'unavailable':
print event.getFrom().getStripped()

C.RegisterHandler('presence', myPresenceHandler)
while C.Process(1):
pass



-------------------------------------------------- run

$ python gtalk.py

use of python __getattr__

use of python __getattr__

class Test:

def __init__(self):
self.number = 4000
self.msg = "Hiii"

def __getattr__(self, name):
if name=='message':
return self.msg
return AttributeError #<--------

d = Test()
print "-------d.message-------", d.message
print "-------d.number-------", d.number
print "-------d.msg-------", d.msg



OUTPUT
=========

-------d.message------- Hiii
-------d.number------- 4000
-------d.msg------- Hiii


More
More