Sunday, March 27, 2011

How to retrieve your twitter feeds in PERL

Retrieving twitter feeds is very simple and easy, you only need an HTTP request that returns format such as JSON, XML, RSS, and ATOM. This method doesn't require authentication.

Just follow the simple steps below using PERL. Hope you like it!

1. Install LWP::UserAgent in your server.

2. Initialize libraries, header and user agent.

require LWP::UserAgent;

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://api.twitter.com/',
             'User-Agent' => $uagent);

3. Compose the HTTP request.

my $twuser = '<your twitter username>';
my $twurl = "http://api.twitter.com/1/statuses/user_timeline.<format>?screen_name=$twuser";

Supported Format:
  • JSON
  • XML
  • RSS
  • ATOM
URL Parameters:
  • user_id - The id of twitter account you want to retrieve.
  • screen_name - The username of twitter account you want to retrieve.
  • since_id - This will return the feeds after or more than the specified message id.
  • max_id - This will return the feeds before or less than the specified message id.
  • count - The number of tweets to be retrieve.
  • page - This will specify the page of the result to retrieve.
  • trim_user - When set to either true, t or 1, each tweet returned in a timeline will include a user object including only the status authors numerical id.
  • include_rts - When set to either true, t or 1, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets.
  • include_entities - When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future.
4. Execute HTTP GET request.

my $response = $lwpua->get($twurl, @header);
my $return = $response->content;


That's it!! Please see below for the complete code using JSON format.

#!/usr/bin/perl

require LWP::UserAgent;
use JSON;

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://api.twitter.com/', 'User-Agent' => $uagent);

my $twuser = '<your twitter username>';
my $twurl = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$twuser";

my $response = $lwpua->get($twurl, @header);
my $return = $response->content;

my $json = JSON->new->allow_nonref;
my $json_text = $json->decode($return);

my @tweets = @{$json_text};

my $message;
foreach $tweet (@tweets)
{
  $message .= $tweet->{text}."\n";
}

print "$message";



1;

Resource: dev.twitter.com

Wednesday, March 23, 2011

How to set up an auto adjust width and height in CSS

Again, our best friend IE has it's own way of doing things. IE interprets width and height as min-width and min-height which is totally different from other browser. Given that, this can be a problem if we want our container to adjust accordingly to the content we want to display.

To resolve this, please see below.

#container {
        background-color:#FFFFFF;
        width:840px;
        height:450px;
}
html>body #container {
        height: auto;
        width: auto;
        min-height:450px;
        min-width:840px;
        overflow:hidden;
}

All browsers including our best friend IE will read through the first set of CSS rule #container and the second set will not be interpret by IE because it uses child selector 'html > body' in which interprets Non-IE browser.

Monday, March 21, 2011

How to get latitude and longtitude values from google maps

There are 2 ways on how to get the latitude and longtitude coordinates from google maps.

First option is to get it using javascript:

Just follow the simple steps below to do it.

1. Go to google maps website - http://maps.google.com

2. Click to the center of the site you want.

3. Once you are at the center, copy and paste the code below on your browser's address bar.

javascript:void(prompt('',gApplication.getMap().getCenter()));

4. A pop-up message will prompt with the latitude and longtitude values enclosing with parenthesis.

5. Check the returned values by putting it to google maps search bar and enter. An arrow will point to the map where the location is.

Problem here is that you have to be at the center of the Map to get the actual coordinates.

Resource: http://lifehacker.com


Second is to get it the easier way by enabling the options on your google maps account:

Just follow the simple steps below to activate.

1. Go to google maps website - http://maps.google.com/

2. Log-in to your google account.

3. On the upper right corner of the page, you will see the Options Icon tab.

4. Click the Options Icon tab and select "Maps Labs".

5. A lightbox page will pop-up displaying all the options available for google maps.

6. Set the "LatLng Tooltip" and "LatLng Marker" to ENABLE, then save changes.

7. Go to the map, zoom in until you get to the site you want, then click and hold the "Shift" key on your keyboard.

