Monday, January 23, 2012

Using GET and POST methods in J2ME

Most of the mobile applications are not alone. They frequently communicate with web services or web applications to accomplish their tasks. Lets see how to make GET and POST requests to a server.
We can use HttpConnection class to make requests.
Lets see what are the basic steps.

Saturday, January 21, 2012

Python Note 8 (Python Utilities)

Summary
filenames = os.listdir(dir) -- list of filenames in that directory path (not including . and ..). The filenames are just the names in the directory, not their absolute paths.
import os

dir="c:/"
files=os.listdir(dir)
for path in files:
    print(path)
                 
Output :
addins
AppCompat
AppPatch
assembly
avastSS.scr
bfsvc.exe


Python Note 7 (the pickle module)

In python we can use serialization functionality using pickle module. it can save live instances of objects to files and retrieve object instances from pickled files.
Code:
import pickle

class Transaction : 
 def __init__(self,userName,trnsID,payment):
  self.userName=userName
  self.trnsID=trnsID
  self.payment=payment
 
 def __del__(self):
  print("Destructed!")
 
 def getPaymentValue(self):
  return self.payment
 
 def getUserName(self) :
  return self.userName
#end of the class

#persisting an object
hndl=open("transactionpickl.dat","wb") #'wb' means writing bytes
t1=Transaction("Kanishka",1232333,22480.75)
pickle.dump(t1,hndl)
print("Objet pickled successfully!")
hndl.close()

#retrieving an object
hndl=open("transactionpickl.dat","rb") ##'wb' means reading bytes
trObj=pickle.load(hndl)
print("__________________________")
print("Data from pickled object!")
print("User Name : {} ".format(trObj.userName))
print("Transaction ID : {} ".format(trObj.trnsID))
print("Payment Name : {} ".format(trObj.payment))
hndl.close()
Note : Remember that we have to use "wb" and "rb" as file modes of the file handler. because pickler use byte reading and byte writing operations to "pickle" and given object to the file system. so we can't use default "String" read and write modes.
Output:
C:\Users\Kanishka\Desktop>python pickletest.py
Objet pickled successfully!
__________________________
Data from pickled object!
User Name : Kanishka
Transaction ID : 1232333
Payment Name : 22480.75
Destructed!
Destructed!

C:\Users\Kanishka\Desktop>

Python Summary

Python Note 6(Classes and Objects)

Sample Code  : General class
#define a class
class User :
 def __init__(self,name,user_id,acc_balance):
  self.Name=name
  self.User_id=user_id
  self.Acc_Balance=acc_balance
  
 def recharge(self,amount):
  self.Acc_Balance+=amount
 
 def withdraw(self,amount):
  if amount <= self.Acc_Balance :
   self.Acc_Balance-=amount
  else :
   pass #do nothing
 
 def getBalance(self): #parameter less method
  return self.Acc_Balance
  
 def __del__(self) :
  print("Destructor started!")
#end of the class
 
usr=User("Kanishka",1133,27000.00)
print("User {0} , Balance {1:5.2f}".format(usr.Name,usr.getBalance()))
usr.withdraw(2000.50) #withdrwaw money
print("User {0} , Balance {1:5.2f}".format(usr.Name,usr.getBalance()))

Friday, January 20, 2012

Python Note 5 (File Handling)

File handling is very easy in python, Lets see an example
datafile=open("myfile.dat","w") #open a file for writing
datafile.write("Sri Lanka,India,Pakistan,Bhutan,Australlia,Canada") #write data
datafile.write("\n")
datafile.write("Apple,Orange,Mango")
datafile.close() #release the file

#reading from the file
datafile=open("myfile.dat","r") #open file for reading
record=datafile.readline()#reding a line (here it is the first line)
mylist=record.strip("\n").split(",") #remove newline character and split the string by comma
print(mylist)
print(len(mylist))

Python Note 4( String Formatting)

Code
import math 

for x in range(1,20) :
 print ("{0:2d} {1:3d} {2:5d}".format(x,x*2,x*3))
 
tmplate="My {} is {}"
print(tmplate.format("country","Sri Lanka"))
print(tmplate.format("name","Kanishka"))

