Monday 10 December 2012

Google app engine with Python 2.7



Explaining the webapp2 Framework


          App Engine includes a simple web application framework, called webapp2.

A webapp2 application has two parts:

  • One or more RequestHandler classes that process requests and build responses   
  • WSGIApplication instance that routes incoming requests to handlers based on the URL
     
import webapp2
class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

app = webapp2.WSGIApplication([('/', MainPage)],
                              debug=True)

  Using the Users Service

 
         Google App Engine provides several useful services based on Google infrastructure, accessible by applications using libraries included with the SDK. One such service is the Users service, which lets our application integrate with Google user accounts. With the Users service, our users can use the Google accounts they already have to sign in to our application.

import webapp2
from google.appengine.api import users
class MainPage(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()

        if user:
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write('Hello, ' + user.nickname())
        else:
            self.redirect(users.create_login_url(self.request.uri))

app = webapp2.WSGIApplication([('/', MainPage)],
                              debug=True)
 

Handling Forms with webapp2

 

                This version has two handlers: MainPage, mapped to the URL /, displays a web form. Guestbook, mapped to the URL /sign, displays the data submitted by the web form.The Guestbook handler has a post() method instead of a get() method. This is because the form displayed by MainPage uses the HTTP POST method (method="post") to submit the form data. If for some reason we need a single handler to handle both GET and POST actions to the same URL, we can define a method for each action in the same class.The code for the post() method gets the form data from self.request. Before displaying it back to the user, it uses cgi.escape() to escape HTML special characters to their character entity equivalents. cgi is a module in the standard Python library.


Using the Datastore

 

                  App Engine's data repository, the High Replication Datastore (HRD), uses the Paxos algorithm to replicate data across multiple data centers .Data is written to the Datastore in objects known as entities. Each entity has a that uniquely identifies it.An entity can optionally designate another entity as its parent; the first entity is a child of the parent entity. The entities in the Datastore thus form a hierarchically structured space similar to the directory structure of a file system. An entity's parent, parent's parent, and so on recursively, are its ancestors; its children, children's children, and so on, are its descendants. An entity without a parent is a root entity.


Using Jinja2 Templates

 

Add the following code to the bottom of the configuration file app.yaml

libraries:- name: jinja2
  version: latest

Add following code to the top of the mainpage handler 

 

import jinja2 
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

 

 Replace the MainPage handler with code that resembles the following:
 
 class MainPage(webapp2.RequestHandler):
    def get(self):
        guestbook_name=self.request.get('guestbook_name')
        greetings_query = Greeting.all().ancestor(
            guestbook_key(guestbook_name)).order('-date')
        greetings = greetings_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'greetings': greetings,
            'url': url,
            'url_linktext': url_linktext,
        }

        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))
 

Using Static Files

 

              Images, CSS stylesheets, JavaScript code, movies and Flash animations are all typically stored with a web application and served directly to the browser.

We create a configuration file   app.yaml with the following content

application: helloworldversion: 1runtime: python27api_version: 1threadsafe: true
handlers:- url: /stylesheets
  static_dir: stylesheets
- url: /.*
  script: helloworld.app
libraries:- name: jinja2
  version: latest
 
 Create a css file with following content for set background colour and font etc
 
body {
  font-family: Verdana, Helvetica, sans-serif;
  background-color: #DDDDDD;
} 
 
Using following codes in html file for access the css file

<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" /> 

After testing we can upload our file to google app engine using foolowing commands 

 python appcfg.py update  "set path"







 

Saturday 8 December 2012

Google App Engine


        Google App Engine lets us to run web applications on Google's infrastructure.App Engine applications are easy to build, easy to maintain, and easy to scale.With App Engine, there are no servers to maintain.

                Google App Engine supports apps written in several programming languages.With App Engine's there are 3 different types of runtime environment.

  • Java runtime environment
  • Python runtime environment
  • Go runtime environment  

 

The Python Runtime Environment

 

                With App Engine's Python runtime environment, we can implement our app using the Python programming language, and run it on an optimized Python interpreter.The primary Python runtime environment uses Python version 2.7.2. we can also choose the older Python 2.5.2 runtime.The Python environment includes the Python standard library. Of course, not all of the library's features can run in the sandbox environment.The Python environment provides rich Python APIs for the datastore, Google Accounts, URL fetch, and email services.

 

