Monday, 21 January 2013

A Simple GPS Android Application


Here is the simple gps application to provide the current location coordinate by just a simple toasy .The app also notifies the gps is on or off when the application searches for the coordinates. This application has one java activity which includes all the classes and modules for this application.

Application inlcudes:
  • location manager: This class provides access to the system location services. These services allow applications to obtain periodic updates of the device's geographical location.
    Includes
        getLastKnownLocation(String provider)
Returns a Location indicating the data from the last known location fix obtained from the given provider.
        requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent intent)
Register for location updates using a Criteria and pending intent.
GPS_PROVIDER feature find the location using satellite. This feature requires uses permission ACCESS_FINE_LOCATION.
  • Location Listener: Used for receiving notifications from the LocationManager when the location has changed.

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Gps extends Activity {

private static final long UPDATES = 1;
private static final long TIME_FOR_UPDATE = 1000;

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);

retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
UPDATES,
TIME_FOR_UPDATES,
new MyLocationListener()
);

retrieveLocationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showCurrentLocation();
}
});

}

protected void showCurrentLocation() {

Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(Gps.this, message,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Gps.this,"Signal is unclear",Toast.LENGTH_LONG).show();
}

}

private class MyLocationListener implements LocationListener {

public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(Gps.this, message, Toast.LENGTH_LONG).show();
}

public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(Gps.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}

public void onProviderDisabled(String s) {
Toast.makeText(Gps.this,
"......Gps is disabled.....\n Please Enable",
Toast.LENGTH_LONG).show();
}

public void onProviderEnabled(String s) {
Toast.makeText(Gps.this,"......Gps is enabled.....",
Toast.LENGTH_LONG).show();
}

}

}
 onProviderEnabled is called when gps is enabled

 onProviderDisable is called when gps is disabled

When button pressed the desired message appeared


Python Flask Using Sqlite

-->
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage.
Sqlite can be used by first creating a connection object that represents the database. The connection can be obtained using “connect” keyword as follows.
Import sqlite3
db=sqlite3.connect(“data.db”)
all the datas will be stored in .db file in the directory where the python script in located and the db file will contain the details as given in query which is specified as follows.
def init_db():
     db=sqlite3.connect('image.db')
     db.cursor().executescript("""drop table if exists entries;
     create table entries(
     filename string not null,
     imagedata string not null);""")
     db.commit()
after creating a connection object we have to create the cursor object to call the execute script command to create the table as specified in the query.
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
we can use “?” placeholder to provide values in python variable to execute script. The reason for using
 “?” in order to avoid the program vulnerable the SQL injection attack.To retrieve data after executing a 
SELECT statement, you can either treat the cursor as an iterator, call  the cursor’s call fetchall() to get a list of the matching rows. 
 for row in cur.fetchall():     print row[index]
cursor may be a pointer to a row or a list of rows which depends upon the script that is
 provided to execute. 

 Flask....

We use route() decorator to tell Flask what URL should trigger our function. The function is
 given a name which is also used to generate URLs for that particular function, and returns
 the message we want to display in the user’s browser.
@app.route("/h/",methods=['POST'])
The code explains the function to execute for the url “/h/” for the method “POST” form the javascript file that runs on browser. The values that are been passed for the post request  parameter can be accessed simply
 by  
 request.form['POST PARAMETER'] 
 These values can be stored into database by
fname=request.form['f'] imagedata=request.form['parameter'] imagedata=pickle.dumps(imagedata) db=sqlite3.connect('image.db') db.cursor().execute('insert into entries (filename,imagedata) values (?,?)',  [fname,imagedata]) db.commit() 
'f' and 'parameter' are the request parameters. The pickle is used to convert the data to an equal string representation to store into database and later can be fetched back using pickle.loads(). Commit funtion is called to save the changes that have made to the database.
  if __name__=="__main__": init_db() app.debug=True app.run()
the init_db function that defined earlier is been called when the program starts to execute.This is done because to setup database before the database operation is executed. If it is not done then the browser will give operational error “not found table named ”....” ”.

Software as a Service


-->
How hardware industry differs from software industry?

Hardware industries are been established for centuries and they are the major assets of the country. After software industries have been established software and hardware integrated projects have been in peek for the growth of technological and social well being. After both sectors grown well all eyes goes to the difference imposed by both sectors and question arises what drives an industry. This post is meant for explanation regarding software but it doesnt mean that sofware is more important.

