Thursday, December 17, 2015

linked list in python

Link list: A list or collection object of multi value elements (node) in which each element has reference to other element.
    Link list is used when relating other elements which in turn becomes  part of network. So node comes in picture. Elements of linked lists are called nodes.
##

# next => just next left or right: not necessarily right to the current node

class Node:
    def __init__(self):
        self.data = None
        self.next = None

class LinkedList:
    def __init__(self):
        self.node = None

    def add_node(self, data):
        new_node = Node()
        new_node.data = data
        new_node.next = self.node
        self.node = new_node

    def show_data(self):
        current_node = self.node
        while current_node is not None:
            print current_node.data
            current_node = current_node.next


l = LinkedList()

for x in range(1,5):
    l.add_node(x)
# The list can be traversed only once
l.show_data()
'''
def print_list(l):
    while l.node is not None:
        print l.node.data
        l.node = l.node.next
'''

#! /usr/bin/env python

class node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node


class linked_list:
    def __init__(self):
        self.cur_node = None

    def add_node(self, data):
        new_node = node() # create a new node
        new_node.data = data
        new_node.next = self.cur_node # link the new node to the 'previous' node.
        self.cur_node = new_node #  set the current node to the new one.

    def list_print(self):
        node = self.cur_node # cant point to ll!
        while node:
            print node.data
            node = node.next



ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)

ll.list_print()
 
 
:#: Link list in C:
 
#include<stdlib.h>
#include<stdio.h>

struct list_el {
   int val;
   struct list_el * next;
};

typedef struct list_el item;

void main() {
   item * curr, * head;
   int i;

   head = NULL;

   for(i=1;i<=10;i++) {
      curr = (item *)malloc(sizeof(item));
      curr->val = i;
      curr->next  = head;
      head = curr;
   }

   curr = head;

   while(curr) {
      printf("%d\n", curr->val);
      curr = curr->next ;
   }
}
 


Tuesday, December 15, 2015

clear list for further use

http://stackoverflow.com/questions/850795/clearing-python-lists


just reinitialize as:
>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

There is other method to delete a list but it has its own issues:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True
You could also do:

>>> a[:] = []

serch key in python dictionary using 'in' in place of has_key or .keys()

best way to use 'in'

a = {'k': 'x', 'p': 'k'}

if k in a:
     print a['k']

k in a => looks 'k' only in the key list.'k' in  a.keys() is not needed - This will unnecessarily slow the processing speed.

Monday, December 14, 2015

Friday, December 11, 2015

django server setup and code

#install django: pip install Django==1.9.2

Applicable for: django-1.9 and python-3.4.3 /django-1.9.3 & python 2.7.
#django version check: django-admin --version
#create django project: 
django-admin startproject mysite .
# Start server if project created successfully:
manage.py runserver   ::check if the site is working fine (default port is 8000):
=>http://localhost:8000/ (accessible on local machine only)
manage.py runserver 10.0.0.036:8081 =>http://10.0.0.36:8081 (accessible from any system on the network)
"

It worked!

Congratulations on your first Django-powered page.

" 
# Check any issue with server coding:
manage.py check
# create application
manage.py startapp bookmarks
# Note: 
A. Server run: Django starts web server listener at the specified port with loading the server configuration from the file settings.py. manage.py has information where the settins.py is located.
B. Connection to the server host at the listening port directs the call to the the listener code. The redirection is done by the system's network layer. The system network layer and the server code works closely.
    The incoming connection request comes to the network layer of the system. Network layer -> Django framework which coordinates the network layer on one side and the code layer on the other side.
    Framework connects the request to the file 'urls.py'. This file sends the request to the properly mapped urls or views.
# Basic urls.py configuration: (main_function to be defined in the file views.py)
from django.conf.urls import url
from bookmarks.views import *

urlpatterns = [
    url(r'^$', main_page),
]
 
