Translate Properties

This is a tool for translating Java properties files, where there are sources in many languages. I needed to translate some of these properties at work, so I knocked up this script to help me out. And it was pretty useful.

I will not go into the details of the code - you can check it out yourself if you're interested. It's pretty clean as code goes, although not so well commented as per usual.

Also, beware, it's GPL-ed! The full text of the license is available at the GNU site.

Anyway, the sources:
1  #!/usr/bin/python
2  
3  # Copyright 2008 Konrad Siek 
4  #
5  # This program is free software: you can redistribute it and/or modify
6  # it under the terms of the GNU General Public License as published by
7  # the Free Software Foundation, either version 3 of the License, or
8  # (at your option) any later version.
9  #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 
19 import os.path;
20 import getopt;
21 import sys;
22 
23 sources = [];
24 empty = ["", "*", None];
25 startAt = 1;
26 output = sys.stdout;
27 sort = False;
28 ignore = False;
29 quiet = False;
30 
31 def addSource (source):
32     if os.path.exists(source):
33         sources.append(source);
34     elif not quiet:
35          sys.stderr.write("Source: '" + source + 
36                           "' does not exist. Skipping...\n");
37          
38 def setLine (line):
39     global startAt;
40     try:
41         number = int(line);
42     except ValueError:
43         if not quiet:
44             sys.stderr.write("Line value: " + line + 
45                              " is not a number. Ignoring...\n");
46         return;
47     if number <= 0:
48         if not quiet:
49             sys.stderr.write("Line value: " + line + 
50                              " must be greater than 0. Ignoring...\n");
51         return;
52     startAt = number;
53     return startAt;
54 
55 def setOutput (path):
56     """
57     Sets the file, which will be used throughout the program to 
58     write results. If this is not done, the module will write to
59     sys.stdout instead.
60         
61     @param path: is the path to the file. 
62     """
63     global output;
64     output = open(path, 'w');   
65         
66 def setSort():
67     global sort;
68     sort = True;
69 
70 def setQuiet():
71     global quiet;
72     quiet = True;
73     
74 def setIgnore():
75     global ignore;
76     ignore = True;
77         
78 def printUsage ():
79     """
80     Print usage information for the script.
81     """
82         
83     sys.stdout.write("Usage:\n");
84     sys.stdout.write("\t"+ sys.argv[0]
85                     +" -s source [-s source ... ] "
86                     +"[-l line ] target\n");
87     sys.stdout.write("\t"+ sys.argv[0] +" -h\n");
88     sys.stdout.write("\t-s source\t\t"
89                     +"Select an output file to write to.\n");
90     sys.stdout.write("\t-l line\t\t"
91                     +"Select a line in the target to start from.\n");
92     sys.stdout.write("\t-o path\t\t"
93                     +"Output results to file, instead of stdout.\n");
94     sys.stdout.write("\t-i \t\t\t"
95                     +"Ignore if all sources have no values "
96                     +"(or value of '*').\n");
97     sys.stdout.write("\t-a \t\t\t"
98                     +"Sort results.\n");
99     sys.stdout.write("\t-q \t\t\t"
100                    +"Quiet mode.\n");
101    sys.stdout.write("\t-h \t\t\t"
102                    +"Show this message.\n");
103    sys.stdout.write("");
104    sys.exit(0);
105    
106def fileToList(path):
107    file = open(path, 'r');
108    lines = file.readlines();
109    file.close();        
110    list = [];
111    counter = 1;
112    for line in lines:
113        if (not line.startswith("#") and (len(line.strip())) > 0):
114            line = line.rstrip("\n");
115            key, separator, value = line.partition("=");            
116            if value.find("=") >= 0:
117                sys.stderr.write("Warning: value of line " 
118                                 +str(counter) + " in " + path);
119                sys.stderr.write(" contains an equals sign '=' (" 
120                                 +line + ")\n");
121            list.append((counter, key, value));
122        counter += 1;              
123    return list;
124    
125def loadSources():
126    lists = {};
127    for source in sources:
128        lists[source] = fileToList(source);
129    return lists;
130
131def popByKey(target, list):
132    for i in range(0, len(list)):
133        line, key, value = list[i];
134        if key == target:
135            del list[i];
136            return line, key, value;
137    return NoneNoneNone;
138
139def dialog(property, sources):
140    sys.stdout.write(property+"\n");
141    for source, line, value in sources:
142        sys.stdout.write("\t"+source+"\t("+str(line)+"): "
143                         +str(value)+"\n");
144    sys.stdout.write("$("+property+"):"); 
145    
146def save(results):
147    if sort:
148        results.sort();
149        
150    printout(results);
151        
152def control(property, value, results):
153    line = sys.stdin.readline().strip();
154    if line == "=stop":
155        save(results);
156        exit(0);
157    elif line == "=skip":        
158        pass
159    elif line == "":        
160        results.append((property, value));
161        pass
162    else:
163        results.append((property, line));
164        
165def printout(list):
166    global output;
167    for key, value in list:
168        output.write(key+"="+value+"\n");
169        
170def outOfScope(target, list):
171    for i in range(0, len(list)):
172        line, key, value = list[i];
173        if key == target:
174            return (line < startAt);
175    return False;
176
177def absent(occurances):
178    for key, line, value in occurances:
179        if empty.count(value.strip()) == 0:
180            return False;
181    return True;
182        
183def parse (target):
184    sources = loadSources();
185    workspace = fileToList(target);
186    results = [];
187    
188    # Translate the lines, which were in the target    
189    for line, key, value in workspace:
190        if line < startAt:
191            continue;
192        occurances = [(target, line, value)];        
193        for s in sources:
194            list = sources[s];
195            l, k, v = popByKey(key, list);
196            occurances.append((s, l, v));
197        if ignore and absent(occurances):
198             continue;
199        dialog(key, occurances);
200        control(key, value, results);
201        
202    # Translate the lines, which were in the sources, but not the target
203    for source in sources:
204        for line, key, value in sources[source]:
205            if not outOfScope(key, workspace):
206                occurances = [(target, line, value)];        
207                for s in sources:
208                    if source != s:
209                        list = sources[s];
210                        l, k, v = popByKey(key, list);
211                        occurances.append((s, l, v));
212                dialog(key, occurances);
213                control(key, results);
214    
215    save(results);
216
217def resolveOptions (optionHandling, argumentHandler):
218    """
219    Handles all the options and parameters for the script with the 
220    provided functions. 
221    
222    @param optionHandling: a dictionary, translating an option string 
223    to a function.Depending on whether the function is parameterless 
224    or has one parameter the option string will be just a letter or a 
225    letter ending in a colon.
226    
227    @param argumentHandler: a function used to handle all the arguments  
228    - it takes one parameter.
229    """
230    
231    string = "".join(["%s" % (i) for i in optionHandling.keys()]);
232    options, arguments = getopt.getopt(sys.argv[1:], string);
233    
234    # Handle options.
235    for key, value in options :        
236        if value != '':
237            optionHandling[key[1:]+":"](value);
238        else:
239            optionHandling[key[1:]]();
240          
241    # Handle arguments.        
242    if len(arguments) > 0 :
243        for argument in arguments:
244            argumentHandler(argument);
245
246if __name__ == "__main__":
247    options = {"s:": addSource, 
248               "h": printUsage, 
249               "l:": setLine, 
250               "o:": setOutput,
251               "a": setSort,
252               "q": setQuiet,  
253               "i": setIgnore}    
254    
255    resolveOptions(options, parse);


