miércoles, septiembre 21, 2011

MS Sql Server Backup / Restore sql commands

Con MS SQL Server es posible realizar backups (respaldos) mediante querys (consultas) sql, a través de una conexión a la base de datos usando nuestra herramienta favorita con la que acostumbramos hacer querys (en mi caso Aqua Fold Datastudio).

Respaldar en el directorio por defecto (backup directory in MSSQL directory) con nombre prueba.bak

BACKUP DATABASE pru
TO DISK='prueba.bak';

Restaurar de un backup que se encuentra en el directorio default
Nota: la base de datos que se quiere restaurar no debe estar en uso.

RESTORE DATABASE pru
FROM DISK='prueba.bak';

Restaurar de un backup hacia una base de datos distinta a la original

RESTORE DATABASE pru2
FROM DISK='prueba.bak'
esto lanza el error siguiente
-- [Error] Script lines: 1-3 --------------------------
-- The file 'c:\mssql2005\MSSQL.1\MSSQL\DATA\pru.mdf' cannot be overwritten.  It is being used by database 'pru'.
--
-- More exceptions ... File 'pru' cannot be restored to 'c:\mssql2005\MSSQL.1\MSSQL\DATA\pru.mdf'. Use WITH MOVE to identify a valid location for the file.

Así que necesitamos ver el contenido del backup para ello usamos:

RESTORE FILELISTONLY
FROM DISK='prueba.bak'
esto muestra algo como lo siguiente:

LogicalName PhysicalName Type FileGroupName Size MaxSize FileId CreateLSN DropLSN UniqueId ReadOnlyLSN ReadWriteLSN BackupSizeInBytes SourceBlockSize FileGroupId LogGroupGUID DifferentialBaseLSN DifferentialBaseGUID IsReadOnly IsPresent <br /> -------------- ------------------------------------------- ------- ---------------- ------- -------------- --------- ------------ ---------- ------------------------------------ -------------- --------------- -------------------- ------------------ -------------- --------------- ---------------------- ------------------------------------ ------------- ------------ <br /> pru c:\mssql2005\MSSQL.1\MSSQL\DATA\pru.mdf D PRIMARY 2293760 35184372080640 1 0 0 DB89AE8F-4F86-4633-9063-7BE019ABF8E9 0 0 1441792 512 1 (null) 17000000041200037 8683BDA0-FDA1-4281-B887-5FEE5FD1CC0D false true <br /> pru_log c:\mssql2005\MSSQL.1\MSSQL\DATA\pru_log.LDF L (null) 573440 2199023255552 2 0 0 A9C91979-20E6-4A67-BAEC-48FC68C3E6B6 0 0 0 512 0 (null) 0 00000000-0000-0000-0000-000000000000 false true <br />

Así que usamos la información anterior para hacer la restauración indicando donde queremos colocar los archivos de la base y el log, para ello usamos el Logical name

RESTORE DATABASE pru2
FROM DISK='prueba.bak'
WITH
MOVE 'pru' TO 'c:\mssql2005\MSSQL.1\MSSQL\DATA\pru2.mdf'
,MOVE 'pru_log' TO 'c:\mssql2005\MSSQL.1\MSSQL\DATA\pru2_log.LDF'

<br /> <br /> -- ALGUNOS EJEMPLOS APLICADOS<br /> <br /> BACKUP DATABASE pru<br /> TO DISK='\\10.0.2.2\buzon\pru.bak'<br /> <br /> RESTORE FILELISTONLY<br /> FROM DISK='\\10.0.2.2\shm_altair\plantilla.bak'<br /> <br /> <br /> RESTORE DATABASE altair_plantilla<br /> FROM DISK='\\10.0.2.2\shm_altair\plantilla.bak'<br /> WITH<br /> STATS=10<br /> ,MOVE 'plantilla_Data' TO 'c:\mssql2005\MSSQL.1\MSSQL\DATA\altair_plantilla.mdf'<br /> ,MOVE 'plantilla_Log' TO 'c:\mssql2005\MSSQL.1\MSSQL\DATA\altair_plantilla_log.ldf'<br /> <br />



=========================================================
BACKUP DATABASE pru
TO DISK='C:\bk\pru.bk';

