Deth

Here's a new script for the new year.

It sometimes happens when I need to, say generate a dot file from a SableCC grammar to have a nice little diagram showing me how the damn thing is supposed to work. When you do one of those, not only does it tent to facilitate using your laptop as a simple toaster, or perhaps a very expensive heating system, but also usually eats up a lot of time. Something like 7 hours, for instance, and you don't know at all when it's going to end... or if it's going to generate anything, or maybe die out of lack of memory.

So it's not something that you want to wait up for until 2 AM - just let it run on it's own, and go to sleep instead. Good plan, yeah?

On the other hand, maybe it's wise to take those electricity bill into account? How about turning it off right after the process finishes (or dies)?

Ah, and did you have the foresight to actually write the shabang which shuts the computer down when the process is done? I never do...

That's where this script comes in. You just tell it to watch the process, and do stuff if it happens to die. It's as simple as that.

So, in the particular case that I described, I'd use it like this:

sudo ./deth sablecc "shutdown -h now";


And it won't work. The script is not prepared to handle the sudo-ing out of the box. Why? Well... you know, because I suck. But it's not a problem, all you need to do is take a peek at line 40 and change `whoami` to just your username, for instance: joe (with no spaces, no inverted commas, no nothing... well, double quotes, if you have to). Problem solved.

There's another variable that you can handle as well, in line 37. The sleep time between checks is here, in seconds. If 5 minutes doesn't cut it for you, modify it right there; no worries, she'll be right.

Yeah, for some reason I didn't feel like doing the entire getopt thing, and make these things settable... that's laziness, that is.

Here's the code.

