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.