Monday, December 16, 2013

Paint app using Django and sqlite3 as databae

Django is a web framework designed to help us build complex web applications simply and quickly. It’s written in the Python programming language.Django takes it name from the early jazz guitarist Django Reinhardt, a gypsy savant who managed to play dazzling and electrifying runs on his instrument even though two of the fingers on his left hand were paralyzed in an accident when he was young.Thus, it’s a fitting name for the framework: Django can do some very complex things with less code and a simpler execution than you’d expect. It doesn’t take a heavy hand to build with Django. The framework does the repetitive work for you, allowing you to get a working website up quickly and easily.

Django setup:

After install django,make a directory to store our project.

Open the terminal and enter the following commands:

mkdir djando
cd django
django-admin.py startproject mysite

this produces:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

This is the general structure of django.Here we didnt add any apps.

First we have to setup the database.Open settings.py and do as following.Here i am using sqlite3 database.


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'test.db',
    }
}

Then enter the command:

python manage.py syncdb   #Creates database and corresponding tables for django

Now its time to add our paint application.so

python manage.py startapp paint

this produces following directory like

├── manage.py
├── paint
│   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
└── mysite
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

Here we are...

Here model view controller(MVC) is the routing procedure or model template view.
In models.py we have to setup database model
In views.py we have to setup routing functions or rendering functions
In urls.py corresponding urls are determined

Then we have to add this app in settings.py

INSTALLED_APPS = (
#    'django.contrib.admin',
#    'django.contrib.auth',
#    'django.contrib.contenttypes',
#    'django.contrib.sessions',
#   'django.contrib.messages',
    'django.contrib.staticfiles',
    'paint',
)


In models.py

from django.db import models

class Pic(models.Model):
        name=models.CharField(max_length=100)
        data=models.CharField(max_length=10000000000)

Then we have to create template directory and static directory inside.
So this will like

├── manage.py
├── paint
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── mysite
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── templates
└── static

Then htmls routing functions are done.To view the codes click here

To view the site i deployed on heroku.Click here

Paint app using Flask and postgresql

Paint application using postgresql i defined earlier is implementing in Flask.Here database is postgresql.

The paint app that was created using HTML5 canvas and javascript is modified with a save option. When each object is drawn all the details about that object is saved as a JSON object. Then it is saved to the postgreSql database.

For example when a Rectangle object is drawn the details such as width, height starting points etc are saved as a JSON object.Then it is added to a list


After everything is drawn the list will contain all the info of drawn objects as a list in the order of appearences.

Then it is saved to the database.

Example: Saving object info using JSON object.

Here on each drawing function JSONDATA.push is used.for example:

jsondata.push({"Type":"pencil", "X0":sX,"Y0":sY,"X1":mX,"Y1":mY,"width":c.lineWidth,"color":c.strokeStyle})data=JSON.stringify(jsondata)

Then this 'data' is posted to python program and insert to database using sql query.

At the time of reloading a selected picture these details are retrieved from database and redrawn in the canvas.
The following code shows how to redraw a rectangle in the canvas. The stringified data is parsed before it is drawn on canvas.

l=JSON.parse(data);

Then check the type in list 'l' and redraw.For example:

if(l[i]['Type']=='line'){
context.beginPath()
x0=l[i]['X0']
y0=l[i]['Y0']
x1=l[i]['X1']
y1=l[i]['Y1']
context.moveTo(x0,y0)
context.lineTo(x1,y1)
context.lineWidth=l[i]['width'];
context.strokeStyle=l[i]['color'];
context.stroke()
context.closePath()
}
context.beginPath()
x0=l[i]['X0']
y0=l[i]['Y0']
x1=l[i]['X1']
y1=l[i]['Y1']
context.moveTo(x0,y0)
context.lineTo(x1,y1)
context.lineWidth=l[i]['width'];
context.strokeStyle=l[i]['color'];
context.stroke()
context.closePath()
}

jsondata.push({"Type":"pencil", "X0":sX,"Y0":sY,"X1":mX,"Y1":mY,"width":c.lineWidth,"color":c.strokeStyle})data=JSON.stringify(jsondata)

