Saturday, November 19, 2011

Google Translate from command line

translate(){ wget -qO- "$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'; }
2010-03-08 03:15:48
Usage:translate <phrase> <source-language> <output-language> Example:translate hello en es
See this for a list of language codes:

translate() { lng1="$1";lng2="$2";shift;shift; wget -qO- "${@// /+}&langpair=$lng1|$lng2" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'; }
allow multiword translations
cmd=$( wget -qO- "$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'; ); echo "$cmd"
2010-03-13 01:09:00
translate <phrase> <source-language> <output-language> works from command line
wget -U "Mozilla/5.0" -qO - "" | sed 's/\[\[\[\"//' | cut -d \" -f 1
tl = target language (en, fr, de, hu, ...);
you can leave sl parameter as-is (autodetection works fine)
substitute "example" with desired string;
curl -s -A "Mozilla" "" | awk -F'"' '{print $2}'
Translates a phrase from English to Portuguese
Translates a string from English to Portuguese by using google translator web service. Source:

Free/open-source machine translation software

Here’s a non-exhaustive list of links to existing free/open-source machine translation systems, which I will try to complete as I find about them. To the best of my knowledge, software listed here has:
Rule-based systems
  • Apertium, a free/open-source rule-based machine translation platform.
  • Matxin, a free/open-source rule-based machine translation system for Basque.
  • OpenLogos, a free/open-source version of the historical Logos machine translation system.
  • Anusaaraka, English-Hindi machine translation system.
Statistical machine translation systems


  • Moses, a statistical machine translation system.
  • Marie, an n-gram-based statistical machine translation decoder.
  • Joshua, an open source decoder for statistical translation models based on synchronous context free grammars
  • Phramer, an open-source statistical phrase-based machine translation decoder
  • GREAT, a decoder based on stochastic finite-state transducers, which includes a training toolkit.

Training translation models

  • Giza++ is a tool to train translation models for statistical machine translation (see also the related mkcls tool to train word classes)
  • Thot is a toolkit to train phrase-based models for statistical machine translation. Read more. Source: DCU School of Computing

Thursday, November 17, 2011

The copy command under DOS


COPY [/Y|-Y] [/A][/B] [d:][path]filename [/A][/B] [d:][path][filename] [/V]
COPY [/Y|-Y] [/A][/B] [d:][path]filename+[d:][path]filename[...] [d:][path][filename] [/V]

Purpose: Copies or appends files. Files can be copied with the same name or with a new name.


COPY is usually used to copy one or more files from one location to another. However, COPY can also be used to create new files. By copying from the keyboard console (COPY CON:) to the screen, files can be created and then saved to disk.

The first filename you enter is referred to as the source file. The second filename you enter is referred to as the target file. If errors are encountered during the copying process, the COPY program will display error messages using these names.

Unlike the BACKUP command, copied files are stored in the same format they are found in. The copied files can be used just as you would use the original (whether the copied file is a data file or a program).

COPY can also be used to transfer data between any of the system devices. Files may also be combined during the copy process. 
Files can be copied to the same directory only if they are copied with a new name. If you copy a file to a different directory without specifying a new name, the file will be copied with the same name. If you attempt to copy a file to the same directory without providing a new name, DOS will cancel the copy and display the message

File cannot be copied onto itself

The COPY command was also discussed in Chapter 1, Introduction, in the downloadable book DOS the Easy Way.


/Y - Causes COPY to replace existing files without providing a confirmation prompt. By default, if you specify an existing file as the destination file, COPY will provide a confirmation prompt. (In previous versions of DOS, existing files were simply overwritten.)

/-Y - Displays a confirmation prompt before copying over existing files.

/A - Used to copy ASCII files. Applies to the filename preceding it and to all following filenames. Files will be copied until an end-of-file mark is encountered in the file being copied. If an end-of-file mark is encountered in the file, the rest of the file is not copied. DOS will append an end-of-file mark at the end of the copied file.

/B - Used to copy binary files. Applies to the filename preceding it and to all following filenames. Copied files will be read by size (according to the number of bytes indicated in the file`s directory listing). An end-of-file mark is not placed at the end of the copied file.

/V - Checks after the copy to assure that a file was copied correctly. If the copy cannot be verified, the program will display an error message. Using this option will result in a slower copying process.


The first filename you enter is the source file; the second file is the target file. To copy the file TEST.DOC from the current directory to drive B (with the same name), enter

copy test.doc b:

To copy the file TEST.DOC to the current directory with the new name, TEST2, enter

copy test.doc test2

To copy and combine (concatenate) the files TEST1.DOC and TEST2.DOC to a new file, TEST3, enter

copy test1.doc+test2.doc b:test3

You can also combine files by using wildcard characters (? and *). To copy all files with a .DOC filename extension on drive C to a new file ALLDOCS on drive B, enter

copy c:*.doc b:alldocs

Other, more complicated, combinations are also possible while copying. For example, to combine all files with a .TXT filename extension with all files that have the same filename and a .DOC extension, copying the newly combined file to a new file on drive B with an .ADD extension, enter

copy *.txt+*.doc b:*.add

In this case, the file TEST.TXT will be combined with the file TEST.DOC resulting in a combined file with the filename TEST.ADD.

Create Batch File to Start or End Window Services

The windows environment can be easily changed by starting or ending various windows services. For example, this method can be used to easily shut down multiple services for a performance boost during game playing.

Update: This article was original crafted for XP; however, I continue to use this technique on my Windows 7 and Windows 8 systems. On more recent Windows systems, the batch file will need to be run as administrator.
Warning: Manipulating windows services can have unpredictable effects on your system. You should create a system restore point before experimenting.
We all want to tweak or windows systems to the extreme to get the quickest, most powerful system possible. Many people will disable multiple window services manually before game playing. What a pain!
Many times people forget what the services do or forget to restart the important ones. Services can be easily changed by creating batch files.
The important commands are the following:
NET START – starts the service
NET STOP – ends the service
For example:
NET STOP "Error Reporting Service"
Output: The Error Reporting Service service was stopped successfully.
Knowing the commands, one can now easily create batch files called something like beforegame.bat and aftergame.bat.
Before.bat would contain all the NET STOP commands to end the nonessential services.
After.bat would be exactly the same except all the NET STOP commands would be replaced with NET START commands to restart all the common services.
A sample of the before.bat file might look something like this:
NET STOP "Error Reporting Service"
NET STOP "FTP Publishing Service"
NET STOP "Messenger"

Likewise, the after.bat file might look something like this:
NET START "Error Reporting Service"
NET START "FTP Publishing Service"
NET START "Messenger"


How To Email Photos To Your Free 25GB Windows Live SkyDrive

While Picasa Web Albums and Flickr are incredibly popular free online photo-storage/sharing services for photos and other files among readers, the limitations of these services’ free accounts might (sooner or later) push you to either upgrade or search for alternative solutions so you won’t have to delete your data.For example, Picasa does integrate well with other Google services, but that also means that all the pictures you upload to Blogger and (the new social messaging tool) Buzz, in addition to Picasa, count toward the 1GB Picasa Web storage limit. As for Flickr, you’re probably already aware that you can only see 200 pictures of your non-pro Flickr collection.

The upgrade prices for extra online storage for photos in Google and Flickr, ($25/year for unlimited storage), aren’t too bad, but as your stream of photos grows every year, so will your premium-account costs. You could get a great deal in photo storage (basically 25GB for $0) in Windows Live Photos thanks to its integration with Windows Live Skydrive, which you already have if you own a Hotmail address or Windows Live ID (signup).
SkyDrive, one of our top 5 free Microsoft Products, will actually give you free online storage for more photos since any file under 50MB will be accepted, but we’ll focus on the SkyDrive-Windows Live Photos kinship as your go-to photo backup/online-storage/sharing solution. Let’s demistify the less-complicated upload option now.

Emailing Pictures To SkyDrive

The email feature is pretty hidden unless you frequently post on your Windows Live Space (the Windows Live equivalent of Blogger), but you can use this regardless of whether or not you’re actively blogging on Spaces. You do need to choose a name for your Space so head to the first option, Choose web address, where you can select a permanent web address.
free online storage for photos
Your Space URL will then be Now you can unleash the beauty and ease of e-mail publishing by pressing on Options on either the Photos or SkyDrive page, and selecting E-mail publishing.
free online storage for photos
Now enter your email, a secret word and choose a default album for your email uploads. Now you can see where naming your Space will come in handy, otherwise, you could have seen “” Each album you have on SkyDrive will be assigned a random code so you’ll get to see all the codes on this page for you to copy to your Contacts in your email or phone. If you decide just to email “” with your pictures, these will appear on your Space blog and on your Live Photos under the album name of Blog images.
Another tip, your email subject will become the photo’s caption, while the title of the photo will just be your photo’s name on your capturing device, but you can always change the cryptic DSCN0852 title of the photo on the website later.
email photos to skydrive
Email is an easy and speedy way to share your mobile pictures (whether it be one or a couple of photos) or if you check your email often.

Other Ways To Upload To Windows Live Photos/SkyDrive

1. Using The Web Interface: Ideal For A Few Photos

After you log in at the Photos Live page, you’ll see that you can Create (a new) album or Add photos to an existing album. The process gets pretty straightforward, but if you’re on Firefox, you’ll miss the option to drag-and-drop your files (but you can individually choose up to 5 files) that you get in Internet Explorer after installing a plugin. There was this wonderful extension that enabled drag-and-drop for any attachment box but it was last updated in November 2009 so let’s hope the developer makes it FF3.6-compatible soon.
free online storage space
If you’re already on your desktop web browser, heading to the site to upload one or a few pictures will be a breeze (or a nightmare if you upload a lot of photos since this can take such a long time.)

2. Publishing Through Windows Live Writer: Ideal For An Album

The next couple of upload options are more “complicated” in that they will require downloading software, but don’t despair, because for example, the ones featured right next up are among Microsoft’s best free products. The first one is Windows Live Writer, number one in our list of top free Microsoft products, which is a super-easy-to-use and extensible blogging tool.
Writing a blog post at Windows Live Writer is too easy not to do. Our introduction and brief beginner’s guide should clarify more features so let us fast-forward to the main reason for including it here: publishing pictures to your Windows Live Space blog (make sure you select this when you’re setting up your accounts) through this blogging client means that your pictures will be uploaded to SkyDrive under Photos, in a new album with the name of your album title.
free online storage space
If you’re a blogger, this will come in handy. As a WYSIWYG editor, Live Writer makes it very intuitive to insert, upload and publish your photo albums (you can even install this plugin to send and share your blog posts to Twitter).

3. Publishing Through Windows Live Photo Gallery: Ideal for A Few Albums

Windows Live Photo Gallery is an improved version of the built-in Windows Vista photo viewer program (Windows Photo Gallery) that allows basic image editing, tagging, and publishing to Windows Live Photos and Flickr. With the right plugins, you can also publish to other popular sites such as Facebook, YouTube, Picasa, etc.
free online storage space
After you click on Publish and select whether you want to create a new album or add pictures to your existing albums (if you’re logged in with your Windows Live ID), WLPG will upload your pictures with an impressive speed. This process is really ideal if you have a lot of albums to upload. You can get Writer and/or the Live Photo Gallery here (just deselect the Windows Live Products that you don’t need.)

4. Using Third Party Apps: Ideal For Lots of Albums/Folders

There are also two really great third party applications (not developed by Microsoft) that make SkyDrive appear as a virtual drive on your computer so you can easily move and/or copy folders and files. This would be ideal to backup/upload and share lots of files and folders, including pictures. These applications, SDExplorer (formerly known as SkyDrive Explorer) and Gladinet may just make your backing up easier.
Summarizing the different upload options:
  • To upload a few pictures, you could either email your photos to SkyDrive, or upload them on the Windows Live Photos/SkyDrive website.
  • To upload and share a whole album, you can try any of the two featured Windows Live products.
  • To back up many albums/folders from your computer, use either Gladinet or SDExplorer. Source:

Terminology Tools

Terminology Tools

Tuesday, November 1, 2011

Free online storage apps

Cloud computing oppens new opportunities for freelancers. One of them is free online file synchronization and storage. Nowadays you can sync your PC files and manage your documents on the go. Share files with your employer or other freelancers. Make an online backup or roll back to previous file version. All these actions are possible with modern online file sharing applications.
Here are the top ten online storage and file sync services that are suitable for freelancing document needs:

1. DROPBOX: Dropbox is a leading folder sync tool. Dropbox gives 2GB free online file storage, which may be increased up to 8GB. Install Dropbox software on PC, Mac, Linux, or mobile devices. Put files you want to store in your Dropbox folder, share a folder with someone, or sync files with other device. I think Dropbox is the easiest file sync software I’ve tried. It’s simple to setup and easy to work with.

2. BOX.NET: is cloud storage that enables you to store files online and collaborate on them within your team. A simple account offers 5GB web space for free with mobile apps access and advanced sharing options.

3. ESNIPS: Esnips provides 5GB free online storage for personal use. Upload files and share them publicly or keep documents in private mode. While online, you can search for other users’ public files or install a toolbar to get instant access to an Esnips account. One small disadvantage of the free Esnips account are the multiple ads in your working area.

4. IDRIVE: iDrive is a perfect tool for online backup. If you want to keep a copy of your important folder on a cloud server, then iDrive is what you are looking for. Download iDrive software, run the application and choose folders to sync. In case of a PC crash, you get your files back. There is 5GB free storage quota.

5. IFOLDER: iFolder is a free open source file synchronization program. To enjoy iFolder, you install the software on your server and on client side as well. iFolder is good software for a small team that is comfortable working with their own server. Thus you make sure that only team members have access to your private files. iFolder has necessary setup documentation for administrators.

6. SKYDRIVE:  Windows Live SkyDrive is free online storage. Enriched with Windows Live Mesh, SkyDrive helps to sync PC folders with your web account. Unfortunately, Live Mesh is available for Windows 7 only. Recently SkyDrive was united with Office 365, so you may collaborate and store Word, Excel, PowerPoint documents online.

7. YOUSENDIT: YouSendit offers 1GB free online storage via email attachments or web folders. The drawback is the provision of your credit card/PayPal data at sign-up page. However, it’s not obligatory and a user can enjoy a Lite account without financial details. Besides, there is an option to purchase advanced security features on a pay-per-use basis. This is a great service for sending single documents to coworkers.

8. ZUMODRIVE: ZumeDrive is an online storage that grants 1GB free web space. However, you have a chance to raise your free quota if you pass a quest game. You can share documents, files and photos after Zumo software installation. But ZumoDrive installation looks a bit more complicated than Dropbox. Source:

Exploring New Languages

Look up the right word, learn how to pronounce it and translate what you want to say into Hungarian.
It is all about understanding each other, François. Whenever we open up a dialogue with someone from another country, we are making an attempt to establish a common ground for communication, usually choosing one language both can understand or, if that fails, translating back and forth.
Quoi? Of course, you are right, mon ami. Sometimes it is difficult to make yourself understood even by those who share your language. Thinking you know what a word means is no guarantee the person you are talking to interprets that word in the same way. That is one of the reasons we have dictionaries—that and Scrabble.
Ah, mes amis! It is good to see you all. Welcome to Chez Marcel, home of fine Linux fare and great wines from the world over. Please sit and be comfortable. François and I were discussing the challenges of being understood and of properly getting your meaning across. François, as you already know all this, quickly go down to the wine cellar and bring back the 1999 Napa Valley Cabernet Sauvignon we were tasting earlier—or rather submitting to quality control.
Words are important and the right words even more so, as every writer can tell you. This especially is true when you are trying to communicate with someone who doesn't share your language. Using your Linux system, you can take some joy in knowing that you are helping to improve understanding between yourself and others.
The meaning of words, true or otherwise, may be no more than a click away. If you are running KDE 3.0 or higher, try this trick. Let's say you want to find the definition of “cooking”. Open up Konqueror, then type dict: cooking in the Location field. Press Enter, and Konqueror does a search for you in the Merriam-Webster Online Dictionary. To do a thesaurus lookup, type ths: cooking instead.
KDE has a nice, integrated dictionary application called Kdict, part of the kdenetwork package. You'll most likely find Kdict in your Utilities menu under the KDE application launcher (the big K). You also can launch it from the shell with the program name kdict (Figure 1). Enter and Kdict connects to various on-line dictionaries to pull up the appropriate definition. Those resources include the Merriam-Webster Dictionary, Wordnet, The Jargon File, The Devil's Dictionary and others.
Figure 1. Kdict provides for easy on-line dictionary lookups.
For rapid-fire access to Kdict, you can pop a handy little applet into your Kicker panel. Here's how: right-click on the big K, select Panel menu®Add®Applet®Dictionary. Now, you should see a new program applet labeled Dictionary with three small buttons to the top right on your Kicker panel. On first start, only the C button is visible (define selected text), and the other two are grayed out.
Figure 2. Rapid-Fire Access to Kdict
Enter text into the small window, either a word or a phrase, press Enter, and Kdict appears with that definition as collected from the various sources. You also can select (double-click) a word on a web page or document you are viewing and click that C button in the applet. Kdict automatically launches and provides the definition for the selected word.
If you aren't running KDE or if you prefer a simpler approach, may I interest you in a lightweight, text-only client that does a similar thing? It's Vishal Verma's edict; I wonder if he looked that word up in the dictionary. You can get edict from The edict program is nothing more than a Perl script, but it does the job quite nicely. In terms of installation, there really isn't much to do after extracting the tarred and gzipped bundle. You can run the script from the directory in which it was extracted, but you'll more than likely want to run a make install to save the script to /usr/bin.
To run the program, type edict followed by the word you want to look up. For a synonym lookup, type ethes followed by a word. If the word you are looking for isn't found, alternatives are offered.
The ethes program is simply a symbolic link to edict. Consequently, a thesaurus lookup is essentially the same process but with different results:
[marcel@mysystem edict]$ ethes program
edict - Your personal command line dictionary.
Verison 1.0.
Looking up "program" in Merriam-Webster Online
Entry Word: program
Function: noun
Text: 1 a formulated plan listing things to be done
or to take place especially in chronological order
<the program of a concert>
Synonyms: agenda, calendar, card, docket,
programma, schedule, sked, timetable
Related Words: bill; slate; plan
Idioms order of the day 2
Synonyms: COURSE 3, line, policy, polity, procedure
Speaking of dictionaries, what is there to say about speaking dictionaries? More to the point, what is there to say about Jeffrey Clement's MWSpeaker, which he describes as the “worst speech synthesis software ever”? Those are his words, mes amis, not mine. The idea is simple, if not a bit silly. You type in a word or a phrase and MWSpeaker reads it back in human speech. The speech in question comes from the Merriam Webster Online Dictionary. In short, it finds each word's corresponding wav file, downloads it and plays it in sequence.
Given that MWSpeaker is a Python script, it requires no compiling per se. Simply download the program from, then unpack the tarred and gzipped bundle. Before you actually can use the program, you need a few additional packages, most notably wxPython, pygame and PythonCard. To run the program, cd to mwspeaker-1.0 (where you unpacked MWSpeaker), and type the following:
mkdir data
python mwspeaker.pyw
The data directory is where the wav files are stored. The GUI is simple. Type a word or phrase, click Say it and wait. I say “wait”, because MWSpeaker downloads each word's wav file in turn before playing your selection. The results can be a lot of fun because the voices saying the words aren't consistent. You wind up with a strange mix of male and female voices.
Figure 3. The Self-Proclaimed World's Worst Speech Synthesizer
All this is wonderful for the English language, but Linux and open-source developers come from every part of the world, after all, as do Linux users. It is true that an English language dictionary is useful to those who don't count English as their first language, but sometimes you must translate.
François, remplisser les verres de nos invités, s'il vous plâit.
To translate French (or Italian, or Spanish, or German and so on) into English, you might find yourself looking for a Babel Fish. What is a Babel Fish, you ask? According to Douglas Adams, the creator of the Hitchhiker's Guide to the Galaxy, it is a small yellow fish that, when put in your ear, simultaneously translates any language you hear into the one you normally speak. But as Douglas Adams wrote, “Meanwhile, the poor Babel Fish, by effectively removing all barriers to communication between different races and cultures, has caused more and bloodier wars than anything else in the history of creation.”
KDE's combination web browser, file manager and Swiss Army knife, Konqueror, has hooks built in to AltaVista's Babel Fish. Surf on over to a foreign language web site, and you easily can translate the information you find there. For my example, I randomly picked a German language newspaper, Die Welt, which I learned means “The World”.
When your page has loaded, click Tools on Konqueror's menubar, select Translate Web Page, then select from one of the language selections in the drop-down list. In my example above, I chose “German to English”, et voilà! You now can read the information in a language that makes more sense to you.
For your own personal and local translation dictionary, you may want to consider taking a look at Ricardo Villalba's wordtrans at (Figure 4). Compiling wordtrans can be a little tricky, but it isn't a great problem. A visit to TuxFinder ( turns up quite a number of precompiled packages. I downloaded both the base wordtrans package along with the wordtrans-kde packages in RPM format and installed them. If you are downloading packages, you do need both. You may also find a wordtrans-qt and a wordtrans-web package.
Figure 4. wordtrans, Your Personal Translation Dictionary
By default, wordtrans comes with English, French, Italian, Portuguese and Spanish translation dictionaries, but more can be added. You'll find links to other language files on the wordtrans web site and in the software itself. When you start up Kwordtrans, it may appear as though nothing happened, but look at your system tray in the Kicker panel and you'll see a little gray book icon. Click here and the Kwordtrans interface appears. To select your language of choice, click Dictionaries in the menubar and choose from the list. Choose the direction of your translation (for example, English to Spanish or Spanish to English), type in a word and press Enter.
As I mentioned, you can add additional dictionaries by clicking View on the menubar and selecting Introduction for some links. This not only extends wordtrans' capabilities, but some of the dictionaries available for download are more extensive than the default ones. To add a downloaded language file, click Dictionaries on the menubar, select New and follow the instructions. I downloaded and installed several from with excellent results.
I'm afraid I do not speak Hungarian, mes amis, but apparently I would have to say az idõ lejárt, which my desktop translator tells me means “time's up”. It is indeed closing time, but there is time enough for another glass of wine before you go. Raise your glass and my faithful waiter, François, happily will take care of you. As you can see, with a little exploration in our Linux kitchens, we may one day be able to communicate effortlessly with the world. Until next time, mes amis, let us all drink to one another's health. A votre santé! Bon appétit! Source:

Being a translator should be hard

“Becoming a translator is easy
It’s no secret that translation has a low barrier to entry, and freelance work an even lower one.
Speak more than one language? Then set up an account on, mass-email your CV to a list of agencies and voilà, you’re a freelance translator. If you want to be especially entrepreneurial, you might even take thirty minutes or so to set up a website, blog and Twitter stream.
There is nothing wrong with any of this. I don’t begrudge anyone their route into translation, nor do I believe a baptism of fire is a requirement to earn your wings as a “real” translator.
But I do think it’s what you do next, after you’ve emailed your CV, set up your LinkedIn profile or had your business cards printed, and every single day thereafter, over a period of weeks, months and years, that secures you a successful, sustainable career in translation.
But being one isn’t
A lot of people become freelance translators, but far fewer stay long in the profession. Translation communities are full of translators complaining about low rates, unfair conditions and clients who take advantage of them.
By my reckoning, these people do not have successful, sustainable careers in translation. So what can they do to change that?
As Aristotle apparently never said, we are what we repeatedly do, and excellence is not an act but a habit.
Significant results don’t materialise overnight – they require continuous (or at least continual) practice combined with a strategic approach, a long-term commitment and plenty of hard work.
Projects that are well paid, satisfying and regular, or clients that are reasonable, interesting and appreciative: there is no magic pill or single way to achieve these things.
They simply require that you put the work in, over and over again.” Source:

ASCII Table and Description

ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose. Below is the ASCII character table and this includes descriptions of the first 32 non-printing characters. ASCII was actually designed for use with teletypes and so the descriptions are somewhat obscure. If someone says they want your CV however in ASCII format, all this means is they want 'plain' text with no formatting such as tabs, bold or underscoring - the raw format that any computer can understand. This is usually so they can easily import the file into their own applications without issues. Notepad.exe creates ASCII text, or in MS Word you can save a file as 'text only'

Ascii Table

Extended ASCII Codes

EBCDIC and IBM Scan Codes

Perl command line interface to Google Translate

# By: Jeremiah LaRocco
# Use to translate between languages.
# Sample run:
# --to french --from english This is a test
# Ceci est un test
use strict;
use warnings;
require LWP::UserAgent;
use Getopt::Long qw(:config pass_through);
use URI::Escape;
use HTML::Entities;
my %languages = ('french'=>'fr', 'spanish'=>'es', 'afrikaans'=>'af', 'albanian'=>'sq',
'arabic'=>'ar', 'belarusian'=>'be', 'bulgarian'=>'bg', 'catalan'=>'ca', 'chinese'=>'zh-cn',
'croatian'=>'hr', 'czech'=>'cs', 'danish'=>'da', 'dutch'=>'nl', 'english'=>'en', 'estonian'=>'et',
'filipino'=>'tl', 'finnish'=>'fi', 'french'=>'fr', 'galician'=>'gl', 'german'=>'de', 'greek'=>'el',
'haitian creole alpha'=>'ht', 'hebrew'=>'iw', 'hindi'=>'hi', 'hungarian'=>'hu', 'icelandic'=>'is',
'indonesian'=>'id', 'irish'=>'ga', 'italian'=>'it', 'japanese'=>'ja', 'korean'=>'ko',
'latvian'=>'lv', 'lithuanian'=>'lt', 'macedonian'=>'mk', 'malay'=>'ms', 'maltese'=>'mt',
'norwegian'=>'no', 'persian'=>'fa', 'polish'=>'pl', 'portuguese'=>'pt', 'romanian'=>'ro',
'russian'=>'ru', 'serbian'=>'sr', 'slovak'=>'sk', 'slovenian'=>'sl', 'spanish'=>'es',
'swahili'=>'sw', 'swedish'=>'sv', 'thai'=>'th', 'turkish'=>'tr', 'ukrainian'=>'uk',
'vietnamese'=>'vi', 'welsh'=>'cy', 'yiddish'=>'yi', );
sub usage {
    my $usage_str = <<END;
Valid command line arguments are:
   $0  [--to <language>] [--from <language>] text...
Optional arguments controlling translation languages:
   --to     Sets the language to translate to
The default value is English (en)
   --from   Sets the language to translate from
The default value is French (fr)
Languages can be specified by name (i.e. French) or by their abbreviation (i.e. fr).
Valid languages are:
    print $usage_str;
    my $curLine = '';
    for my $key (sort keys %languages) {
        $curLine = sprintf('%s %20s %7s  ', $curLine, $key, '('.$languages{$key}.')');
        if (length($curLine)>100) {
            print "$curLine\n";
            $curLine = '';
    print "$curLine\n";
sub main {
    my $help;
    my $to = 'en';
    my $from = 'fr';
    if ($help || $#ARGV==-1) {        usage;
    if ($languages{lc $from}) {
        $from = $languages{lc $from};
    if ($languages{lc $to}) {
        $to = $languages{lc $to};
    my @words = @ARGV;
    map uri_escape, @words;
    my $url = "$from|$to&text=" . join('+', @words);
    my $ua = LWP::UserAgent->new;
    my $res = $ua->get($url);
    if ($res->is_success) {
        my $sentence = join(' ', @words);
        # my $translated = decode_entities($res->content);
        if ($res->content =~ /<span title="$sentence" onmouseover="'#ebeff9'" onmouseout="'#fff'">(.*?)<\/span>/) {
            my $translated = decode_entities($1);
            print "$translated\n";
    else {
        die $res->status_line;