tmplate="Hello {name} , your role is {role}"
print(tmplate.format(name="Kanishka",role="Admin"))
print(tmplate.format(name="Sampath",role="User"))

print("The value of 'PI' is approximately {0:0.3f}".format(math.pi))
print("The value of 'e' is approximately {0:0.5f}".format(math.e))

#old formatting
print('The value of PI is approximately %5.3f' % math.pi)
Result

Wednesday, January 18, 2012

Python Note 3 (Functions)

We can define number of functions in same python script.
Code
#function1
def cube(x) :
 return x**3

#function2
def maxVal(x,y) :
 if x > y :
  return x
 else :
  return y

print (cube(3))
print (maxVal(12,22))


Lets see how to import functions in another python script.
There are 2 importing methods
  1. import a single function
  2. import all functions under a "namespace"(python script)
  • import a single function
assume we have implemented a function called factorial() in a python script named as mylib.py .
from mylib import factorial
print (factorial(4))

So we can call function directly.

Other way
import mylib
print (mylib.factorial(4))

In this method there may be some anomalies if we are going to import 2 functions with same name and signature in different scripts.

Python Note 2 (String manipulations)

Code
mystr="Sri Lanka"
print( len(mystr) )
print( mystr.upper() )
print( mystr.lower() )
print( mystr[1])
print( mystr[-1])

mylist = [10, "Ajith", 67.3, 78.2]
print(mylist)
print( mylist[0] )
print( mylist[3] )
print( mylist[-1] )
print( mylist[-2] )

sublist=mylist[1:3]
print (sublist)
sublist=mylist[1:]
print (sublist)
print(sublist)
mylist.append("Java")
mylist.append(1988)
print(mylist)
#otherlist=[2,5,1,5,6]
otherlist=["Pineapple","Apple","Mango","Banana","Acorn Squash","Coconut","Apricot"]
print(otherlist)
otherlist.reverse()
print(otherlist)
otherlist.sort()
print(otherlist)
Result

Python Note 1

Python is an interpreted language. Nesting is done using indentation. I have used Python 3.2.2 in this note.


Sample python program demonstrating Python operators.

