Archive

Archive for the ‘Ruby’ Category

RMagick4J: status update

February 27th, 2009 Serabe No comments

In first place, my apologies if the lack of a new release or new feature is disturbing someone.

Currently, I’m working on new effects and I need a good convolve method for them to work. In the begining, I tried to replicate the convolve method, but finally I prefer to use the ConvolveOp class, expanding the image previously for replicating some ImageMagick functionality about surrounding pixels (Java has only two options while ImageMagick has a few more). And here is the problem. I cannot get the bunch of code working. Maybe, I’m overlooking something; maybe I’m not. If I cannot get it working in two days or so, I will ask (or even cry) for help.

End of report.

article clipper RMagick4J: status update
 
share save 171 16 RMagick4J: status update
Categories: JRuby, Programming, Ruby Tags: , ,

If you are (un)happy with Ruby 1.8.7

February 12th, 2009 Serabe No comments

There are two interesting topics in the Ruby Forum being discussed right now. Both opened by George Brown (the guy behind Prawn). They are:

I’ve read every single message because backwards compatibility in Ruby 1.8.7 is something that I do not fully understand. It all started with this comment in Jaime’s blog. There, Jaime wondered if Ubuntu did the right thing by updating Ruby to 1.8.7, even if that version breaks rails (in fact, it did). Well, in this case, my humble opinion was yes, Ubuntu did well by updating Ruby. But now, let’s consider other things.

So far, I’ve seen two kind of complains against Ruby 1.8.7:

  • Coding working in 1.8.6 that doesn’t work in 1.8.7. I’ve been talking James Coglan about it, and the one of the errors was that his code relied on the order of the keys in a hash. But, there are other he hasn’t been able to fix, and is something regarding regular expression. I am unhappy with this kind of “new features”.
  • Other people is complaining about working code in 1.8.7 that does not work in 1.8.6. I really understand them, because they program really cool gems and they have to test if they have used not-valid-1.8.6 code. I wouldn’t care too much about but we must keep in mind that 1.8.7 is a minor release.

Finally, I just want to say that, as many people has pointed out before me, it would be better to migrate to 1.9.1. Common! It has been already released! Anyway, that’s not the point of the discussion. It is all about a minor release with too many changes (I’m not talking about bugfixes). Do I like the new things? Yes, I do (except some that I cannot really understand). Am I happy with Ruby 1.8.7? No, I’m not because it is suppose to be a minor version release and it is making too much noise.

article clipper If you are (un)happy with Ruby 1.8.7
 
share save 171 16 If you are (un)happy with Ruby 1.8.7

Why I like JRuby

November 7th, 2008 Serabe No comments

Some days ago Tom forwarded me an email from Mikael Lammentausta. Mikael found an issue with rmagick4j. Using this Mikael's script

RUBY:
  1. require 'rubygems'
  2. require 'gruff'
  3.  
  4.   def basic_graph()
  5.     g = Gruff::Line.new
  6.     g.theme = {
  7.       :colors => ['#7F0099', '#2F85ED', '#2FED09','#EC962F'],
  8.       :marker_color => '#aaa',
  9.       :background_colors => ['#E8E8E8','#B9FD6C']
  10.     }
  11.     g.hide_title = true
  12.  
  13.     g.legend_font_size = 12
  14.     g.marker_font_size = 16
  15.     g.hide_dots = false
  16.  
  17.     return g
  18.   end
  19.  
  20.  
  21.   def bmi(params={})
  22.     g = basic_graph()
  23.  
  24.     g.y_axis_label = 'BMI'
  25.  
  26.     bmis = [24.3, 23.9, 23.7, 23.7, 23.6, 23.9, 23.6, 23.7, 23.4, 23.4, 23.4, 22.9]
  27.  
  28.     g.data( 'BMI', bmis )
  29.     g.hide_legend = true
  30.     return g
  31.   end
  32.  
  33.  
  34. g=bmi
  35. g.write 'graph.jpg'

You get two different outputs.

graph 300x225 Why I like JRuby

MRI-generated

graph1 300x225 Why I like JRuby

JRuby

As you may see, the numbers are wrong in JRuby... or not.

Looking at gruff code, I saw the problem was in the label method.

RUBY:
  1. def label(value)
  2.   if (@spread.to_f % @marker_count.to_f == 0) || !@y_axis_increment.nil?
  3.     return value.to_i.to_s
  4.   end
  5.   if @spread> 10.0
  6.     sprintf("%0i", value)
  7.   elsif @spread>= 3.0
  8.     sprintf("%0.2f", value)
  9.   else
  10.     value.to_s
  11.   end
  12. end

