Archive for the ‘ Languages ’ Category

HtmlUnit : GUI Java Less browser

HtmlUnit – Welcome to HtmlUnit.

HtmlUnit is a “GUI-Less browser for Java programs”. It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc… just like you do in your “normal” browser.

It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use.

It is typically used for testing purposes or to retrieve information from web sites.

Sending email with ruby – TMail

Simple email sending:

require 'NET / SMTP'
require 'TMail'
require 'base64'
Mail = TMail:: = ''
Mail.from = ''
Mail.subject = 'Test Mail ' =
Mail.Mime_Version = '1 .0 '
Mail.Set_Content_Type 'text', 'plain', {'charset'=>'UTF-8'}
Mail.Body = 'This is Test Mail . '
Net:: SMTP.start("", 587, "", "username", "password") do | SMTP | SMTP.sendmail(Mail.encoded, Mail .from,

Send attachments:

require 'NET / SMTP'
require 'TMail'
require 'base64'
# object
Mail = TMail:: = ''
Mail.from = ''
Mail.subject = 'Test Mail' =
Mail.Mime_Version = '1 .0 '
Mail.Set_Content_Type 'multipart', 'mixed', {"boundary" => "Somethingspecial"}
# body
Mail_Body = TMail::
Mail_Body.Set_Content_Type 'text', 'plain', {'charset'=>'UTF-8'}
Mail_Body.Body = 'Ge almost'
Mail.Parts.push(@ Mail_Body)
# Attachments
Attach = TMail::
Attach.Body = Base64.Encode64 File.Open('foo.jpg', "rb").read
Attach.Set_Content_Type 'image','jpg','name'=>'foo.jpg'
Attach.Set_Content_Disposition ' Attachment ','filename'=>'foo.jpg'
Attach.transfer_encoding = 'base64'
# attach
# send
Net:: SMTP.start("", 587, " ", "username", "password") do | SMTP | SMTP.sendmail(Mail.encoded, Mail.from,

Avoid race condition for file creation

race condition in the common lock on file? – Stack Overflow.

A possible solution to this is to use IO redirection and bash’s noclobber mode, which won’t redirect to an existing file. We can use something similar to:

if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
   # BK: this will cause the lock file to be deleted in case of other exit
   trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT

   # critical-section BK: (the protected bit)

   rm -f "$lockfile"
   trap - INT TERM EXIT
   echo "Failed to acquire lockfile: $lockfile."
   echo "Held by $(cat $lockfile)"