The code is also available at GitHub as python/translate_properties.py.
Continue Reading...

Init cowsay

Yes! The script to end all scripts! This is just what you need!

Ok, so it's a script to basically put a command into your ~/.bashrc file. I did it a long, long time ago, because... well, I suppose for no reason really, but it cam in handy, when I was doing a lot of stuff on a lot of different machines, and logging in through ssh to other machines at the same time, and it was useful for the cow to remind me where I was entering.

Right, so it's not very useful. Also it is now overblown, because there's all these options! When I first made the script it was just:
cp ~/.bashrc ~/.bashbuprc && echo 'cowsay -e xx -T \ U -f small.cow $USER@$HOSTNAME' >> ~/.bashrc

and now it is 100 lines of code...

Anyway, it requires cowsay, which I just got going sudo apt-get install cowsay. cowsay is very configurable, so you can make whatever creature you want as your console splash article. You can even specify any command you want with the -c switch!

And then, when you get bored, just use the -r switch to revert.

Important safety notice! This may screw something up with your .bashrc file! It shouldn't, but it might, so don't trust nobody and back it up.

Without further ranting, here's the script:
1  #!/bin/bash
2  #
3  # Init cowsay
4  # Enters cowsay into your local .bashrc file, so that you see 
5  # a dead cow every time you use the temrinal. 
6  # Yes, the very thing you need!
7  # It is actually possible to use this with other commands and files.
8  #
9  # Potential issues:
10 #   Potential serious damage to your ~/.bashrc file is possible!
11 #   Best to keep backup of the file!
12 # Parameters:
13 #   -r|--remove     Remove line instead of adding
14 #   -f|--force      Force insert even if line already exists
15 #   -h|--help       Print usage and quit
16 #   -b|--backup     Backup bashrc file
17 #   -c|--command    Use a custom command instead of cowsay
18 # Requires:
19 #   cowsay (http://www.nog.net/~tony/warez/cowsay.shtml)
20 # Author:
21 #   Konrad Siek 
22 
23 # Initiate arguments
24 insert='true'
25 force='false'
26 backup='false'
27 command='cowsay -e xx -T \ U -f small.cow $USER@$HOSTNAME'
28 bashrc="$HOME/.bashrc"
29 
30 # Use getopt to parse command arguments.
31 options=`getopt    -o b::rc:fh \
32     --long backup::,remove,command,help,force \
33     -n $0 -- "$@"`
34 
35 # Proceed if everything is OK.
36 if [ $? == 0 ] 
37 then
38     # Set the parsed command options.
39     eval set -- "$options"
40 
41     # Setup selected options
42     while true ; do
43         case "$1" in
44             -r|--remove
45                 # Remove line instead of adding
46                 insert='false'
47                 shift 
48             ;;
49             -f|--force
50                 # Force operation even if line already exists
51                 force='true'
52                 shift 
53             ;;
54             -h|--help
55                 # Print usage 
56                 echo "Usage: $0 (options)"
57                 echo "\t-r|--remove\t\tRemove line instead of adding"
58                 echo "\t-f|--force\t\tForce insert even if line already exists"
59                 echo "\t-h|--help\t\tPrint usage"
60                 echo "\t-b|--backup\t\tBackup bashrc file"
61                 echo "\t-c|--command\tUse a custom command instead of cowsay"
62                 exit 0;
63                 shift 
64             ;;
65             -b|--backup)
66                 # Backup bashrc file
67                 backup='true'
68 
69                 # Optionally set backup file name
70                 if [ $2 != '' ] 
71                 then
72                     backup_file=$2
73                 fi
74                 shift 2
75             ;;
76             -c|--command)
77                 # Use a specific command instead of cowsay
78                 command=$2
79                 shift 2
80             ;;
81             --) 
82                 # Stop parsing options
83                 shift
84                 break
85             ;;
86             *) 
87                 # Weird error
88                 echo "Something went horribly, horribly wrong in the interior."
89                 exit 1 
90             ;;
91             esac
92     done
93     
94     # Check if the command is already in there
95     if [ ! -e $bashrc ]
96     then
97         exists='0'
98     else
99         exists=`cat $bashrc | fgrep "$command" | wc -l`
100
101        # Backup on demand
102        if [ $backup == 'true' ]
103        then
104            cp $bashrc $backup
105        fi
106    fi
107
108    if [ $insert == 'true' ] 
109    then    
110        # Check if we should insert it nevertheless 
111        continue=`expr \( $force == 'true' \| $exists == '0' \) `
112        # echo "not $exists and $force is $continue"
113
114        # If possible, add the command in the appropriate place
115        if [ $continue != '0' ]
116        then
117            # Insert command into file
118            echo "$command" >> $bashrc
119        else
120            # Oh noes!
121            echo "$0: Command '$command' already exists in file '$bashrc'."
122            echo "$0: If you know what you're doing you can try the -f option."
123            exit 1;
124        fi
125
126    else
127        if [ $exists != '0' ]
128        then
129            # Remove all lines that match from file
130            cat $bashrc | fgrep -v "$command" > $bashrc
131        else
132            # Nothing to do...
133            echo "$0: Nothing to do - command '$command' not in file '$bashrc'."
134        fi
135    fi
136fi