8. You will noticed that every time you move the cursor while holding shift button, latitude and longtitude changes accordingly.


Hope you like it!! Yeah men!!

Sunday, March 20, 2011

Setting up a style in table header and data records

Just sharing you the basic but a good look style for table display.

table tr td, table tr th {
        font-size: 9px;
        background-color: #ECEFF5;
        border: 1px dotted #0B3485;
        color: #0B3485;
        height: 25px;
        padding: 2px;
        vertical-align: middle;
}


Details are as follows:
  • font-size - The size of the font you want.
  • background-color - The background color of your table.
  • border - The border of your table, I set it to 1px dotted to be not so usual.
  • color - The color of your text.
  • height - The height of each table row.
  • padding - This is to setup a padding in displaying records.
  • vertical-align - To align the data vertically. I set it to middle to vertically align it in center.

Setting up a style in form input button

By default, input button and submit type is not really in a good look.. I recommend to style it with a simple CSS entry below. Hope you like it!!

input[type="button"], input[type="submit"] {
    background-color#1E6591;
    border2px solid #1E6591;
    color#FFFFFF;
    font-size11px;
    font-weightbolder;
}


Details are as follows:
  • background-color - This is the background color of your button.
  • border - The border of your button.
  • color - The color of the text in a button.
  • font-size - The font size of the text of the button.
  • font-weight - The font weight of the text of the button. This is either normal or bold. By default it's equal to normal.

Setting up a style in form input text and textarea

By default, input text and textarea in a form is not really in a good look.. I recommend to style it with a simple CSS entry below. Hope you like it!!

input[type="text"], textarea {
        background: #f9f9f9;
        border: 1px solid #ccc;
        box-shadow: inset 1px 1px 1px rgba(0,0,0,0.1);
        -moz-box-shadow: inset 1px 1px 1px rgba(0,0,0,0.1);
        -webkit-box-shadow: inset 1px 1px 1px rgba(0,0,0,0.1);
        padding: 2px;
        font-family: "lucida grande",verdana,tahoma,arial,sans-serif;
}


Details are as follows:
  • background - This will be the color of the box shadow
  • border - Color of the box border
  • box-shadow - This is the current standard in CSS shadow settings
  • -moz-box-shadow - This is used to support way too old version of Mozilla
  • -webkit-box-shadow - This is used to support other browser
  • padding - To implement padding between other elements.
  • font-family - To put a style in fonts for textarea and input text.

Hope this helps a lot. Happy coding!!

Wednesday, March 16, 2011

How to checkin to foursquare via backend using PERL and PHP

Checking in to foursquare is more likely the same as posting a shout out, tweet or status in social network like facebook and twitter.

Foursquare follows authentication via OAuth and this post will teach you how to do it via back-end using PERL and PHP.

I assume you already read my post on how to Login to foursquare via back-end in PERL. You should be able to understand it first to proceed with authentication and do the check-in in users behalf.

Just follow the simple steps for your implementation.

1. You must have a Client ID and the Callback URL. If you don't have yet, create one by going to foursquare developers link - http://developer.foursquare.com/

2. To register a new consumer, click the "Manage OAuthConsumers" link or go to OAuth page - https://foursquare.com/oauth/

3. Enter your Application Name, Application Website, and Callback URL. Please take note that your Callback URL will be your Redirect URI.

4. After successful registration, Client ID and Client Secret will be generated.

5. What we need from now is the Client ID and once we have it, we can now start the coding part.

6. First thing we have to do is to login to users account via back-end. Please see post - Login to foursquare via back-end in PERL

7. After successful login, next step is to authenticate your application. To authenticate your app, you should pass a Client ID and your Callback URL that was registered from Consumer Registration.

$client_id = '<your client id>';
$redirect_uri = '<your callback url>';

$response = $lwpua->get("https://foursquare.com/oauth2/authenticate?client_id=$client_id&response_type=code&display=touch&redirect_uri=$redirect_uri", @header);

$form_data = $response->content;
$form_data =~ s/\n//g;