x=10
y=12
print(x+y)
print(x-y)
print(y/x)
print(y//x)
print(x*y)
print(y%x)
print(x**y)
print(-x)
Result
Sample python program demonstrating input capabilities and string concatenation in python.

numInt=int(input("Enter an integer : "))
numFloat=float(input("Enter a float :"))
strName=input("Enter a String : ")
numTot=numInt+numFloat
print("Hello " + strName + " Total is " + str(numTot))
Result
• Write a python program to input a length in mm and convert it to inches.
• 25.4 mm = 1 inch

lenmm=float(input("Enter length in mm : "))
leninch=(1/25.4)*lenmm
print("Length in inches : " + str(leninch));
• Write a python program to input a temperature in Celcius and convert it to Fahrenheit.
• fahrenheit = 9/5* celcius +32

tempinCelc=float(input("Enter temperature in celcious : "))
tempinFer=(9/5)*tempinCelc + 32
print("Temp in Fahrenheit : " + str(tempinFer))
• Write a program to input a mark and display Pass if it is greater than or equal to 50.
Otherwise display Fail.

marks=int(input("Enter your marks : "))
if marks >= 50  :
 print("Pass!")
else:
 print("Fail!")
• Write a program to input a number. Display if it is an even or an odd number.
number=int(input("Enter a number : "))
if number%2 == 0 : 
 print("Even number")
else:
 print("Odd number")

• Write a program to input the marks of a
student and calculate the grades.
• > 75 – A
• 65 to 75 – B
• 55 to 64 – C
• 45 to 54 – S
• < 45 - W
#this is not an efficient way to calculate grade
#this is only for demonstrating if,elif,else statements
marks=int(input("Enter your marks : "));
if marks&gt;75 and marks &lt;=100 :
 grade="A"
elif marks &gt;= 65 and marks &lt;= 75 :
 grade="B"
elif marks &gt;= 55 and marks &lt; 65 :
 grade="C"
elif marks &gt;= 45 and marks &lt; 55 :
 grade="S"
elif marks &lt; 45 and marks &gt;= 0 :
 grade="W"
else :
 grade="Invalid Marks"

print("Your Grade is : " + grade)
Note : Above code is intended to demonstrate conditions, if, elsif statements.

• Write a python program to implement following  algorithm

number=int(input("Enter a number : " ));
if number > 0 :
 if number%3==0 :
  print("The number is positive and divisable by 3")
else :
 print("The number is zero or negative")
  • While Condition
• Write a program to Print numbers 1 to 9

num=1
while num < 10 :
 print(num)
 num+=1
print("Loop ended!");

• Write a program to Print numbers
1,3,5,7,9
i=0
while i<10 :
 if i%2==1:
  print(i)
 i+=1
• Write a program to print the tables of 7
num=1
while num <14 : 
 print ("7 x " + str(num) +" = " + str(7*num) )
 num+=1
  • range() command
range() command generates a list. list is a data structure very similar to an array. By the way list can contain data of different types.
range(1,10) produces the list
[1,2,3,4,5,6,7,8,9]
for loop can be used to iterate within a list

numlist=range(1,10)
for val in numlist :
 print(val)
numlist=range(1,10,2)
for val in numlist :
 print(val)
  • Defining a list explicitly
mylist=["Java","PHP",1133,"Python",2.33]
for val in mylist :
 print(val)
it works same for strings.
mylist="Sri Lanka"
for val in mylist :
 print(val)

Monday, January 16, 2012

J2ME with LWUIT (UI Toolkit Widgets) part 3

In this note, I would like to note down how to create a Ticker, Calendar
Any label can be configured as a Ticker.
  • Ticker
            Image ico = Image.createImage("/img/arrow.png");
            Label lblTicker = new Label("Hello! This is a Ticker!");
            lblTicker.setIcon(ico);

            Form frm=new Form();
            frm.addComponent(lblTicker);
            frm.show();
                    
            //finally
            lblTicker.startTicker(100, true);

J2ME with LWUIT (UI Toolkit Widgets) part 2

Lets see how to use Tabbed pane, ComboBox TextArea, TextField

  • TabbedPane
I am going to use Containers with TabbedPanes because it provides an easy way to organize widgets

Sunday, January 15, 2012

J2ME with LWUIT (UI Toolkit Widgets) part 1

There are very important UI widgets available in LWUIT lets demonstrate them.

J2ME with LWUIT (Commands)

Definitely we may need to use commands because users must have a simple way to command our app. Though we can use buttons to get user commands, it may not be the best options. By using commands we can easily place the frequently used commands in our app.

J2ME with LWUIT (Initializing)

LWUIT is a SWING like lightweight widget library for J2ME. It is very useful for software development with J2ME. I could find a very useful guide for LWUIT. It is available here.

LWUIT class hierarchy is useful when we use LWUIT wifgets.

Friday, January 6, 2012

Queries in HIBERNATE

Querying is one of most important part in Hibernate. For this purpose we have to use HQL (Hibernate Query Language). HQL is simpler than SQL and bit differ from SQL. Here in HQL we consider on Classes instead of Tables and we consider on Attributes instead of Columns.
Lets see how to querying from Hibernate.
For this example I have used a College , Student relation which is a one to many association.
College.java
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class College {

 private int collegeId;
 private String collegeName;
 private List<Student> students;
 
 @Id
 @GeneratedValue
 public int getCollegeId() {
  return collegeId;
 }
 
 public void setCollegeId(int collegeId) {
  this.collegeId = collegeId;
 }
 
 public String getCollegeName() {
  return collegeName;
 }
 
 public void setCollegeName(String collegeName) {
  this.collegeName = collegeName;
 }
 
 @OneToMany(targetEntity=Student.class,cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="college")
 public List<Student> getStudents() {
  return students;
 }
 
 public void setStudents(List<Student> students) {
  this.students = students;
 }
}
Student.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;


@Entity
public class Student {

 private int studentId;
 private String studName;
 private College college;
 
 @Id
 @GeneratedValue
 public int getStudentId() {
  return studentId;
 }
 
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 
 public String getStudName() {
  return studName;
 }
 
 public void setStudName(String studName) {
  this.studName = studName;
 }
 
 @ManyToOne
 @JoinColumn(name="college_id")
 public College getCollege() {
  return college;
 }
 
 public void setCollege(College college) {
  this.college = college;
 }
 
}
Test.java
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;


public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  AnnotationConfiguration config=new AnnotationConfiguration();
  config.addAnnotatedClass(College.class);
  config.addAnnotatedClass(Student.class);
  config.configure("hibernate.cfg.xml");
  
  //creating tables
//  new SchemaExport(config).create(true, true);
  
  //adding sample data
//  SessionFactory factory=config.buildSessionFactory();
//  Session session=factory.getCurrentSession();
//  
//  session.beginTransaction();
//  
//  College c1=new College();
//  c1.setCollegeName("Richmond College");
//  
//  College c2=new College();
//  c2.setCollegeName("Mahinda College");
//  
//  Student st1=new Student();
//  st1.setStudName("Kanishka Dilshan");
//  st1.setCollege(c1);
//  Student st2=new Student();
//  st2.setStudName("Sajith Athukorala");
//  st2.setCollege(c1);
//  Student st3=new Student();
//  st3.setStudName("Sampath Bandara");
//  st3.setCollege(c1);
//  
//  Student st4=new Student();
//  st4.setStudName("Dasun Pathirana");
//  st4.setCollege(c2);
//  Student st5=new Student();
//  st5.setStudName("Kasun Sameera");
//  st5.setCollege(c2);
//  
//  session.save(c1);
//  session.save(c2);
//  session.save(st1);
//  session.save(st2);
//  session.save(st3);
//  session.save(st4);
//  session.save(st5);
//  
//  session.getTransaction().commit();
  
  //query part
  
  SessionFactory factory=config.buildSessionFactory();
  Session session=factory.getCurrentSession();
  session.beginTransaction();
  
  Query query=session.createQuery("from Student s where s.studName like :name_p");
  query.setParameter("name_p", "%k%");
  List lst=query.list();
  printTheList(lst);
  
  session.getTransaction().commit();
  System.out.println("Size : " + lst.size());

 }
 
 private static void printTheList(List lst){
  Iterator itr=lst.iterator();
  while(itr.hasNext()){
   Student s=(Student) itr.next();
   System.out.println(s.getStudName());
  }
 }

}