es tan simple como lo anterior, pero hay que asegurarnos de que la cuenta con la que corre el proceso de sql server tiene permiso de escritura en el path donde queremos guardar el archivo de backup, por lo que hay que darle permiso en las propiedades de seguridad a la carpeta, en mi caso el sqlserver corre con la cuenta NETWORK SERVICE y al darle permiso ya no saldra un error como este:

Cannot open backup device 'C:\bk\pru.bk'. Operating system error 5(Access is denied.)

Si el backup es muy grande, podemos agregar lo siguiente para recibir notificación sobre el progreso, en este caso solicitamos notificación cada 10%  (WITH STATS=10) y el comando quedaría así:

BACKUP DATABASE pru

TO DISK='C:\bk\pru.bk'
WITH STATS=10;

Restore sql


Restoringaoeu

Más información:

http://technet.microsoft.com/en-us/library/ms186865(SQL.90).aspx

martes, septiembre 20, 2011

configuring several ips on the same network interface (card)

(creating or setuy virtual ethernet devices on a single physical device)
(creating or setup virtual IP address on a single interface)

now our interface is binded to the three IPs

if you want to check with your eyes, run

ifconfig

and you will see something like this

eth0      Link encap:Ethernet  direcciónHW 00:04:75:ab:cd:ef  
          Direc. inet:192.168.1.50  Difus.:192.168.1.255  Másc:255.255.255.0
          ACTIVO DIFUSIÓN MULTICAST  MTU:1500  Métrica:1
          Paquetes RX:0 errores:0 perdidos:0 overruns:0 frame:0
          Paquetes TX:0 errores:0 perdidos:0 overruns:0 carrier:0
          colisiones:0 long.colaTX:1000 
          Bytes RX:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupción:20 Dirección base: 0xe000 

eth0:1    Link encap:Ethernet  direcciónHW 00:04:75:ab:cd:ef  
          Direc. inet:192.168.1.100  Difus.:192.168.1.255  Másc:255.255.255.0
          ACTIVO DIFUSIÓN MULTICAST  MTU:1500  Métrica:1
          Interrupción:20 Dirección base: 0xe000 

eth0:2    Link encap:Ethernet  direcciónHW 00:04:75:ab:cd:ef  
          Direc. inet:192.168.1.200  Difus.:192.168.1.255  Másc:255.255.255.0
          ACTIVO DIFUSIÓN MULTICAST  MTU:1500  Métrica:1
          Interrupción:20 Dirección base: 0xe000

related info:


http://itsecureadmin.blogspot.com/2007/02/creating-virtual-ip-addresses-on-linux.html

lunes, septiembre 19, 2011

find command modifier to locate only directories

find . -type d -iname "*_vti_*"

VirtualBox port forwarding from HOST to GUEST

Accesing a virtualbox virtual machine's network services from the host operating system

When running a VirtualBox VirtualMachine(VM), the networking inside the VM by default is in a private network in NAT, generaly 10.0.2.x, so the GUEST can access the HOST network services, but the HOST and the outside world is unable to reach the GUEST network services.

According to the VirtualBox Manual, there are different modes of network emulation, by default the NAT mode.

A way to map (forward) a HOST port to a GUEST port exists and is posible to configure from the command line (the VM should not be running):

$ VBoxManage modifyvm windows-server --natpf1 "iis,tcp,,8080,,80"

In this case:
windows-server is the name of the VM
iis is the name of the rule
tcp the protocol, could be udp also
the host IP is left blank
the hostport is 8080
the guest IP is left blank
the guestport is 80

The restriction with this approach is that all the inbound traffic is reverse NATed so the GUEST VM will see the origin IP as 10.0.2.2.

jueves, septiembre 15, 2011

como convertir .nrg a .iso in linux

(how to convert from .nrg image to .iso image)

los archivos .nrg son images de un CD o DVD creadas con el software de grabación NERO Burning, sin embargo es de más utilidad tener el archivo de imagen en formato .iso, el cual es un estandar y es el más aceptado por las aplicaciones y podemos arrancar las maquinas virtuales desde un .iso

así que hay que convertirlo y en linux no hay mayor problema, solo tenemos que instalar el paquete nrg2iso