How To Use The App Engine To Host An Application


              At first we download and  install the Google App Engine SDK in our systemThen we can register our application with unique application id and application name in our google app engine account.We can create a folder in our system containing 3 files. First one is the file which to be upload to the google app engine,second is the configuration file called app.yaml this file describes which handler scripts should be used for which URLs.


                       application: nithinconwaysgameoflife
                       version: 1
                       api_version: 1
                       runtime: python
                       handlers:

                      - url: /.*
                      script: main.py 

here nithinconwaysgameoflife is the application id.
Third one is main.py ,the python file where we access our web application file.


                          import wsgiref.handlers
                          from google.appengine.ext import webapp
                          from google.appengine.ext.webapp import Request
                          from google.appengine.ext.webapp.util import run_wsgi_app
                          from google.appengine.ext.webapp import template

                          class mainh(webapp.RequestHandler):
                              def get(self):
                                  self.response.out.write(template.render("game.html",{}))  
      
                         def main():
                             app = webapp.WSGIApplication([
                                 (r'.*',mainh)], debug=True)
                             wsgiref.handlers.CGIHandler().run(app)


                          if __name__ == "__main__":
                                     main()

Testing the Application

 

With a handler script and configuration file mapping every URL to the handler, the application is complete. We can now test it with the web server included with the App Engine SDK.

Type the command on terminal


google_appengine/dev_appserver.py "path to applicationid folder"
 
we can test the application by visiting the following URL 


http:// localhost:8080/

 

Upload the application to google app engine 


$cd google_appengine


after enter the  google_appengine folder in the system.

Type the following command on terminal


python appcfg.py update " path to applicationid folder".


Enter your google user name and password at the prompt
Now we can see our application run with url  http://applicationid.appspot.com/ on google app engine



click here for see example

 

 


Wednesday 5 December 2012

CountDown Timer


         CountDown Timer is an application for set the time and start the counting down in seconds,minutes,hours etc.The language used for develop the countdown timer is javascript in html canvas.The main idea for contdown timer is refreshing the canvas on every call of setInterval( ) which is set for 1000ms.

      There is two text box for enter the time in minutes and seconds.Three buttons are available for start,stop and set.The start button is used for start counting down, the stop button is used for stop the timer and the set button is used for set the initial time.

There are four functions are mainly used for develop the timer.


function counter()

      This function is used for counting down in second and minutes based on some conditions which depend the initial value.This function return the message "Time out" when seconds ==00 and minutes ==00.

function start()

      This function is used for start the timer.within this function call of setInterval( ) which is set for 1000ms.

function set()

            This function is used for set the inital time in seconds and minutes.

function stop()

            This function is used for stop the timer.Within this function call clearInterval() .


Click here for download the code for CountDown Timer in javascript.


COUNTDOWN TIMER








COUNT DOWN TIMER
minutes: seconds:

Monday 3 December 2012

Conway's Game of Life



                 The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970.The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.


Rules

  1. Any live cell with fewer than two live neighbors dies, as if caused by under population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Algorithm 

               Life patterns are represented as two-dimensional arrays in computer memory. Typically two arrays are used, one to hold the current generation, and one in which to calculate its successor. Often 0 and 1 represent dead and live cells respectively. A nested for-loop considers each element of the current array in turn, counting the live neighbors of each cell to decide whether the corresponding element of the successor array should be 0 or 1. The successor array is displayed. For the next iteration the arrays swap roles so that the successor array in the last iteration becomes the current array in the next iteration.

Examples of patterns

                   Many different types of patterns occur in the Game of Life, including still lifes, oscillators, and patterns that translate themselves across the board.examples of these three classes are shown below, with live cells shown in black, and dead cells shown in white.


Still lifes                                               Oscillators                                                             Spaceships 

                                               

                                             
 block                                                   Blinker (period 2)                                                              Glider                                              

                                                           


                              
    Beehive                                                Toad (period 2)                                                        LWSS
                                                                                                 
                                   
              
                               
        Loaf                                                  Beacon (period 2)                             

                                    
            

        

      Boat                                          Pulsar (period 3)                                                                   
  
                                                




   Click here for downloading the Conway's Game of Life Code.

 

