Wednesday, September 27, 2006

Reinstalling grub from the Debian install DVD


Steps -
  • Boot from DVD and start install in expert mode
  • When partitioning stage is reached, press Ctrl+Alt+F2 to switch to the other console
  • Make a new dir to mount the boot partition, for example /disk
  • mount the root partition on /disk.
  • Do a chroot to the root partition: issuing chroot /disk
  • Run grub command to enter grub shell
  • Type in the root disk for grub - root (hd0,1). This is /dev/hda2 on my system
  • Type the following command to install grub on /dev/hda: setup (hd0).
  • Type quit, exit from chroot, unmount all disks and reboot.

Tuesday, September 26, 2006

Using a string with embedded quotes in PLSQL

Add one more single quote next to the one you want to escape.
SQL> select 'the sopranos'''
2 from dual
3 /

'THESOPRANOS'
-------------
the sopranos'

Or use Chr():
SELECT 'alan'||chr(39)||'s database' FROM Dual

PLSQL is Weird!

A PLSQL Problem with Two Solutions


Requirement:
I have a table with columns - A,B, and C where Primary Key is (B,C). I need a procedure that takes a group of B,C pairs and returns the corresponding group of A values.

Problem 1: How to input a group of (B,C) pairs?
Solution : Input a String with Syntax "A1~B1,A2~B2,A3~B3" etc.

Problem 2:
Solution a: (Tough but educational) :
Pseudoish SQL code follows -
TYPE bc_tab_type AS TABLE OF varchar2(100);
CREATE OR REPLACE PROCEDURE p(
bc IN varchar2,
a OUT sys_refcursor)
AS
var_bc_tab bc_tab_type := bc_tab_type();
-- Declare other vars
BEGIN
-- Parse the input comma seperated string
-- and put values in a PLSQL table type
var_bc := bc;
var_length := LENGTH(var_bc);
WHILE ( (var_length > 0))
LOOP
var_comma_position := INSTR(var_bc, ',');
IF var_comma_position > 0 THEN
var_tok := SUBSTR(var_bc,1,var_comma_position - 1);
var_bc := SUBSTR(var_bc, var_comma_position + 1, var_length - var_comma_position);
ELSE
var_tok := var_bc;
var_bc := '';
END IF;
var_bc_tab.extend;
var_bc_tab(var_bc_tab.Last) := var_tok;
var_length := LENGTH(var_bc);
END LOOP;

-- populate out cursor
OPEN a FOR
SELECT a FROM table
WHERE (b || '~' || c) IN (SELECT * FROM TABLE(CAST(var_bc_tab AS bc_tab_type)));
EXCEPTION
WHEN OTHERS THEN
IF a%ISOPEN THEN
CLOSE a;
END IF;
END p;
/


Solution b: (Easy and Unexpected!):
Pseudoish SQL Code Ahead -
-- BLAH BLAH
...
-- No need to parse string bc
...
query := 'SELECT a FROM table ';
query := query || 'WHERE (b || ''~'' || c) IN (';
query := query || bc || ')';

-- populate out cursor
OPEN a FOR query;
..
/

Whoa!!! Now this is just tooo surreal for me! I'd call it 'arbitrary fluidity' that we can use a string in place of a SQL QUERY in an OPEN CURSOR FOR statement! Though it saved me loads of head banging in this case, it just makes PLSQL seem all the more mysterious..

- AJ

Calling a plsql procedure with out parameter from sqlplus

Sample code follows -

SQL> var c refcursor
SQL> exec p ( tabstr_t('dual','all_objects'), :c)
SQL> print c

Thursday, September 21, 2006

Bypassing Infy firewall for downloading Sourceforge.net packages


Infy network firewall inexplicably blocks sf.net downloads. To overcome this one can download the files from http://www.files-library.com/. Just search for the package name at the main page.

Passing Arrays of Objects between Java and PLSQL

Recently I had to transfer a lot of tabular data to a PLSQL procedure from Java. The most obvious answer seemed to be to represent the data as an array of records. Searched on the net to find this example solution.

On the Java side, Records are plain java classes. On SQL side, the java objects are mapped to a corresponding SQL Object type. The whole thing is passed as an Array (Table in SQL).


CODE FOLLOWS -

create or replace and compile java source named Person as

import java.sql.*;
import java.io.*;

