Popular posts

Pages

Saturday, April 23, 2011

A Beautiful Thought

When I read it at first, I did not think of it much. But as I dwelt upon it, gradually the truth behind the idea made itself completely evident. I had heard it umpteen times before, from elders, in books, in the form of quotes, but this was the simplest and most effective form of it. It is: "Thoughts crystallize into actions, and actions quickly solidify into habits". Simple as that. It is very succinct and discreet, but holds the wisdom of worlds.
To test the veracity of the said statement, I took examples from my own experience. To my surprise, it never failed. And why should it? Of-course some wise man must have seen the world before he said it.

Thoughts, then, are the ultimate foundation upon which the outcome of every event of our life rest. Which is why every great man, be it Bapu, Einstein or as a matter of fact even Hitler, emphasized on changing the core thoughts of the masses to obtain desired result. It is only natural that thoughts which reside inside of us, will, in someway express themselves. It is then, only a matter of time and circumstance, that the faithful servant of thought, Action, will show itself. And it is straight-forward enough, you will reap the outcomes of the similar fashion. You will agree with me that if one continues to be in some state of mind, he becomes, or in other words, starts living that state sooner or later. He becomes that state eventually. That state becomes his habit of living and it is certain that everything that will follow in his life will be a mere extension to his state of mind.
Let us take the very typical example of a dissatisfied employee. He may be unhappy with his compensation, environment, the way his employer behaves with him, or he does not find himself suitably skilled with the role of the job. If the employee is a person who harbors only negative thoughts, let us see what is most likely to happen. Since he is unhappy with his work, all negatives thoughts surround him. He thinks ill of his boss, lowly of his job and his life. Action follow thoughts. His interest will suddenly decline in job. He is mostly seen cribbing about everything in his life and polluting the air around him by spreading negativity. Now as a result of all this, the only logical outcome is that the boss notices that he is a non-performer and is morally degrading the environment, and dismisses him, perhaps after some counselling which turns out to be futile and ends in a fight. So, we see that the thoughts which the person fixated upon, finally, resulted in negative outcome for him and most probably for people around him, like his family. Now in same circumstances, had the person been of a positive mindset, the outcome would have been greatly opposite. He thinks foremost, that as he is unhappy about his job he has to do something about it. He thinks of improving his skills, or speaking to the boss, about what is it that is wrong with him. As the thoughts mature, his actions imitate them. He starts building his skills and makes himself better than he was yesterday, or the day before. His mood also cheers up. The quality of his work improves inch by inch and it begins to shine. Then it becomes a habit. With his new found energy and enthusiasm he gives innovative ideas and profitable inputs to the business. A day comes, when amazed by the changes, his boss gives him a raise, and starts trusting him. Good things begin to happen. New opportunities also find him, like a much better job, good friends, and eventually his life takes a 360 degree turn. And he then himself becomes the the state, with which he started.

These examples are common in life and I have witnessed both cases first hand. It can be confidently said, that if one controls his thoughts, he can change his life. There is nothing which can stop him. Because the truth is, what you think, you become. It will not happen suddenly, but gradually it is bound to happen. All that is required to build your thinking and keep your thoughts high and unperturbed. Nature is such, that what you keep thinking, will slowly surround you in your everyday life. From no-where, things, opportunities, people and events which match your frequency of thinking will come to you from all directions. If you are sensitive you may already have noticed it happen at some point, but may have attributed it to chance. It is not chance but a law of nature.

There are no limits to the benefits that we can draw from this knowledge. We can reach anywhere we want, we can learn any skill we wish to, we can be as rich as aspire ...anything is possible. The only mandate is, those positive thoughts, are to be kept alive in one's mind, undiminished, untarnished by tiny obstacles, which naturally will come along the way. There is absolutely nothing which cannot be achieved. Remember, what we think, we will do. And what we do, the outcome will invariably be of same nature. Keep your thinking high and you will always reach higher.

- the usual me

Saturday, April 9, 2011

perl script to use google language translate API

I created this script which translated text from one language to another using yahoo's http://babelfish.yahoo.com/ services. But its not the one which i'm going to talk about. That is because in the yahoo version i used perl's LWP module to do a post query on the yahoo server and get back the http response, much like what we see on a browser, and got the translated text using pattern matching operations. That is one crude way of getting things done, but it works!

Now this does the same job but using google services (translate.google.com) and the respective APIs. Its a more sophisticated and efficient way of achieve the same result. Google has exposed the API and the methods for doing this job. You can call them from applications such as - your software, your mobile app, your website or a small script (like tihs one), etc. Mind you, it is illegal to use it for commercial purposes.

