Thursday, April 4, 2013

Apache ant Build files


Apache ant Build files

 Introduction
Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks.

How install Apache Ant (on windows)


The Apache Ant distribution package can be downloading as a zip file from the Apache site and extract it to the location that Ant should install. Then, add the environment variables to the system as follow.

ANT_HOME=path to ant extracted folder
PATH=path to ant folder/bin



Open command prompt and type “ant” will give the result shown below. If this result will receive, then the installation is success.

Buildfile: build.xml does not exist!
Build failed


How work with Ant


In order to execute a build process with Ant, need a build script called “build.xml”. The build script is used to define where the library files are located, where the source code are located, how to compile, make directory , delete directory, make jar file, run jar files, run batch files and many more. In order to do this, it is required to know the basic commands in the Apache Ant. Following example shows the sample build script that compile a simple HelloWorld.java file and  run it.

<?xml version="1.0"?>
<project name="HelloWorld" default="run" basedir=".">
                <property name="src" location="src" />
                <property name="bin" location="bin" />
                <property name="build" location="build" />
                <target name="clean">
                                <delete dir="${bin}" />
                                <delete dir="${build}"/>
                </target>
                <target name="compile" depends="clean" >
<mkdir dir="${bin}" />
                                <javac destdir="${bin}" srcdir="${src}" debug="true"></javac>
                </target>
                <target name="jar" depends="compile">
                                <mkdir dir="${build}"/>
                                <mkdir dir="${build}/jar"/>
                                 <jar destfile="${build}/jar/HelloWorld.jar" basedir="${bin}">
                                                 <manifest>
                                                                <attribute name="Main-Class" value="HelloWorld"/>
                                                </manifest>
                                </jar>
                   </target>
<target name="run">
                                 <java jar="${build}/jar/HelloWorld.jar" fork="true"/>
                </target>
</project> 


 The steps of the build process (methods) can be defined inside the tag “target”. It is possible to give a name for each target and dependency. The dependency means, before run that target the dependent target will be run by the Ant. For an example, if execute compile target, since it depends on the clean target, the clean target will run first. Inside the “property” tag, the source directory, bin directory and other required paths with a logical name can be defined. The name of the project can be defined inside the “project” tag and also the default method that run, if required method does not specify when run the build script. The basedir is defined, from where the relative path should consider. For an example, the folder structure of the “HelloWorld” is as below.

 
                      Folder structure of the “HelloWorld” project

When executing clean target, if there is a directory called “bin” or “build”, that directory will be delete. When executing compile target, a directory will be created called “bin” and java file that inside the “src” folder, will be compiled and class files will be copied in to the bin folder. When executing “jar” target, a directory will be created called “build” and another directory will be created inside that called “jar”. Then the jar file will be created and the main class attribute will be added to the Manifest file of the jar. When executing “jar” target, the jar file will be run and print the result “Hello World”.

String Templates


StringTemplate is a template engine library used for generating text from data structures. StringTemplate's distinguishing characteristic is that it strictly enforces model-view separation unlike other comparable template engines. It is particularly good at multi-targeted code generators, multiple site skins, and internationalization/localization. It is also developed for multiple languages, such as Java, C#, Python. Following code show the steps of a simple “Hello World” printing using StringTemplates.

import org.antlr.stringtemplate.*;

StringTemplate hello = new StringTemplate("Hello, $name$");
hello.setAttribute("name", "World");
System.out.println(hello.toString());

Friday, March 29, 2013

disable cache on html5 application

I have developed an android application which continuously get update from a server through AJAX call and there is a PHP file on the server which respond to the AJAX request. My application working properly in localhost. But after i install the application on my android phone, First two or three updates are successfully happens and then after it gives me the historical value( not update).

The problem is the cache. Application hold values on cache and give the cache data when request through AJAX.

I fixed this problem by simply added few codes on the top of my server side PHP file fro disabling the cache. Below is the code.


header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

Wednesday, March 27, 2013

XmlHTTPRequest: “XML Parsing Error: no element found”