The code is also available at GitHub as bash/init_cowsay.
Continue Reading...

Entering beta testing

dgg, the greasemonkey script for digg.com, is starting beta testing. The purpose of dgg is to allow users to completely ignore articles containing certain keywords or articles coming from particular websites. Please leave feedback! Download it!
Continue Reading...

Entering beta testing

dgg, the greasemonkey script for digg.com, is starting beta testing. The purpose of dgg is to allow users to completely ignore articles containing certain keywords or articles coming from particular websites. Please leave feedback! Download it!
Continue Reading...

TINGYA dominates 45th Maharashtra State Government Awards in Aurangabad

TINGYA created history, first time in the history of Marathi state awards, a film has bagged 9 awards in total. For the first time a TINGYA has got two best film awards.
TINGYA bags awards at very prestigious MAHARASHTRA STATE GOVERNMENT FILM AWARDS on 29th April at Aurangabad.Already Sharad Goyekar was annouced as Best Child Actor when nominations are declared. Also tingya honored as Best Film in 2007-08 year.
Awards are:

1. Best film: Late. Dadasaheb Falke award.
2. Best director: Late. Bhalji Pendharkar award.(Mangesh Hadawale)
3. Best Regional Film: Late Dada Kodke Award and Shankar Rao Mohite Patil Award.
4. Best Director: Late: Anant Mane Award.(Mangesh Hadawale)
5. Best Dialogue: Late. Acharya Atre Award.(Mangesh Hadawale)
6. Best Supporting Actress: Late Shanta Hublikar Award.(Madhavi Juvekar)
7. Best Lyrics: Late G. D. Madgulkar Award.(Prakash Holkar)
8. Best Critics Actress: Late Hansa Wadker Award.(Chitra Nawathe)
9. Best Child Actor: Late Gajanan Jahagirdar Award. (Sharad Goyekar)

