Report inadequate content

Exportar una consulta de Mysql en un fichero CSV

Si tienes una tabla o consulta que quieres exportar a CSV tienes dos maneras muy fáciles de hacerlo. La primera es dentro de la consola mysql utilizando después del SELECT la opción INTO OUTFILE. Esto escribirá en el fichero externo que indiques el contenido de la consulta. La segunda opción es desde la propia línea de comandos utilizando la opción "Batch".

Diferencias entre método 1 y 2: El primero permite especificar la terminación de las líneas en el csv así como si quieres comillas en cada campo. El segundo escribe en el CSV los campos delimitados por tabulación sin más. La segunda es la opción más senclla y rápida para la mayoría de casos.

Opción 1: Exportar una consulta SQL a CSV desde la consola Mysql

Si por ejemplo quieres que cada campo de tu consulta se separe con punto y coma y cada registro por un salto de línea windows (\r\n) o Unix (\n), lo que vendría a ser un CSV vaya!, solo tienes que hacer algo como:

SELECT
        *
FROM
        tu_tabla
WHERE
        condicion
-- Aqui viene la exportación
INTO OUTFILE
        '/tmp/fichero_salida.csv'
        FIELDS TERMINATED BY ';'
        OPTIONALLY ENCLOSED BY '\"'
        LINES TERMINATED BY '\r\n';

Puedes cambiar el formato fácilmente cambiando los caracteres. En este caso el fichero final estaría en la carpeta /tmp, un lugar fácil para evitar problemas de permisos

Opción 2: Exportar una consulta SQL a CSV desde terminal

Este método es todavía más simple, pero asume que quieres los campos separados por tabulación, cosa que si vas a usar un Excel o similar quizá sea lo más práctico y rápido.

Para ello basta con pasar dos parámetros básicos:

  • -e: Indicando la consulta que quieres hacer entre comillas
  • -B: para indicar que quieres recibir la consulta en modo "batch" (campos separados por tabs)

Supongamos que nos conectamos a mysql, con el contenido de la primera línea...

mysql -u root --password=elquesea mibasededatos \
-e "SELECT * FROM tabla where ...." -B > fichero_salida.csv

... en la segunda tienes la parte que hace la exportación. Ahora tendrás en el fichero_salida.csv el resultado de la consulta delimitado por tabulaciones y si hay cualquier error lo verás por pantalla.

{
}

Best distraction-free writing programs

I am not a writer, but as many other mortals a lot of times I need to write long documents or put my ideas alltogether. For anyone who works with a computer and needs to write text in a non-distracting environment these tools will be very useful.

These programs usually are full-screen and only let you see the text you are typing, and usually plain text (without any formats). It might sound simple or even ridiculous, but I am more productive when I stop receiving notifications and being tempted of clicking on that little red number showing unread email or any other procastinators.

Here is the list of distraction-free software for both Windows and Mac.

Distraction-free software for Mac

This is the environment where I use this kind of programs the most.

WriteRoom

I used WriteRoom for free a couple of years ago, now the product has evolved and is commercial but surely the most complete of all.

Ommwriter

It comes in two flavours Ommwriter Dana I and Ommwriter Dana II. The first one is free, the second one is commercial, but you can pay the amount you want, minimum $4.11 I do use this program as my personal choice. Here is a video, and also lets you understand what all this programs are about:

Other programs

I haven't fully tested these ones, but they do the same:

 If you need to write a whole book, with images, chapters and so on an interesting tool is Scrivener (site, trial download)

Distraction-free software for Windows

If you are looking for a distraction-free writing software for Windows, have a look to:

 

 

Musica online gratis y sin anuncios

Desde hace ya bastantes meses vengo usando Grooveshark. Un servicio de streaming que te permite escuchar la música que quieras de forma gratuita, que a diferencia de Spotify en su versión gratuita no ponen cortes publicitarios, cosa que se agradece enormemente. Grooveshark solo muestra un banner en un lado del reproductor web, por lo que se puede dejar abierto en segundo plano y seguir con otras cosas.

Grooveshark

Hoy he descubierto además PlayListNow, un servicio que ofrece música en función de lo que estés haciendo en ese momento. Completando la frase de lo que estás haciendo en este momento te sugiere varias playlists, eso si, hay que escribirlo en inglés, pero el servicio vale la pena. Los usuarios pueden crear playlists nuevas asociadas a un momento concreto.

Playlistnow

