Getting easy badges on Stack Overflow

Stack Overflow uses Badges as a gamification technique to increase user activity. If you’re looking to get a couple of badges easily without much effort on your own part, look no further than the Enthusiast and Fanatic badges.

Stack Overflow badges

All you have to do to gain each of these badges is view the site (while logged in with your account) for 30 consecutive days for the Enthusiast bagde, and 100 consecutive days for the Fanatic. If however you have multiple linked accounts, this can be a bit tedious, as you have to view the site for each account (i.e. Serverfault, Programmers, WordPress etc).

To automate this process on a windows PC, we can create a simple batch script that can open up your preferred browser with multiple tabs. This means we just have to double click the batch file to open up the various sites in a browser, and as long as we haven’t actually logged out of Stack Overflow, the site will update our “consecutive days visited” count.

In this example I’ll use Firefox, as you can use the commandline to open up a new FireFox window, with tabs to specified URLs. This is helpful because I’ll put the custom command line arguments in the batch file to automate opening up the websites in the browser. I’ll create a new batch file called stack.bat on my C:\. The batch file will have the following contents.

@echo off
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" "http://stackoverflow.com/users/XXXX" "http://gamedev.stackexchange.com/users/XXXX"

To further automate the process, we will use the Windows Task scheduler to create a daily task that will run our batch file every day. This removes the need for any manual steps in the process, so that we won’t have to worry about actually doing anything in order to get the badges (i.e. this will remove the risk of accidentally missing a day).

To create a daily task, go to the Control Panel > Schedule tasks.

windows scheduler

Then select from the menu, Action > Create a Basic Task.

windows scheduler basic task

This will bring up the basic task wizard, where you can give the task a name and a description, then click next. The trigger is what will cause the task to run, so select “Daily” and the time of day you want the task to run. For action, select “Start a program”, and then browse to the batch program. You can then click next and finish.

windows scheduler basic task details

You can of course do this on a Mac using different techniques, and that will be the subject of a future post.

Parse a Date from a String using SimpleDateFormat

calendar date august 28

Here’s some quck code for easily turn a Date into a readable String, using a given format.