For this translate API, you've to generate an activation key (tied to your google account). 
First section is the creation of a LWP::UserAgent object. Then for sanity, convert the text to webformat. Then I've created the url with editable parameters as variables. The text to be converted is $str and needs to be given as command line argument. I like German so its my language of choice for converted text. The response object is created by the get function on UA object. The 'content' method is used on response object for the output, whereas the error state and message are captured in 'is_success' and 'status_line' methods of the response obj. Again, for the desired line in the http response content we need to use pattern matching as shown.

The idea is, how the google (or any) api can be leveraged with perl's lwp module to do some fun programming or something more useful which can solve real problems at your work/school/college. If you've something to share, do comment.
Here's the code:

## google translate API

# https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q=hello%20world&source=en&target=de

use Strict;
use LWP::UserAgent;
use URI::Escape;

if ($ARGV[0] eq "") {
print "Usage: perl lwp12 \"text to be converted\""; die; }
$ua = LWP::UserAgent->new();

$str = uri_escape ($ARGV[0]);
$tolang = "de";

$url = "https://www.googleapis.com/language/translat/v2?key=<yourPersonalKeyHere>&q=" 
. $str 
. "&source=en&target="
. $tolang;

$resp = $ua->get ($url);

if ($resp->is_success) {
$newstr = $resp->content;
$newstr =~ /Text":\s"(.*)"\n/;
print "Text in $tolang:\n$1\n"; }

else { print "Program failed with message: ", $resp->status_line;}
# END


Here is how it runs:

>perl lwp12googletranslate.pl "My first program."
Text in de:
Mein erstes Programm.


Output while error handling:

>perl lwp12googletranslate.pl "my first wife"
Program failed with message: 404 Not Found

Monday, April 4, 2011

perl program to report port status

This program here checks and reports the status of ports on a windows machine. The objective was to check whether some application (web site) was running and hence using those ports. The logic is simple. The ports (actually, ip:port combination) which are needed to be monitored are listed in a file. This could have been kept inside the code, for better performance. But i wanted to keep the "logic" portion separate from "data" portion so data / logic can be edited independently without affecting other by mistake. And ofcourse it is easier for the user to open a file and edit the port file, rather than going through the code and getting in unimportant details. So the port status is available thru windows "netstat -an" command. The status of our ports is checked and the output is logged into a separate log file. This log file, by the way, is read by another software which then puts the data on display for the user. Here's the program. First section is the custom timestamp for log file. Then every port entry in our file (first foreach loop) is compared with every netstat o/p line (second foreach loop) and mark a flag if matched. Then get out of inner loop, check the flag value, and log the entry with a custom message. I guess thats about it. At some places, such as pattern matching, it can be done more efficiently (with less characters) but i like to keep it simple. i think some advanced users may be able to do it with lesser line of code too. Basically it is a straight forward program which produces desired results. For perl beginners it might prove to be helpful and can be used in other similar situations.

#
#
# Purpose: Script to report status of active ports on Windows machine
# Associated Files: 
# 1. portlist.txt - list of ports. File required in current directory.
# 2. log_status.txt - port status log. File is generated in current directory.
# Date: 29 March 2011 
# Author: Abhishek Danej
# Revisions:
#

use Strict;
use Time::Local;

##
## USER EDITABLE PARAMETERS
##
$portfile = "portlist4.txt"; #path to list of ports file
$logfile = "log_status.txt"; #path to log file
$true_msg = "Listening"; #success message in log file
$false_msg = "Not found"; #failure message in log file
##
## END
##

## NON USER EDITRABLE SECTION

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$mon = $mon+1;
foreach $val ($sec, $min, $hour, $mday, $mon) {
$val = "0" . $val if ($val < 10); 
}
$timestamp = ($year+1900) . "-" . $mon . "-" . $mday . "," . $hour . ":" .  $min . ":" . $sec;

#$timestamp = scalar(localtime());
$host = `hostname`;
chop ($host);

open (LOG, ">>$logfile") || die "Cannot open Log file";

#@portlist = ("4757","1111","1101","6000","7153","57153");
unless (open (PORTS, "<$portfile")) {
print LOG "$timestamp ERROR: Cannot open portlist.txt file, program quitting.\n";
die "Cannot open port file."; }
@portlist = <PORTS>;

open (FH, "netstat -an |");
@lines = <FH>;

foreach $ip_port (@portlist) {

$flag = 0;
$ip_port =~ s/\s*\b(\d+\.\d+\.\d+\.\d+):(\d+)\b.*\n*/$1:$2/;
next if ($ip_port !~ /:/);
print "Now checking: $ip_port";
# EACH LINE OF NETSTAT
foreach $line (@lines) {
if ($line =~ /$ip_port\b/ && $line =~ /LISTENING/ && $line =~ /\b0.0.0.0\b/) {
$flag = 1;
last; }
}
if ($flag == 1) {
print LOG "$timestamp,$host,$ip_port,$true_msg\n"; }
else {
print LOG "$timestamp,$host,$ip_port,$false_msg\n"; }

}

close (PORTS);
close (LOG);
# END