By using flask the whole paint app became efficient ,interactive and useful

To view this code : Click here

To view the paint app which i deployed in heroku click here

Friday, November 1, 2013

Python-Flask microblog Application Using Sqlite3

  Here i am defining how to create a Python-Flask application using database Sqlite3.First we should know what is Flask?What is the use of Flask?
   Flask is a framework in python for Web development.It has specific structure.

Folders should be like this structure.

Flaskapp /
                / templates /        # contains html files
                / statics /             # contains js,images,css
                / static / css
                / .py files            # main files for application routing and database management

Flask can be install using:
       sudo pip install Flask
   
     In a python-Flask application, a routing python program is needed which determines the url routing.We can define sql query inside this or outside as a single python file.

     To start the routing program,let  route.py. First an instance of Flask is to be created inside route.py
app=Flask(__name__)
Then defines the routing functions.Here i am showing how does this works:

Let me define how the html and python program interacts:

we want to do a python function or change url when a button in html press.This done by

html
<a href='/post'>button name</a>
Here button name will see as a link,but it can modify as button using css

route.py

@app.route('/post')
def func():
      -----------
      -----------
Here it is...when you click the link that function works.

Accessing Database:

         We can add separate python file for creating database.

let datadb.py

To create sqlite3 database 
   
import sqlite3 as lite
import sys
con=lite.connect("blog.db")
with con:
        cur=con.cursor()
        cur.execute("DROP TABLE IF EXISTS posts")
        cur.execute("CREATE TABLE posts(id integer primary key autoincrement,title TEXT,text INT)")

   Here created blog.db (database name),created  table posts
I think this much knowledge is needed for accessing database.you can refer the codes through the link i am added in last.


To view program code: Click here


Monday, September 30, 2013

Simple Paint Application using HTML5 Canvas


         Paint application is used to draw curves,pictures,import images,etc..Here is a simple Paint App i designed for beginners.This done using HTML and javaScript.Canvas(drawing area) created using Html tags.That is Picturising the window is done by Html tags and the functions done using javaScript.


         JavaScript insert elements from documents using:
                  document.getElementById(id)

   This App includes mouse events.For eg:

   My Paint App View:


     Canvas and buttons are designrd using HTML where the functions are done with JavaSsript.

MouseEvents:


 function events(){b.onmousedown=md;b.onmouseup=mu;b.onmousemove=mv;}  
 function md(e){img=c.getImageData(0,0,b.width,b.height);sX=e.x;sY=e.y;pulse="on";}  
 function mu(e1){eX=e1.x;eY=e1.y;pulse="off";}  
 function mv(e2){mX=e2.x;mY=e2.y;if (pulse=="on"){c.putImageData(img,0,0);draw();}}  

LineTool:


 c.beginPath();c.moveTo(sX,sY);c.lineTo(mX,mY);c.stroke();c.closePath();  

