Friday, December 9, 2011

How-To find the closest point of a MultiLineString from a Point in PostGIS

I had the same trouble before with MultiLineStrings, I realized that when a MultiLinestring can't be merged, all functions like ST_ClosestPoint and ST_Line_Locate_Point doesn't work.(you can know if a MultiLineString can't be merged using the ST_LineMerge function) I've made a pl/pgSQL function based in an old maillist but I added some performance tweaks, It only works with MultiLineStrings and LineStrings (but can be easily modified to work with Polygons). First it checks if the geometry only has 1 dimension, if it has, you can use the old ST_Line_Interpolate_Point and ST_Line_Locate_Point combination, if not, then you have to do the same for each LineString in the MultiLineString. Also I've added a ST_LineMerge for pre 1.5 compatibility :


CREATE OR REPLACE FUNCTION ST_MultiLine_Nearest_Point(amultiline geometry,apoint geometry)
  RETURNS geometry AS
$BODY$
DECLARE
    mindistance float8;
    adistance float8;
    nearestlinestring geometry;
    nearestpoint geometry;
    simplifiedline geometry;
    line geometry;
BEGIN
        simplifiedline:=ST_LineMerge(amultiline);
        IF ST_NumGeometries(simplifiedline) <= 1 THEN
            nearestpoint:=ST_Line_Interpolate_Point(simplifiedline, ST_Line_Locate_Point(simplifiedline,apoint) );
            RETURN nearestpoint;
      END IF;
--      *Change your mindistance according to your projection, it should be stupidly big*
        mindistance := 100000;
        FOR line IN SELECT (ST_Dump(simplifiedline)).geom as geom LOOP
                adistance:=ST_Distance(apoint,line);
            IF adistance < mindistance THEN
                mindistance:=adistance;
                nearestlinestring:=line;
            END IF;
        END LOOP;
        RETURN ST_Line_Interpolate_Point(nearestlinestring,ST_Line_Locate_Point(nearestlinestring,apoint));
    END;
    $BODY$
      LANGUAGE 'plpgsql' IMMUTABLE STRICT;

Wednesday, September 7, 2011

Java HMTL-like Imagemap

How many of you ever wanted to use an imagemap in Java (awt - swingx)?, well all you need to do is download the code from github and you need to make an image for each element of the imagemap and put the region or element in the place that you want it to appear, It's easier if you open the whole image in photoshop or gimp, and just start to create layers for each region, and save each layer in a different file, like this:



A tooltip shows you in which region the pointer is, you just need to add a click event listener to get the id of the region that was clicked:

Saturday, May 7, 2011

Why I don't like unity?

First of all, lets think why someone use linux, maybe most of us started being script kiddies, others in school had to use it in some courses, others in theirs work. But the ones that use it everyday, like it because its as cool or as practical as you want. For example I use default configurations of the desktop environment in my work's linuxes and for my personal machines I use a tweaked version with all the candy-eye you can get. For many of us, adopting gnome 3 was the natural evolution of ubuntu, but for Mark Shuttleworth it seems wrong. Instead he went for unity, actually unity its only Mark's favorite compiz configuration. Another issue is the unilateral changes he is making to the layout just to mention a few, Why they moved the window management icons to the left????
Lets take for example my configuration, its a 10.04 ubuntu with compiz and awn.





Only with a few extra tweaks it does everything gnome 3 and unity does. So??? we will have to wait a little to see how it ends.

Tuesday, July 20, 2010

sqlite4java + java (singleton) example

When I heard about sqlite4java, I didn't found any working example, so here is one:
First I've made a singleton object to connect to SQLite, but also I've made a few methods to make even more easier to use sqlite4java.



import com.almworks.sqlite4java.*;
import java.io.File;
import java.util.Stack;

public class SQLiteDB {
private static final SQLiteDB INSTANCE = new SQLiteDB();
SQLiteConnection db;
SQLiteStatement st;
// Private constructor prevents instantiation from other classes
private SQLiteDB() {
try{
db = new SQLiteConnection(new File("default.ndb"));
db.open(true);
} catch (SQLiteException ex){
System.out.println("Instantiation SQLiteException: " + ex.getMessage());
}
}
public static SQLiteDB getInstance() {
return INSTANCE;
}
public boolean exec(String str){
try{
st = db.prepare(str);
st.stepThrough();
st.dispose();
return true;
} catch (SQLiteException ex){
System.out.println("Query Execution SQLiteException: " + ex.getMessage());
return false;
}
}

public boolean prepareQuery(String str){
try{
st = db.prepare(str);
} catch (SQLiteException ex){
System.out.println("Prepare Query SQLiteException: " + ex.getMessage());
return false;
}
return true;
}

public Object[] fetch(){
try{
if(!st.step()){
st.dispose();
return null;
}
else{
if(st.hasRow()) {
int columns = st.columnCount();
Stack stack = new Stack();
for(int column = 0 ; column < columns ; column++)
stack.push(st.columnValue(column));
return stack.toArray();
} else {
st.dispose();
return null;
}
}
} catch (SQLiteException ex){
System.out.println("Fetch SQLiteException: " + ex.getMessage());
}
st.dispose();
return null;
}
public void close(){
db.dispose();
}
}

Then the test class:



public class SQLiteTest {


public static void main(String[] args) {

SQLiteDB db = SQLiteDB.getInstance();


db.exec("CREATE TABLE t1 (t1key INTEGER PRIMARY KEY,data TEXT,num double,timeEnter DATE);");
db.exec("INSERT INTO t1 VALUES(1, 'This is sample data', 3, NULL);");
db.exec("INSERT INTO t1 VALUES(2, 'More sample data', 6, NULL);");
db.exec("INSERT INTO t1 VALUES(3, 'And a little more', 9, NULL);");

Object[] res;
db.prepareQuery("select * from t1");

while((res=db.fetch()) != null){
System.out.println("Results: " + res[0] + " : " + res[1] + " : " + res[2] + " : " + res[3]);
}

db.close();

}
}

Thursday, November 19, 2009

Connect Java with Mysql

If you have problems with CLASSPATH java.lang.ClassNotFoundException: com.mysql.jdbc.Driver, this might work:

1.-
install the java - mysql connector:
sudo apt-get install libmysql-java

2.-
gedit ~/.bashrc

3.-
add this 2 lines at the end:

CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java.jar
export CLASSPATH

thats it!

Friday, January 23, 2009

Compile gtk+ apps on Windows

If you've already googled this, you must know that you need MinGW and MSYS.

Here is an installer of MSYS 1.0.10
Install it with default settings.... (path: c:/msys/1.0)



They say you can find the lastest version of MSYS here:(I didn't find the .exe(Installer) of newest version)
http://sourceforge.net/project/showfiles.php?group_id=2435



Now install : MinGW

A better Howto of installing MSYS and MinGW (Actually the original) can be found here

After MSYS and MinGW are installed you need to install GTK+ development files and some other tools like pkg-config...
Now things are going to get messy. I don't know how to do this in another way but this works....

An installer of gtk+ dev files can be found here ( Last stable version....)
Default path of installation is c:/Program Files/Common or some windowsish path ....
Install it in the same path you installed MSYS (default MSYS installation path C:\msys\1.0\ )

If you want to, you can find the newer version of gtk+ dev files here
Then edit a file that should be here c:/msys/1.0/lib/pkgconfig/cairo.pc
Remove this part:" pixman-1 >= 0.10.0" or something like that (I can't remember exactly, I've already deleted that part LOL)

Don't forget to compile with this command:

gcc -Wall -g `pkg-config --cflags libglade-2.0` -o hello hello.c `pkg-config --libs libglade-2.0`

here is an explanation of why compiling that way....


Congratulations Now you can compile your gtk+ programs in Windows...
I think that this way is less painful than cross-compiling ......

P.S. Sorry for my bad English......

Tuesday, October 28, 2008

Howto install odbc mysql

Primero si necesitas necesitas estas bibliotecas:

$sudo apt-get install libmyodbc
$sudo apt-get install unixodbc-dev

Despu├ęs necesitamos agregar el driver de mysql a unixodbc
abre el archivo odbc.ini ya agrega esto:

$sudo gedit /etc/odbcinst.ini


[MySQL]
Description = MySQL driver
Driver = /usr/lib/odbc/libmyodbc.so
Setup = /usr/lib/odbc/libodbcmyS.so
FileUsage = 1

despues necesitamos agregar la base de datos a la que se quiere conectar
abre el archivo odbc.ini:

$sudo gedit /etc/odbc.ini


[ODBC Data Sources]
test = Connector/ODBC 3.51 Driver DSN

[test]
Driver = /usr/lib/odbc/libmyodbc.so
Description = Connector/ODBC 3.51 Driver DSN
Server = localhost
DSN = test
Port = 3306
Socket = /var/lib/mysql/mysql.sock
User = DB_USER_NAME
Password = DB_PASSWORD
Database = DB_NAME
ServerType = MySQL
Option =
TraceFile = /var/log/mysql_test_trace.log
Trace = 0

[Default]
Driver = /usr/lib/odbc/libmyodbc.so
Description = Connector/ODBC 3.51 Driver DSN
Server = localhost
DSN = test
Port = 3306
Socket = /var/lib/mysql/mysql.sock
User = DB_USER_NAME
Password = DB_PASSWORD
Database = DB_NAME
ServerType = MySQL
Option =
TraceFile = /var/log/mysql_test_trace.log
Trace = 0

Y damos de alta al driver con este template, crea un archivo donde quieras:
template1.txt:

[MySQL]
Description = MySQL database
Driver = MySQL
SERVER = localhost
USER = DB_USER_NAME
PASSWORD = DB_PASSWORD
PORT = 3306
DATABASE = DB_NAME

Y para terminar este comando en la terminal

$ odbcinst -i -s -f template1.txt