# main_page function in views.py
# Create your views here.
from django.http import HttpResponse
def main_page(request):
    output = '''
    <html>
    <head><title>%s</title></head>
    <body>
    <h1>%s</h1><p>%s</p>
    </body>
    </html>
    ''' % (
    'Django Bookmarks',
    'Welcome to Django Bookmarks',
    'Where you can store and share bookmarks!'
    )
    return HttpResponse(output)
===== This completes basic modifiable server setup =====
# Setup database
# Create essential tables for already specified defaults apps in:
 
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
These applications are included by default as a convenience for the common case.
=> command: manage.py migrate
 Note: to create table for an app, the models.py must have the table definition. Above applications already has the table definitions in their corresponding models.
# Create tables for new app 'bookmarks': Modify the file models.py
from django.db import models
class Link(models.Model):
    url = models.URLField(unique=True)

Note: django field types: example: models.CharField(maxlength=200)
https://docs.djangoproject.com/en/1.9/ref/models/fields/ 

Now add the new app to the INSTALLED_APPS configuration:
'bookmarks.apps.BookmarksConfig',
AS:
INSTALLED_APPS = [
    'bookmarks.apps.BookmarksConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
=> After each modification of model the following two command must run:
manage.py makemigrations bookmarks(the app name)
# Check what SQL will run when 'manage.py migrate will run': 
=>manage.py sqlmigrate bookmarks 0001 
manage.py migrate
# Now database is setup. Play around the database with django shell:
=>manage.py shell
>>> from bookmarks.models import *
>>> link1 = Link(url='http://www.packtpub.com/') 
>>> link1.save()
>>> link2 = Link(url='http://www.example.com/')
>>> link2.save()
>>> link2.url
>>> link2.url = 'http://www.google.com/'
>>> link2.save()
To get a list of all available Link objects, type the following:
>>> links = Link.objects.all()
>>> for link in links:
... print link.url
...
To get an object by ID, type the following:
>>> Link.objects.get(id=1)
<Link: Link object>
Finally, to delete a link, use the following:
>>> link2.delete()
>>> Link.objects.count()
# User management:
Fortunately for us, management of user accounts is so common that Django comes with a user model ready for us to use. This model contains fields that are often associated with user accounts, such as username, password and email and so on. The model is called User and it's located in the django.contrib.auth.models package.
To explore the contents of this model, open the interactive console and type
the following:
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[]  : The user list is empty because no user is created.
# Create super user:
manage.py createsuperuser
Provide the asked in formation
Check on the shell:
c:\test>manage.py shell
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> User.objects.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'User' is not defined
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: admin>]
>>>

You can examine the fields of User objects by using the dir function:
>>> user = User.objects.get(id=1)
>>> dir(user)
You will get a very long list of attributes. Among them you will find the username, email address and password. Good news! This model fulfills our needs. Django provides all the necessary attributes for our user objects, and we can use directly use the User model directly without any extra code.
# create user link table for relational database:
insert the code below in the models file:
from django.contrib.auth.models import User
    class Bookmark(models.Model):
    title = models.CharField(maxlength=200)
    user = models.ForeignKey(User)
    link = models.ForeignKey(Link)
 
Updated modelds.py
from django.db import models
from django.contrib.auth.models import User
 
class Link(models.Model):
    url = models.URLField(unique=True)
 
class Bookmark(models.Model):
    title = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    link = models.ForeignKey(Link) 
Then run
manage.py makemigrations bookmarks
manage.py migrate
(the above two command need to run because models.py updated)
 
# Putting views in templates folder
-create 'templates' folder in the app folder (bookmarks)
#Note:
Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures aDjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS. 

# create a file called main_page.html in the templates folder with the
following content:
<html>
<head>
<title>{{ head_title }}</title>
</head>
<body>
<h1>{{ page_title }}</h1>
<p>{{ page_body }}</p>
</body>
</html>
 