public class Person implements SQLData
{
private String sql_type = "PERSON_T";

public int person_id;
public String person_name;

public Person () {}

public String getSQLTypeName() throws SQLException { return sql_type; }

public void readSQL(SQLInput stream, String typeName) throws SQLException
{
sql_type = typeName;
person_id = stream.readInt();
person_name = stream.readString();
}

public void writeSQL(SQLOutput stream) throws SQLException
{
stream.writeInt (person_id);
stream.writeString (person_name);
}

}
CREATE TYPE person_t AS object
EXTERNAL NAME 'Person' LANGUAGE JAVA
USING SQLData (
person_id NUMBER(9) EXTERNAL NAME 'person_id',
person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
)

CREATE TYPE person_tab IS table OF person_t;

create or replace and compile java source named arraydemo as
import java.util.Date;
import java.io.*;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ArrayDemo
{

public static void passArray() throws SQLException
{
Connection conn = new OracleDriver().defaultConnection();

ArrayDemo a = new ArrayDemo();

Person pn1 = new Person();
pn1.person_id = 1;
pn1.person_name = "TestName1";

Person pn2 = new Person();
pn2.person_id = 2;
pn2.person_name = "TestName2";

Person pn3 = new Person();
pn3.person_id = 31;
pn3.person_name = "TestName3";

Person[] P_arr = {pn1, pn2, pn3};

ArrayDescriptor descriptor =
ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );

ARRAY array_to_pass =
new ARRAY( descriptor, conn, P_arr);

OraclePreparedStatement ps =
(OraclePreparedStatement)conn.prepareStatement
( "begin give_me_an_array(:x); end;" );

ps.setARRAY( 1, array_to_pass );
ps.execute();
}
}


create or replace
procedure give_me_an_array( p_array in person_tab )
as
begin
for i in 1 .. p_array.count
loop
dbms_output.put_line('Person Id:'|| p_array(i).person_id||' Name: '||p_array(i).person_name);
end loop;
end;

create or replace
procedure show_java_calling_plsql
as language java
name 'ArrayDemo.passArray()';


set serveroutput on

exec show_java_calling_plsql

Improving R2D3


My R2D3 Project was supposed to be a blender/python based General Purpose Robotic Development Environment. Sadly enough all it does at the present moment is the following -
  1. Simulate Forward/Inverse Kinematics and ACL Interpretation for a specific proprietary 5DOF Robotic Arm (Scorbot Er5, which was used in my college Robotics Lab).
  2. Look Pretty (and that's Blender's handywork, not mine).
The simulation, though working well, is somewhat limited in its capabilities -
  1. The ACL Interpreter acccepts only a subset of ACL commandset.
  2. The ACL Editor is vaporware.
  3. Dynamics is not supported.
Other planned subparts are not even functional -
  1. Controlling the actual robot via serial communication with an ACL Controller.
  2. Server for accepting commands over a network connection.
Also when I started the project I was just learning Blender and Python so the quality of code needs improvement.

Therefore I plan to do the following -
  1. Modularise R2D3.py into generic and robot specific functionalities.
  2. Add code to enable assembly of any kind of Robot.
  3. Complete the Server for accepting commands over a server.
I hope to see this project bundled with Blender someday :)

Sunday, September 17, 2006

The most promising *free* game idea I have seen yet..


http://www.planeshift.it/

A massive virtual role playing game with a persistantly online ever-alive fantasy world! Totally free as in speech!

KDE Hogs The Sound System

From the KDE Control Center > Sound and Multimedia > Sound System -

"KDE takes exclusive control over your sound hardware, blocking programs that may want to use it directly."

On my machine this causes many games to either block or crash or work without sound. Thankfully the solution is also provided in the control center -

"If KDE sound system sits idle, it can give up this exclusive control."

Here you can setup the time interval in seconds, amount of inactivity, after which KDE will stop hogging the sound system. I keep this setting at 1 sec and it works like a charm!

Thursday, September 14, 2006

Transparent Draggable GUI Blocks in Javascript


Trying to create a Transparent Block GUI for the News Display. This looks promising.

Blender Head Tutorial


Started modeling a head in Blender following this tutorial. Will post results soon.

Simple Neural Network Code in Python




Found the following public domain code for a simple neural network implementation in Python (The training data is mine) -




# Back-Propagation Neural Networks
#
# Written in Python. See http://www.python.org/
# Placed in the public domain.
# Neil Schemenauer