$ sudo apt-get install nrg2iso

luego para convertir

$ nrg2iso file.nrg file.iso

y listo!!! ya podemos utilizar la imagen con mucho más software sin requerir el ñero

jueves, septiembre 08, 2011

Convertir secuencia de imagenes a video

$ ffmpeg -f image2 -r 1 -i cuadro%04d.png -r 25 video.avi

La opción -f image2 le indica a ffmpeg que la entrada es una secuencia de imagenes.

Se puede facilmente con el comando ffmpeg %04d indica que los nombres de imágenes son a 4 digitos 0000 hasta el 9999.
Si las imagenes tienen nombres con 2 digitos usaríamos %02d, y si solo tienen el número sin mascara (1, 2,3, ... 9, 10, ..., 21) solo utilizamos %d.

La primera -r indica cuantas imagenes van por cada segundo.

La segunda -r indica el número de cuadros por segundo del video.

video.avi es el nombre del archivo de salida

martes, septiembre 06, 2011

Compiling PHP 5 with GD support

To compile php apache module from sources, with GD library support in ubuntu 10.04 LTS, you need to run:

$ sudo apt-get install libgd2-xpm-dev libjpeg62-dev

running configure

$ ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pgsql=/usr/local/pgsql8.1 --with-zlib --enable-mbstring --with-gd --with-jpeg-dir=/usr/lib

viernes, agosto 26, 2011

Reflection

Socializing is the mechanics of hypocrisy administration and management.

miércoles, agosto 10, 2011

Solving festival problem "can't open /dev/dsp"

edit:

.festivalrc in your home directory and add the following
(Parameter.set ‘Audio_Command “aplay -q -c 1 -t raw -f s16 -r $SR $FILE”)
(Parameter.set ‘Audio_Method ‘Audio_Command)


miércoles, agosto 03, 2011

linux routing

Habilitar a cualquiera para poder modificar las rutas:


if you did the following as root:
setcap cap_net_admin=+eip /sbin/route

anyone that could run the route command could do routing changes. so a possibility is to make /sbin/route mode 0550 and a special routing group and have the process be run by a user in that routing group.

lunes, agosto 01, 2011

netcat (tcp/ip swiss knife) examples

Taked from http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples/

the site was down, so I preserve the content got by google cache

One of the Linux command line tools I had initially under-estimated is netcat or just nc. By default, netcat creates a TCP socket either in listening mode (server socket) or a socket that is used in order to connect to a server (client mode). Actually, netcat does not care whether the socket is meant to be a server or a client. All it does is to take the data from stdin and transfer it to the other end across the network.

The simplest example of its usage is to create a server-client chat system. Although this is a very primitive way to chat, it shows how netcat works. In the following examples it is assumed that the machine that creates the listening socket (server) has the 192.168.0.1 IP address. So, create the chat server on this machine and set it to listen to 3333 TCP port:
$ nc -l 3333
On the other end, connect to the server with the following:
$ nc 192.168.0.1 3333
In this case, the keyboard acts as the stdin. Anything you type in the server machine’s terminal is transfered to the client machine and vice-versa.

Transfering Files

In the very same way it can be used to transfer files between two computers. You can create a server that serves the file with the following:
$ cat backup.iso | nc -l 3333
Receive backup.iso on the client machine with the following:
$ nc 192.168.0.1 3333 > backup.iso
As you may have noticed, netcat does not show any info about the progress of the data transfer. This is inconvenient when dealing with large files. In such cases, a pipe-monitoring utility like pv can be used to show a progress indicator. For example, the following shows the total amount of data that has been transfered in real-time on the server side:
$ cat backup.iso | pv -b | nc -l 3333
Of course, the same can be implemented on the client side by piping netcat’s output through pv:
$ nc 192.168.0.1 3333 | pv -b > backup.iso
Other Examples
Netcat is extremely useful for creating a partition image and sending it to a remote machine on-the-fly:
$ dd if=/dev/hdb5 | gzip -9 | nc -l 3333
On the remote machine, connect to the server and receive the partition image with the following command:
$ nc 192.168.0.1 3333 | pv -b > myhdb5partition.img.gz
This might not be as classy as the partition backups using partimage, but it is efficient.
Another useful thing is to compress the critical files on the server machine with tar and have them pulled by a remote machine:
$ tar -czf - /etc/ | nc -l 3333
As you can see, there is a dash in the tar options instead of a filename. This is because tar’s output needs to be passed to netcat.
On the remote machine, the backup is pulled in the same way as before:
$ nc 192.168.0.1 3333 | pv -b > mybackup.tar.gz

