Put your message here! Contact me for more information
 
 







 

Archive for the ‘Tutorials’ Category


 

I was implementing an Ajax feature for a project and felt the need to display messages (progressing, savings prompt, etc.) to the users visibly and unobtrusively. Usually, to indicate a background activity, I tend to hide the link/button/checkbox and show a spinning indicator when the Ajax request was created, then return the link when the request has completed. In this case, there is no user-controllable submit button. It is a photo album page which allows users to rearrange their photos by simply dragging-and-dropping the photos into the correct positions. The positions are saved automatically on the fly. If I am to implement a typical spinning indicator, I have to make sure that it is visible enough for the user to know that the positions are being saved. However, if the user is at mid-page, any indicator at the top section of the page won’t be visible. If I place the indicator at the bottom of the page, I still run into the same situation. My solution is to implement a smart “Prompt” bar that stays affixed to the screen. With Prototype and Scriptaculous, implementation is a breeze.

Show, don’t just tell
Here is a demo which you can try out.

Details
This is made possible by using the “position:fixed” feature of CSS. According to W3Schools,

position: fixed
An element with position: fixed is positioned at the specified coordinates relative to the browser window. The element’s position is specified with the “left”, “top”, “right”, and “bottom” properties. The element remains at that position regardless of scrolling. Works in IE7 (strict mode)

The markup
Here is the HTML for the prompt bar. You can place this HTML anywhere in the page. Ideally it should be outside any container.

Some Prompt Here
Cross

CSS