8. If this is the first time you authenticate your app, return page will be asking users permission to "Allow" the application to access account details and transact in users behalf. We can do this in back-end by implementing REGEX to get the NAME parameter of the value="Allow", then passed it on to authentication URL - https://foursquare.com/oauth2/authenticate.

$form_data =~ /form method="post" action="(.*?)"(.*?)input value="Allow" type="submit" name="(.*?)" class="input_button"/ig;

$form_action = $1;
$form_allow = $3;

$response = $lwpua->get("https://foursquare.com/oauth2/authenticate?$form_allow=Allow", @header);
$form_data = $response->content;

9. After allowing the application, foursquare will redirect the user to redirect URI that we set on step #7. Your callback URL or redirect URI must capture the CODE parameter and exchange it with TOKEN. This can now be done via PHP.

10. Foursquare will pass the CODE parameter via GET method on our Callback URL. Our Callback URL should be able to capture it and use it in exchange of an access token. To get an access token, we should pass the CODE parameter, Client ID, Client Secret, Callback URL, and Grant Type to the access token URL - https://foursquare.com/oauth2/access_token. Client ID, Client Secret, and Callback URL are data from the consumer registration, and the Grant Type should be equal to "authorization_code". Please take note that this is now on PHP.

$client_id = '<your client id>';
$client_secret = '<your client secret>';
$redirect_uri = '<your callback url>';
$grant_type = 'authorization_code';

$code = $_GET['code'];      
$oauthurl = "https://foursquare.com/oauth2/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=$grant_type&redirect_uri=$redirect_uri&code=$code";

11. As per implementation below, I use the open stream to get the contents and convert it to JSON which will then return an object with an access token.

$url_handler = fopen("$oauthurl", 'r');
$json = json_decode(stream_get_contents($url_handler));
fclose($url_handler);

$token = $json->access_token;

13. Now that you have the Token, we are now ready to do the Foursquare Check-in. Going back to PERL, what we need to do here is to do a POST request to Foursquare API URL - https://api.foursquare.com/v2/checkins/add. venueId will be the place or location you want to check-in, shout is optional if you want your post to have a custom message, broadcast can be of public or private, and lastly the oauth_token which is the access token we get from step #12. Again, this is now in PERL.

$intVenueID = "<the venue id you want to check-in>";
$strShout = "<your shout message>";
$strToken = "<your access token>";

$response = $lwpua->post("https://api.foursquare.com/v2/checkins/add",
                      ['venueId' => $intVenueID,
                       'shout' => $strShout,
                       'oauth_token' => $strToken,
                       'broadcast' => 'public,faceboook,twitter'], @header);

print $response->content;

That's it!! Hope you were able to follow. In case you don't, you can refer to the scripts below. Good luck and enjoy!!

- Here's the PERL script, it composes of 2 sub functions: check_foursquare_login() and post_foursquare_checkin()


#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://foursquare.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = "<your foursquare username>";
my $strPass = "<your foursquare password>";
my $client_id = "15NGPG2GHI3S1UFMST01FOO0ABPXNFFTGJVTVSZS55W1UN4A";
my $redirect_uri = "http://localhost/foursquare/foursquare.php";
my $status = "testing foursquare status";

my $form_data = &check_foursquare_login($strUser, $strPass, $client_id, $redirect_uri);

if ($form_data =~ /^OK\|/)
{
  my ($strTag, $intUserID, $strToken) = split /\|/, $form_data, 3;
  &post_foursquare_checkin($intUserID, $strToken, '', $status);

  unlink($cookie_file);
  print "done!";
}
else
{
  $form_data =~ /form method="post" action="(.*?)"(.*?)input value="Allow" type="submit" name="(.*?)" class="input_button"/ig;

  my $form_action = $1;
  my $form_allow = $3;

  my $response = $lwpua->get("https://foursquare.com/oauth2/authenticate?$form_allow=Allow", @header);
  $form_data = $response->content;

  if ($form_data =~ /^OK\|/)
  {
    my ($strTag, $intUserID, $strToken) = split /\|/, $form_data, 3;
    &post_foursquare_checkin($intUserID, $strToken, '', $status);

    unlink($cookie_file);
    print "done!";
  }
  else
  {
    unlink($cookie_file);
    print "error authentication!";
  }
}