The problem can be found in line 10. With a right input, you can make

RUBY:
  1. (@spread.to_f % @marker_count.to_f == 0) || !@y_axis_increment.nil?

false and have a @spread < 3.0. Then look at this code:

RUBY:
  1. i = 23.599999999999998
  2. puts i

In JRuby, you get what you expect 23.599999999999998 but, in MRI, you get 23.6. So, that was the problem. JRuby is more precise than MRI.

NOTE:
jruby 1.1.5 (ruby 1.8.6 patchlevel 114) (2008-11-03 rev 7996) [i386-java]
ruby 1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0]

article clipper Why I like JRuby
 
share save 171 16 Why I like JRuby
Categories: General, JRuby, Programming, Ruby Tags: , , ,

Problem 3

October 12th, 2008 Serabe No comments

Wording: (Original) The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

Solution:
First the code:

RUBY:
  1. include Math
  2. def prime_factors(num, factor=2)
  3.   return []  if num <= 1
  4.   next_pf = (factor..(sqrt(num).ceil)).find(lambda {num}){ |x| num%x == 0 }
  5.   return [next_pf] + prime_factors(num/next_pf, next_pf)
  6. end
  7.  
  8. puts prime_factors(600851475143).max

The code is a direct port from the one in PyEuler. It is based mainly in the idea that the first factor of a number is always prime.

Line 3 breaks recursion and line 4 works out the next prime factor (actually, it finds the smallest factor). For doing this, it uses find method. If no element match the criteria, then it returns the number (that is what the lambda block is for).

Finally, line 5 merges the results and line 8 print the result.

This time just one code is showed.

article clipper Problem 3
 
share save 171 16 Problem 3

RMagick4J 0.3.6

August 16th, 2008 Serabe No comments

I am glad to announce a new version of rmagick4j.

RMagick4J aims to implement the ImageMagick funcionality and the C
portions of RMagick for make it works in JRuby.

Current stable version: 0.3.6
Project URL: http://code.google.com/p/rmagick4j/
Installation: gem install rmagick4j

Google Summer of Code project should be thanked for making this new
release possible.

In release 0.3.6 you can find the next improvements:

  • More Draw primitives (clip-path [creatin a clip-path and using a
    clip-path], fill-rule, rotate, scale [reimplemented], skewX, slewY,
    stroke-linecap, stroke-linejoin, stroke-miterlimit, translate).
  • Solve a bug with transparent stroke and line primitive.
  • Added the following Draw instance methods:
    • annotate
    • get_multiline_type_metrics
  • Solved a bug that caused the background become black while resizing
    images with alpha channel.

Please try out your applications with rmagick4j and help us provide
feedback. It is our goal to make a fully-compatible implementation of
RMagick4j in JRuby.

article clipper RMagick4J 0.3.6
 
share save 171 16 RMagick4J 0.3.6

Sustituyendo a las animadoras con Ruby en Mac.

August 12th, 2008 Serabe No comments

El título del post puede sonar raro, pero lo que voy a mostrar hoy es cómo conseguir tu propia animadora en Mac con Ruby. Lo que haremos será hacer que nuestro ordenador, con una orden como:


ruby cheerleader.rb Serabe

Nos muestre por pantalla:


Dame una S
Dame una E
Dame una R
Dame una A
Dame una B
Dame una E
SERABE!!!

Además, utilizando el comando say de Mac, nos lo dirá (si queréis que lo grite, subid el volumen al máximo).

Empecemos con el código:

RUBY:
  1. string =  ARGV.join(' ')

Aquí simplemente recogemos los parámetros pasados por consola y los concatenamos con un espacio entre medias. Ahora la parte interesante:

RUBY:
  1. string.each_byte do |b|
  2.   if /[a-zA-Z]/ =~ b.chr
  3.     shout = 'Dame una '+b.chr.upcase
  4.     puts shout
  5.     `say #{shout}`
  6.   end 
  7. end

Para cada letra, una vez comprobado que es una letra y no un espacio, construimos un grito ('Dame una S'), lo imprimimos por pantalla y hacemos que el comando say lo diga.

Finalmente, con un

RUBY:
  1. puts string.upcase + '!!!'
  2.  
  3. `say #{string}`

Imprimimos la última frase.

Ya habéis visto cómo crearos vuestra propia cheerleader. En próximos episodios veremos cómo añadirle autoregeneración como Claire.

article clipper Sustituyendo a las animadoras con Ruby en Mac.
 