Continue Reading...

Article in Mumbai Mirror by Shanta Gokhale(One of the most eminent film critic)

"In a class of its own"

'Unlike Satyajit Ray’s Pather Panchali, Mangesh Hadawale’s film Tingya goes to Cannes with no misgivings about poverty portraying India ‘in a bad light’.'


Tingya comes to Mumbai with awards and a legend streaming behind it. The legend is that a young man from Junnar, Mangesh Hadawale, wanted to make a film about a boy and a bull. He narrated his script to 41 producers, all of whom said it was a good story, but sorry, not their cup of tea.

The 42nd producer was Ravi Rai. Hadawale met him by the merest chance. Rai heard the story and said, “Let’s make it.” His only stipulation was, “Make it exactly as you told it.” That must have sounded to Hadawale like a hundred violins playing. So he made Tingya. And now it has won prestigious awards at home and is all set to go to Cannes.

The film’s gamut of emotions move in a completely natural way, leaving us free to learn our own moral-political lessons

I cannot help remembering Satyajit Ray’s Pather Panchali at this point. When this classic film was proposed as an entry for the Cannes Film Festival, a number of powerful voices were raised against the idea. The film would show India “in bad light” they said. It was okay to be abjectly poor but not okay to show the world that you were. Fortunately Pandit Nehru had seen the film and loved it. He intervened and Pather Panchali not only went to Cannes but won the Special Jury Prize for the Best Human Document.

When Tingya goes to Cannes, no voices will be raised against it. India has four (10?) of the world’s richest men, its techies have taken over Silicon Valley, its beauty queen promotes French hair colour and there’s Bollywood, the eternal dream. India’s image is made. Tingya can go tell its story, no problem.

This then is the story. A small farmer’s old bull, Chitangya, falls into a ditch and is permanently incapacitated. The farmer has paid through his nose for a sack of potatoes which await sowing. But Chitangya cannot pull the plough. The farmer faces Sophie’s choice. Unless he sells Chitangya, he cannot buy another bull. Unless he buys another bull, he cannot plough. Unless he ploughs, his family will starve and the money-lender will be at his throat. But Chitangya and the farmer’s younger son, Tingya, have grown up together. Tingya cannot live without him. To make matters worse, Chitangya cannot be sold for farm work. He can only be sold for slaughter. Tingya bawls. With a child’s unanswerable logic he asks why his friend Rashida’s grandmother, who is also old and cannot work, isn’t being sold off to the butcher.