Calendar cal = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd h:mm a");
output.prinln(dateformat.format(cal.getTime());

This will produce the output:

2011-08-28 5:16 PM

The following is from the SimpleDateFormat API and explains the valid characters that can be used to create a date format.

Letter Date or Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Text
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800

Write to other users connected to the same Linux machine

If someone else is connected to the same Linux machine as you, have a conversation with them using “write user tty”.

First, to find out who is connected to the machine, use the “who” command. It will display the username and the details of the user.

$ who
user1    pts/0        2011-08-15 11:10 (subdomain.domain.com)
user2    pts/1        2011-08-15 15:05 (subdomain1.domain1.com)

Then write your message to the user in the following format.

$ write user2
Hello

The important thing to note is the need to hit the enter key after you type “write username”, and then when you finish typing your message, you can hit ctrl+d to send the message.

The message that the user will receive will look like similar to the following.

$
Message from user1 on pts/0 at 15:15 ...
Hello
EOF

Related link: http://en.wikipedia.org/wiki/Write_(Unix)

Rename MSSQL column name

If you ever need to rename a column name for a given table in Microsoft SQL server, do it with the following command.

EXEC sp_rename 'mytablename.[myoldcolumn]', 'mynewcolumn', 'COLUMN'

Backup MySQL database table

You can easily create a backup of a single MySQL database table and then restore it into the same database or another database, using the following MySQL commands.

mysqldump mydatabase mytable > mytable.sql -u username -ppassword

mysql mydatabase < mytable.sql -u username -ppassword

Disable pasting into a form field

Sometimes clients have rigid ideas on how they want site users to interact with their site. From opening up links in new tabs/windows, to trying to force a web page to print a certain way. It generally is a good idea to not mess with the user’s expected experience by overriding their default settings.

form paste disabled

Having stated the obligatory disclaimer, here is how you can disable the ability to paste into a text field in a from (for example, when you want a user to confirm that they have typed in their password correctly). This will work with IE8 FireFox Chrome & Safari Win.

  <input type='text' onCopy="return false" onDrag="return false" onDrop="return false" onPaste="return false"/>

Related link:
http://unnisworld.wordpress.com/2007/10/31/how-to-disable-copy-paste-and-autocomplete-for-an-html-textbox/#comment-1485

Check directory and file size in Linux

A few quick commands to check disk, directory and file sizes on a Linux platform.

#check partition sizes in human readable form
df -h

#check directory size in human readable form
du -s -h /var/log/

#check every directory size in human readable form under a specified directory.
du -s -h /var/log/*

#check file size for a particular file
ls -l /var/log/myfile.zip

Unterminated string literal error caused by script tag

I love StackOverflow. Any question not already answerable by searching the site’s content can be solved fairly quickly by posting the aforementioned problem to the masses of people trying to improve their reputation. (Ok ok, so occasionally they’re trying to improve the world’s collective knowledge as well).

Today’s stumbling block came in the form of some Javascript that was producing an “unterminated string literal” error. After carefully checking the code multiple times for errant quotation or line break characters, StackOverflow pointed me in the direction of the closing script tag which was in the problematic string.

unterminated string stack overflow

Apparently a closing script tag can cause an issue for several modern browsers.

Yay for the wisdom of crowds.

View YouTube Video in Full HD

You can quite easily display a YouTube video on your page by displaying the video in an iframe element, using the HTML which you can get by viewing the YouTube video of your choice, and then clicking on the “embed” link, and selecting your options.

The resultant HTML is similar to the following, which specifies the dimensions, and includes the ?hd=1 parameter which tells YouTube to stream the HD version of the video if it exists.

<iframe width="1280" height="750" src="http://www.youtube.com/embed/Ywu1DeqXTg4?hd=1" frameborder="0" allowfullscreen></iframe>

While you can manually overwrite the default height and width dimensions, YouTube won’t serve the HD version of the video if you set the dimensions too small (this is explained in the the API).

“The AS3 player will automatically play the version of the video that is appropriate for your player’s size. If an HD version of a video is available in the AS3 player and that is the appropriate version for your player, then that is the version that will play.”

You can combine this iframe HTML with Fancybox to display the video in an overlay window without much work. For example, the following snippet will display a pop up window with the video when the page loads, by loading the JavaScript content we specify (i.e. the YouTube video) into the FancyBox overlay.

<script type="text/javascript">
  jQuery(document).ready(function() {
    jQuery.fancybox(
      '<iframe width="1280" height="750" src="http://www.youtube.com/embed/Ywu1DeqXTg4?hd=1" frameborder="0" allowfullscreen></iframe>',
      {
        'autoDimensions'  : false,
        'width'           : 1280,
        'height'          : 'auto',
        'transitionIn'    : 'none',
        'transitionOut'   : 'none'
      }
    );
  });
</script>

Another way to display a video in a Fancybox overlay is to create a link which when clicked, it can display inline content (which in this case is a YouTube video). The following snippet will let you will attach the event listener on the specified link, and also gives an example of the related HTML.

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery("a.fancybox").fancybox({
    'imageScale': true,
    'padding': 0,
    'zoomOpacity': true,
    'zoomSpeedIn': 300,
    'zoomSpeedOut': 300,
    'zoomSpeedChange': 300,
    'overlayShow': true,
    'overlayColor': "#666666",
    'overlayOpacity': 0.3,
    'enableEscapeButton': true,
    'showCloseButton': true,
    'hideOnOverlayClick': true,
    'hideOnContentClick': false,
    'frameWidth':  1280,
    'frameHeight':  750,
    'centerOnScroll': true
  });
});
</script>

<a href="#youtube" class="fancybox">
Link</a>

<div style="display:none" id="youtube"><iframe width="1280" height="750" src="http://www.youtube.com/embed/Ywu1DeqXTg4?hd=1" frameborder="0" allowfullscreen></iframe></div>

Tweet! jQuery plugin for an easy Javascript Twitter client

I needed a quick and easy way to display a Twitter feed on a website, purely on the client side. Tweet! came to the rescue, as it just requires you to add in a CSS file and the Javascript plugin itself (after you have already added jQuery to the page, but then, we all do that anyway these days, right?).

tweet for twitter

Then you just give an identifier to a HTML element (in this case, we’ll add the class “tweet” to a div), and use jQuery’s ready function to initialize the plugin and automagically display the required feed on the page.

<div class="tweet"></div>
<script type="text/javascript">
jQuery(document).ready(function(){
      jQuery(".tweet").tweet({
        join_text: "auto",
        username: "phillipnairn",
        avatar_size: 48,
        count: 3,
        loading_text: "loading tweets..."
      });
    });

</script>

Here’s the result:

Awesome, right?