Sunday, 16 December 2012

My Coursera Certificate For Scala


Completed Certification course for Functional Programming Principles in scala from www.coursera.org

Paint Application Using Javascript




      Stroke Thickness       Eraser Thickness

Monday, 10 December 2012

Python Webapp2 framework

App engine includes simple web application framework called webapp2. Webapp2 is already installed in google app engine environment. It can be used in python by importing webapp2 library.
      Webapp2 includes two features:
         Request Handler class that processes requests and build classes
         WSGIApplication instance which routes incoming requests to handlers.

 import webapp2

     class MainPage(webapp2.RequestHandler):
         def get(self):
             self.response.write('hello')

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


This code defines one request handler, MainPage, mapped to the root URL (/). When webapp2 receives an HTTP GET request to the URL /, it instantiates the MainPage class and calls the instance's get method. Inside the method, information about the request is available using self.request. webapp2 sends a response based on the final state of the MainPage instance.
The application itself is represented by a webapp2.WSGIApplication instance. The parameter debug=true passed to its constructor tells webapp2 to print stack traces to the browser output if a handler encounters an error or raises an uncaught exception.

Google app engine is equipped with features which provides an interactive session with users:
  • User Service:  get_current_user() function checks for the user is signed in or not.If the user is signed in then returns the user object otherwise returns None and users.create_login_url() returns the google account sign in page so as to sign in after the check for the current user fails.
  • High Replication DataStore : which uses paxos algorithm to replicate data along multiple data centres.The Datastore is extremely resilient in the face of catastrophic failure, but its consistency guarantees may differ from what you're familiar with. It includes a data modelling API which can be used by importing the google.appengine.ext.db module. Datastore has a sophisticated query engine for datamodels. Like sql language we can call gql by which provides access to the App Engine Datastore query engine's features using a familiar syntax.
  • Templates  : There are many templating system in python two of them are jinja2 and Django.  App Engine includes the Django and Jinja2 templating engines. To configure jinja2 library by adding the following in app.yaml file     
                                libraries:
                                 -  name: jinja2
                                    version: latest

for a template file one has to implement an html file which specifies the template of the app, by using that template we can implement jinja_environment.get_template(name) takes the name of a template file, and returns a template object. template.render(template_values) takes a dictionary of values, and returns the rendered text. The template uses Jinja2 templating syntax to access and iterate over the values, and can refer to properties of those values. In many cases, you can pass datastore model objects directly as values, and access their properties from templates.

Friday, 7 December 2012

Google App Engine Uploading Static Html

Google app engine is an is a platform as a service (PaaS) cloud computing platform for developing and hosting web applications in Google-managed data centers. Applications are sandboxed and run across multiple servers. App Engine offers automatic scaling for web applications—as the number of requests increases for an application, App Engine automatically allocates more resources for the web application to handle the additional demand.
                You can serve your app with your own domain with "example.xyz.com" or you can host for free in appspot.com provided for free for first 1 GB of usage. Further usage will be charged as per the subscribed amount of data. Google app engine is supported by three runtime environments python, Java and Go.

App engine includes following features :
  •  dynamic web serving, with full support for common web technologies
  • persistent storage with queries, sorting and transactions
  • automatic scaling and load balancing
  • APIs for authenticating users and sending email using Google Accounts
  • a fully featured local development environment that simulates Google App Engine on your computer
  • task queues for performing work outside of the scope of a web request
  • scheduled tasks for triggering events at specified times and regular intervals
 App Engine's Python runtime environment, you can implement your app using the Python programming language, and run it on an optimized Python interpreter. App Engine includes rich APIs and tools for Python web application development.The App Engine software development kits (SDKs) for Java, Python, and Go each include a web server application that emulates all of the App Engine services on your local computer. Each SDK includes all of the APIs and libraries available on App Engine.

Each SDK also includes a tool to upload your application to App Engine. Once you have created your application's code, static files and configuration files, you run the tool to upload the data. The tool prompts you for your Google account email address and password.

See  GOOGLE APP SDK   for sdk download.

You should use two commands from the sdks

dec_appserver.py - Python development server
       It  includes a web server application you can run on your computer that simulates your application running in the App Engine Python runtime environment.

appcfg.py
       You can use this command to upload new versions of the code, configuration and static files for your app to App Engine.

For Uploading your html application you should create a folder for you application with the name of your application. The folder includes three files app.yaml, a python file and the static file which you need to host on google app engine.

app.yaml is an configuration file which is used to describe which handler should be used to different urls.
The file includes
application: helloworld 
version: 1 
runtime: python27
 api_version: 1 
threadsafe: true
 
handlers:- url: /.*
  script: helloworld.app
 
 
Application is helloworld in this case which is an unique application id which would be assigned when you register your web app in appspot.com for free. Version is the application version, your new updations can be assigned to further new versions.
      Runtime is the version of python you are running in your system. This application is threadsafe so the same instance can handle several simultaneous requests. Threadsafe is an advanced feature and may result in erratic behavior if your application is not specifically designed to be threadsafe.Every request to a URL whose path matches the regular expression /.* (all URLs) should be handled by the app object in the helloworld module. 