Muy interesante parece también Musicuo, quienes dicen que por subir más de 1000 canciones te dan una cuenta VIP (¿no son muchas?). Extremadamente parecido a iTunes y este sí totalmente en Español.

Musicuo

Además de Spotify, Grooveshark, Playlistnow o Musicuo existen otros muchos servicios para escuchar música online, incluso más experimentados en la red como Deezer o Last.fm. Internet está plagado de ellos.

Deezer

¿Y tu cuál usas? ¿O todavía reproduces la música desde el fichero?

{
}

Instalar PHP 5.3 en MAMP

Actualización: La nueva versión de MAMP ya trae PHP 5.3 por lo que ya no es necesario hacerlo a mano. Bájate la última versión!

Hola,

A día de escribir este post MAMP viene con la versión 5.2.11 de PHP por lo que no se pueden utilizar muchas de las funciones interesantes que tiene la nueva versión, yo concretamente quería utilizar funciones de fecha como DateTime::createFromFormat() y los namespaces. Para solucionarlo he hecho lo siguiente

A la conciencia vuestra irá si se os rompe la configuración (a mi me va):

Instrucciones para instalar PHP 5.3 en Mac con MAMP

1) Descargar la versión 5.3 de la página de Snapshots a día de hoy este es el fichero comprimido

2) Descomprimir y navegar por terminal hasta el lugar donde se ha descomprimido

3) En la terminal, dentro de la carpeta lanzar el configure con las opciones de vuestro Config:

./configure --with-mysql=/Applications/MAMP/Library --with-apxs2=/Applications/MAMP/Library/bin/apxs --with-gd --with-jpeg-dir=/Applications/MAMP/Library --with-png-dir=/Applications/MAMP/Library --with-zlib --with-freetype-dir=/Applications/MAMP/Library --prefix=/Applications/MAMP/bin/php5 --exec-prefix=/Applications/MAMP/bin/php5 --sysconfdir=/Applications/MAMP/conf/php5 --with-soap --with-config-file-path=/Applications/MAMP/conf/php5 --enable-track-vars --enable-bcmath --enable-ftp --enable-gd-native-ttf --with-bz2=/usr --with-ldap --with-mysqli=/Applications/MAMP/Library/bin/mysql_config --with-sqlite --with-ttf --with-t1lib=/Applications/MAMP/Library --enable-mbstring=all --with-curl=/Applications/MAMP/Library --enable-dbx --enable-sockets --enable-bcmath --with-imap=shared,/Applications/MAMP/Library/lib/imap-2006i --enable-soap --with-kerberos --enable-calendar --with-pgsql=shared,/Applications/MAMP/Library/pg --enable-dbase --enable-exif --with-libxml-dir=/Applications/MAMP/Library --with-gettext=shared,/Applications/MAMP/Library --with-xsl=/Applications/MAMP/Library --with-pdo-mysql=shared,/Applications/MAMP/Library --with-pdo-pgsql=/Applications/MAMP/Library/pg --with-mcrypt=shared,/Applications/MAMP/Library --with-openssl --with-apxs2=/usr/sbin/apxs --with-png-dir=/usr/X11 --with-freetype-dir=/usr/X11

4) Si todo va bien (el punto anterior es la madre del cordero):

make
make install

Si encontráis errores podéis desactivar las librerías que os fallan (si no las necesitáis) y si no en el proyecto Fink podéis descargar un montón de ellas y lanzar los -with-librerira-tal=/sw etc...

Pasar enlaces Youtube a un punto de tiempo específico

Muchas veces pasamos enlaces de Youtube donde la parte interesante no llega hasta cierto punto. Puedes pasar a tus colegas el enlace para que salte directamente a un minuto y segundo que tu quieras.

Si por ejemplo quieres que un video empieze en el minuto 1 y el segundo 2 tan sólo tienes que añadir al final:

#t=1m02s

Delante de la m los minutos y delante de la s los segundos. Así de fácil. Por ejemplo:

http://www.youtube.com/watch?v=tTJMerul33E#t=1m02s

Desde el enlace anterior saltarás directamente a la escena de la Ostra Azul de la película Loca Academia de Policía.

"Unicomp Customizer" mechanical keyboard review

Unicomp mechanical keyboardAmong all the facts that remind me that I am getting old, one of them is chatting with other fellows about the technology we were using back when we started working at our first jobs. It has been 16 years since then in my case, and I sometimes find myself talking about how it was like working with a 386 and 4mb of ram, typing lots of text in such a fantastic wordprocessor as it was Wordperfect, switching from Windows 3.1 to Windows 95 and MS Word afterwards --which was such a bad experience in many ways--. I also clearly remember working with Mac OS 8 for the first time at a desktop publishing job, or the first time I played with a Silicon Graphics Octane machine and its Irix companion.