Play the game


  




Conway's Game of Life

LISP INTERPRETER



              Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older.The name LISP derives from "LISt Processing". Linked lists are one of Lisp languages' major data structures, and Lisp source code is itself made up of lists.

The table  will explain the syntactic rules and the semantic rules of the lisp language



  Language Interpreter 

 

         A language interpreter has two parts:

 

Parsing

 

          The parsing component takes an input program in the form of a sequence of characters, verifies it according to the syntactic rules of the language, and translates the program into an internal representation.

Execution


       The internal representation is then processed according to the semantic rules of the language, thereby carrying out the computation.



Here is the code for Lisp interpreter in python is given.


Parsing:read and parse


read(s)

         This function is used for Read a Scheme expression from a string

tokenize(s) 

        This function is used for Convert a string into a list of tokens.here  's' is the given input string
 
read_from(tokens)
   
       This function is used for Read an expression from a sequence of tokens.

atom(token)
     
      This function is used for separate token into the numbers and others.if the token is a number it is taken as number and others are grouped in to other group.

 

Execution


eval( )

      This function is the heart of the lisp interpreter.This function is used for Evaluate an expression in an environment.Within the function check the all conditions of the lisp language and evaluate the expression based on the syntactic rules and the semantic rules.

class Env(dict)
 
       Env is a subclass of dict, which means that the ordinary dictionary operations work on it.In addition there are two methods, the constructor __init__ and find to find the right environment for a variable.

Here is the code for Lisp interpreter in javascript is given




Sunday 2 December 2012

Huffman Coding


                  Huffman Coding is an entropy encoding algorithm used for lossless data compression.Huffman coding uses a specific method for choosing the representation for each symbol, resulting in a prefix code,that expresses the most common source symbols using shorter strings of bits than are used for less common source symbols.Huffman coding is equivalent to simple binary block encoding.

Compression

          
             The technique works by creating a binary tree of nodes. These can be stored in a regular array, the size of which depends on the number of symbols.
A node can be either a leaf node or an internal node. Initially, all nodes are leaf nodes, which contain the symbol itself, the weight  of the symbol and optionally, a link to a parent node which makes it easy to read the code (in reverse) starting from a leaf node. Internal nodes contain symbol weight, links to two child nodes and the optional link to a parent node. As a common convention, bit '0' represents following the left child and bit '1' represents following the right child.

The simplest construction algorithm uses a priority queue where the node with lowest probability is given highest priority:

  1. Create a leaf node for each symbol and add it to the priority queue.
  2. While there is more than one node in the queue:
    1. Remove the two nodes of highest priority (lowest probability) from the queue
    2. Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.
    3. Add the new node to the queue.
  3. The remaining node is the root node and the tree is complete.

                 If the symbols are sorted by probability, there is a linear-time (O(n)) method to create a Huffman tree using two queues, the first one containing the initial weights (along with pointers to the associated leaves), and combined weights (along with pointers to the trees) being put in the back of the second queue. This assures that the lowest weight is always kept at the front of one of the two queues:

  1. Start with as many leaves as there are symbols.
  2. Enqueue all leaf nodes into the first queue (by probability in increasing order so that the least likely item is in the head of the queue).
  3. While there is more than one node in the queues:
    1. Dequeue the two nodes with the lowest weight by examining the fronts of both queues.
    2. Create a new internal node, with the two just-removed nodes as children (either node can be either child) and the sum of their weights as the new weight.
    3. Enqueue the new node into the rear of the second queue.
  4. The remaining node is the root node; the tree has now been generated. 




Decompression

               
                The process of decompression is simply a matter of translating the stream of prefix codes to individual byte values, usually by traversing the Huffman tree node by node as each bit is read from the input stream.Before this can take place, however, the Huffman tree must be somehow reconstructed. In the simplest case, where character frequencies are fairly predictable, the tree can be reconstructed and thus reused every time, at the expense of at least some measure of compression efficiency.


huffman coding using python code can be download from here.