For testing you can use development web server command which runs a web server listening on port 8080, you can check in the status typing url http://localhost:8080/

The python file is webapp2 framework which has two parts 
  • one or more RequestHandler classes that process requests and build responses
  • a WSGIApplication instance that routes incoming requests to handlers based on the URL
 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("prasanthtimer.html",{}))  
      
def main():
    app = webapp.WSGIApplication([
        (r'.*',mainh)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)


if __name__ == "__main__":
    main()
The static file which you would to upload can be specified as a filenname in double quotes. The html file with javascript will also work for this upload.

Now all the configuration is been done now you can upload the file by the following command:
appcfg.py update helloworld/
Now you can find your application running on
 http://your_app_id.appspot.com
Have fun.....!!!!!!!!!!!!

Wednesday, 5 December 2012

CountDown Timer

Here is an simple CountDown timer which is done javascript. The idea behind is refreshing the canvas on every call of setInterval( ) which is set for 1000ms.
     There are three button which are "SET" , "START", "STOP". The set button calls the function time which draws the value from the textfield on to the canvas. The start button calls the timer function in which setInterval() is called for decrementing and displaying on canvas. The stop button is for calling clearInterval() to stop the running timer.

Here is the Timer

STOP     =>  Stop Timer  
START   =>   To start the timer
SET       =>   To set the initial value
Initial Value: MIN:: SEC::

Conways Game Of Life

A Conways Game Of Life is a cellular automaton which consists of a regular grid of cells, each in one of a finite number of states, such as on and off (in contrast to a coupled map lattice). The grid can be in any finite number of dimensions. For each cell, a set of cells called its neighborhood (usually including the cell itself) is defined relative to the specified cell. An initial state (time t=0) is selected by assigning a state for each cell. A new generation is created (advancing t by 1), according to some fixed rule (generally, a mathematical function) that determines the new state of each cell in terms of the current state of the cell and the states of the cells in its neighborhood. Typically, the rule for updating the state of cells is the same for each cell and does not change over time, and is applied to the whole grid simultaneously, though exceptions are known, such as the Probabilistic Cellular Automata and asynchronous cellular automaton.
                              The game is usually a zero-player game i.e the evolution is by its initial value that is provided by a random number generator. The game has following rules. 
  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
 Many different types of patterns occur in the Game of Life, including still lifes, oscillators, and patterns that translate themselves across the board.Some of them frequently occurs all depends on the initial position(seed).
The different patterns are: 

Oscillators                                              Still Lifes                                           Spaceships




                      



By including all the patterns here is the whole Game!!!!!




A Tiny Lisp Interpreter

Most of the computer languages has a lot of syntactic notations, for lisp family of languages the syntax is based on lists in parameterized prefix notations like passing argument to a function in parenthesis. In this tiny lisp interpreter we are including only a small subset of all the keywords that is lisp.
       The code has been done in javascript to incorporate in html language for a better visual experience.

  1. 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. In a simple interpreter the internal representation is a tree structure that closely mirrors the nested structure of statements or expressions in the program. In a language translator called a compiler the internal representation is a sequence of instructions that can be directly executed by the computer.
  2. Execution: The internal representation is then processed according to the semantic rules of the language, thereby carrying out the computation. Execution is implemented with the function eval.

The program takes the prefix inputs and via parser function converts it into lists of lists. By this internal representation the execution function takes each list elements and evaluates each expression.The evaluation is done by eval function, for expression mapping is done by associate array to map each operate to its expressions.

lisp]=> (define square (lambda (r) (* r r)))
lisp]=> (square 12)
144
 For the interpreter when "define" interpreters then checks for the second string in the associate array for the presence of the function name, if not then the string is added and the rest of the expression is been mapped to the array.

Instead of associate array we have used environment class which is a subset of associate array inorder to incorporate find function to find the keys of the array.

Now for the function parse. Parsing is traditionally separated into two parts: lexical analysis, in which the input character string is broken up into a sequence of tokens, and syntactic analysis, in which the tokens are assembled into an internal representation.For this purpose we have used tokenize function.

          function tokenize(s)
         {  
               s=s.replace(/\(/g," ( ").replace(/\)/g," ) ").split(" ") 
               var p=[];  
                for(i in s)
               { 
                      if(s[i]!="")
                     { 
                            p.push(s[i]); 
                     } 
               }  
                    return p;
             }

To keep up a good interactive session we have used custom repl which would look for user inputs.

  process.stdin.resume();
   process.stdout.write('lisp]=> ');
  process.stdin.on('data',function(input){
  input = input.toString();
  var val = eval(parse(tokenize(input)))
  if (val != undefined)
  {
    process.stdout.write('Result:'+val);
  }
  else {process.stdout.write('lisp]=> ');

Click here for the whole code.