# update the file views.py:
from django.http import HttpResponse
from django.template import RequestContext, loader
def main_page(request):
    template = loader.get_template('main_page.html')
    variables = RequestContext(request, {
    'head_title': 'Django Bookmarks',
    'page_title': 'Welcome to Django Bookmarks',
    'page_body': 'Where you can store and share bookmarks!'
    })
    output = template.render(variables)
    return HttpResponse(output)
 
# Django forms:
A. without django form:
step-1:  app's html page: create form tag on required html page of the django app and specify action=<any_page_name> and method=<get or post>
 <form action="/search1/" method="get">
        <input type="text" name="q">
        <input type="submit" value="Search">
 </form>
Note: any_page_name does not need to exist for django powered site 

step-2: site's urls.py:  add any_page_name and and any_function_name for url redirection/filtering/validation to the urls.py
Example: url(r'^search1/$', search),
Note: 
1. ^$ => just server url, i.e http://localhost:800, because ^ => start
and $ => end : means empty string
2. The functions in views.py represent a html page, because after executing that function a page is sent to the browser with that (function name) name in the browser address. example: http://localhost:8000/my_function will directly call the python function 'my_function' in the file views.py
3. The definitions in views.py are also called 'views'. Creating a view or page in django powered server is same as creating or calling a function from views.py 
step-3: app's views.py: add definition of the function any_function_name specified in site's urls.py
 Example:
def search(request):
    if 'q' in request.GET:
        message = 'You searched for: %r' % request.GET['q']
    else:
        message = 'You submitted an empty form.'
    return HttpResponse(message)
 
 
 
 
 


  
 

Wednesday, December 9, 2015

python question-answer

Best way to read file:

with open(file_name) as fp:
    fp.read()


write lines to file
-----

with open(file_name, 'w') as fp:
    fp.writelines(text)


-----














Get prime numbers:

nums = range(2, 50)
for i in range(2, 8):
    nums = filter(lambda x: x == i or x % i, nums)

print nums


-----
Remove duplicates from a list: [use one line command 'set': this removes duplicates: it may sort also but no guarantee of ordering: to sort use 'sorted']

a = [8,8,9,10]
b = set(a)
print b
=> [8,9,10]

---





write lines to file: create file easy way

def create_file('file_name', 'text'):
    with open(INDEX_HTML,"w") as fp:
        fp.writelines(html_contents)


create_file('test.txt', 'hello world')



   

color console text on windows

https://www.burgaud.com/bring-colors-to-the-windows-console-with-python/

color_console.py
=====
 """
Colors text in console mode application (win32).
Uses ctypes and Win32 methods SetConsoleTextAttribute and
GetConsoleScreenBufferInfo.

$Id: color_console.py 534 2009-05-10 04:00:59Z andre $
"""

from ctypes import windll, Structure, c_short, c_ushort, byref

SHORT = c_short
WORD = c_ushort

class COORD(Structure):
  """struct in wincon.h."""
  _fields_ = [
    ("X", SHORT),
    ("Y", SHORT)]

class SMALL_RECT(Structure):
  """struct in wincon.h."""
  _fields_ = [
    ("Left", SHORT),
    ("Top", SHORT),
    ("Right", SHORT),
    ("Bottom", SHORT)]

class CONSOLE_SCREEN_BUFFER_INFO(Structure):
  """struct in wincon.h."""
  _fields_ = [
    ("dwSize", COORD),
    ("dwCursorPosition", COORD),
    ("wAttributes", WORD),
    ("srWindow", SMALL_RECT),
    ("dwMaximumWindowSize", COORD)]

# winbase.h
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12

# wincon.h
FOREGROUND_BLACK     = 0x0000
FOREGROUND_BLUE      = 0x0001
FOREGROUND_GREEN     = 0x0002
FOREGROUND_CYAN      = 0x0003
FOREGROUND_RED       = 0x0004
FOREGROUND_MAGENTA   = 0x0005
FOREGROUND_YELLOW    = 0x0006
FOREGROUND_GREY      = 0x0007
FOREGROUND_INTENSITY = 0x0008 # foreground color is intensified.