share save 171 16 Sustituyendo a las animadoras con Ruby en Mac.
Categories: Programming, Ruby Tags: , ,

RMagick: Dibujar con patrones

July 22nd, 2008 Serabe No comments

Una interesante cualidad de la clase Draw de RMagick es la posibilidad de definir patrones a través del método pattern.

En primer lugar, lo básico:

RUBY:
  1. require 'rubygems'
  2. require 'RMagick'
  3.  
  4. include Magick

Ahora definamos el patrón. Para ello, necesitamos cinco parámetros, el nombre, dos números que recomiendo ponerlos a cero (después de unas cuantas pruebas, no he notado diferencias notables) y después las dimensiones del patrón.

RUBY:
  1. draw = Draw.new
  2.  
  3. draw.pattern('circles', 0, 0, 10, 10) do
  4.   draw.stroke 'none'
  5.   draw.fill 'red'
  6.   draw.rectangle 0, 0, 10, 10
  7.   draw.stroke 'LightGreen'
  8.   draw.fill 'blue'
  9.   draw.circle 5, 5, 5, 0
  10. end

Ya, por último, dibujamos un cuadrado y lo plasmamos en una imagen de 300x300.

RUBY:
  1. draw.stroke 'circles'
  2. draw.stroke_width 25
  3.  
  4. draw.fill 'none'
  5.  
  6. draw.polygon 150,0, 300,150, 150,300, 0,150
  7.  
  8. img = Image.new 300, 300
  9.  
  10. draw.draw img
  11.  
  12. img.write 'pattern.jpg'

Obteniéndose el siguiente resultado:

pattern RMagick: Dibujar con patrones

Dibujo con patrón como brocha

article clipper RMagick: Dibujar con patrones
 
share save 171 16 RMagick: Dibujar con patrones

New RMagick4J release.

July 9th, 2008 Serabe 1 comment

RMagick aims to implement the ImageMagick funcionality and the C portions of RMagick for make it works in JRuby.

Current stable version: 0.3.5
Project URL: http://code.google.com/p/rmagick4j/
Installation: gem install rmagick4j

Google Summer of Code project should be thanked for making this new release possible.

In release 0.3.5 the following improvements have been made:

  • Implemented Draw primitives (affice, arc, pattern, path).
  • Improved Image and ImageList:
  • Implemented more of Pixel (from_HSL, to_HSL, <=>, fcmp, intensity).
  • Implemented the fill classes.
  • Added a side-by-side (MRI vs JRuby) image testing tool named Bullseye.
  • Added 680 color names. It can search, but not retrieve the name correctly capitalized.
  • Changed gem name from RMagick4J to rmagick4j.

This version should allow Gruff Graphs and Ruports to largely work without issues. Please try out your applications with rmagick4j and help us provide feedback. It is our goal to make a fully-compatible implementation of RMagick4j in JRuby.

article clipper New RMagick4J release.
 
share save 171 16 New RMagick4J release.

Ay, Serabe, que no haces nada ni tan siquiera regular.

May 18th, 2008 Serabe 3 comments

Hoy me he tirado unas cuatro horas para encontrar un bug, uno de estos puñeteros bichos que te atrapan y te dejan cosas como estas:
black Ay, Serabe, que no haces nada ni tan siquiera regular.
Para que os hagáis una idea, tenía que ser esto:
really black Ay, Serabe, que no haces nada ni tan siquiera regular.
Como se puede apreciar, son sensiblemente diferentes. Así que cuatro horas de mi vida han transformado lo primero, en lo segundo.

El problema venía en que, tal y como Tom (mi mentor del GSoC) propuso, se ha cambiado la clase PixelPacket de forma que ahora trabaja con enteros. El problema, mejor no os lo cuento que es más aburrido que lo anterior.

En fin, que hoy me voy a la cama con un ego más grande que el de Enrique Dans.

article clipper Ay, Serabe, que no haces nada ni tan siquiera regular.
 
share save 171 16 Ay, Serabe, que no haces nada ni tan siquiera regular.

Sweating blood

April 28th, 2008 Serabe No comments

Si alguno está investigando sobre las Stories de RSpec, y no consigue hacerlas funcionar, un

RUBY:
  1. require 'spec/story'

debería solucionarlo todo...

Joder lo que hace mi inutilidad y mi falta de documentación.

article clipper Sweating blood
 
share save 171 16 Sweating blood
Categories: Programming, Ruby Tags: , , , , ,
Improve the web with Nofollow Reciprocity.