Custom Search

Friday, March 20, 2015

python why List and Dictionaries are automatically global?


  
>>> #changing a list entry is like calling a member function on the list.
... #For example a[3]=100 is Equal to a.__setitem__(3,100)
...
>>> #Without global, an assignment creates a new local.
...
>>> #In Python, if you do not assign to a variable inside a function it
... #will look for that variable in more global scopes until it finds it.
...
>>> a = range(5)
>>> def mutate(a):
...     a[3] = 100

...
>>> mutate(a)
>>> print a[3]
100
>>>
>>>
>>>
>>> a = range(5)
>>> def mutate(b):
...     a[3] = 100

...     #Equal to a.__setitem__(3,100) 
...
>>> mutate(a)
>>> print a[3]
100
>>>
>>>
>>>
>>> a = range(5)
>>> def mutate(b):
...     b[3] = 100
...
>>> mutate(a)
>>> print a[3]
100



Tuesday, March 17, 2015

python StringIO usages


http://www.dotnetperls.com/stringio

http://stackoverflow.com/questions/7996479/what-is-stringio-in-python-used-for-in-reality


1)
* To unit-test a script that does a lot of printing, by redirecting sys.stdout to a StringIO instance for easy analysis;
* To create a guaranteed well-formed XML document (a custom API request) using ElementTree and then write it for sending via a HTTP connection.
* Not that you need StringIO often, but sometimes it's pretty useful.

2)
* StringIO gives you file-like access to strings, so you can use an existing module that deals with a file and change almost nothing and make it work with strings.

* For example, say you have a logger that writes things to a file and you want to instead send the log output over the network. You can read the file and write its contents to the network, or you can write the log to a StringIO object and ship it off to its network destination without touching the filesystem. StringIO makes it easy to do it the first way then switch to the second way.

3)
In cases where you want a file-like object that ACTS like a file, but is writing to an in-memory string buffer: StringIO is the tool. If you're building large strings, such as plain-text documents, and doing a lot of string concatenation, you might find it easier to just use StringIO instead of a bunch of mystr += 'more stuff\n' type of operations.




Monday, March 16, 2015

How to increment a numeric string '0000000001' in python?

>>>
>>> for x in range(1, 20):
...     "%(#)010d" % {'#': x}

...
'0000000001'
'0000000002'
'0000000003'
'0000000004'
'0000000005'
'0000000006'
'0000000007'
'0000000008'
'0000000009'
'0000000010'
'0000000011'
'0000000012'
'0000000013'
'0000000014'
'0000000015'
'0000000016'
'0000000017'
'0000000018'
'0000000019'
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> for x in range(1, 20):
...     "%(replace)010d" % {'replace': x}

...
'0000000001'
'0000000002'
'0000000003'
'0000000004'
'0000000005'
'0000000006'
'0000000007'
'0000000008'
'0000000009'
'0000000010'
'0000000011'
'0000000012'
'0000000013'
'0000000014'
'0000000015'
'0000000016'
'0000000017'
'0000000018'
'0000000019'
>>>
>>>

http://stackoverflow.com/questions/23270503/how-to-increment-a-numeric-string-0000000001-in-python


Wednesday, March 11, 2015

Ubuntu Install OpenSSH Server and Enable SSH from Remote Machine

1)
Check whether SSH Server running or not
#sudo netstat -tuplen | grep 22
#sudo dpkg -L ssh



2)
Install OpenSSH Server and SSH
#sudo apt-get update
#sudo apt-get install ssh

3)
Try to SSH from remote machine
#ssh username@ip-of-machine



Tuesday, March 10, 2015

How to Django Debug TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK

from django.db import transaction
from saju.core.models import Agent

1)
Error Case-1
===============

@transaction.commit_manually
def f1():
    print 1
    try:
        a=Agent.objects.filter(id=454200).all()[0]
        a.contact_email="bla@blabla.com"
        a.save()   
        raise Exception("dummy exception")
    except Exception as e:
        raise e
        transaction.rollback()   
    transaction.commit()

2)
Error Case-2
===============

@transaction.commit_manually
def f1():

    print 1
    try:
        a=Agent.objects.filter(id=454200).all()[0]
        a.contact_email="bla@blabla.com"
        a.save()
    except Exception as e:
        transaction.rollback()
    raise Exception("dummy exception")   
    transaction.commit()

3)
Solution-1
===============

###How to see the Actual error ?
###Add a "try..final" block with "transaction.rollback()" to see the Actual error

@transaction.commit_manually
def f1():

    try:
        print 1
        try:
            a=Agent.objects.filter(id=454200).all()[0]
            a.contact_email="bla@blabla.com"
            a.save()   
            raise Exception("dummy exception")
        except Exception as e:
            raise e
            transaction.rollback()   
        transaction.commit()
    finally:
        transaction.rollback()