BACKGROUND_BLACK     = 0x0000
BACKGROUND_BLUE      = 0x0010
BACKGROUND_GREEN     = 0x0020
BACKGROUND_CYAN      = 0x0030
BACKGROUND_RED       = 0x0040
BACKGROUND_MAGENTA   = 0x0050
BACKGROUND_YELLOW    = 0x0060
BACKGROUND_GREY      = 0x0070
BACKGROUND_INTENSITY = 0x0080 # background color is intensified.

stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo

def get_text_attr():
  """Returns the character attributes (colors) of the console screen
  buffer."""
  csbi = CONSOLE_SCREEN_BUFFER_INFO()
  GetConsoleScreenBufferInfo(stdout_handle, byref(csbi))
  return csbi.wAttributes

def set_text_attr(color):
  """Sets the character attributes (colors) of the console screen
  buffer. Color is a combination of foreground and background color,
  foreground and background intensity."""
  SetConsoleTextAttribute(stdout_handle, color)

=====

color_test_pytgho_26.py

-----
"""
Test module color_console (Python 2.6). Does not work with Python 3.0 (mainly
due to the usage of print. In Python 3.0 print is a builtin function and no more
a statement.
$Id: test26_color_console.py 534 2009-05-10 04:00:59Z andre $
"""

import color_console as cons

def test():
  """Simple test for color_console."""
  default_colors = cons.get_text_attr()
  default_bg = default_colors & 0x0070
  cons.set_text_attr(cons.FOREGROUND_BLUE | default_bg |
                     cons.FOREGROUND_INTENSITY)
  print '==========================================='
  cons.set_text_attr(cons.FOREGROUND_BLUE | cons.BACKGROUND_GREY |
                     cons.FOREGROUND_INTENSITY | cons.BACKGROUND_INTENSITY)
  print 'And Now for Something',
  cons.set_text_attr(cons.FOREGROUND_RED | cons.BACKGROUND_GREY |
                     cons.FOREGROUND_INTENSITY | cons.BACKGROUND_INTENSITY)
  print 'Completely Different!',
  cons.set_text_attr(default_colors)
  print
  cons.set_text_attr(cons.FOREGROUND_RED | default_bg |
                     cons.FOREGROUND_INTENSITY)
  print '==========================================='
  cons.set_text_attr(default_colors)

if __name__ == "__main__":
  test()

-----

color_test_pytgho_30.py

-----

"""
Test module color_console (Python 3.0). Does not work with Python 2.6.
$Id: test_color_console_py30.py 535 2009-05-11 02:48:29Z andre $
"""

import color_console as cons
import sys

def test():
  """Simple Pyton 3.0 test for color_console."""
  default_colors = cons.get_text_attr()
  default_bg = default_colors & 0x0070
  default_fg = default_colors & 0x0007
  cons.set_text_attr(cons.FOREGROUND_BLUE | default_bg |
                     cons.FOREGROUND_INTENSITY)
  print('===========================================')
  cons.set_text_attr(cons.FOREGROUND_BLUE | cons.BACKGROUND_GREY |
                cons.FOREGROUND_INTENSITY | cons.BACKGROUND_INTENSITY)
  print('And Now for Something', end=' ')
  sys.stdout.flush() # Force writing first part of the line in blue
  cons.set_text_attr(cons.FOREGROUND_RED | cons.BACKGROUND_GREY |
                cons.FOREGROUND_INTENSITY | cons.BACKGROUND_INTENSITY)
  print('Completely Different!')
  cons.set_text_attr(default_colors)
  cons.set_text_attr(cons.FOREGROUND_RED | default_bg |
                     cons.FOREGROUND_INTENSITY)
  print('===========================================')
  cons.set_text_attr(default_colors)

if __name__ == "__main__":
  test()