Note :
The simplest way to execute a HQL query is
  • Start a transaction
  • Create a Query object using session.createQuery("HQL Query")
  • Set parameters if any
  • Retrieve the HQL result to a List object by executing list() method in the Query object
  • Now it is the time to play with the retrieved List object :)
Eg :
session.beginTransaction();
Query query=session.createQuery("from Student");
List listResults=query.list();
session.getTransaction().commit();
Note 2 :
:name_p is a parameter. in HQL colon(:) is used to denote the beginning of a parameter.

Result :

Thursday, January 5, 2012

Many to Many Mapping

Wednesday, January 4, 2012

One To Many Mapping

One to One Bi Directional mapping

One To One Mapping

Monday, January 2, 2012

Inheritance Mapping

Basically there are 3 types of inheritance mapping. We may use those methods suitably.
  • SINGLE_TABLE (default)
  • JOINED
  • TABLE_PER_CLASS
Model

Sunday, January 1, 2012

Compound Primary Keys in HIBERNATE

Most of the time we need only 1 primary key. But there are some situations we may need compound primary keys.
Here in hibernate it is simple. We can use 2 classes into 1 table strategy.
Account.java
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Account {

 private AccountCompoundKey compoundKey;
 private int accBalance;
 
 @Id
 public AccountCompoundKey getCompoundKey() {
  return compoundKey;
 }
 public void setCompoundKey(AccountCompoundKey compoundKey) {
  this.compoundKey = compoundKey;
 }
 public int getAccBalance() {
  return accBalance;
 }
 public void setAccBalance(int accBalance) {
  this.accBalance = accBalance;
 } 
}

 
© Copyright 2035 kani.stack.notez
Theme by Yusuf Fikri