Site mainly dedicated to diffusion of Ruby/RoR, Security, Evolutionary Algorithms and BSD/GNU Linux Operating Systems.
martes, 30 de septiembre de 2014
Agile update the records for clients public ip address
The main goal of this project is to update the client record dinamically for the ip address and name in a secure environment. In many cases, you have many servers in different places and they don't have and ip public address, it's important to know the current ip public address for a client because you need do many administration tasks like backups, updates etc.
You can visit the project in github repository:
https://github.com/cmonterrosa/agile_update_public_address
miércoles, 16 de enero de 2013
How install Java 6 JDK on Ubuntu 12.04
First, it's important to create the file for add ppa repositories, you can make a file called :
#!/bin/bash
if [ $# -eq 1 ]
NM=`uname -a && date`
NAME=`echo $NM | md5sum | cut -f1 -d" "`
then
ppa_name=`echo "$1" | cut -d":" -f2 -s`
if [ -z "$ppa_name" ]
then
echo "PPA name not found"
echo "Utility to add PPA repositories in your debian machine"
echo "$0 ppa:user/ppa-name"
else
echo "$ppa_name"
echo "deb http://ppa.launchpad.net/$ppa_name/ubuntu precise main" >> /etc/apt/sources.list
apt-get update >> /dev/null 2> /tmp/${NAME}_apt_add_key.txt
key=`cat /tmp/${NAME}_apt_add_key.txt | cut -d":" -f6 | cut -d" " -f3`
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys $key
rm -rf /tmp/${NAME}_apt_add_key.txt
fi
else
echo "Utility to add PPA repositories in your debian machine"
echo "$0 ppa:user/ppa-name"
fi
after, you should move this file
Add the ppa repo
Update the list
Install the packets:
cmonterrosa@server:/tmp$touch add-apt-repository#!/bin/bash
if [ $# -eq 1 ]
NM=`uname -a && date`
NAME=`echo $NM | md5sum | cut -f1 -d" "`
then
ppa_name=`echo "$1" | cut -d":" -f2 -s`
if [ -z "$ppa_name" ]
then
echo "PPA name not found"
echo "Utility to add PPA repositories in your debian machine"
echo "$0 ppa:user/ppa-name"
else
echo "$ppa_name"
echo "deb http://ppa.launchpad.net/$ppa_name/ubuntu precise main" >> /etc/apt/sources.list
apt-get update >> /dev/null 2> /tmp/${NAME}_apt_add_key.txt
key=`cat /tmp/${NAME}_apt_add_key.txt | cut -d":" -f6 | cut -d" " -f3`
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys $key
rm -rf /tmp/${NAME}_apt_add_key.txt
fi
else
echo "Utility to add PPA repositories in your debian machine"
echo "$0 ppa:user/ppa-name"
fi
after, you should move this file
cmonterrosa@server:/tmp$ sudo cp add-apt-repository /usr/sbin/Add the ppa repo
sudo add-apt-repository ppa:flexiondotorg/javaUpdate the list
sudo apt-get updateInstall the packets:
sudo apt-get install sun-java6-jdk sun-java6-pluginmartes, 8 de enero de 2013
OpenBSD pf vs Linux iptables: A Comparison
This weekend, I decided it would be a good idea to turn my Linux router/firewall into an OpenBSD router/firewall. Clockfort recommended it, so I decided to grab backups of my iptables rules, install OpenBSD, and learn pf.
I learned iptables about a year ago, when I first built this router/firewall. It acts like those little home gateways that you get; it does NAT, DHCP, DNS, etc. I've also used iptables to firewall my desktop and laptop (though those rule sets were significantly simpler than the firewall).
iptables doesn't have any of that. iptables are primarily populated through the iptables command. You can use iptables-save and iptables-restore to save and load iptables rules from a file. The file is basically a bunch of iptables commands with the iptables bit omitted. Another alternative is to write a bash script that loads your iptables rules one by one. That option gives you the benefit of using variables so that it's trivial to change IPs or similar.
I used iptables-save and restore to configure my iptables rules, and just wrote rules to that file in a similar syntax when I wanted to reconfigure parts of my firewall.
With pf, packets traverse the flat pf.conf file. Even if a packet matches a rule, it continues to process the packet all the way down the configuration file. Only if a rule contains the "quick" option does pf stop processing and take action before hitting the end of the rule set. If a packet makes it all the way to the end of the config file, the last action specified from a rule that matched that packet is taken.
With iptables, packets are processed by various chains in different order, depending on the source and destination in the packet. For example, normal outgoing packets are processed by the OUPUT chain on the filter table. Various rules within that chain may cause processing to hop over to a different set of rules on a user-defined chain, or might take action on a packet. When a packet matches a rule description, processing on that chain stops immediately, and the action is taken.
pf, you can change tables, variables, lists and anchors on the fly. Anchors are a really cool feature of pf. They are basically sub-rulesets that have names. So if you define an anchor somewhere in your ruleset, you can call pfctl and totally redefine the rules within that anchor. You can even write anchors to files, and load them from different files.
iptables can do all of the same stuff. However with iptables, you can load all sorts of modules that do far more intensive filtering than pf. You can filter based on state (no, you can't filter based on state in pf), where they are (geoip), time, statistics, ToS, and much more. There are so many target extensions for iptables, it is ridiculous. And if that isn't enough, you can pass the packet into userspace and write a script to filter it further there.
With iptables, all of your packets pass through all of your rules. This can really slow things down, especially if you have complicated rulesets. If you use all sorts of crazy iptables modules, that will slow it down pretty heavily too. And if you pass the packet into userspace for further processing, it will slow it down even more.
Configuration
The first notable difference between pf and iptables: pf has a config file! It also has variables, lists and tables that you can manually populate which ease configuration. You can even include other config files in case you need to split your config for whatever reason. When you're done modifying the config file, just call pfctl -f /etc/pf.conf and it'll load that rule set and start filtering.iptables doesn't have any of that. iptables are primarily populated through the iptables command. You can use iptables-save and iptables-restore to save and load iptables rules from a file. The file is basically a bunch of iptables commands with the iptables bit omitted. Another alternative is to write a bash script that loads your iptables rules one by one. That option gives you the benefit of using variables so that it's trivial to change IPs or similar.
I used iptables-save and restore to configure my iptables rules, and just wrote rules to that file in a similar syntax when I wanted to reconfigure parts of my firewall.
Rule Processing
The next most obvious way they differ is how they process rules. iptables has various tables, each with different chains that packets traverse, whereas pf just processes packets straight down the config file.With pf, packets traverse the flat pf.conf file. Even if a packet matches a rule, it continues to process the packet all the way down the configuration file. Only if a rule contains the "quick" option does pf stop processing and take action before hitting the end of the rule set. If a packet makes it all the way to the end of the config file, the last action specified from a rule that matched that packet is taken.
With iptables, packets are processed by various chains in different order, depending on the source and destination in the packet. For example, normal outgoing packets are processed by the OUPUT chain on the filter table. Various rules within that chain may cause processing to hop over to a different set of rules on a user-defined chain, or might take action on a packet. When a packet matches a rule description, processing on that chain stops immediately, and the action is taken.
Dynamic Modification
pf really just owns iptables here. To dynamically update your rules with iptables, you just write new rules on the fly. If you want to do a bunch, you would write a bash script to delete some rules, and write new ones.pf, you can change tables, variables, lists and anchors on the fly. Anchors are a really cool feature of pf. They are basically sub-rulesets that have names. So if you define an anchor somewhere in your ruleset, you can call pfctl and totally redefine the rules within that anchor. You can even write anchors to files, and load them from different files.
Packet Filtering
pf is pretty simple concerning what it can filter for. It can filter based on protocol, TCP flags, source IP, destination IP, interface, and port. There is also some slightly more advanced filtering, like antispoof, unicast reversing, and passive operating system finger printing. For the majority of situations, this kind of firewall control is fine.iptables can do all of the same stuff. However with iptables, you can load all sorts of modules that do far more intensive filtering than pf. You can filter based on state (no, you can't filter based on state in pf), where they are (geoip), time, statistics, ToS, and much more. There are so many target extensions for iptables, it is ridiculous. And if that isn't enough, you can pass the packet into userspace and write a script to filter it further there.
Performance
pf is fast. I said before that you can't filter packets in pf based on state. That doesn't mean that pf isn't a stateful firewall. It definitely recognizes state, as it passes packets that are part of an established connection without even processing them with pf. This means the majority of your packets skip your firewall rules entirely. This isn't nearly as insecure as it sounds, since most iptables rulesets pass packets that are part of an established state anyway. It definitely has the distinct advantage of making it faster though.With iptables, all of your packets pass through all of your rules. This can really slow things down, especially if you have complicated rulesets. If you use all sorts of crazy iptables modules, that will slow it down pretty heavily too. And if you pass the packet into userspace for further processing, it will slow it down even more.
Conclusion
pf and iptables are both great firewalling solutions, but cater to people of different needs. pf is ridiculously fast, but lacks some of the more avanced features of iptables. Since my router/firewall box doesn't really need those advanced iptables features, and since it needs to be fast, I'm gonna stick with pf for now.jueves, 26 de julio de 2012
RbConfig - accessing your Ruby Environment
RbConfig is a useful library that comes with your Ruby installation.
These are just a few examples. RbConfig::CONFIG contains a lot of information about the environment.
jueves, 10 de noviembre de 2011
Login into Redmine using Mac OS X Open Directory
I was looking information about how connect my a Redmine Application (Tracker Issues) to my own Open Directory on Mac OS X Server, and there are a few lines about it. I write the variables for configuring easy and quick.
Name: OpenDirectory
Host: My-Server_Ip or DNS Name
Port: 636 (I'm using over SSL)
Account: uid:diradmin,cn=users,dc=domain,dc=com,dc=mx
password: ******
DN Base: cn=users;dc=domain,dc=com,dc=mx
On-the-fly user creation = yes
Attributes
Login: uid
FirstName: cn
LastName: sn
Email: mail
Name: OpenDirectory
Host: My-Server_Ip or DNS Name
Port: 636 (I'm using over SSL)
Account: uid:diradmin,cn=users,dc=domain,dc=com,dc=mx
password: ******
DN Base: cn=users;dc=domain,dc=com,dc=mx
On-the-fly user creation = yes
Attributes
Login: uid
FirstName: cn
LastName: sn
Email: mail
miércoles, 29 de junio de 2011
Installing RMagick on Mac OS X Snow Leopard
This used to be quite a complicated task to install ImageMagick and RMagick from source, but these days (thanks to some great work by others) it’s easy…
First install ImageMagick using this install script hosted on github (http://github.com/masterkain/ImageMagick-sl):
Now simply sit back and wait. (Oh, you’ll need to enter your password at some points as the libraries are installed into /usr/local).
Then, once that’s done, RMagick is installed by:
First install ImageMagick using this install script hosted on github (http://github.com/masterkain/ImageMagick-sl):
cd ~/src
git clone git://github.com/masterkain/ImageMagick-sl.git
cd ImageMagick-sl
sh install_im.sh
Now simply sit back and wait. (Oh, you’ll need to enter your password at some points as the libraries are installed into /usr/local).
Then, once that’s done, RMagick is installed by:
gem install rmagick
lunes, 14 de marzo de 2011
Deploy Applications with Mongrel Cluster for Ruby on Rails
INSTALL MONGREL CLUSTER
sudo apt-get install ruby1.8-dev
sudo gem install -y mongrel mongrel_cluster
Installing RMagick on Ubuntu 9.04 (Jaunty)
sudo apt-get install libmagickwand-dev imagemagick
sudo gem install rmagick
Ruby :: The bundled mysql.rb driver has been removed from Rails 2.2
sudo apt-get install libmysqlclient-dev
sudo gem install mysql
sábado, 20 de febrero de 2010
Easy Groups Authentication in Ruby on Rails using before_filter
first It's necessary to create two new tables: a table called groups with the fields (id, groupname, description) and other table called systables, with the fields (id, group_id, controller). Then create a file login_system.rb in the Lib folder under the main project. This file it's the library for send a filter to "before_filter" method in a rails controller. the modified code it's above:
finally, in a controller write a line like this:
require_dependency "user"
module LoginSystem
protected
def autorizado?(user, controller)
@usuario= User.find(user)
@grupo = @usuario.grupo.id.to_i
@systable = Systable.find(:all, :conditions => ["grupo_id = ? and controller = ?", @grupo, controller])
if @systable.empty?
return false
else
return true
end
end
#------ Group permissions ------------
def check_permissions
if not protect?(action_name)
return true
end
if @session['user'] and autorizado?(@session['user'], controller_name)
return true
end
store_location
access_denied
return false
end
# overwrite if you want to have special behavior in case the user is not authorized
# to access the current operation.
# the default action is to redirect to the login screen
# example use :
# a popup window might just close itself for instance
def access_denied
redirect_to :controller=>"/account", :action =>"login"
end
# store current uri in the session.
# we can return to this location by calling return_location
def store_location
@session['return-to'] = @request.request_uri
end
# move to the last store_location call or to the passed default one
def redirect_back_or_default(default)
if @session['return-to'].nil?
redirect_to default
else
redirect_to_url @session['return-to']
@session['return-to'] = nil
end
end
finally, in a controller write a line like this:
class CatalogosController < ApplicationController
before_filter :check_permissions
end
jueves, 18 de febrero de 2010
Disable USB devices on GRUB in Ubuntu 9.10 Karmic Koala
For security it's important to disable all usb devices for not get out information, then I write a small bash script that do it. I hope that work succesfully.
#!/bin/bash
cp /etc/default/grub /tmp && cd /tmp
sed 's/splash/splash nousb/g' grub > grub.2 && sudo mv grub.2 /etc/default/grub
echo "Disable USB on GRUB..."
jueves, 3 de diciembre de 2009
Generate new certificate for jabber server on OpenBSD
Modify the configuration file
Modify the line for set certificate value before load the configuration file
In the command line generate the key
Finally restart the service
sudo vi /etc/ejabberd/ejabberd.cfgModify the line for set certificate value before load the configuration file
[{5222, ejabberd_c2s, [{access, c2s},
{max_stanza_size, 65536},
starttls_required, {certfile, "/etc/ejabberd/server.pem"},
{shaper, c2s_shaper}]},
In the command line generate the key
openssl req -new -x509 -newkey rsa:1024 -days 3650 \
-keyout privkey.pem -out server.pem
openssl rsa -in privkey.pem -out privkey.pem
cat privkey.pem >> server.pem
rm privkey.pem
Finally restart the service
sudo ejabberctl restart
lunes, 23 de noviembre de 2009
Active Record Without Rails and PostgreSQL
a script for connect a database and copy a single table in two tables, copy and save with the .rb extension for execute with Ruby, for example "inicio2tablas.rb" and run in a command line
cmonterrosa@dibd02:~$ ./inicio2tablas.rb mydatabase myhost #!/usr/bin/ruby -w
require 'rubygems'
require 'active_record'
#--------- Carlos Augusto Monterrosa Lopez / cmonterrosa@gmail.com
def usage
STDERR.puts "Uso:
#{File.basename $0} dbname host"
exit 1
end
usage if ARGV.size != 2
dbname = ARGV[0]
host = ARGV[1]
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:database => dbname,
:username => 'your-user',
:password => 'your-password',
:encoding => 'utf8',
:host => host )
#------ Declaramos las clases para mapear las tablas --------
class Inicio < ActiveRecord::Base
set_table_name :inicio
end
class Palabra < ActiveRecord::Base
set_table_name :palabras
has_many :significados
end
class Significado < ActiveRecord::Base
set_table_name :significados
belongs_to :palabra
end
puts "Cargando palabras..."
@contador=0
@inicio= Inicio.find(:all)
@inicio.each do |inicio|
@palabra = Palabra.create(:palabra => inicio.palabra,
:abreviatura => inicio.abreviatura)
@contador+=1
#------------ Vinculamos los significados -------------
(1..12).each do |num|
next if inicio["significado#{num}"].nil? || inicio["significado#{num}"].empty?
@palabra.significados.create(:significado => inicio["significado#{num}"])
end
end
puts "Finalizo la carga de palabras.."
puts "Total: #{@contador}"
Etiquetas:
active record,
Carlos Augusto Monterrosa Lopez,
postgresql,
ruby on rails
viernes, 16 de octubre de 2009
How to migrate MySQL backup to PostgreSQL
Hi, the first step is generate a dump with all data from your mysql database. for example. I am working in Ubuntu 8.04 Hardy Heron
enter your password and mysqldump generate a file with the BD backup. then you have tu run the script to format this file.sql into postgresql valid format.
This script is available in:
http://pgfoundry.org/frs/download.php/1535/mysql2pgsql.perl
where file-pgsql.sql is the file valid for introduce the schema and data into postgresql.Now we are going to restore the schema and the rows.
where -h option is host, in this case is the localhost, -d is the database and -U is the owner of the database.
Comments with
Carlos Augusto Monterrosa Lopez
cmonterrosa@gmail.com / cmonterrosa@sef-chiapas.gob.mx
cmonterrosa@dibd02:~$ mysqldump dbname > file.sql -u root -p
enter your password and mysqldump generate a file with the BD backup. then you have tu run the script to format this file.sql into postgresql valid format.
This script is available in:
http://pgfoundry.org/frs/download.php/1535/mysql2pgsql.perl
cmonterrosa@dibd02:~$ perl mysql2pgsql.perl file.sql file-pgsql.sql
where file-pgsql.sql is the file valid for introduce the schema and data into postgresql.Now we are going to restore the schema and the rows.
cmonterrosa@dibd02:~$ psql -h localhost -d diccionarios -U cmonterrosa -W
where -h option is host, in this case is the localhost, -d is the database and -U is the owner of the database.
Comments with
Carlos Augusto Monterrosa Lopez
cmonterrosa@gmail.com / cmonterrosa@sef-chiapas.gob.mx
Etiquetas:
Carlos Augusto Monterrosa,
MySQL,
Mysqldump,
postgresql,
sef-chiapas.gob.mx
martes, 29 de septiembre de 2009
GLOBAL AND LOCAL SELECTION IN DIFFERENTIAL EVOLUTION FOR CONTRAINED NUMERICAL OPTIMIZATION
Global and Local Selection in Differential Evolution for Constrained Numerical Optimization
Efrén Mezura-Montes and Carlos A. Monterrosa López
ABSTRACT
The performance of two selection mechanisms used in the most popular variant of differential evolution, known as DE/rand/1/bin, are com- pared in the solution of constrained numerical op- timization problems. Four performance measures proposed in the specialized literature are used to analyze the capabilities of each selection mech- anism to reach the feasible region of the search space, to find the vicinity of the feasible global op- timum and the computational cost (measured by the number of evaluations) required. Two para- meters of the differential evolution algorithm are varied to determine the most convenient values. A set of problems with different features is cho- sen to test both selection mechanisms and some findings are extracted from the results obtained.
Keywords: Constrained Numerical Optimiza- tion, Differential Evolution, Selection Mecha- nisms.
THE PAPER WAS PUBLISHED AT "Journal of Computer Science & Technology", in October 2009
AND YOU CAN DOWNLOAD HERE
Efrén Mezura-Montes and Carlos A. Monterrosa López
emezura@lania.mx
cmonterrosa@gmail.com
Laboratorio Nacional de Informática Avanzada (LANIA A.C.) Rébsamen 80, Centro, Xalapa, Veracruz, 91000
Instituto Tecnológico de Tuxtla Gutiérrez
Depto. de Ingeniería en Sistemas Computacionales
Carretera Panamericana Km. 1080, Tuxtla Gutiérrez, Chiapas
ABSTRACT
The performance of two selection mechanisms used in the most popular variant of differential evolution, known as DE/rand/1/bin, are com- pared in the solution of constrained numerical op- timization problems. Four performance measures proposed in the specialized literature are used to analyze the capabilities of each selection mech- anism to reach the feasible region of the search space, to find the vicinity of the feasible global op- timum and the computational cost (measured by the number of evaluations) required. Two para- meters of the differential evolution algorithm are varied to determine the most convenient values. A set of problems with different features is cho- sen to test both selection mechanisms and some findings are extracted from the results obtained.
Keywords: Constrained Numerical Optimiza- tion, Differential Evolution, Selection Mecha- nisms.
THE PAPER WAS PUBLISHED AT "Journal of Computer Science & Technology", in October 2009
AND YOU CAN DOWNLOAD HERE
jueves, 10 de septiembre de 2009
How to convert iso-8859-1 into utf-8-charset files
the solution:
using bash shell and using Linux - of course !
iconv --from-code=ISO-8859-1 --to-code=UTF-8 ./oldfile.htm > ./newfile.html
using bash shell and using Linux - of course !
jueves, 13 de agosto de 2009
ActiveRecord::StatementInvalid customize messages
I tried to customize the active record error messages on Rails project, and I was boring to find the answer, the simple way of have my personal messages is use a begin rescue block, an example is above, I am working with RoR 1.26 and PostgreSQL.
The function is delete_row and is in application.rb (Global controller)
The function is delete_row and is in application.rb (Global controller)
#---- written by Carlos Augusto Monterrosa Lopez
def delete_row(row)
begin
row.destroy
flash[:notice]="Row deleted"
redirect_to :action => 'list', :controller => "#{params[:controller]}"
rescue
flash[:notice]="Here you personal error message"
redirect_to :action => 'list', :controller => "#{params[:controller]}"
end
end
jueves, 23 de julio de 2009
solaris ps
solaris ps
Was trying to find a specific process to kill today on a solaris machine at work.
and then select the process id (pid) and kill them
Was trying to find a specific process to kill today on a solaris machine at work.
ps -ef | grep Process
and then select the process id (pid) and kill them
sudo kill pid
lunes, 20 de julio de 2009
Error Please install the postgresql adapter: `gem install activerecord-postgresql-adapter
I'm installing postgresql adapter for Ruby on Rails 1.2.6 and I found this error for create a model, then I installed 2 files, I am working on Ubuntu 8.04 Hardy Heron, I only write:
I can create a model and database migration.
comments at cmonterrosa at gmail.com
sudo apt-get install libdbi-ruby1.8 libpgsql-ruby1.8 ruby1.8-devI can create a model and database migration.
comments at cmonterrosa at gmail.com
Etiquetas:
active record,
carlos monterrosa,
postgresql,
rails,
RoR
sábado, 13 de junio de 2009
Writing Latex Documents with Ruby
I worked in my thesis about Evolutionary Algorithms, and in the job I worked in Ruby Language, then I want to share with the community the mix of the technologies.
The source code is above:
The source code is above:
#!/bin/ruby -w
#Carlos Augusto Monterrosa Lopez -------- cmonterrosa@gmail.com ----
#------------- Compilador para codigo de latex -----------------
#------ Funcion que identifica al caracter ------------------
def identifica(caracter)
case caracter
when /[0-9]/
#print "#{caracter} = Numero\n"
return "numero"
when /[a-z]|[A-Z]/
#print "#{caracter} = alfanumerico\n"
return "letra"
when /$/
#print "#{caracter} = delimitador\n"
return "delimitador"
when /\s/
return "espacio"
end
end
#----------- Etapa de lexico ----------------------
def lexico
archivo='C:\texto.txt'
@palabra=Hash.new
@palabras=[]; @numeros=[]
File.open(archivo,"r").each{|line|
line= line.strip.split(//)
@palabra_string=""
@numeros_string=""
break if line.empty?
for caracter in line
if caracter[0] == 32
@palabra[:palabra]=@palabra_string if @palabra_string!= ""
@palabra[:tipo]="palabra" if @palabra_string != ""
#------- numeros -----------
@palabra[:palabra]=@numeros_string unless @numeros_string==""
@palabra[:tipo]="numero" unless @numeros_string == ""
@palabras << @palabra unless @palabra.empty?
@palabra_string=""
@numeros_string=""
@palabra={}
else
case identifica(caracter)
when "letra"
@palabra_string = (@palabra_string + caracter).to_s
when "numero"
@numeros_string = (@numeros_string + caracter).to_s
end
end
end #cierra el for
if @palabra_string!=""
@palabra[:palabra]=@palabra_string
@palabra[:tipo] = "palabra"
@palabra_string = ""
end
if @numeros_string!=""
@palabra[:palabra]=@numeros_string
@palabra[:tipo] = "numero"
@numeros_string=""
end
@palabras << @palabra if @palabra.size == 2
@palabra={}
} #cierra ciclo principal de lineas
return @palabras
#---- Retorna un arreglo de palabras ----------
end
#---- El programa valida la siguiente sintaxis -----
#---- The ruby program validate the next sintax ----
# MARGEN SUPERIOR 30
# MARGEN INFERIOR 40
def sintaxis
@palabras_reservadas= %w{margen izquierdo derecho superior inferior titulo}
@palabras=lexico() #------ Mandamos a llamar a la etapa de lexico -------
#----------- Recorremos el archivo---------------
if @palabras[0].has_value?("margen") || @palabras[0].has_value?("MARGEN")
@palabras.delete_at(0)
if @palabras[0].has_value?("superior")
@palabras.delete_at(0)
if @palabras[0][:tipo]== 'numero'
@superior=@palabras[0][:palabra].to_i
@palabras.delete_at(0)
# ------------- empieza el segundo margen --------------
if @palabras[0].has_value?("margen")
@palabras.delete_at(0)
if @palabras[0].has_value?("inferior")
@palabras.delete_at(0)
if @palabras[0][:tipo]== 'numero'
@inferior=@palabras[0][:palabra]
@palabras.delete_at(0)
else
exit(1)
end
else
#puts "se esperaba la palabra inferior"
end
else #------------else del segundo margen
#puts "se esperaba el margen inferior"
end
else
#puts "sintaxis incorrecta debiste de poner un numero"
exit(1)
end
else
puts "sintaxis incorrecta"
exit(1)
end
@margen_string = '\marginsize{' + @superior.to_s + 'cm}{' + @inferior.to_s + 'cm}{3cm}{3cm}'
@palabras.each {|hash|
if @palabras_reservadas.include?(hash[:palabra].to_s)
#print "reservada "
else
#print "#{hash[:palabra]} "
end
}
else
#print "debe de empezar con la palabra margen"
end
end
#--------------- Definicion de clase y metodos para latex -----------
class LaTeX
def initialize()
@nesting = 0
@indent = " "
end
# Allows the user to change the default indenting (default is two spaces
# per nesting)
attr_accessor :indent
# Return the string for a newline
def newline()
return "\\\n"
end
# Return the string for a newline that won't break a page
def newline!()
return "\\*\n"
end
# Return a string for the LaTeX symbol
def latex()
return "\\LaTeX"
end
# Return a string for a comment, ended with a carriage-return
def comment(comment)
return "% #{comment}\n"
end
# Let % be an alternative way to specify a comment
alias_method :%, :comment #,
# Return an indented string, terminated by a newline if it isn't a comment
# that is already newline-terminated
def indent(str)
s = indent?(str)
if not s =~ /^\s*%.*\n/ then
s << "\n"
end
return s
end
# Return an indented string that is never newline-terminated
def indent?(str)
s = ""
@nesting.times do
s << @indent
end
s << str
return s
end
# Create a new LaTeX command
def newcommand(cmd, func)
method_missing("newcommand", "\\#{cmd}", func)
end
# Print a LaTeX command using the rules specified above
def method_missing(symbol, *args)
symbol = symbol.to_s.gsub('!', '*')
symbol = symbol.to_s.gsub('_star', '*')
nl = !(symbol =~ /(\?|_suppress)\*$/)
symbol = symbol.gsub('\?', '')
symbol = symbol.gsub('_suppress', '')
s = ""
if block_given? then
s << __begin__(symbol, *args) << __gen_newline__(nl)
nesting_tmp = @nesting
@nesting = @nesting.succ
s << proc.call()
@nesting = nesting_tmp
s << __end__(symbol) << __gen_newline__(nl)
else
s << indent?("\\#{symbol}#{__arg_list__(args)}#{__gen_newline__(nl)}")
end
return s
end
alias_method :__cmd__, :method_missing
alias_method :__env__, :method_missing
# Return the arguments of a LaTeX function; Use an array to specify
# optional arguments
def __arg_list__(args)
s = ""
args.each do |arg|
case arg
when Array
s << "["
arg.each do |a|
s << "#{a},"
end
s.chop!
s << "]"
else
s << "{#{arg}}"
end
end
return s
end
# Return a newline if nl is true, otherwise return an empty string
def __gen_newline__(nl)
return nl ? "\n" : ""
end
def __begin__(symbol, *args)
return indent?("\\begin{#{symbol}}#{__arg_list__(args)}")
end
def __end__(symbol)
return indent?("\\end{#{symbol}}")
end
end
def lee_archivo
archivo='C:\texto.txt'
@cadena= String.new
File.open(archivo,"r").each{|line| @cadena = @cadena + line.strip.to_s }
return @cadena
end
#----------- Ciclo principal -------------
sintaxis()
@conjunto_palabras = ""
@palabras.each{|palabra|@conjunto_palabras = @conjunto_palabras + " " + palabra[:palabra].to_s}
l = LaTeX.new
s =
l.documentclass("article") +
l.newcommand("foo", l.latex) +
'\usepackage{anysize}' + "\n" +
@margen_string + "\n" +
l.newenvironment("myitemize", l.__begin__("itemize"), l.__end__("itemize")) +
l.document {
l.title("#{l.LARGE?} Esta es una prueba") +
l.author("Me") +
l.date() +
l.maketitle() +
l.section("Escribiendo #{l.foo_suppress} documentos en Ruby") {
l.indent(l % "COMENTARIOS") +
l.indent("Aqui ponemos un texto.....") +
l.indent(@conjunto_palabras)
} +
l.section("Mas acerca #{l.foo_suppress} Ruby") {
l.myitemize {
l.item?(["a)"]) + "articulo a.\n" +
l.item?(["b)"]) + "articulo b.\n"
}
}
}
puts s
Suscribirse a:
Entradas (Atom)