#prompt
{ position: fixed; width: 400px; height: 20px; border: 1px solid #7F7F7F;z-index: 9999; background-color: #F3FF8F; }

#prompt_message
{ float: left; text-align: center; width: 380px; font-weight: bold;}
#prompt_close
{ float: right; width:16px;}

We have to set the prompt bar’s position to be fixed so that it will stay in place when we scroll the browser window.

The script
The javascript code is fairly simple, since Prototype and Scriptaculous already do the all the heavy lifting (e.g. positioning, animation). The only catch with position:fixed div is that we cannot center the prompt div using CSS. We have to explicitly set the left coordinate before we display the bar (line 16, _center() method). This is to also useful when the user resizes the browser window, we recalculate the position and center the div accordingly.

    var Prompt = {
      autoHideTime: 5000

      ,display: function( msg, options ) {
        $('prompt_message').innerHTML = msg;
        Prompt.show();
        if( options && options.autoHide )
          setTimeout('Prompt.hide()', options.autoHideTime || Prompt.autoHideTime );
      }

      ,working: function(msg, options) {
        msg = '  ’ + msg;
        Prompt.display( msg, options );
      }

      , _center: function(){
        $(’prompt’).style.left = ( ( document.viewport.getWidth() - parseInt( $(’prompt’).offsetWidth ) ) / 2 ) + ‘px’ ;
      }

      ,show: function(){
        Prompt._center();
        new Effect.Move ($(’prompt’),{ x: parseInt( $(’prompt’).style.left ), y: 0, mode: ‘absolute’, duration: 0.2 });
      }
      ,hide: function( msg) {
        new Effect.Move ($(’prompt’),{ x: parseInt( $(’prompt’).style.left ), y: -30, mode: ‘absolute’, duration: 0.1 });
      }
    }

Since the code is simple enough, I’d like to leave the details to you to work out.

Enjoy!

Download

I packaged the demo as a zip file so you can grab it and have some fun. Cheers!

view comments
 

AutoHotKeyI guess my relationship with the Lenovo 3000 N100 laptop is a complicated one: as much as I hated the Home/End/Page up/Page down combo madness, I truely missed that 2 extra buttons that my Dell D830 doesn’t have. Now instead of just flicking my finger to hit Home or End, I have to move my entire arm to reach for either End or Home. Even though now I won’t make any mistakes with Home/End jumping as with the Lenovo, I have to slow down the typing with the Dell…. NO! Only if Dell put the 2 extra home/end button next to their Arrow buttons… Why can’t we just live happily with each other? Is it really that hard to design a good working keyboard, or is it me that just being picky about laptop keyboard?

“Good news everyone…”, as the Professor Farnsworth would say in his quite-mischevious voice, I have the fix for my crave for the Home/End buttons. AutoHotKey allows me to map custom shortcut to the keyboard, especially the Windows key. I mostly use the Windows key as the … boss key to quickly hide my stuff on the screen (Window + D), or run command (Window + R), or start Explorer (Window + E), even though these days I prefer xplorer2. With AutoHotKey, I was able to map Window + A to the Home Button, and Window + S to the End button, saving me from wiggling my arm around.

So if you are not satisfied with your laptop keyboard, give AutoHotKey a try. Maybe it will save you some aggravation.

Here is the small script to remap your Home and End button: AutoHotKey.ahk

view comments
 

Dell Latitude D830 I had to order a new replacement for my new Dell Latitude D830. I thought that there was something wrong with my particular D830’s battery compartment since there is a gap between the memory and the rest of the laptop body. I have a 9-Cell battery and it was not fully tight-fit. The gap wasn’t that big but I could actually wiggle the battery and had it making some clicking noise. So I had Dell send me a new replacement. An exact D830 was sent to me. It’s so exact that the same issue happens, again! 2 brand new D830, same wiggling battery compartment! Anyhow, I think I just live with it since I can fix the issue by putting a small peace of folded paper between the battery and the compartment wall to nudge-fit it. I think that the issue is specific to the 9-Cell battery and the D830. Buyer beware!

SystemRescueCDEnough of my rant. I actually want to talk how I transfered the image of the first D830 to the other one using the SystemRescueCD. SystemRescueCD is a Linux-bootable image that contains all the utilities for disk imaging, partitioning, and other utilities. The ISO is about 160MB. All I had to do was burning it to a blank CD and grabbing my external USB drive to store my image files.

While waiting for my replacement D830, I installed everything I want to the “defective” laptop: Launchy, FireFox, Office, VisualStudio 2005, Rails, e-texteditor, Notepadd++, Cropper, FileZilla, Xplorer2, Xampp, Cygwin, MySQL GUI toolkit, etc.. Everything was about 10GB of data.

I booted the laptop using the SystemRescue CD with my 500GB Seagate FreeAgent external USB Drive (man, I feel like I’m doing free-advertisements now). The linux distro booted up and successfully recognized my USB drive. Next I went into the GUI with startx since I’m not too hot about the command line, plus I can have multiple XTerm’s side-by-side in X. Now it’s time to get down to the cloning business.

Mounting and Imaging the external USB drive

  • First of all, my Seagate FreeAgent drive was NTFS-formatted by the manufacture. Secondly, I wasn’t sure where the device was mapped inside the /dev. Digging around, I found these commands:
    • # lsusb (to list all USB devices)
  • I saw that my Seagate drive was detected properly with an entry in the list. Further more, running dmesg, I confirmed that the Linux LiveCD recognized my drive:
    • # dmesg | grep -i “SCSI” (this command is to grep the boot-up kernel messages for the word “SCSI” to make sure the kernel detected the device when it was booting)
  • Cool, but now I thought to myself, “how am I supposed to know which device in the /dev folder is my USB?” Actually I made an educated guess here and got lucky. The USB drive was mapped to the /dev/sdb1. I guess with some greppings through the lsub/ other cryptic linux commands/ blind guesses/ beginner’s luck, you’ll find which entry in the /dev folder is your USB drive. Nonetheless, try /dev/sdb1 first, you never know.
  • With my newly gained knowledge (and power), I was ready to mount my drive and start a mini cloning factory:
    • # mkdir /seagate (to create a new mount folder placeholder)
    • # mount -t ntfs /dev/sdb1 /seagate (to mount the NTFS-formatted USB drive to the /seagate folder)
  • I was able to mount the USB drive to the /seagate folder using the above command. However, it was read-only since the LiveCD OS did not know the linux permission of the drive. I found out about this when the imaging utility partimage failed to write the image file to the drive. The correct mount command to enable Linux permission is
    • # mount -t ntfs-3g /dev/sdb1 /seagate (notice the ntfs-3g param)

    Afterwards I was able to write a test file to my USB drive ( #echo “test” > /seagate/test.txt ) and seeing all the Linux permissions on the files ( # ll /seagate )

  • I then started partimage. I selected my partition to be imaged, put in the filename in the “Image path” box (/seagate/d830). I didn’t bother with the gzip since I really just image this one time. For my laptop, imaging 10GB took 7 minutes. The files on the USB drive was spillted into files like “d830.000“, “d830.001“, etc.
  • I then unmount the USB drive with
    • # umount -f /seagate

    I remember the LiveCD complained about some other processes were also accessing the device. To find out which process was using the resource, I did a

    • lsof | grep /seagate (list all processes that are opening the /seagate folder)

    Ah, I had a XTerm which I had CD’ed into the /seagate folder. Silly me! I cd to another folder and afterwards, umount was able to finish its job.

Restoring the image

  • Since the replacement one is an exact duplicate, I didn’t have to pay much attention to the partition image. I popped the SystemRescueCD in, switched the USB drive to connect to the replacement laptop, and booted it up with the CD.
  • I went through almost the exact same steps as above: mount the drive using the -ntfs-3g param, then start partimage. Only this time I chose “Restore” instead of creating image and the file name was “/seagate/d830.000“. Partimage automatically picked up the rest.
  • The entire restoring process took another 7 minutes.

I restarted the laptop and crossed my fingers. To my delight, my Windows XP Pro was up and running, even my fingerprints profile was loaded correctly. I swiped my finger, smiled to myself, and thought that it wasn’t too bad, at least I didn’t have to use Norton Ghost — everything was open-source. Just have to love it!

Final Words

I hope you enjoy this post and find it useful. Now I have to finish up posting this blog, pack the original laptop to send it back to Dell, and get busy finding a piece of paper to fix the battery issue for the replacement laptop. Then I can resume doing Rails and Wars of Earth…

Links & References

view comments
 

VS2005 LogoSince these days I practically live inside Visual Studio (and e editor at night for RoR), here is a small list of shortcuts for Visual Studio. These shortcuts will vary depend on your coding environment, but so far these I have tested to work for VB# environment in VS2005.  Enjoy!

“CTRL + K” chorded shortcuts
(Just hold CTRL down and type “K” then “N” for example)

  • CTRL + K, C: comment out the selected lines
  • CTRL + K, U: un-comment out the selected lines.
  • CTRL + K, K: new bookmark
  • CTRL + K, N: jump to next bookmark
  • CTRL + K, P: jump to previous bookmark
  • CTRL + K, F: format the selected lines
  • CTRL + K, I: show summary for the current token (e.g. variable type, Class summary, etc.)

Code Manipulations

  • CTRL + Shift + Space: show signature/ parameters info for the current function. Use Up/Down arrow key to go through list as usual
  • CTRL + Space: show Intellisent Popup.
  • CTRL + L: cut the current line
  • CTRL + Shift + L: delete the current line
  • CTRL + U: convert to lower case
  • CTRL + Shift + U: convert to uppercase
  • I can’t resist to include the highly addictive chorded shortcut CTRL + K + C/U for quickly commenting/ uncommenting code block
  • CTRL + Shift + F: Find for multiple files
  • CTRL + Shift + H: Find & Replace for multiple files
  • CTRL + F: find in current document.
    • F3: find next
    • Shift + F3: find previous
  • CTRL + K, I: show summary for the current token (e.g. variable type, Class summary, etc.)

Code Maneuvering

  • F12: go to definition
  • Shift + F12: go to declaration
  • CTRL + - (hyphen): jump to previous position
  • CTRL + Shift + - (hyphen): jump to next
  • CTRL + G:  go to line #

Regions/ code blocks

  • CTRL + M, O: Collapse all region blocks
  • CTRL + M, M: toggle current block (such as collapsing/ expanding a method block)
  • CTRL + M, P: toggle comment block (?)
  • CTRL + M, L: Expand/ Collapse All

Build-Debug

  • CTRL + Shift + B : build solution
  • CTRL + F5: Run without Debugging
  • Shift + F5: Break Debugging (VS2005 default key combination for this is changed, but you can reassign back to the “conventional” VS2003 way. Or use Shift + Break - the new combination)
  • F9: set breakpoint
  • CTRL + Shift + F9: clear all breakpoints
  • CTRL + ALT + V, L: Open Locals Window (Debug)
  • CTRL + ALT + V, A: Open Autos Window (Debug)
  • CTRL + ALT + C: Open Call stack Window (Debug)
  • Ctrol + Alt + W, [1,2,3,4]: Open Watch windows (Debug)

Miscellaneous

  • CTRL + Tab: switch between opening files. Hold
  • CTRL + PAGE UP/ DOWN: tab between available “view” of the currently opened document (e.g. Design view, Source View, etc.)
  • CTRL + W: select the word under the current caret position. (Watch out for this since in both IE and FF, CTRL W will close the current tab.)
  • ALT + Mouse Drag: Retangular block selection (e editor also has this feature and make it even better)
  • CTRL + I, then type the search word, then F3: incremental search (a.k.a. search-in-place)

Important Windows

  • CTRL + ALT + L: Solution Explorer
  • CTRL + ALT + K: Task List
  • CTRL + ALT + O: Output
  • CTRL + Shift + C: Class View
  • CTRL + ALT + V, L: Locals (Debug)
  • CTRL + ALT + V, A: Autos (Debug)
  • CTRL + ALT + C: Call stack (Debug)
  • CTRL + ALT + W, [1,2,3,4]: Watch windows (Debug)
  • CTRL + ALT + V, [1,2]: Find Results windows

Productivity Enhancements

  • Any comments with TODO keyword can be listed in the Task List window. (You may have to switch to “Comments” instead of User Tasks) [now I’m pretty excited since both RoR’s “rake notes” and VS2005’s Task List both use the same TODO format — one less thing to remember!]

Links
This list is compiled by myself, but here are some other useful links for Visual Studio shortcuts:

view comments
 

Stock QuoteI’m back from a period of hibernation. Lots of exciting stuff and new things, just barely have enough time to sleep and catch up with all the pending projects that I’ve been crazily taking on. Anyway, today I’d like to share something that maybe useful for someone out there: how to retrieve live stock quote data using Yahoo quote service with ColdFusion.

I was working on a project which originally utilizes the WebServiceX.net’s [[http://www.webservicex.net/stockquote.asmx/GetQuote|StockQuote web service]]. Things were working fine until WebServicex.net is down, as of today, March 22nd, 2007, with a big fat “Service Unavailable”

“Crap!” was what I said to myself. Luckily my work buddy forwarded a [[http://aspalliance.com/articleViewer.aspx?aId=112&pId=#Page2|link]] to an article on how to access the Yahoo Stock Quote service using ASP.NET (C#). Bingo! This was exactly what I needed. Based on the article, I was able to hack out the code using ColdFusion to retrieve stock info in just a few lines of code (or markup since I don’t really consider ColdFusion a real “language”)

===== Yahoo Stock quote CSV service =====
First of all, I didn’t even know if this service ever exists. I don’t really know where the official Yahoo documentations for the Stock Quote CSV service is (anybody knows the link please let me know). More ironically, I used Google to search for tutorials on how to use the Yahoo Stock Quote API. Anyway, this is the URL to request a CSV (comma-separated values) file containing stock information for a particular symbol, in this case, YHOO (I think I do have to give Yahoo some credits for the free service)http://quote.yahoo.com/d/quotes.csv?s=YHOO&f=l1c1v
with
* **s=SYMBOL**: with SYMBOL is the actual stock symbol
* **f=REQUESTED_FORMAT_STRING** where the REQUESTED_FORMAT_STRING is a string of letters representing what fields to be requested. The oder of the letters will be used as the order of the fields in the returned CSV.\\ I messed around and found out about the meaning of the letters used in the **f** parameter. If you want the full information about the symbol, you can use **f=sl1d1t1c1ohgvj1pp2wern** instead.http://quote.yahoo.com/d/quotes.csv?s=YHOO&f=sl1d1t1c1ohgvj1pp2wern Don’t sweat, here comes the explanation for each letter (or letter-digit pair)
* s: the symbol name
* l: last value (or current price). If you use l alone, you will get back a string similar to Mar 22 - 31.26
* l1: (letter l and the number 1) to just get the last value of the symbol
* d: d alone will give you 0, while d1 will return the current date (e.g. 3/22/2007)
* t: t by itself will request the yahoo-generated chart. However, you will get back the chart image with a whole bunch of other HTML garbage, e.g. src=http://chart.yahoo.com/c//y/yhoo.gif" alt="Chart">


* t1: the time of last update, for example 4:00pm.
* c: the change amount. Can either be used as c or c1.
* o: opening value
* h: high value
* g: low value
* v: volume
* j: 52-week low.
* j1: the market cap. This is string like “42.405B” for $42 billion. Man… that can buy **a lot** of hamburger or bowls of phở
* p: after hour price (?)
* p1: (?)
* p2: change percentage e.g. “-0.10%”
* w: 52-week range
* e: EPS (Earning per share)
* r: P/E (Prince/Earning) ratio
* n: Company name

(This list is hand-compiled by me based on my own interpretation. If you find any explanation being inaccurate, please let me know)

===== The Code =====
ColdFusionThe code is pretty simple: we will read from the result the Yahoo CSV service using the tag into a variable. This variable will then contain the comma-separated values list of what we put in for the f parameter. Back to our example, the URL we are requesting is http://quote.yahoo.com/d/quotes.csv?s=YHOO&f=l1c1v, which will return to us a string 31.26,-0.03,13249801. Since the response is in CSV format, we can utilize the ColdFusion List functions like ListLen(), ListGetAt() to access the values.

Here is the CFML code snippet





#stockInfo#




* First, we construct the Yahoo Stock Quote service URL. We are requesting for last price, change amount, and the stock volume.
* Next we use the cfhttp tag to request the url, then grab the content into the cfhttp.FileContent variable and assign to the stockInfo variable. stockInfo will contain something similar to 31.26,-0.03,13249801
* To get the different values in the list, we use ListGetAt() with the appropriate index. And remember, indices of Array and List in ColdFusion start at 1, not 0.

That’s it!

===== Final Remarks =====
I hope you will find this useful. Thanks to Yahoo for providing a free stock quote service. I know I can **abuse** this CSV service as much as possible before getting banned because it’s Yahoo. Any services other than those of Yahoo, Google, Microsoft, I will probably have some guilty thoughts before doing anthing. But it’s Yahoo so I really don’t have no guilt abusing it. Just kidding though. I do appreciate the free (as in free beer) stock quote service.

===== References =====
* Bromberg, Peter, PhD. [[http://www.eggheadcafe.com/articles/20010404.asp|Build a C# Stock Quote WebService and Client using the WebService Behavior HTC (Part I)]]
* Perry, Jason. [[http://aspalliance.com/articleViewer.aspx?aId=112&pId=#Page2|Building a Yahoo stock quote ticker]]

view comments