sub check_foursquare_login
{
  my ($strUser, $strPass, $client_id, $redirect_uri) = @_;

  # log-in to foursquare
  my $response = $lwpua->post('https://foursquare.com/mobile/login',
                      ['username' => $strUser,
                       'password' => $strPass], @header);
  $cookie_jar->extract_cookies( $response );
  $cookie_jar->save;

  $response = $lwpua->get("https://foursquare.com/oauth2/authenticate?client_id=$client_id&response_type=code&display=wap&redirect_uri=$redirect_uri", @header);

  $form_data = $response->content;
  $form_data =~ s/\n//g;

  return $form_data;
}

sub post_foursquare_checkin
{
  my ($strUserID, $strToken, $intVenueID, $strShout) = @_;
  my ($response);

  $response = $lwpua->post("https://api.foursquare.com/v2/checkins/add",
                      ['venueId' => $intVenueID,
                       'shout' => $strShout,
                       'oauth_token' => $strToken,
                       'broadcast' => 'public,faceboook,twitter'], @header);

  return $response->content;
}



1;


- Here's the PHP script. Save this in your web server and set this as your callback URL in consumer registration.


<?

$client_id = "15NGPG2GHI3S1UFMST01FOO0ABPXNFFTGJVTVSZS55W1UN4A"; // hotshots client id
$client_secret = "NEHCL3UL0KS1QJD22NLIQ5RMR4BL4IUZIJZW25VHSJ4JPZKB";
$grant_type = "authorization_code";
$redirect_uri = "http://localhost/foursquare/foursquare.php";

$code = $_GET['code'];

if ($code) {
        // get access token
        $oauthurl = "https://foursquare.com/oauth2/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=$grant_type&redirect_uri=$redirect_uri&code=$code";

        $url_handler = fopen("$oauthurl", 'r');
        $json = json_decode(stream_get_contents($url_handler));
        fclose($url_handler);

        $token = $json->access_token;
        if ($token) {
                $info_contents = `curl https://api.foursquare.com/v2/users/self?oauth_token=$token`;
                $json = json_decode($info_contents);
                $userid = $json->response->user->id;

                echo "OK|$userid|$token";
        }
}


?>

Monday, March 14, 2011

How to embed a custom youtube player in your website


For you to be able to embed a youtube player in your website, you should have a youtube account to access into.

If you have one already, just follow the simple steps below and you were able to create a custom player that you can put into your website.

1. Go to youtube website - http://youtube.com and enter your username and password.

2. Once logged-in, go to custom player page - http://www.youtube.com/custom_player.

3. On the custom player page, enter your desired player name and description.

4. Select the theme color that you like.

5. Select the layout for your player.

6. Choose the content that you want to be played. Contents are either your own videos, your favorite videos, or one of your playlist. Don't forget to click the "Select" button to confirm the contents that you want.

7. To finally generate the code, just click the "Generate Code" button and the embed code will be generated.

8. Copy the embed code and click the "Finish" button to go to your list of players.

9. To add the newly created player into your site, just paste the code you just copied and save it. You should be able to see the player you just created in your site.

10. To edit your players, go to this link - http://www.youtube.com/my_players then select the player you want to edit. The chosen layout will not be editable.

Hope you like it!! This is just a sample implementation. Thank you for reading this post.

Thursday, March 10, 2011

Converting numeric values to currency formatted numbers in PERL

While developing a particular report in Perl, I just noticed that my output for currency values are just numbers without commas and decimal points. So, I do some research to check for an existing function in Perl that simply do this conversion but didn't find anything.. No choice.. I have to create a sub function that converts numeric values to currency values, and I did and now sharing this to you..

Please see sample code and sub function that I just created. Hope you like it!!

#!/usr/bin/perl

$number = 4356789; # sample data
$currency = &convert_to_currency($number);

print "Here we go in Peso value: P$currency\n";