4)
Solution-2
===============

###How to see the Actual error ?
###Add a "try..final" block with "transaction.rollback()" to see the Actual error
@transaction.commit_manually
def f1():

    try:
        print 1
        try:
            a=Agent.objects.filter(id=454200).all()[0]
            a.contact_email="bla@blabla.com"
            a.save()
        except Exception as e:
            transaction.rollback()
        raise Exception("dummy exception")   
        transaction.commit()
    finally:
        transaction.rollback()





How to Django Aggregate with Distinct

1)
Open Django shell
#python manage.py shell

2)
>>>
>>>
>>> from django.db.models import Count
>>> from bla.core.models import Building
>>>
>>> Building.objects.filter(agent=454200).aggregate(count=Count('user'))
{'count': 29}
>>>

>>>
>>> Building.objects.filter(agent=454200).aggregate(count=Count('user', distinct=True))
{'count': 7}
>>>

>>>
>>>
>>>
>>> user_tot = 0
>>> for b in Building.objects.filter(agent=454200).all():
...     if b.user:
...         user_tot += 1
...
>>>
>>>

>>> user_tot
29
>>> 

>>>
>>>

Monday, March 9, 2015

How to Get the SQL Query from Django QuerySet

1)
Open django shell
#python manage.py shell

2)
Import the model class
>>> from bla.models import Building

3)
Print the SQL query
>>> print Building.objects.all().query
OR
>>> Building.objects.all().query.__str__()




Friday, March 6, 2015

How to Ubuntu Install SimpleScreenRecorder and Start Recording with Audio

1)
Install Simple Screen Recorder

http://www.maartenbaert.be/simplescreenrecorder/#download

#sudo add-apt-repository ppa:maarten-baert/simplescreenrecorder
#sudo apt-get update
#sudo apt-get install simplescreenrecorder


2)
Load module-loopback to record Audio

#pactl load-module module-loopback

3)
UnLoad module-loopback After Recording

#pactl unload-module module-loopback

4)
How to Start Recording


4a)
Minimize the simplescreenrecorder window

4b)
Press "Ctrl + r" to Start the Recording
Press "Ctrl + r" again to Pause the Recording

5)
How to Stop Recording and Save it.


5a)
Press "Ctrl + r" to Pause the Recording

5b)
Open simplescreenrecorder window and click on "Save recoding" button.


Thursday, March 5, 2015

Python How to find all submodules of a module

How to find all submodules of module kazoo

>>> import kazoo
>>> import pkgutil

>>>
>>>
>>>
>>> dir(kazoo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>>
>>>
>>>
>>>#List all submodules of module kazoo
>>> for x in pkgutil.iter_modules(kazoo.__path__):
...     x

...
(, 'client', False)
(, 'exceptions', False)
(, 'handlers', True)
(, 'hosts', False)
(, 'interfaces', False)
(, 'loggingsupport', False)
(, 'protocol', True)
(, 'recipe', True)
(, 'retry', False)
(, 'security', False)
(, 'testing', True)
(, 'tests', True)
>>>
>>>
>>>
>>> kazoo.client
Traceback (most recent call last):
  File "", line 1, in
AttributeError: 'module' object has no attribute 'client'
>>>
>>>
>>>
>>> import kazoo.client
>>> import kazoo.exceptions
>>> import kazoo.handlers

>>>
>>>

OR



>>>#List all submodules of module kazoo
>>> for x in pkgutil.walk_packages(kazoo.__path__):
...     x

...
(, 'client', False)
(, 'exceptions', False)
(, 'handlers', True)
(, 'hosts', False)
(, 'interfaces', False)
(, 'loggingsupport', False)
(, 'protocol', True)
(, 'recipe', True)
(, 'retry', False)
(, 'security', False)
(, 'testing', True)
(, 'tests', True)
>>>
>>>
>>>

How to Install Python SimpleGUI SimpleGUICS2Pygame for your CodeSkulptor Programs

1)
Install
#pip install SimpleGUICS2Pygame

2)
#python
>>> import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
>>>
>>> #Event handler
... def tick():
...     print "tick!"
...
>>> #Register handler
... timer = simplegui.create_timer(1000,tick)
>>>
>>>
>>> #Start timer
... timer.start()
>>> tick!
tick!
tick!
tick!
tick!
tick!

How to install simplegui in Ubuntu Linux

1)
Install Tkinter
#sudo apt-get install python-tk

2)

Install simplegui
#pip install simplegui
OR
#easy_install simplegu
i