I have an html5 application which get details from database through javascript. It is working properly on localhost. But after i move the database to hosting place i get the error XmlHTTPRequest: “XML Parsing Error: no element found”.

This error come because of same origin policy. That mean in my case, database in one host and my application in an another host.

I fix this issue by following steps.(i call database hosting is hostA and my application hosting hostB)

* I have php file on hostA. I add below code to the top of the file.
header('Access-Control-Allow-Origin: *');


Wednesday, February 13, 2013

Reorder/Reset auto increment primary key?


Following query can be used for reorder auto increment of a table.In this example reorder the id column of users table. If there are foreign key, make sure the action is cascade.

SET @count = 0;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;

Tuesday, February 12, 2013

locks in python thread

When doing multi threading program in any language, it is a big problem when having shared variables or some shared objects. In this kind of situation, it is required to lock some variables until finish the some process of one thread. In order to do this we can use locks. In python there is a library for import in order to do this.

ex:

from threading import  Lock

......
....

#initialize lock
lock=Lock()

.....

#when needed to add lock
lock.acquire()
#do the stuff
#remove lock
lock.release()

copy object to another object using python

it is really easy to copy object with all attributes to another object in python. All you need to import copy library.

ex:

import copy

class Test:
       def __init__(self,name):
              self.name=name

def main():
       a=Test('madura')
       b=copy.deepcopy(a)

This will copy Test class object a, to Test class object b with the attribute values

Monday, February 11, 2013

Thursday, January 17, 2013

generate number of random numbers that have not repeat in a given range in python


random.sample(range(1, 16), 3)
[11, 10, 2]

get element, sublist and length of a list using python


d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


>>> d[9]
9


>>> d[-1]
9


>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]


>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]


>>> len(d)
10

Matrix in python

There are no inbuilt function for define matrix. You can define the matrix as a list of list as follow


table= [ [ 0 for i in range(6) ] for j in range(6) ]
print table


result

[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

make a list of class objects


class Person(object):
    """__init__() functions as the class constructor"""
    def __init__(self, name=None, job=None, quote=None):
        self.name = name
        self.job = job
        self.quote = quote
       
print
# make a list of class Person(s)
personList = []
personList.append(Person("Payne N. Diaz", "coach", "Without exception, there is no rule!"))
personList.append(Person("Mia Serts", "bicyclist", "If the world didn't suck, we'd all fall off!"))
personList.append(Person("Don B. Sanosi", "teacher", "Work real hard while you wait and good things will come to you!"))
personList.append(Person("Hugh Jorgan", "organist", "Age is a very high price to pay for maturity."))
personList.append(Person("Herasmus B. Dragon", "dentist", "Enough people can't find work in America!"))
personList.append(Person("Adolph Koors", "master-brewer", "Wish you were beer!"))
personList.append(Person("Zucker Zahn", "dentist", "If you drink from the fountain of knowledge, quench your thirst slowly."))



print "Show one particular item:"
print personList[0].name
print
print "Sort the personList in place by job ..."
import operator
personList.sort(key=operator.attrgetter('job'))
print "... then show all quotes and who said so:"
for person in personList:
    print "\"%s\"  %s (%s)" % (person.quote, person.name, person.job)
   
print
print "Show the quote(s) from any dentist:"
look = 'dentist'
for person in personList:
    if look in person.job:
        # title() capitalizes the job's first letter
        print "%s %s: \"%s\"" % (person.job.title(), person.name, person.quote)
       
print
print "What the heck did the person named Sanosi say?"
look = "Sanosi"
for person in personList:
    if look in person.name:
        print "%s: \"%s\"" % (person.name, person.quote)

for loops in python


for num in range(10,20):  #to iterate between 10 to 20
   for i in range(2,num): #to iterate on the factors of the number
      if num%i == 0:      #to determine the first factor
         j=num/i          #to calculate the second factor
         print '%d equals %d * %d' % (num,i,j)
         break #to move to the next number, the #first FOR
   else:                  # else part of the loop
      print num, 'is a prime number'