Hardware
  • Harware designs are to be finished before manufacture otherwise it would lead to a great disaster wasting all the resources and if finds default then whole harware has to be replaced. Also the quality of the hardware diminishes with time and the cost of upgrade seems to be infinitely.
Software
  • Software evolves over time to integrate new functionalities and new features.When there is a bug then the new version can be released,it only matters for few line of code to be replaced.

There are two kinds of softwares

Legacy software are those which satisfies users needs but difficult to evolve due to design inelegance or antiquated technology.Currently, 60% of s/w maintenance cost is used for adding new functionality to the legacy s/w and only 17% for bug fixing.

Beautiful software meets customer needs and are easy to evolve.

There are different approaches for s/w development.
First one is Waterfall model. The levels in waterfall model are:
  1. Requirement specification
  2. Design
  3. Construction(implementation or coding)
  4. Integration
  5. Testing and debugging
  6. Installation
  7. Maintenance
The main drawback of this model is that, when the customer is unclear or less specific about the requirements, the developed model mail fail to meet the goals.
The second one is Spiral model. In this model, a prototype is built in every phase discussed above and then developed in each phase.
  1. Determine the objectives, alternatives, and constraints on the new iteration.
  2. Evaluate alternatives and identify and resolve risk issues.
  3. Develop and verify the product for this iteration.
  4. Plan the next iteration.
This also helps in back tracking, reversing or revising the process.


The third is Agile model. The key features of this model are:
  • Embraces change as a fact of life: continuous improvement vs. phases.
  • Developers continuously refine working but incomplete prototype until customers happy, with customer feedback on each iteration (every ~2 weeks).
  • Agile emphasizes Test-Driven Development (TDD) to reduce mistakes, written down User Stories to validate customer requirements, Velocity to measure progress.

Testing and Formal methods

Testing cannot be exhausting. Testing has many levels:
  • The base thing is called unit testing. That's testing to see if a single method does what's expected.
  • The next level is module or functional testing to test across individual units, like with across classes versus within a class.
  • Integration testing is to try and see if a bunch of modules communicate correctly. It's a more narrow interface., and each time when we add one of these things, we're assuming the one below does that work.
  • Finally, at the top is system or acceptance testing, tests weather the whole program meet what the customer wants it to do.
Types of Testing:
  1. Coverage testing specifies the percentage of code paths that have been tested.
  2. Regression testing is used to automatically rerun old tests to ensure that the current version still works at least as well as it used to.
  3. Continuous integration testing, which means the entire program is tested every time new code is checked in, versus later phases.


Software as a Service (SaaS)

Software as a Service (SaaS) delivers software and data as a service over the Internet, usually via a thin program such as a browser that runs on local client devices instead of binary code that must be installed and runs wholly on that device. Eg: searching, social networking, and videos.

Service oriented Architecture(SOA)

SOA defines how to integrate widely disparate applications for a Web-based environment and uses multiple implementation platforms. Rather than defining an API, SOA defines the interface in terms of protocols and functionality. An endpoint is the entry point for such a SOA implementation. SaaS is a special case of a software architecture where all components are designed to be services. SOA actually means that components of an application act as interoperable services, and can be used independently and recombined in other applications.The contrasting implementation is considered a 'software silo', which rarely has APIs to internal components.
SaaS has 3 demands on infrastructure,
  • Communication- Allow customers to interact with the services.
  • Scalability- Fluctuations in demand during new services to add users rapidly.
  • Dependability- Service and communication available at any time.
The critical distinction of SOA is that no service can name or access another service’s data; it can only make requests for data through an external API.
Collections of commodity small-scale computers connected by commodity Ethernet switches- clusters, offeres scalable and much cheaper serving.The public cloud services or utility computing offers computing, storage, and communication at pennies per hour.

In order to efficiently use a SOA, the architecture must meet the following requirements:
  • Interoperability among different systems and programming languages that provides the basis for integration between applications on different platforms through a communication protocol. One example of such communication depends on the concept of messages.
  • Desire to create a federation of resources. Establish and maintain data flow to a federated database system. This allows new functionality developed to reference a common business format for each data element.



Cloud Computing
Cloud computing is the use of computing resources (hardware and software) that are delivered as a service over a network (typically the Internet).Cloud Computing provides the scalable and dependable hardware computation and storage for SaaS. Cloud computing consists of clusters of commodity servers that are connected by local area network switches, with a software layer providing sufficient redundancy to make this cost-effective hardware dependable.


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.....!!!!!!!!!!!!