Posted: August 12th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, linux | Tags: bluetooth, linux, Open Source, Programming | No Comments »
El año pasado Movistar había lanzado una campaña muy pedorra en el subte, en donde unos carteles en el piso te invitaban a prender tu Bluetooth y te enviaban un file. Lo que te enviaban era una simple imagen, con tanto texto que en mi celular era casi ilegible y no tenía consigna alguna.
Sin embargo esto sirvió para que me encaprichara y quisiera armar algo similar para la oficina, orientado a que un cliente que viene a una reunión se pueda llevar un regalo, que en este caso es un juego J2ME.
Hacerlo realmente es una boludez. El real problema, que no voy a tratar acá, es tener una placa Bluetooth soportada por Linux (creo que esta solución aplica Windows, pero no lo probé), lo que puede resultar complicado. Yo en mi anterior laptop fallé en cada intento. Hoy en día en mi MacBook anda todo out-of-the-box por suerte así que pude jugar un poco.
El protocolo que se utiliza para intercambiar cosas es Object Exchange (OBEX) y tenemos una excelente biblioteca llamada OpenObex. A nosotros nos interesa particularmente ObexFTP que nos da el File Transfer sobre Obex.
El primer problema que tuve es que en Jaunty no está el binding de ruby, por lo que me tuve que bajar el source y diff de Karmic y crear mis libobexftp-ruby_0.22-1_i386.deb y sus dependencias.
Salvando eso, con los ejemplos del wiki sale muy fácil. La biblioteca nos permite descubrir devices, abrir channels y enviar archivos en pocas líneas. Acá un en ruby ejemplo :
#!/usr/bin/env ruby
require 'obexftp'
puts "Scanning BT..."
intfs = Obexftp.discover(Obexftp::BLUETOOTH)
dev = intfs.first # Es un array, podríamos iterar sobre todas las encontradas
channel = Obexftp.browsebt(dev, Obexftp::PUSH)
cli = Obexftp::Client.new(Obexftp::BLUETOOTH)
puts cli.connectpush(dev, channel)
puts cli.put_file('ver.jpg')
puts cli.disconnect
Hacer lo mismo en Python, Perl o cualqueir otro lenguaje soportado es igual de simple.
Obviamente es muy minimalista: agarra el primer device encontrado, abre un channel para hacer un PUSH (si el device no soporta PUSH retorna -1 según creo), luego abre la conexión y le envía el archivo.
Desde el celular vemos un mensaje de que se está abriendo una conexión y luego el detalle de lo que se quiere enviar, nombre del archivo, tipo de archivo, tamaño, etc. Podemos aceptarlo o rechazarlo. De aceptarlo se descarga pero no se guarda ni se instala, es un paso extra que debemos decidir si lo hacemos o no.
Un problema que encontramos para enviar juegos es que algunos celulares están bloqueados para esa función (para así vendértelos por el portal WAP oficial de tu carrier). Ya lo pudimos probar con varios celulares Nokia, Motorola y Samsung y funciona razonablemente bien.
Sobre este ejemplo nosotros tenés un poco más de trabajo, ya que guardamos los device ID y el contenido enviado, así cuando volvés te damos un contenido diferente
. Si además no podés recibir el juego, te pasamos una imágen simpática
.
(Via El Futirifoken.) Original Link: Regalando cosas por Bluetooth
Posted: July 25th, 2009 | Author: FreedomCoder | Filed under: Uncategorized | Tags: News, Open Source, Programming, Windows | 8 Comments »
Hello Hello!
I’m happy to announce — 24 hours late on it — that the voting is over for the website contest I started last month for getting RubyInstaller (known as OneClick) a new home.
Thank all the designers who participated
First I would like to thank all the designers that contributed over the wiki with their design proposals and comments.
Thank you contributors
Second but no less important a huge thank you to all the members of the Ruby community that contributed money to the campaign over pledgie.
26 people donated 900 dollars!!!
The designer who created the selected design is going to receive all that.
Thank you!
Selection of the design
So, the polldaddy results:
With a total of 339 votes:
| Participant |
Votes |
% |
| Pavel Macek |
160 |
47% |
| Ben Alpert |
100 |
29% |
| Francesco Agnoletto |
43 |
13% |
| Thuva Tharma |
25 |
7% |
| Silviu Postavaru |
11 |
3% |
Congratulations Pavel Macek!
I must say that was hard choice to all who voted, I couldn’t personally decide which one to vote since each design focused on important aspects.
Thanks to the community
Thank everyone that spread the word over Twitter, blog posts and mailing lists.
What’s next?
Well, now getting in touch with designer and arrange the GitHub repository for him to publish the HTML and CSS of the designs.
Then, built it over Radiant application and deploy!
Over the past weeks Jon has been working on documentation, FAQ and collecting information at the GitHub wiki page.
Thanks Jon!
Once everything is in place, content will be ported/migrated to the new website.
When the final installers?
There are still some issues with own Ruby tests, but expect a newer preview release soon.
THANKS EVERYBODY WHO VOTED AND DONATED!
(Via DEV_MEM.dump_to(:blog) – Multimedia systems blog.) Original Link: RubyInstaller: Voting is over and the results are…
Posted: July 25th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, SQL | Tags: Open Source, Programming, SQL | No Comments »
I just released an updated version of SQLite3/Ruby, officially to RubyForge!
Read the news here
This release includes binaries for Windows, but not any kind of binary, but fat ones!
That means that using either 1.8 or 1.9 versions of Ruby you will be able to access SQLite3/Ruby bindings and script your craziest applications!
This also solves the major PITA for gem update that lot of user experienced in the past.
Don’t forget to read a getting started guide here
Now is time to hunt down MySQL gem author and politely ask him integrate my patches
(Via DEV_MEM.dump_to(:blog) – Multimedia systems blog.) Original Link: SQLite3/Ruby 1.2.5 Released!
Posted: July 23rd, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming | Tags: how-to, Open Source, Programming, twitter | No Comments »
Recently, I had to create a twitter live feed for a work I’m doing…. so I found the gems for searching in twitter, but all of them were working with the search.json api, but since my client wanted the same results that he saw in twitter.search.com, I created a lib for that project (following the gem example code), in order to use the search.atom api and parse the xml results with hpricot.
If you deal with the same problem, here you have the code
require ‘rubygems’
require ‘net/http’
require ‘cgi’
class Twitter
TWITTER_SEARCH_API_URL = ‘http://search.twitter.com/search.atom’
DEFAULT_TIMEOUT = 5
HEADERS = { “Content-Type” => ‘application/rss+xml’,
“User-Agent” => ‘twitter-search’ }
def self.search(opts)
search_for = ‘#twitter’
url = URI.parse(TWITTER_SEARCH_API_URL)
url.query = sanitize_query(opts)
ensure_no_location_operators(url.query)
req = Net::HTTP::Get.new(url.path)
http = Net::HTTP.new(url.host, url.port)
http.read_timeout = DEFAULT_TIMEOUT
res = http.start { |h| h.get(”#{url.path}?#{url.query}”, HEADERS) }
if res.code == ‘404′
raise “Twitter responded with a 404 for your query”
end
self.parse_search(res.body)
end
def self.sanitize_query(opts)
if opts.is_a? String
“q=#{CGI.escape(opts)}”
elsif opts.is_a? Hash
“#{sanitize_query_hash(opts)}”
else
raise “sanitique_query expects a String or a Hash”
end
end
def self.sanitize_query_hash(query_hash)
query_hash.collect{|key, value| “#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}” }.join(’&’)
end
def self.ensure_no_location_operators(query_string)
if query_string.include?(”near%3A”) ||
query_string.include?(”within%3A”)
raise “near: and within: are available from the Twitter Search web interface, but not the API. The API requires the geocode parameter. See dancroak/twitter-search README.”
end
end
def self.parse_search(body)
doc = Hpricot.parse(body)
entries = []
items = (doc/:entry)
items.each do |raw_item|
entry = {}
entry
(Via Rorra’s blog.) Original Link: rails twitter search using search.atom
Posted: July 17th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, how-to, rake | Tags: how-to, Open Source, Programming, rake | No Comments »
Problema: Quiero ejecutar un comando desde otro directorio en rake (por ejemplo, ejecutar un makefile que está en un subdirectorio).
Solución: Agrego al rakefile la posibilidad de ejecutar comandos en otro directorio. Para eso, al principio de mi rakefile puse:
require 'fileutils'
def sh_in_dir( dirname, *args, &block )
old_path = pwd
FileUtils.chdir( dirname )
sh( *args, &block )
FileUtils.chdir( old_path )
end
Happy hacking,
Aureliano.
(Via aurelianito.) Original Link: rake sh en otro directorio
Posted: July 15th, 2009 | Author: FreedomCoder | Filed under: Uncategorized | Tags: how-to, News, Open Source, Programming, Windows | No Comments »
A few days of silence in the middle, but definitely progress in Windows land… Readline, new packages and more news…
Pure-Ruby Readline for the win!
If was the case that under your environment every time you use IRB your CPU went crazy, you will be happy to hear that we found the problem.
More than just find it, we put our some money to it and paid Park Heesob (from win32utils project fame) to code a Pure-Ruby Readline library.
The crazy part is that works on 1.8, 1.9, on Windows and Linux!, even more crazy, it also worked under Rubinius!
The code is in GitHub here
Latest packages in RubyInstaller download page have replaced the GNU Readline binary with it, and IRB now works normally.
Ruby 1.9.1-p129 got out.
As announced in Ruby-Lang website (here) 1.9.1-p129 went out last week.
While test on Windows for either trunk and 1.9.1 branch still segfault, I decided to do another release of this and put the 7zip packages in the downloads page at RubyInstaller.
Yes, no official Windows Installer yet, still need to iron some quirks (mentioned in previous post here)
Again, you can download those from usual place
Moved to Windows 7
I definitely been one of the late adopters in OS changes. Been using Windows XP for work for the past 7 years (moved directly from Windows NT4) — yeah, love to skip versions.
So decided to install latest Release Candidate as main OS, and start using it. So far, the experience has been great.
Keep in mind that I rarely turned my laptop off or restarted it (even with XP). Sleep and hibernation are the two options I mostly use, and haven’t restarted the computer since installed Windows 7, so is good
The following is a list of things I noticed that will love to expand in other posts:
Mount Users in other partition, don’t keep with your system
Like on Linux, dedicate a partition to your personal files, so I did it for the user folder. Is tricky, but can be done. This ease the restoration process of the OS since you don’t need to worry about losing your personal files.
Set HOME
Ensure HOME get set to %HOMEDRIVE%@%HOMEPATH%@. This is to make RubyGems and Ruby expansion of @~@ will work properly (and avoid nasty issues with known scripts or gems).
Console 2 halts
For some reason, the combo of Console 2 and VIM when working with Git just halts, not accepting any input. This also affected IRB, which lead me to think that is readline related.
Anyhow, installed GVim and installed Fabio Akita’s vimfiles (instructions here)
Then, ensured Git uses it doing git config --global core.editor gvim
Hidden files behave as read only?
Found that Ruby and some programs don’t let you modify hidden files. They just return access denied.
This seems weird, since Notepad can edit those files without issues.
Will investigate further, seems a bad usage of Windows API.
Don’t pollute your system.
Put all your tools, DLLs and your scripts in your user folder. Mine is %HOME%\Tools\bin, add this to your User environment variables: %HOME%\Tools\bin, et voila!
Don’t copy files to system32 blindly, this includes SQLite3, MySQL or any of these tools, putting things there make things harder to find or update later.
Also, that requires Admin rights, which are annoying if you don’t have them (I have UAC to the highest value to avoid do any stuff that normal non-admin users will do).
See my Tools layout
Some gem issues and news
While doing the move to new OS, decided to build a few gems again, and maybe update them.
MySQL 5.1 and mysql gem are a nightmare, stick to 5.0 for now.
Yeah, it seems that mysql Ruby C Extension have several memory issues. Stick to 5.0 for know (or switch to DataMapper, I heard they got things working on Windows!)
Been working in my own fork to support MinGW properly. Check the code at GitHub:
http://github.com/luislavena/mysql-gem
Almost 100% cross-platform SQLite3 ruby gem!
Lot of progress on this, partially stolen from do_sqlite3 (and viceversa!)
My fork here is capable to build Windows binaries on Linux/OSX.
Ideas of making fat binaries are around, but I believe this can be worked out with some love to RubyGems (discussed last year).
Will make binaries of those gems this week.
So, what are you waiting for?
Start using it!, like Mike Hodgson that reported his success here
(Via DEV_MEM.dump_to(:blog) – Multimedia systems blog.) Original Link: RubyInstaller: Updated packages, and other news.
Posted: July 15th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming | Tags: Open Source, Programming, www | No Comments »
Hoy me pidieron agregar un Sitemap para uno de los trabajos que hicimos para el gobierno y me encontré con que los plugins que uso para esta tarea no me cerraban de forma cómoda. El problema es que este sitio tiene, además del contenido dinámico, muchas páginas estáticas que no puedo referenciar desde un modelo, por lo que debía forzarlas y era bastante molesto.
Buscando encontré una solución práctica para este caso (donde hay pocas páginas, menos de 1k) que usa un crawler para recorrer todo el sitio y obtener las URLs a agregar al sitemap. El script que presentan me sirvió, aunque tuve que hacerle algunos cambios menores.
El primer problema que tenía era que me agregaba páginas que no deben ir en un sitemap (ni ser indexadas) como las de login, recuperar clave, form de registración, etc. Por lo que tuve que modificar ligeramente el código para no seguir los enlaces que estuvieran marcados con rel="nofollow" y para eso modifiqué en el método extract_and_call_urls la última línea como sigue :
links.each{ |link|
extract_and_call_urls(link.href) unless
!can_follow?(link) || ignore_url?(link.href) ||
@visited_pages.include?(link.href)
}
Y definiendo el nuevo método :
def can_follow?(link)
return false if link.nil? ||
(link.attributes["rel"] && link.attributes["rel"].include?("nofollow"))
true
end
Entonces, cuando el crawler encuentra un enlace que el developer marcó que no debe seguirse en una indexación (esto es principalmente para los crawlers de los search engines) se ignora y no se agrega al sitemap.
El otro cambio menor fue que tenía algunas URLs con el path completo y por default siempre me agregaba al inicio el domain name, por lo que me quedaban URLs inválidas, por lo que hice la siguiente modificación :
# Antes
xml.loc(@starting_url + url)
# Después
xml.loc(url.include?(@starting_url) ? url : (@starting_url + url))
Una vez probado el script hice una tarea rake para poder correrla fácil desde un cronjob :
# lib/tasks/sitemap.rake
require 'lib/crawler'
desc "Generate the sitemap file"
task :sitemap => :environment do
start_url = ENV["URL"] || "http://localhost:3000"
Crawler.new(start_url, (ENV["CREDS"] if ENV["CREDS"]), ENV["QUIET"] || false, ENV["SITEMAP"] || false, ENV["DEBUG"] || false)
end
Y listo, lo último fue hacer un deploy y configurar un cron.dayli para que cree el sitemap actualizado :
rake sitemap URL=http://www.haciendoelcolon.buenosaires.gob.ar SITEMAP=true
Así una vez por día se actualiza el sitemap y se hace un ping a google para que sepa que debe pasar a reindexar el contenido.
Esto tiene varias desventajas (pero aún así para este sitio sirve a su propópito) :
- No se puede priorizar cada tipo de contenido fácilmente
- La fecha de última modificación es inexacta
- Carga el webserver para generar el sitemap
Código completo : crawler.rb
(Via El Futirifoken.) Original Link: Sitemaps vía crawling
Posted: July 14th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Security | Tags: Open Source, Programming, Ruby, Security | No Comments »
Finally, after weeks of work, the first stable Beta of ESearchy is up and running in github’s gem repository.
Esearchy is a small library capable of searching the internet for email addresses. Currently, the supported search methods are engines such as Google, Bing, Yahoo, PGP servers, GoogleGroups, Linkedin, etc , but I intend to add many more.
Also, the library searches inside .pdf, .docx, .xlsx, .pptx, asn and .txt files for emails addresses and adds them to the list of found accounts. Finally, we have support for .docs files but for now only in Windows Platforms. (For more information visit: Github .
In order to install it you simple add the repository and then install the gem, as shown below.
-
> gem sources -a http://gems.github.com
-
> gem install FreedomCoder-esearchy
Once the gem is installed, you can create a new search opening and/or use the “esearchy” CLI tool but it’s really basic so far and it does not has all of the plugins.
-
require ‘esearchy’
-
-
ESearchy::LOG.level = ESearchy::APP #Output to the stdout.
-
-
ESearchy.create "domain.com" do |d|
-
d.yahoo_key = "yourAPIkeygoeshere"
-
d.bing_key = "yourAPIkeygoeshere"
-
# if you want to also look in LinkedIn
-
d.company_name "Company Name"
-
#A user is needed in order to search within Linkedin
-
d.linkedin_credentials "myuser@linkedin.com", "mypwd"
-
d.maxhits = 50
-
d.search
-
d.save_to_file "company_emails.txt"
-
end
If you have any comments, issues or want to submit a bug please do so on
http://github.com/FreedomCoder/esearchy/issues
Hopefully it will be useful to you.
(Via 自由編碼人.) Original Link: First stable beta of ESearchy is out!
Posted: July 13th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming | Tags: Open Source, Programming, www | No Comments »
While programming Esearchy I had to create a simple class to retrieve random user agents. You may say but why you would want something like this, and the answer is simple:
“Try to trick the search engines, so they would not block me”.
Yeah, I know this might not even works, but it’s still cool. =D
Well here it goes
Use it at your own discretion and listen to your ghost …
(Via 自由編碼人.) Original Link: Random User Agents
Posted: July 13th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Rails | Tags: Open Source, Programming, Rails | No Comments »
Este es el primer post de una serie que he decidido comenzar titulada “Analizando commits de rails edge”. Aclaro que los post no van a tener orden alguno y que voy a comentar los que me llaman la atención a _mí_
.
En este caso el commit se trata de agregar a rails la nueva forma de interpolación de strings que trae ruby 1.9 ( la idea es que se pueda usar con versiones menores también), pueden ver el código en este archivo:
activesupport/lib/active_support/core_ext/string/interpolation.rb
Cómo uds sabrán en Ruby se pueden interpolar strings de la siguiente manera:
>>"%s, %s" % ["Masao", "Mutoh"]
=> "Masao, Mutoh"
Cómo lo explica el comentario en el código:
# call-seq:
# %(arg)
# %(hash)
#
# Format - Uses str as a format specification, and returns the result of applying it to arg.
# If the format specification contains more than one substitution, then arg must be
# an Array containing the values to be substituted. See Kernel::sprintf for details of the
# format string. This is the default behavior of the String class.
# * arg: an Array or other class except Hash.
# * Returns: formatted String
# Example:
# "%s, %s" % ["Masao", "Mutoh"]
#
# Also you can use a Hash as the "named argument". This is recommended way so translators
# can understand the meanings of the msgids easily.
# * hash: {:key1 => value1, :key2 => value2, ... }
# * Returns: formatted String
# Example:
# For strings.
# "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
#
# With field type to specify format such as d(decimal), f(float),...
# "%d, %.1f" % {:age => 10, :weight => 43.4}
Es decir que ahora podemos interpolar strings de la siguiente manera:
>> "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
ArgumentError: malformed format string - %{
from (irb):2:in `%'
from (irb):2
>>
Auuuchh! estoy probando con un irb con ruby 1.8.6, así que necesito requerir el archivo:
>> require 'activesupport/lib/active_support/core_ext/string/interpolation.rb'
=> true
>> "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
=> "Masao, Mutoh"
Ahora sí! podemos interpolar string nombrados pasando un hash como argumento, Hermoso!
Estuve mirando en los fuentes de Ruby 1.9 y no encuentro dónde está escrita esta nueva funcionalidad, el método que define la interpolación con”%” es rb_str_format_m y está en la línea número 1202 del archivo string.c en el trunk de ruby, pero sólo está la vieja forma de interpolación. Entonces dónde está ? Alguien sabe?
Es más hice esta prueba:
$ irb1.9
require 'activesupport/lib/active_support/string/interpolation.rb'
=> true
irb(main):002:0> "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
ArgumentError: malformed format string - %{
from (irb):2:in `%'
from (irb):2
from /usr/bin/irb1.9:12:in `'
Y la versión que tengo de ruby 1.9 es:
ruby 1.9.0 (2008-06-20 revision 17482) [i486-linux]
Un poco vieja, probemos con ruby 1.9 compilado desde trunk
ruby 1.9.2dev (2009-07-11 trunk 24027) [i686-linux]
./ruby -e 'puts "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}'
Masao, Mutoh
Funcionó! entonces en algún lugar tiene que estar.

(Via Gastón Ramos – Ruby, Rails….) Original Link: Rails edge, Ruby 1.9 style String interpolation support