Security

It is obvious that using netcat in the way described above, the data travels in the clear across the network. This is acceptable in case of a local network, but, in case of transfers across the internet, then it would be a wise choice to do it through an SSH tunnel.
Using an SSH tunnel has two advantages:
  1. The data is transfered inside an encrypted tunnel, so it is well-protected.
  2. You do not need to keep any open ports in the firewall configuration of the machine that will act as the server, as the connections will take place through SSH.
You pipe the file to a listening socket on the server machine in the same way as before. It is assumed that an SSH server runs on this machine too.
$ cat backup.iso | nc -l 3333
On the client machine connect to the listening socket through an SSH tunnel:
$ ssh -f -L 23333:127.0.0.1:3333 me@192.168.0.1 sleep 10; \
        nc 127.0.0.1 23333 | pv -b > backup.iso
This way of creating and using the SSH tunnel has the advantage that the tunnel is automagically closed after file transfer finishes. For more information and explanation about it please read my article about auto-closing SSH tunnels.

Telnet-like Usage

Netcat can be used in order to talk to servers like telnet does. For example, in order to get the definition of the word “server” from the “WordNet” database at the dict.org dictionary server, I’d do:
$ nc dict.org 2628
220 ..............some WELCOME.....
DEFINE wn server
150 1 definitions retrieved
151 "server" wn "WordNet (r) 2.0"
server
     n 1: a person whose occupation is to serve at table (as in a
          restaurant) [syn: {waiter}]
     2: (court games) the player who serves to start a point
     3: (computer science) a computer that provides client stations
        with access to files and printers as shared resources to a
        computer network [syn: {host}]
     4: utensil used in serving food or drink
.
250 ok [d/m/c = 1/0/18; 0.000r 0.000u 0.000s]
QUIT
221 bye [d/m/c = 0/0/0; 16.000r 0.000u 0.000s]

Works as a Port Scanner too

A useful command line flag is -z. When it is used, netcat does not initiate a connection to the server, but just informs about the open port it has found. Also, instead of a single port, it can accept a port-range to scan. For example:
$ nc -z 192.168.0.1 80-90
Connection to 192.168.0.1 80 port [tcp/http] succeeded!
In this example, netcat scanned the 80-90 range of ports and reported that port 80 is open on the remote machine.
The man page contains some more interesting examples, so take the time to read it.

Notes

All the above examples have been performed on Fedora 5/6. Netcat syntax may vary slightly among Linux distributions, so read the man page carefully.
Netcat provides a primitive way to transfer data between two networked computers. I wouldn’t say it’s an absolutely necessary tool in the everyday use, but there are times that this primitive functionality is very useful.

martes, julio 05, 2011

Set up Kyocera Mita 1820 in Ubuntu 10.04, for job accounting or with password for printing

Set up Kyocera Mita 1820 in Ubuntu 10.04, for job accounting or with password for printing

I was able to setup job accounting for a Kyocera mita 1820, so I can print in the job printer, this is how I did it:

0) Default Ubuntu Add Printer procedure (I am using ubuntu 10.04 but this can apply to other versions or distributions)

1) In CUPS, change job accounting to an arbitrary code, say "00000000" then accept changes
( this can be done either in System > Administration > Printers, select your printer, right mouse click, options, in the dialog:
Printer Options, scroll to Job Acounting (below of Job Settings), and choose the 00000000

2) As root, edit the ppd file for the printer: it is located in /etc/cups/ppd/ and titled "printer.ppd" with "printer" being the cups name for the printer.

sudo gvim /etc/cups/ppd/Kyocera-Mita-KM-1820.ppd