RectangleTool:


 c.strokeRect(sX,sY,mX-sX,mY-sY);c.stroke();if(f==1){c.fillRect(sX,sY,mX-sX,mY-sY);  

CircleTool:


 c.beginPath();c.arc(Math.abs(mX+sX)/2,Math.abs(mY+sY)/2,Math.sqrt(Math.pow(mX-sX,2)+Math.pow(mY-sY,2))/2, 0, Math.PI*2);  
 c.stroke();if(f==1){c.fill();}c.closePath();  

Penciltool:

 c.moveTo(sX,sY);c.lineTo(mX,mY);c.stroke();sX=mX;sY=mY;  

In this way i set function fill() ,Stroke() etc..
For full program: Click here

Thursday, September 26, 2013

Lisp Interpreter in Python and JavaScript

    LISP is a family of computer programming languages with a long history, fully parenthesized Polish prefix notation.Lisp is specified in 1958.Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older (by one year). Like Fortran,The name LISP derives from "LISt Processing". Linked lists are one of Lisp language's major data structures, and Lisp source code is itself made up of lists.   LISP expressions are composed of forms. The most common LISP form is function application. LISP represents a function call f(x) as (f x). For example, cos(0) is written as (cos 0).LISP expressions are case-insensitive. It makes no difference whether we type (cos 0) or (COS 0).Some functions, like "+" and "*", could take an arbitrary number of arguments. In our example, "*" took three arguments. It could as well take 2 arguments, as in "(* 2 3)", or 4 arguments, as in "(* 2 3 4 5)".Numeric values like 4 and 6 are called self-evaluating forms: they evaluate to themselves.

Defining a function in LISP : 


 (define (add a b)
  (+ a b))  
(add 3 4)  #4
  Lisp interpreter in Python : LISP.py .(for more details click here)
  Lisp interpreter in JavaScript : LISP.js

Monday, September 23, 2013

Huffman Compression

         A data compression technique which varies the length of the encoded symbol in proportion to its information content,that is the more often a symbol or token is used, the shorter the binary string used to represent it in the compressed stream.Huffman codes can be properly decoded because they obey the prefix property, which means that no code can be a prefix of another code, and so the complete set of codes can be represented as a binary tree, known as a Huffman tree.
        The least length codes correspond to the most often occurring symbols allowing to perform compression. For example, the sequence “aaaaaaaa” contains only one symbol ‘a' that corresponds to the Huffman code with size 1 bit; after encoding the output sequence will have size 1 byte - thus compression ratio will be 8.Because generally a character uses 8 bits.Huffman encoding is based on the principle that letters that appear more frequently should have a smaller code than the ones that are used less often. So, in the English language, vowels would be used more than the letter 'z', and would get shorter codes.

Huffman program  in python Huffman.py
Huffman program in javaScript Huffman.js


For example: Huffman Tree for String "malayalam"

                                                  

Generating Huffman Tree is also simple.We can just check in Huffman Tree Generation

       So Generally The idea behind Huffman coding is to find a way to compress the storage of data using variable length codes. Our standard model of storing data uses fixed length codes. For example, each character in a text file is stored using 8 bits. There are certain advantages to this system. When reading a file, we know to ALWAYS read 8 bits at a time to read a single character. But as you might imagine, this coding scheme is inefficient. The reason for this is that some characters are more frequently used than other characters. Let's say that the character 'e' is used 10 times more frequently than the character 'q'. It would then be advantageous for us to use a 7 bit code for e and a 9 bit code for q instead because that could shorten our overall message length.
Huffman coding finds the optimal way to take advantage of varying character frequencies in a particular file. On average, using Huffman coding on standard files can shrink them anywhere from 10% to 30% depending to the character distribution.

Wednesday, September 4, 2013

Word count programs in Python



text file a.txt:     
      India is my country and all Indians are my brothers and sisters.I love my country and I am proud of its rich and varied heritage.I shall always strive to be worthy of it.I shall give my parents, teachers and all elders respect and treat everyone with courtesy.To my country and my people, I pledge my devotion. In their well-being and prosperity alone lies my happiness.
 >>>from collections import Counter  
 >>>import re  
 >>>import os  
 >>>list_word=re.findall("\w+",open('a.txt').read().lower())  
 >>>for i in Counter(list_word):
 . . .  print i,'-',Counter(list_word)[ i ]  

#
and - 8
all - 2
everyone - 1
love - 1
pledge - 1
give - 1
being - 1
is - 1
india - 1
it - 1
alone - 1
are - 1
in - 1
respect - 1
its - 1
happiness - 1
prosperity - 1
varied - 1
their - 1
indians - 1
to - 2
parents - 1
treat - 1
rich - 1
heritage - 1
be - 1
brothers - 1
elders - 1
shall - 2
am - 1
of - 2
courtesy - 1
worthy - 1
sisters - 1
with - 1
people - 1
strive - 1
lies - 1
i - 5
country - 3
proud - 1
well - 1
teachers - 1
always - 1
my - 8
devotion - 1

another program for word count:
 >>>d={}  
 >>> list_word=re.findall("\w+",open('a.txt').read().lower())  
 >>>for i in list_word:  
 . . .   d[i]=d.get(i,0)+1  
 >>>d  
# dict of word as above

another program for word count:
 >>> list_word=re.findall("\w+",open('a.txt').read().lower())  
 >>> for i in list(set(list_word)):  
 . . .  print i,list_word.count(i)