sub convert_to_currency
{
        my ($number) = @_;

        $number = sprintf("%.2f", $number);
        $number = "$1,$2$3" while ($number =~ /(.*\d)(\d\d\d)(.*)/i);
        return $number;
}



1;

Sunday, March 6, 2011

CSS class for transparency that all browsers support

Personally, one of my favorite in web designs are transparency. It gives life to your site as you will have layers of texts and images in one look.

It's great thing haa!! but did you know that having that in your site is a challenge for us programmers? That is because we have to consider all browsers to support transparency in one time setting.

Good thing..!! The class below will resolve the implementation of transparency for all browsers.

.transparency {
    opacity: 0.5;
    filter: alpha(opacity=50);
    -moz-opacity: 0.5;
    -khtml-opacity: 0.5;
}

Below are the CSS properties we used:
  • opacity: 0.5; - This is the current standard in CSS transparency settings. This will work in most versions of Firefox, Safari, and Opera.
  • filter: alpha(opacity=50); - This one is for our best friend IE.
  • -moz-opacity: 0.5; - This one you need for way too old version of Mozilla.
  • -khtml-opacity: 0.5; - This one you need for old Safari (1.x).
Resource: css-tricks.com

Thursday, March 3, 2011

How to create a directory watcher in PERL


Most of the time, we want to achieve a REAL-TIME processing. However, there are some limitations that we don't have control over, and one of the best example is without having a direct connection to the application you are processing into.

One way to achieve a REAL-TIME processing without a direct connection is to have a back-end processing that will watch and process transactions. This is what we called directory watcher.

With this post, it will help you create a directory watcher in PERL. Just follow the simple steps below to do that.

1. Set the look up directory where you want your script to look into.

2. Create a NON-ENDING loop using WHILE() syntax. To create a NON-ENDING loop, we just have to pass a variable or condition that will always results to TRUE. Example below pass a variable 1 that results to TRUE. And as best practice, a SLEEP function should be implemented every end of each loop, this is for the script not to eat too much of the memory.

while(1) {
  # this creates a non ending loop coz 1 is equal to true..

  sleep 1;
}

3. Inside your WHILE loop, you have to OPEN the look up directory by using OPENDIR() syntax. And as best practice, you need to close the directory every end of the loop.

opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";

4. Loop the files we read from a look up directory.

opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";
while ($file = readdir(DIR))
{
  # file names from a reading directory...
}
closedir DIR;


Hope you like it!! Please see the complete code below for your implementation.

#!/usr/bin/perl

$lookup_dir = "<directory to look into>";

while(1)
{
        print "lookup directory: $lookup_dir\n";

        opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";
        while ($file = readdir(DIR))
        {
                if (($file ne '.') && ($file ne '..') && ($file !~ /^\./))
                {
                        print "here file: $file\n";
                        # do what you want with the file...
                }
        }

        closedir DIR;
        sleep 1;
}




1;

How to make a form post request in PERL


The FORM POST is the most common method of transferring data to a web application. On this post, we will have this implement in PERL which is known to be a back-end processing script.

This is really simple, just follow the 3 simple steps below.

1. Install the Perl Library in your server.
  • LWP::UserAgent

2. Initialize user agent and headers.

require LWP::UserAgent;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => '<domain of where to do post request>',
             'User-Agent' => $user_agent);

3. Execute post request with the Parameters in array form and get the return by calling $object->content.

$response = $lwpua->post('<url of where to do post request>',
                            ['<parameter1>' => '<value1>',
                             '<parameter2>' => '<value2>',
                             '<parameter..n>' => '<value..n>'], @header);

$return = $response->content;

Hope you like it!! Please see code below for the complete implementation of form post request.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://domain.to.post.com',
             'User-Agent' => $user_agent);

$response = $lwpua->post('http://domain.to.post.com/some.action.page',
                            ['parameter1' => 'value1',
                             'parameter2' => 'value2',
                             'parameter3' => 'value3'], @header);

$return = $response->content;

print "$return\n\ndone!";



1;

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.