2. Search this section:
======
*% Management Code Definitions
*OpenUI *KmManagment/Job Accounting: PickOne
*OrderDependency: 60 AnySetup *KmManagment
*DefaultKmManagment: MG00000000
*KmManagment Default/Off: ""
*KmManagment MG00000000/00000000: "(00000000) statusdict /setmanagementnumber get exec"
*KmManagment MG00000001/00000001: "(00000001) statusdict /setmanagementnumber get exec"
.....
======

3. change this line:
===
*KmManagment MG00000000/00000000: "(00000000) statusdict /setmanagementnumber get exec"
===
using your code (ex. 7947) TO:
===
*KmManagment MG00000000/7947: "(7947) statusdict /setmanagementnumber get exec"

Save, and restart cups:

sudo service cups restart

This worked for me.

miércoles, junio 15, 2011

Wii: Pantalla negra al correr juegos del Virtual Console

Básicamente el problema que se presenta, es que la Wii se queda en pantalla negra al correr juegos del Virtual Console, y según algunos blogs en la red esto se debe a el tipo de cable que usamos para conectar nuestra wii a la pantalla.

Si usamos cable composite (el que viene por default con la wii y es de 3 salidas) no hay problema.

Si usamos el cable de componente, el problema se presenta cuando estamos en modo 480i, y se resuelve si cambiamos al modo 480p, lo cual podemos hacer en la pantalla de configuraciones del wii.

El modo 480p nos da mejor imagen que el 480i, esa es la utilidad de cambiar el cable composite por el cable componente.

En algunos blogs sugieren que se puede pasar de un modo a otro, si la wii no esta bloqueada y esta en la pantalla negra, entonces apretar la tecla Home, acceder al manual del juego, y mediante la combinación de botones Z + A + 2 (modo interlaced 480i) ó Z + A + 1 (modo progresivo o 480p)  se puede cambiar de modo.

Espero esta información les sea de utilidad.

sábado, mayo 07, 2011

Kindle feedback: About ebook lending

the question on lending is complex

but for personal lending there is a better solution, instead of limiting the number of lendings, a better aproach is reproducing the same that happen with real books, that means the transferability of the book, in this case, if we buy an ebook we have access rights to it for lifetime, and the solution, is we can transfer our book to other, losing access to the book, so like in the real book, there is only one copy, so our friend retransfer the book to us or we have to buy another instance, that is a fair way of doing the lending thing

this can also be a better solution for librarys, who can buy a several copies of the books, and only one user has access to the book, there is still a lot of work to do in terms of the formats and interoperability of all this stuff

viernes, mayo 06, 2011

mejorando la experiencia de uso de google reader en el Kindle

Leer en el kindle, con su e-ink pearl resulta en un gran descanso para los ojos y permite leer más cómoda y rápidamente que en las pantallas LCD, e incluso permite leer bajo la luz del sol, lo cual muchas personas no se han permitido disfrutar porque tienen cierta resistencia a gastar alrededor de unos 2300 pesos en un dispositivo como el Kindle, pero yo lo recomiendo altamente

Ahora bien los contenidos de los periodicos para kindle tienen un costo, pero también podemos usar sin pagar nada, el maravilloso agregador RSS de Google, y el navegador del kindle para visualizarlo, sin embargo en el kindle de 6'' queda una área reducida para leer pero hay ciertos atajos y trucos para maximizar nuestra experiencia

Aquí les doy mis recomendaciones, que no solo funcionan en el kindle sino también cuando usen el google reader en otro dispositivo, básicamente se trata de usar el teclado para navegar por las noticias en una forma sencilla y rápida, por otro lado les recomiendo activar el m

[tecla] : función, (pongo la tecla entre parentesis cuadrados para fines ilustrativos pero no hay que teclear los parentesis cuadrados)

[f ]: nos permite pasar al modo de lectura en pantalla completa quitando todos los elementos distractivos del reader

[p] : nos permite mover el focus a la sigiuente entrada
[n] : nos permite mover el focus a la entrada anterior
[o] : nos permite abrir la entrada que tiene el focus

[barra espaciadora] : nos permite avanzar en la lectura de página en página
[shift]+[barra espaciadora] : nos permite retroceder en la lectura una página

[shift]+[u] : nos muestra el listado de suscripciones
[shift]+[j] : nos permite mover el focus a la siguiente suscripción