1  #!/bin/bash
2  #
3  # Deth
4  #
5  # A watchdog for the death of processes. After specifying 
6  # the list of processes to watch (either by name of PID)
7  # the script waits for them to turn off, in which case the 
8  # specified command is run (and sent into the background).
9  # When all watched processes die, the script exits.
10 
11 # The commands are translated into PIDs at the beginning 
12 # only, so if you want to watch gcalctool, and, while this
13 # script is already running, turn on another instance of
14 # gcalctool, the new instance will be completely ignored.
15 #
16 # The script checks for the death of the specified processes
17 # and then goes to sleep for a specified period of time. 
18 # Since this does not need to be a very precise script, it's 
19 # currently set to checking every 5 minutes - this can be
20 # changed by modyfing the value of SLEEP_TIME.
21 #
22 # The script only watches processes which belong to the
23 # current user. To modify this set the value of USERNAME.
24 
25 # Potential issues:
26 #   When selecting by command name, all fitting PIDs
27 #   are watched, without any further discrimination.
28 # Parameters:
29 #   List of running commands and/or PIDs.
30 #   The last argument is always the command to run when
31 #       each of them turns off.
32 # Author:
33 #   Konrad Siek
34 #
35 
36 # How long to wait between pings. In seconds.
37 SLEEP_TIME=300
38 
39 # Limit the watched processes to the current user.
40 USERNAME=`whoami`
41 
42 # Check if enough arguments to even try getting the PIDs.
43 if [ $# -lt 2 ] 
44 then
45     echo -e "Usage: \n\t$0 [pids] [commands] action\n"
46     exit -1
47 fi
48 
49 # Convert all arguments to a PID array
50 declare -a array
51 while [ "$2" != "" ]
52 do 
53     if [ `expr "$1" : "[0-9][0-9]*"` != 0 ]
54     then
55         # Add PIDs to the array as they are.
56         if [ $(\
57             ps U $USERNAME -u $USERNAME -o pid \
58                         | grep "^ *$1 *\$" | wc -l) != 0 ]
59         then
60             array=${array[@]} $1 )
61         else
62             echo "PID $1 is not valid, ignoring." >& 2
63         fi
64     else
65         # Extract PIDs from name and add them to the array.
66         array=${array[@]} $(\
67             ps U $USERNAME -u $USERNAME -o pid,comm \
68             | awk -v f=$1 '$2==f {printf($1" ")}' ) )
69     fi    
70     shift
71 done
72 
73 # The last parameter is the action done on death of processes.
74 ACTION=$1
75 
76 # No array can be generated - no PIDs were discerned.
77 if [ ${#array[@]} = 0 ] 
78 then
79     echo "No PIDs were supplied." >& 2
80     exit -2
81 fi
82 
83 # Work the magic. 
84 while [ 1 ]
85 do
86     # Check if anything changed, and act.
87     i=0len=${#array[@]}
88     while [ $len -gt 0 ]
89     do                
90         # Ignore empty elements.
91         if [ "${array[$i]}" = '' ] 
92         then
93             # Point to next element
94             i=$(($i + 1))    
95             continue
96         fi    
97 
98         # Fewer elements to visit left.
99         len=$((len - 1))
100
101        # Check if process dies.
102        if [ $(\
103                        ps U $USERNAME -u $USERNAME -o pid \
104                        | grep "^ *${array[$i]} *\$" | wc -l) = 0 ]
105        then
106            # Process is dead, execute action.
107            $ACTION &
108            unset array[$i]
109        fi
110
111        # Point to next element
112        i=$(($i + 1))
113    done    
114
115    # If nothing left to do, quit.
116    if [ ${#array[@]} = 0 ] 
117    then
118        exit 0;
119    fi
120
121    # Wait a bit before continuing.
122    sleep $SLEEP_TIME;
123done



The code is also available at GitHub as bash/deth.

P.S. I hate those gorram, depressing date changes.
Continue Reading...

'Tingya' bagged Bronze award in the Best Film categories

On as special event in Mumbai of V Shantaram Award 2008 ceremony, Tingya won the Bronze award in Best film category. Tingya was nominated in four categories like best film,best director,best debut director and best child actor. Other films such as Taare zameen par, A Wednesday,Jodhaa Akbar,Rock On were also nominated in several categories.
Continue Reading...

Ping all

If you happen to have many computers in your local network, and you want to find out which ones are working at the moment without getting up, well, there are several ways to do this, probably. Same for when you have DNS turned on and want to know what IP addresses all those computers have got at the moment.

So this might be yet another way to do this.

Its advantage is that it's straightforward. Its disadvantage is that it's rather crude and can be slow. Oh, and it doesn't find out the names of all those computers running non-gnu/linux systems... although, personally, I don't care about that very much.

It's written in Perl, because writing it in Bash would hurt too much, as it lacks easily-manipulated arrays and a way of getting the hostname out of the IP (well, I couldn't find a way) and Python doesn't provide anything to ping out of the box... I'm not good at Perl so a) I had a chance to practice and b) the code probably sucks tremendously in some bits.

I wanted to do the main monitoring using Perl's own ping object, but somehow it didn't want to produce correct results for non-gnu/linux systems... and a ping function shouldn't be so finicky. Whether, I used it wrong or there is something wrong with my configuration, it was easier to use an external ping command, redirect its output to /dev/null and return something if it finds a computer. All that is done on line 76.

Before pinging, the IP addresses for pinging are generated, one by one and put into an array. This is perhaps not the best way to do this, but it's rather convenient... not to mention that it's good practice.

Enough banter, here's the code.

#!/usr/bin/perl 
#
# Ping all
#
# Pings all ip addresses within the specified range and
# retrieves the name
#
# Parameters:
#   range start - IP address at which to check,
10#   range end - last IP address to check.
11# Example:
12#   pingall 10.0.0.10 10.0.0.20 
13#   Checks all the addresses between .10 and .20
14# Author:
15#   Konrad Siek
16
17use Socket;
18
19# Quit, if no range is specified.
20# Note: Number of parameters in Perl is one lower.
21die "Usage: $0 <range start> <range end>\n" if ($#ARGV != 1);
22
23# Validate IP and return its more manageable form.
24sub to_ip {
25    my $message = "$_[0] is not a valid IP.";
26    my @array = split(/\./, $_[0]);
27    die $message if $#array != 3;
28    foreach $e (@array) {
29        die $message if $e =~ m/[^0-9]+or $e > 255;
30    }
31    return @array;
32}
33
34# Check the validity of range IPs and turn them into arrays.
35my @start_range = to_ip(@ARGV[0]);
36my @end_range = to_ip(@ARGV[1]);
37
38# Increment the IP to the next. Roll over if overflow occurs.
39sub increment {
40    @array = @_;
41    for($i = 3; $i >= 0;) {
42        if(@array[$i] >= 255) { 
43            $i--;
44        } else {
45            @array[$i]++;
46            return @array;
47        }
48    }    
49    return (0000);
50}
51
52# Compare two IP arrays.
53sub compare {
54    @a = @_[0..3];
55    @b = @_[4..7];
56    for($i = 0; $i < 4; $i ++) {
57        if(@a[$i] < @b[$i]){
58            return -1;
59        }
60        if(@a[$i] > @b[$i]){
61            return 1;
62        }
63    }
64    return 0;
65}
66
67# Prepare list of addresses within range.
68@addresses = ();
69while (compare(@start_range@end_range) <= 0) {
70    @addresses[++$#addresses] = join('.'@start_range);
71    @start_range = increment(@start_range);
72}
73
74# Ping each of the addresses from the prepared list.
75foreach $address (@addresses) {
76    my $return = `ping -c 5 $address > /dev/null && echo 1`;
77    my $state = $return == 1 ? '+' : '-';
78    my $inet_addr = inet_aton($address);
79    my $hostname = gethostbyaddr($inet_addr, AF_INET);
80    print "[$state]\t$address\t$hostname\n";
81}


The code is also available at GitHub as perl/ping_all.
Continue Reading...

Quantum Of Solace [DVDSCR.MD]


Synopsis: Même s'il lutte pour ne pas faire de sa dernière mission une affaire personnelle, James Bond est décidé à traquer ceux qui ont forcé Vesper à le trahir. En interrogeant Mr White, 007 et M apprennent que l'organisation à laquelle il appartient est bien plus complexe et dangereuse que tout ce qu'ils avaient imaginé... Bond croise alors la route de la belle et pugnace Camille, qui cherche à se venger elle aussi. Elle le conduit sur la piste de Dominic Greene, un homme d'affaires impitoyable et un des piliers de la mystérieuse organisation. Au cours d'une mission qui l'entraîne en Autriche, en Italie et en Amérique du Sud, Bond découvre que Greene manoeuvre pour prendre le contrôle de l'une des ressources naturelles les plus importantes au monde en utilisant la puissance de l'organisation et en manipulant la CIA et le gouvernement britannique... Pris dans un labyrinthe de traîtrises et de meurtres, alors qu'il s'approche du vrai responsable de la trahison de Vesper, 007 doit absolument garder de l'avance sur la CIA, les terroristes et même sur M, afin de déjouer le sinistre plan de Greene et stopper l'organisation..
.
Continue Reading...

Le Jour où la Terre s'arrêta

Synopsis: L'arrivée sur Terre de Klaatu, un extraterrestre d'apparence humaine, provoque de spectaculaires bouleversements. Tandis que les gouvernements et les scientifiques tentent désepérément de percer son mystère, une femme, le docteur Helen Benson, parvient à nouer un contact avec lui et à comprendre le sens de sa mission. Klaatu est là pour sauver la Terre... avec ou sans les humains.

Continue Reading...

Mesrine : L'Instinct de mort


Synopsis Des années 60 à Paris au début des années 70 au Canada, le parcours criminel hors norme d'un petit voyou de Clichy nommé Jacques Mesrine.

Continue Reading...

Naruto Shippuden - Le Film 1


Synopsis:
Naruto va mourir ! En effet, notre ninja doit protéger Shion, la prêtresse du pays des démons. Elle est la seule à pouvoir sceller un monstre qui menace de détruire notre monde. Mais Shion a également prédit sa mort à Naruto. Pour éviter que cette prophétie ne se réalise, le jeune homme doit s’écarter de Shion, mais il est bien décidé à mener sa mission jusqu’au bout... Hajime Kamegaki.


Continue Reading...

Mamma Mia !


Synopsis :C'est en 1999, sur la ravissante île grecque de Kalokairi que l'aventure romantique commence, dans un hôtel méditerranéen isolé, la villa Donna, tenu par Donna, sa fille Sophie et le fiancé de Sophie, Sky. Juste à temps pour son mariage prochain, Sophie poste nerveusement trois invitations destinées à trois hommes bien différents dont elle pense que l'un d'eux est son père. De trois points du globe, trois hommes s'apprêtent à retourner sur l'île - et vers la femme - qui les avait enchantés 20 ans auparavant.

Continue Reading...

Rédemption


Synopsis: Sean Porter, un officier contrôleur judiciaire, a décidé de créer une équipe de football avec des jeunes détenus réputés pour être dangereux. Il est convaincu que c'est le seul moyen de leur enseigner leur respect d'eux-mêmes et des autres et de leur apprendre à s'intégrer dans la société. Mais Porter doit auparavant faire face à la résistance de ses supérieurs et à l'hostilité des coaches des autres équipes universitaires qui ne veulent absolument pas voir leurs joueurs affronter des criminels sur le terrain.

Continue Reading...

pineapple express




http://rapidshare.com/files/156577835/Pineapple.Express.2008.DVDSCR.XviD-HEFTY.part1.rar
http://rapidshare.com/files/156621330/Pineapple.Express.2008.DVDSCR.XviD-HEFTY.part2.rar
http://rapidshare.com/files/156651691/Pineapple.Express.2008.DVDSCR.XviD-HEFTY.part3.rar
http://rapidshare.com/files/156673189/Pineapple.Express.2008.DVDSCR.XviD-HEFTY.part4.rar
Continue Reading...

Grizzly Park - Exclue [DVDRIP]




Lien Rapidshare poster par nemesis5454 :
http://rapidshare.com/files/130683994/BonG-Gp-Nems.part1.rar
http://rapidshare.com/files/130685195/BonG-Gp-Nems.part2.rar
http://rapidshare.com/files/130686093/BonG-Gp-Nems.part3.rar
http://rapidshare.com/files/130686580/BonG-Gp-Nems.part4.rar
Continue Reading...

Happy strings

Yup, it's Dada again! I love useless things!

So, I was browsing through Think Python and found an exercise to print stuff on the screen. I figured it would be fun just to make it in one go - no loops or anything.

Here's how it looked. And by the way, you can run all the code in a Python interpreter - it's all safe.

1print \
2( ('+' + 5 * '-') * 3 + '+' + "\n" + \
3( ( '|' + 5 * ' ' ) * 3 + '|' + "\n" ) * 2 ) * 3 + \
4('+' + 5 * '-') * 3 + '+'


But then I figured... that's not nearly fun enough. So, long story short, I made this:

1print \
2',' + '_' * 2 + ',' + '\n' + \
3'(' + 'x' * 2 + ')' + '_' * 4 + '\n' + \
4'(' + '_' * 2 + ')' + ' ' * 4 + ')' + '\\' + '\n' \
5+ ' ' + 'U' + '|' * 2 + '-' * 2 + '|' * 2 + ' ' * 2 + '*'


Much more fun.

So then, I took it up a notch and wrote a program to generate that sort of thing. It took me three complete attempts, because I mostly produced bugs today... damn bugs. But it's all nice and thought-through now.

Here's the code:
#!/usr/bin/python
#
# Happy strings

# More or less purposeless script, which takes strings, splits
# them up  into characters and then creates a Python print 
# statements which  reproduce the same strings in a 
# complicated, slightly less readable form... but a slightly 
# happier form, methinks.
10#
11# Parameters:
12#   a list of strings to reproduce
13# Author:
14#   Konrad Siek
15
16import sys
17
18def escape_string(string):
19    if string in ["\'", "\"", "\\"]:
20        return "\\" + string
21    elif string == "\n":
22        return "\\n"
23    return string
24
25def output_string(string, counter, last):
26    output = "'" + escape_string(string) + "'"
27    if counter != 1:
28        output += ' * ' + str(counter)
29    if not last:
30        output += ' + '
31    return output
32
33for string in sys.argv[1:]:
34    output = 'print '
35    previous = None
36    counter = 0 
37    length = len(string)
38    for i in range(0, length):
39        character = string[i]
40        if character == previous:
41            counter += 1
42        else:
43            if previous != None:                
44                output += output_string(
45                    previous, 
46                    counter, 
47                    False
48                )
49            counter = 1
50            previous = character
51    output += output_string(
52        previous, 
53        counter, 
54        True
55    )
56    print output
57


Yay!

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

lala moulati ana9a maghribia

seo

 

Blogroll

Site Info

Text

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