import math
import random
import string

random.seed(0)

# calculate a random number where: a <= rand < fill="0.0):" m =" []" ni =" ni" nh =" nh" no =" no" ai =" [1.0]*self.ni" ah =" [1.0]*self.nh" ao =" [1.0]*self.no" wi =" makeMatrix(self.ni," wo =" makeMatrix(self.nh," ci =" makeMatrix(self.ni," co =" makeMatrix(self.nh," sum =" 0.0" sum =" sum" sum =" 0.0" sum =" sum" output_deltas =" [0.0]" error =" targets[k]-self.ao[k]" hidden_deltas =" [0.0]" error =" 0.0" error =" error" change =" output_deltas[k]*self.ah[j]" change =" hidden_deltas[j]*self.ai[i]" error =" 0.0" error =" error">', self.update(p[0])

def weights(self):
print 'Input weights:'
for i in range(self.ni):
print self.wi[i]
print
print 'Output weights:'
for j in range(self.nh):
print self.wo[j]

def train(self, patterns, iterations=10000, N=0.5, M=0.1):
# N: learning rate
# M: momentum factor
for i in xrange(iterations):
error = 0.0
for p in patterns:
inputs = p[0]
targets = p[1]
self.update(inputs)
error = error + self.backPropagate(targets, N, M)
if i % 100 == 0:
print 'error %-14f' % error


def demo():
# Teach network
pat = [
[[0,0,0,1], [0]],
[[0,0,1,0], [0]],
[[0,1,0,0], [0]],
[[1,0,0,0], [0]],

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

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

[[1,1,1,1], [1]],
]

# create a network with two input, two hidden, and one output nodes
n = NN(4, 16, 1)
# train it with some patterns
n.train(pat)
# test it
n.test(pat)



if __name__ == '__main__':
demo()

Monday, September 11, 2006

Haskell based Genetic Programming


Note#1 : Researching Haskell based genetic programming today. Found a good resource in PolyGP.

Found source here using Google.

A Thesis by the same guy for GP and Functional Programming.

His Publications page has more Genetic Programming material.

Todo#1 : Add the sources link to the relevant Haskell wiki page.

Edit : To compile the sources, two changes needed to be made on my system -
  1. Convert import Trace to import Debug.Trace across all files.
  2. Edit file Main.hs as follows -
Remove import Random() from Main.hs and add the following code -
-- Use seeds s1 in 1..2147483562 and s2 in 1..2147483398 to generate
-- an infinite list of random Ints.
randomInts :: Int -> Int -> [Int]
randomInts s1 s2 =
if 1 <= s1 && s1 <= 2147483562 then
if 1 <= s2 && s2 <= 2147483398 then
rands s1 s2
else
error "randomInts: Bad second seed."
else
error "randomInts: Bad first seed."
where
rands :: Int -> Int -> [Int]
rands s1 s2 = z' : rands s1'' s2''
where
z' = if z < 1 then z + 2147483562 else z
z = s1'' - s2''

k = s1 `quot` 53668
s1' = 40014 * (s1 - k * 53668) - k * 12211
s1'' = if s1' < 0 then s1' + 2147483563 else s1'

k' = s2 `quot` 52774
s2' = 40692 * (s2 - k' * 52774) - k' * 3791
s2'' = if s2' < 0 then s2' + 2147483399 else s2'


-- Use seeds s1 in 1..2147483562 and s2 in 1..2147483398 to generate
-- an infinite list of random Doubles.
randomDoubles :: Int -> Int -> [Double]
randomDoubles s1 s2 = map (\x -> ((fromIntegral x)/(fromIntegral m))) (randomInts s1 s2)
where
m :: Int
m = maxBound

Sunday, September 10, 2006

Two minor things - KDE Ark and MTNL Network


Two minor things I want to remember -
  1. KDE Ark does not work with zip files on my system (Debian Sarge + KDE 3.3.2). It complains "zip utility was not found". The solution was to create a soft link to program "unzip" (from the unzip package) called "zip" in /usr/bin.
  2. ADSL net stops working if the ethernet connection is even momentarily disrupted (for example when I take out the ethernet wire and plug it back in). To restore the network, go to System>Networking and disable Ethernet connection and exit. Then restart Networking and enable Ethernet connection. Voila!

Syntax Versus Semantics

Starting a blog as a container for my notes.