[shift]+[k] : nos permite mover el focus ala suscripción previa
[shift]+[o] : abre la suscripción que tiene el focus

el uso de estas teclas y el modo de lectura a pantalla completa hace que la experiencia de lectura sea aceptable, eso sí tenemos que tener nuestro kindle en un lugar con cobertura wifi

¿de donde puedo bajar peliculas, música y libros en internet?

pues hay muchos lugares, y hay que aclarar que esto te pone un parche en el ojo, pero si lo aceptas, pues es bajo tu propia responsabilidad

estan los sitios de torrents para bajar mediante un software que descargue torrents

busca en

http://torrent-finder.info

es un metabuscador de torrents pero ahí ves los sitios de torrents más usados como son
http://piratebay.org
http://isohunt.com
etc, en cada sitio puedes buscar las pelis o la música

luego otra opción es buscarlas en los foros de compartición donde generalmente o te ponen el torrent o el link de descarga en sitios de archivos

puedes probar usando un buscador para esto como http://filecrop.com el cual te lleva a enlaces para descarga directa cosa que google difícilmente hace, para gestionar de mejor manera tus descargas de este tipo de enlaces, te recomiendo un software que se llama jdownloader (http://jdownloader.org/download/index), basado en java por lo que corre sin problemas en windows, linux y mac y que se encarga de esperar por tí a que los archivos puedan ser descargados y puedes definir una cola de descargas

miércoles, marzo 23, 2011

Las explicaciones y el entendimiento ...

    - Para ti es fácil, nunca tuviste que darme una explicación.
    - Mira, aunque te hubiera dado todas las explicaciones del mundo, la decisión final es tuya, la última palabra es tuya, tu decides como reaccionar.
    Lo mismo ocurre con tu caso, tu le diste tus razones y explicaciones, si se enoja o no, si entiende o no, es su decisión, ya no es tu problema.

lunes, febrero 14, 2011

¿a cuantas mujeres has tocado el alma?

Es más fácil dejar entrar a alguien a tu cama, que dejarse tocar un pedacito del alma, porque el alma, es esa aura que cuando alguien la toca, se transforma y dejarse tocar el alma es dejarse cambiar, entregarse de una manera tan brutal, que el hombre que te toca el alma tiene que ser el hombre adecuado, el hombre que realmente la aprecie, tal vez esa sea la definición del hombre ideal, el hombre que cuando te toque el alma, te transforme, a lo mejor eso es amar, entregarse por completo, a pesar del riesgo que eso significa, que te partan el alma, otra vez.

Si llegar a entender quienes somos es un ejercicio tan difícil como tratar de descifrar una complejisima ecuación matemática, entender quien es el otro se antoja una labor francamente imposible, ¿porque los que dicen amarnos hacen lo que hacen? ¿porque se permiten ser débiles o cobardes o traidores? ¿y nosotros? ¿que debemos hacer? ¿odiarlos por no cumplir con el ideal que nos hicimos de ellos,? ¿desterrarlos de nuestras vidas? ¿vengarnos? ¿cerrarnos en nosotros mismos para que no vuelvan a tocarnos el alma?

O tratar de entender que el otro al igual que nosotros, está lleno de contradicciones, de zonas luminosas y zonas oscuras, entendernos a nosotros mismos y comprender al otro, ¿perdonar o no perdonar? Esa es la verdadera cuestión.

Esto es parte de un guión, ¿alguien adivina donde aparece este texto?

martes, febrero 08, 2011

Crítica a los periodistas, o a los que redactan las noticias

En esta ocasión quiero expresar una crítica sobre la mala práctica de los comunicadores, en cuanto a la forma de generar titulares que desinforman o mal informan y que transmiten una idea equivocada al lector que solo mira el titular sin leer la nota completa. Me animo a realizar este comentario, porque veo que es una falta recurrente en la que caen gran cantidad de comunicadores y de medios. Se puede decir que de alguna manera es una forma de amarillismo.