I perfecly recall using various IBM computers back in 1994, among Olivetti's, HP and other unnamed PC clones, and this IBM machines where all about sturdiness and quality of materials. That's when I had my first contact with IBM's model M mechanical keyboards, and I have been in love with them ever since. I have always been a very fast typing guy, and I immediately appreciated the accuracy of the model M keys response. I typed much more quicker with them and they also were a joy to use, perfect for continous typist hard work. I still think there are no better keyboards in the world should you click more than 1000 keys per day.

Now, try to explain marvels about this keyboards to someone ten years younger than you, who has never seen a keyboard more sophisticated than a Logitech one. Tell them about IBM's patented buckling spring "clicky" keys, about real concurrent multi keypresses, about superb tactile feedback. Tell them about these keyboard's lack of fancy multimedia buttons or usb ports... Forget it, they probably won't get it, and of course it's not their fault, as they are also not to blame for having never used a Commodore 64 or a real typewriter.

Despite my love for the mechanical keyboards, I recon I have been using membrane Apple keyboards at home during the last few years, and dull Dell keyboards at all my different works. But this has changed now, at least at my work's cubicle, thanks to the Unicom Customizer keyboard I bought a few days ago.

This keyboard is the real thing

It turns out that this little Unicomp company bought IBM's model M keyboard patents from Lexmark, which in turn bought them from IBM a few years ago, so the keyboards built by Unicomp are the real thing. And it is so true, this Customizer black keyboard has been built with the same technology and equipment the original keyboards were built with, and it shows: super sturdy, noise-clicky, mechanical keyboard heaven. At $69 (plus overseas delivery in my case) it is no cheap, but this keyboard cannot be considered expensive neither, given its construction quality and the fact that it will easily serve me for more than 10 years.

A keyboard is the main tool of my livelihood and one of the main tools of most of my hobbies. It makes sense to try to get the best tool for the job. The three most important parts of a computer in my opinion are the keyboard, mouse, and monitor. CPU? RAM? Hard disk space? I'll take whatever you give me. But the things I interact with on a constant basis, I want those things to be comfortable.

Experiencing a superb mechanical keyboard

The Unicomp Customizer black keyboard comes along also with a Wow factor, which may be a plus for some. I can tell you this old fashion keyboard has grabbed the attention of literally everyone that has come by my place, always in a positive way. When my setup of dual screens full of Vim sessions and the customizer get combined, the result is a powerful hackish, super productive image, it always seems I am working hard, which of course may not be the case, but anyway.

The keys have a lot of weight to them compared to the bland feel of modern keyboards (which usually use some rubber or plastic dome under the keys). The Customizer's keys have little springs in them, and you can feel the keys pushing back on your fingers as you type. You will clearly feel the difference with any other keyboard you've used before. The weight might lead to fatigue though; the keys are harder to press than other keyboards and my hands feel like they're getting a workout in comparison. That's not been my experience so far, so the worry may be unfounded.

The version of the keyboard I got has a modern Super ("windows") modifier key, but you can get a version without even that, if you like. I also ordered command and options keys as an option, should I use the keyboard attached to a mac computer in the future. You have to specify you want this extra keys by filling a comment text field during purchase, though, so remember it if you pretend to do so. The extra cost for this five keys is $10.

Very important to me, as a Vimmer, is the position and size of the Escape key. On the Customizer, Escape is positioned off by itself in the corner as it should be, with a ton of space between itself and the number row, and the Escape key itself is freaking enormous. This is a huge plus in my book. You can't miss Escape on this keyboard. Similarly, all the other keys are the right sizes and in the right places.

Veredict

So how is the Unicomp Customizer? It's solid, standard, unique, and has a nice retro, minimalist style that I personally enjoy. It's also huge, loud, and relatively expensive. Is it worth buying? If you have the money to spend, I think it is. I don't regret the buy at all. When I go to work and start typing on this stunning old school keyboard, I'm always pleasantly surprised.

 

Sources and related links

Reset iTerm preferences to default

If you have messed up your iTerm application preferences you can aways return to the factory settings by deleting your iTerm preferences file. Just delete the following file:

rm ~/Library/Preferences/net.sourceforge.iTerm.plist

This will delete your profiles, very useful when you have remapped keys and you can't remember how to go back.