Sunday, 16 December 2012
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 - A
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.
At first we download and install the Google App Engine SDK in our system. Then 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.
here nithinconwaysgameoflife is the application id.
Third one is main.py ,the python file where we access our web application file.
http:// localhost:8080/
after enter the google_appengine folder in the system.
Type the following command on terminal
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
How To Use The App Engine To Host An Application
application: nithinconwaysgameoflife
version: 1
api_version: 1
runtime: python
handlers:
- url: /.*
script: main.py
version: 1
api_version: 1
runtime: python
handlers:
- url: /.*
script: main.py
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()
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
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
- Any live cell with fewer than two live neighbors dies, as if caused by under population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by overcrowding.
- 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)
Play the game
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:
- Create a leaf node for each symbol and add it to the priority queue.
- While there is more than one node in the queue:
- Remove the two nodes of highest priority (lowest probability) from the queue
- Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.
- Add the new node to the queue.
- 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:
- Start with as many leaves as there are symbols.
- 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).
- While there is more than one node in the queues:
- Dequeue the two nodes with the lowest weight by examining the fronts of both queues.
- 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.
- Enqueue the new node into the rear of the second queue.
- 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.
Monday, 12 November 2012
lazy evaluation and the Sieve of Eratosthenes in Scala
Lazy evaluation can be described as an expression that has a value, but that is not evaluated until it's actually needed. Some functional languages are described as Pure Lazy to reflect the fact that all evaluation is performed
on demand. Haskell is on such language. Scala has both aspects of strict
evaluation and lazy evaluation, as such it couldn't be referred to as
'pure' in either sense.
By means of the simplest example to illustrate Lazy
evaluation, consider the following interaction with the Scala :
scala> lazy val a = b + 1; lazy val b = 1; a: Int = <lazy> b: Int = <lazy> scala> a res9: Int = 2 scala> b res10: Int = 1
This illustrates lazy evaluation, without defining the 'vals' as lazy
the statement lazy val a = b + 1; lazy val b = 1; as val a = b + 1; val
b = 1; couldn't be evaluated because b would be undefined when
evaluating a!.
The examples are based on the Sieve of Eratosthenes. Eratosthenes was an ancient Greek Mathematician from 276 BC – c. 195 BC. The
Sieve of Eratosthenes is a ancient algorithm for finding prime numbers
from 2 .. n. Stated simply, this algorithm can be expressed as :
- Create a list of all the numbers from 2 .. n.
- Starting at p = 2
- Strike out all multiples of p up until n from the list
- Let p now be the first (lowest) number that has not been struck-off the list
- Repeat the last two steps until p^2 > n
- All remaining numbers not struck from the list are prime
The following Scala code shows the way to implement the Sieve using Scala Lazy streams.
object Primes1 { def primes : Stream[Int] = { var is = Stream from 2 def sieve(numbers: Stream[Int]): Stream[Int] = { Stream.cons( numbers.head, sieve(for (x <- numbers.tail if x % numbers.head > 0) yield x)) } sieve(is) } def main(args : Array[String]) = { primes take 100 foreach println } } object Primes2 { def primes = { def sieve(is: Stream[Int]): Stream[Int] = { val h = is.head Stream.cons(h, sieve(is filter (_ % h > 0))) } sieve(Stream.from(2)) } def main(args: Array[String]) { println(primes take 100 toList) } }
Scala - Pattern Matching
Pattern matching is the most widely used feature of Scala.Scala provides great support for pattern matching for processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches.An arrow symbol => separates the pattern from the expressions.
object Test {
def main(args: Array[String]) {
println(matchTest(3))
}
def matchTest(x: Int): String = x match
{
case 1 => "one"
case 2 => "two"
case _ => "many"
}
}
The block with the case statements defines a function which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. Following is an example which matches a value against patterns of different types:
object Test {
def main(args: Array[String]) {
println(matchTest("two"))
println(matchTest("test"))
println(matchTest(1))
}
def matchTest(x: Any): Any = x match {
case 1 => "one"
case "two" => 2
case y: Int => "scala.Int"
case _ => "many"
}
}
The first case matches if x refers to the integer value 1. The second case matches if x is equal to the string"two". The third case consists of a typed pattern; it matches against any integer and binds the selector value x to the variable y of type integer. Following is another form of writing same match...case expressions with the help of braces {...}:
object Test {
def main(args: Array[String]) {
println(matchTest("two"))
println(matchTest("test"))
println(matchTest(1))
}
def matchTest(x: Any){
x match {
case 1 => "one"
case "two" => 2
case y: Int => "scala.Int"
case _ => "many"
}
}
}
Sunday, 11 November 2012
Memory management in Android
Android devices are usually battery-powered and it is designed to manage memory (RAM) to keep power consumption at a minimum.When an Android application is no longer in use, the system will automatically
suspend it in memory - while the application is still technically "open,"
suspended applications consume no resources (e.g. battery power or processing
power) and sit idly in the background until needed again.
This has the dual benefit of increasing the general responsiveness of
the device, since applications don't need to be closed and reopened from scratch
each time, but also ensuring background applications don't waste power
needlessly.
Android manages the applications stored in memory automatically: when memory is low, the system will begin killing applications and processes that have been inactive for a while, in reverse order since they were last used.. This process is designed to be invisible to the user, such that users do not need to manage memory or the killing of applications themselves.
Confusion over Android memory management has resulted in third-party task killers becoming popular on the Google play store, where users mistakenly believe that they are required to manage applications and RAM themselves, similar to on a desktop operating system such as Windows.Third-party Android task killers are generally regarded as doing more harm than good.
Tuesday, 6 November 2012
Emergency Medical Support System in Android
Emergency Medical Support System is a system to manage emergency health problems and critical conditions of patients.This medical application in Android phones is a very useful and life saving utility.This system stores the medical conditions of the user and the contacts of the doctors and hospitals he had. The system provides single touch access to contact the persons and organisations,It provides Medical data and contacts for first responders and hospital staff to use in case of an emergency.The online website is used for store the database.The GPS service is used for locate the place and based on this location the list of nearest hospitals is retrieve from the online data base.EMSS provides the facilities given below
- A list of people to call during emergency
- Insurance information store and retrieve immediately
- Doctor's name,number,etc are store and call during emergency
- Medical conditions store and retrieve immediately
- Any special instructions for first responder
- Details of nearby hospitals can be accessed by GPS
- Call to the nearby hospitals
- Ambulance calling
- Sms service
Any special instructions or other information you wish to provide can be given.The use of gps service enhances the scope of this system.The system is implemented in java language along with tools like eclipse and android sdk.
Scala - Exception Handling
Scala's exceptions works like exceptions in many other languages like Java. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn't actually have checked exceptions.
To handle exceptions use a try{...}catch{...} block like in Java except that the catch block uses matching to identify and handle the exceptions.
Throwing exceptions:
Throwing an exception looks the same as in Java.create an exception object and then throw it with the throw keyword:
throw new IllegalArgumentException
Catching exceptions:
Scala allows to try/catch any exception in a single block and then perform pattern matching against it using case blocks as shown below:
import java.io.FileReader
import
java.io.FileNotFoundException
import java.io.IOException
object Test {
def main(args: Array[String]) {
try {
val f = new
FileReader("input.txt")
} catch {
case ex: FileNotFoundException
=>>{
println("Missing file
exception")
}
case ex: IOException => {
println("IO
Exception")
}
}
}
}
The behavior of this try-catch expression is the same as in other languages with exceptions. The body is executed, and if it throws an exception, each catch clause is tried in turn
Subscribe to:
Posts (Atom)