Para muestra basta un botón, y en este caso se trata de Diario TI http://www.diarioti.com/gate/n.php?id=28721 en dicha nota titulada “Descargas Piratas, Series de TV en internet distribuyen malware”, si solo leemos el titular, pues nos quedamos con una idea falsa de que al descargar capítulos de nuestra serie favorita por internet de torrents o sitios de descarga directa no oficiales, estamos descargando malware, lo cual al leer con detalle na nota nos damos cuenta de que no es el caso, ya que más bien los distrbuidores de malware aprovechan el interes de la gente por las series de tv, para poner enlaces de descarga falsos que realmente llevan a la gente a descargar programas troyanos y malware, y en este caso un título más apropiado sería “Interés en la descarga de series de tv por internet es aprovechado para distribuir malware”.

jueves, enero 20, 2011

Comparación entre los distintos formatos de compresión (zip,gzip,bzip2,rar,7z), tamaño de compresión, tiempo do compresión, descompresión.



Comparación entre los distintos formatos de compresión (zip,gzip,bzip2,rar,7z), tamaño de compresión, tiempo do compresión, descompresión.


Comparative between compression formats (zip,gzip,bzip2,rar,7z), compression size, compression time, decompression time.


Este comparativo se realiza sobre la compresión de un archivo grande, especificamente un archivo de imagen (.iso) de un juego de GameCube, y los elementos que se miden son el tamaño y el tiempo de compresión, en todos los casos se utiliza el nivel de compresión máxima con el fin de ver que formato brinda la mejor compresión.


This comparative is about the compression of a big file, specificaly a (.iso) image file of a GameCube game, the measure properties are compression time and compression size, in all the cases maximum compression level is used to be able to see witch format performs better.


Formato (format) parametros (params) Tamaño (size)
bytes
Tiempo (time) Tiempo descompresion
ORIGINAL 1459,978240
zip (.zip) -9 1272,705622 6m 56s 2m 9s
gzip (.gz) -9 1272,705473 6m 51s 2m 2s
bzip2 (.bz2) -9 1268,500602 31m 22s 8m 48s
rar (.rar) -m5 1212,932724 49m 13s 2m 41s
p7zip (.7z) defaults 1185,334394 31m 27s 6m 37s
p7zip -mx=9 1159,741390 42m 1s
p7zip -m0=LZMA2 -mx=9 1158,557214 37m 33s, 45m 9s 6m 4s

Como podemos ver los formatos que más se la rifan son el .rar y el .7z, por una diferencia considerable con los otros por lo que realizo más pruebas para estos dos formatos específicos con más archivos:

formato Tamaño Tiempo
original 1459,978240
rar a -m5 x.iso.rar x.iso 1163,104105 47m 49s
7z a -m0=LZMA2 -mx=9 x.iso.7z x.iso 1123,311172 2h 33m 1s
7z a -m0=LZMA2 -mx=9 -md=32m x.iso.7z x.iso 1147,526305 31m 35s

Como se aprecia en la tabla anterior, el 7z da una mejor compresión pero se tarda 2 horas para conseguir 40Mb menos, supongo que es por el tamaño default con que asigna el diccionario ya que consume gran cantidad de memoria, y me di cuenta que utilizo espacio de intercambio, por lo que probablemente eso impacto en tanto tiempo de ejecución, para comprobar realice la prueba definiendo el tamaño de diccionario limitando la cantidad de memoria requerida, según wikipedia, la cantidad requirida de RAM es 10 veces el tamaño del diccionario al comprimir y el tamaño del diccionario al descomprimir.

Así que con un diccionario de 32Mb -md=32m el tiempo de ejecución se reduce considerablemente incluso a un tiempo menor que el rar, con una compresión mejor.


Aquí el resultado con otro archivo, como se puede ver .7z obtiene mejor tiempo y una reducción considerable de 107Mb menos que .rar

formato Tamaño Tiempo
original 1459,978240
rar a -m5 832,572483 38m 42s
7z a -m0=LZMA2 -mx=9 -md=32m 725,846076 32m 33s

El resultado de otro archivo:


formato
Tamaño
Tiempo
original
1459,978240
rar a -m5
1212,932751
48m 21s
7z a -m0=LZMA2 -mx=9 -md=32m
1159,129496
34m 24s


Puede que valga la pena hacer un estudio sobre el .7z para ver la relación entre a) tamaño de diccionario, b) compresión obtenida, c) tiempo de ejecución.