Estoy a cargo de un grupo de estudio de programación de software para audio. Actualmente nos estamos encontrando los Jueves de 6 a 8 pm en La Miscelánea. La entrada es libre y están tod@s muy invitad@s!
Si quieren mas info o seguir los temas que tocamos en el grupo, suscríbanse a la lista de correos.
Author Archives: Rafael Vega
Una lista de comandos y trucos.
Comandos y trucos que siempre olvido
Administración de usuarios y grupos en Linux
1 2 3 4 5 6 7 | useradd mombre_usuario groupadd nombre_grupo passwd mombre_usuario cat /etc/passwd cat etc/group usermod -a -G nombre_grupo nombre_usuario # Agrega el usuario al grupo secundario usermod -g nombre_grupo nombre_usuario # Cambia el grupo primario del usuario |
Postgres
1 2 3 4 5 6 7 8 9 10 | # Server: sudo -u postgres service postgresql start|stop|restart sudo -u postgres createdb dbname #Client: sudo -u postgres pqsl #Set password $ sudo -u postgres psql template1 template1=# \password |
Buscar y remplazar texto en muchos archivos
1 | find ruta/archivos -type f -exec sed -i 's/busqueda/remplazo/g' {} \; |
Crear thumbnails de una imagen
1 | convert Aab_001.jpg -resize 29x29^ -gravity center -extent 29x29 Aab_001.small.jpg |
Copia de archivos a un servidor remoto
1 2 | rsync -avzu /ruta/local usuario@host:/ruta/en/servidor #Preserva usuarios, grupos, fechas rsync -rvzu /ruta/local usuario@host:/ruta/en/servidor #No preserva usuarios, grupos, fechas |
Renombrar muchos archivos
1 | for i in *; do j=`echo $i | cut -d . -f 1`; j=$j"_32.png"; mv $i $j; done |
Limpiar cache de iconos en gnome
1 | sudo gtk-update-icon-cache --force <nombre del theme> |
Cambiar los atajos de teclado de cualquier aplicación en Ubuntu 12.04 y Unity
Tomado de aqui.
Usando gconf-editor, navegar a org->gnome->desktop->interface y activar la opción can-change-accels.
Luego inicie la aplicación que quiere configurar con la opción UBUNTU_MENUPROXY=0. Por ejemplo UBUNTU_MENUPROXY=0 nautilus. Ahora puede poner el mouse sobre cualquier opción del menu y teclear el atajo deseado.
Instalar varias versiones de Ruby con rbenv
1. Instalar rbenv y el plugin ruby-build
1 2 3 4 5 6 7 8 9 | cd git clone git://github.com/sstephenson/rbenv.git .rbenv echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile echo 'eval "$(rbenv init -)"' >> ~/.bash_profile mkdir -p ~/.rbenv/plugins cd ~/.rbenv/plugins git clone git://github.com/sstephenson/ruby-build.git exec $SHELL |
2. Instale la versión de ruby que quiera
1 2 | rbenv install 1.9.2-p290 --with-openssl-dir=/usr/local rbenv rehash |
3. Use la nueva versión de ruby
1 2 | rbenv global 1.9.2-p320 ruby -v |
Cómo evitar que nautilus dibuje el fondo del escritorio en XFCE.
gsettings set org.gnome.desktop.background show-desktop-icons false
3. Programación gráfica con <canvas> y Javascript.
2. Introducción a Javascript.
-
Lenguaje de scripting típicamente usado para controlar el funcionamiento de un navegador web y para agregar interactividad a documentos HTML.
-
También utilizado como lenguaje de scripting de propósito general y para programar lógica del lado del servidor en aplicaciones web. Ver Nodejs Muy recomendado!!! Por ejemplo: Crear un servidor web con javascript y nodejs es re-fácil:
1
2
3
4
5
6
7
8
9
10var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');Para correr el servidor, ponga el código anterior en un archivo llamado servidor.js y ejecute la siguiente línea en una terminal:
1$ node servidor.js
Sintaxis
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | // Tomado sin permiso de http://javascript.infogami.com/Javascript_in_Ten_Minutes ////////////////////////////////////// // Basic Types var intValue = 1; var floatValue = 3.0; var stringValue = "This is a string\n"; /////////////////////////////////////// // Array var emptyList = []; var homogenousList = [1, 2, 3]; var heterogenousList = ["one", 2, 3.0]; /////////////////////////////////////// // Property Map // var emptyMap = {}; var homogenousMap = {"one": 1, "two": 2, "three": 3}; var heterogenousMap = {"one": 1, "two": "two", "three": 3.0}; /////////////////////////////////////// // Functions as values // var callable = function (message) { // <-- notice assignment window.alert("Callable called with message = " + message); } function createClosure(initial) { var res = function () { initial = initial + 1; window.alert("Closure with modified state " + initial); } return res; } /////////////////////////////////////// // Functions as arguments // function callCallable(f, x) { f(x); } function composeCallables(f, g, x) { f(g(x)); } /////////////////////////////////////// // Objects // function MyObject(name, value) { this.name = name; this.value = value; } /////////////////////////////////////// // Objects with Member Functions // function Message(message) { this.message = message; } Message.prototype.show = function() { window.alert("Message.show() with message = " + this.message); } |
Document Object Model
El DOM es una representación programática de un documento XML o HTML. En un navegador, se utiliza para acceder o modificar secciones del documento HTML que se está visualizando usando Javascript.
Un ejemplo simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <article id="primer_articulo"> <h1>Titulo del artículo</h1> <p class="resumen"><img src="http://foo.com/bar.jpg" alt="Una foto cuadrada y nítida">Blah Blah Blah Blah</p> </article> <script type="text/javascript"> var image = document.getElementById('primer_articulo').childNodes[3].childNodes[0]; for( var x = 0; x < image.attributes.length; x++ ) { if( image.attributes[x].nodeName.toLowerCase() == 'alt' ) { window.alert('El alt de la imagen es: ' + image.attributes[x].nodeValue ); } } </script> |
jQuery
El problema con la API del DOM es que no es muy compacta y existen muchas diferencias entre las implementaciones en diferentes navegadores. Como ejemplo mire este artículo que discute en mas de 5000 palabras como suscribirse a un evento click
Una alternativa altamente adoptada es la librería jQuery que brinda una API mucho mas compacta, métodos que encapsulan las diferencias entre navegadores y otras APIs para diferentes tareas como ajax,
Un ejemplo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Parrafos</title> <style type="text/css" media="screen"> p { font-family: "Helvetica Neue", "Helvetica", "Arial", "sans-serif"; font-size:18px; color: #333; border: 1px solid #AAA; width:400px; margin:20px auto; cursor: pointer; } </style> </head> <body> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <script src="jquery-1.7.1.min.js" type="text/javascript"></script> <script src="jquery.color.min.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $('p').click(function(){ $('p').animate({ 'color':"#333", 'font-size': '18px', 'padding': '0px' }); $(this).animate({ 'color':"#0000AA", 'font-size': '22px', 'padding': '10px' }); }); }); </script> </body> </html> |
Algunas cosas nuevas en HTML5
Almacenamiento local de datos
1 2 | window.localStorage.setItem('value', area.value); window.localStorage.setItem('timestamp', (new Date()).getTime()); |
Bases de datos locales
1 2 3 4 | var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); //5MB db.transaction(function(tx) { tx.executeSql("SELECT * FROM test", [], successCallback, errorCallback); }); |
Cache de aplicaciones
Permite cargar un documento una vez y utilizarlo después cuando no haya conexión a internet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <html manifest="cache.appcache"> --- window.applicationCache.addEventListener('updateready', function(e) { if (window.applicationCache.status == window.applicationCache.UPDATEREADY) { window.applicationCache.swapCache(); if (confirm('A new version of this site is available. Load it?')) { window.location.reload(); } } }, false); --- cache.appcache: CACHE MANIFEST # version 1.0.0 CACHE: /html5/src/logic.js /html5/src/style.css /html5/src/background.png NETWORK: * |
Web workers
Permiten iniciar hilos de ejecución paralelos, haciendo que las aplicaciones respondan mucho mejor.
1 2 3 4 5 6 7 8 9 10 | // En main.js: var worker = new Worker('task.js'); worker.onmessage = function(event) { alert(event.data); }; worker.postMessage('data'); // En tasks.js self.onmessage = function(event) { // Do some work. self.postMessage("recv'd: " + event.data); }; |
Web sockets
Permiten dejar establecida la comunicación con un servidor.
1 2 3 4 5 6 | var socket = new WebSocket('ws://html5rocks.websocket.org/echo'); socket.onopen = function(event) { socket.send('Hello, WebSocket'); }; socket.onmessage = function(event) { alert(event.data); } socket.onclose = function(event) { alert('closed'); } |
Notificaciones
Permiten mostrar un mensaje por fuera de la ventana del navegador, incluso cuando está minimizado.
1 2 3 4 5 6 | if (window.webkitNotifications.checkPermission() == 0) { window.webkitNotifications.createNotification(imagen, titulo, texto).show(); } else { window.webkitNotifications.requestPermission(); } |
Geo-locación
Permite preguntar al sistema operativo la ubicación geográfica del usuario.
1 2 3 4 5 6 7 8 | if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latLng = new google.maps.LatLng( position.coords.latitude, position.coords.longitude); var marker = new google.maps.Marker({position: latLng, map: map}); map.setCenter(latLng); }, errorHandler); } |
Ejercicios
- Programe un carrusel de imágenes usando html, css y javascript.
Taller HTML5
Esquema del curso
- Introducción a HTML y CSS.
- Introducción a Javascript.
- Programación gráfica con <canvas> y Javascript.
- Programación de aplicaciones estilo escritorio.
- HTML5 como sistema de desarrollo para aplicaciones móviles y de escritorio.
1. Introducción a HTML y CSS.
Definición
Hipertext Markup Language es un lenguage para anotar texto de manera que sea sintácticamente distinguible de ese texto. Es usado por los navegadores web para describir e interpretar documentos de texto, imágenes y sonido y presentarlos como páginas web audibles o visibles.
Guardar archivo codificando como UTF-8 en VIM
En lugar de usar el habitual :w se debe usar :w ++enc=utf8 y eso es todo :)
Para mas info: :help ++enc
Como usar fuentes de Mac (dfont) en Linux
Utilice fondu para convertir los archivos dfont en archivos ttf y luego utilice fontmanager para instalar las fuentes en formato ttf.
Como montar imágenes dmg en Linux
Primero, toca determinar si la imágen esta comprimida o no usando el comando file: $ file nombre_imagen.dmg. Si devuelve algo como VAX COFF executable not stripped – version 376, la imágen está comprimida. Si devuelve algo como Macintosh HFS Extended version 4 data, la imágen no está comprimida.
Para montar una imágen no compprimida:
1 2 | modprobe hfsplus mount -t hfsplus -o loop nombre_imagen.dmg /media/nombre_imagen |
Y para montar una que no esté comprimida:
1 2 3 | dmg2img -i nombre_imagen.dmg -o nombre_imagen-uncompressed.img modprobe hfsplus mount -t hfsplus -o loop nombre_imagen-uncompressed.img /media/nombre_imagen/nom |
Incrementar o decrementar un numero en VIM
Simplemente ponga el cursor sobre un número y <C-x> ó <C-a>.