Finally Tingya learns that you can’t argue against old age and death. Nor can you equate human life with animal life. He also learns that life means birth as well.

There’s much else that happens in Tingya. Other threads, dark and bright, are woven into the main story to create the enduring fabric that is village life. Poverty gives the villagers the strength and stoicism to fight for survival against every odd. The noose hangs in the background, but mutual support keeps some necks out of it.

One scene sticks in the mind. It is twilight. Tingya sits on the threshold of the house. His mother comes from the river with a pitcher of water. “Never sit in the doorway when Lakshmi is entering the house,” she admonishes. Tingya asks, “What does that mean — Lakshmi is entering the house?” The mother goes indoors without a word.

That is the great strength of this film — the absence of heavily underlined “messages” and of contrived attempts to squeeze tears out of deeply emotional scenes. Hadawale’s touch is sure. He allows the story to tell itself through beautifully shot locations, perfectly paced editing, punchy dialogue and intense, controlled performances. Its emotions move between love, fear, anxiety, frustration, grief and humour in a completely natural way, like the seasonal cycle itself, leaving us free to learn our own moral-political lessons.

Finally, I’d see the film again just to see Sharad Goekar’s Tingya and Tarannum Pathan’s Rashida.

- Shanta Goghale (One of the most eminent film critics)
Continue Reading...

Sharad Goyekar adopted by Patil family

'Tingya' (Sharad Goyekar) spent his life before in remote place in Rajuri in Junnar taluka. Now he will stay in pune city at 'Anand Park' on paud road with his new family. Tingya is adopted by Mr.Prakash Patil and his wife Priya Patil. Patil family adopted Tingya for improvement in his education and development of skills.Patil family belogs to educational field and they wish that Tingya complete his whole education staying with their family.
Continue Reading...

TINGYA rated four stars by SCREEN magazine

SCREEN weekly magazine ratings----

SCREEN a weekly magazine rated TINGYA with 4 stars out of 5. SCREEN ratings to TINGYA based on Sharad Goyekar and Tarannum Pathan's good performance, Mangesh Hadawale's outstanding direction and producer Ravi Rai's choice of script .
Continue Reading...

Sharad Goyekar adjudged Best Child Actor in 45th MAHARASHTRA STATE GOVERNMENT FILM AWARDS

As TINGYA is nominated in 45th MAHARASHTRA STATE GOVERNMENT FILM AWARDS in seven categories, state government already declared Sharad Goyekar(tingya) as best child actor for year 2007-08.This is his 3rd best child actor award only for tingya. Sharad will get honored at Aurangabad on 29th April in award distribution ceremony.
Continue Reading...

TINGYA nominated in 45th MAHARASHTRA STATE GOVERNMENT FILM AWARDS in seven catagories

TINGYA is yet to release on 11th April this week and already gathering enormous attention by various film awards.This time TINGYA nominated in 45th MAHARASHTRA STATE GOVERNMENT FILM AWARDS in seven categories including best film,best story,best child actor,best dialogs,best lyrics,critics special award for best actor and best actress, and best supporting actress. The award ceremony is held on 29th April at Aurangabad in presence of Maharashtra Chief Minister , home minister and other maharashtra state government officials.


Nominated categories in details are,



1. Best Film

2. Best Story

3. Best Supporting Actress (Madhavi Juvekar as 'Anjana' )

4. Critics special award for Best Actor (Vitthal Umaap as 'Banubhai')

5. Critics special award for Best Actress (Chitra Nawathe as 'Nani')

6. Best Lyrics (Prakash Holkar)

7. Best Dialogs (Mangesh Hadawale)



Continue Reading...

TINGYA got Best Debut production's film in 2nd V. SHANTARAM awards

Yet another success for TINGYA's Ravi Rai's Small Town Boy production. This time TINGYA honoured as a Best production's first film(Debut) at 2nd prestigious V. Shantaram awards on evening at mumbai on 5th April .
Continue Reading...

lala moulati ana9a maghribia

seo

 

Blogroll

Site Info

Text

telechargementz Copyright © 2009 WoodMag is Designed by Ipietoon for Free Blogger Template