Disable Dropbox While Running on Battery Power

This Autohotkey script allows you to run custom commands based on your systems AC power status.
By default, the script will disable Dropbox when the battery is discharging, and restart it once AC power is restored.

The script can be easily modified to preform any task on either "AC Power On" or "AC Power Off" events by modifying the corresponding function. Please note that if your Dropbox daemon is not installed in the default directory, you may have to modify the script appropriately.

I was inspired to write this after reinstalling my laptop when I suddenly discovered a dramatic improvement in battery life. With Dropbox as a prime suspect, I was looking for a simple way to turn it on and off depending on the laptops power state. I hope you find this script useful for keeping Dropbox, and any other power hungry apps you may have in check.

If you've found any other original uses for the script, I'd love to hear about them in the comments!

Download the AHK Script

Source Code:

;; Close Programs Based On Laptop Power State
;; By Boaz Arad
;; http://www.boazarad.com
;;http://www.machinereadable.net/2011/05/disable-dropbox-while-running-on.html


;;Define Custom commands to be run while switching from battery-
;;power to AC power or vice versa

ACPowerOn() ;Run when plugged in
 {
 ;Default Dropbox install dir - modify if necessary 
 DropBoxExe=%A_AppData%\Dropbox\bin\Dropbox.exe 
 Run %DropBoxExe%
 ;MsgBox "AC Power On"
}

ACPowerOff() ;Run when unplugged
 {
 Process, close, Dropbox.exe
 ;MsgBox "AC Power Off"
}

/*
Notes:
Since "On AC Power" and "On AC Power, Charging" are two seperate events
"ACPowerOn" may be run twice When the is plugged in and it's battery is
already charged to over 95% of capacity. This issue can be solved by
setting "B_Threshold" (below) to the maximum charge level of your laptop
battery. This is necessary since if your battery is at full capacity,
plugging in your laptop will not set the battery status to "Charging".
*/
B_Threshold=95
/*
Made Possible by:
Wrapper to catch Power Management events by TheGood
 (http://www.autohotkey.com/forum/topic40008.html)
Shimanov's ReadInteger function:
 (http://www.autohotkey.com/forum/topic6144.html)
AC/Battery status by antonyb
 (http://www.autohotkey.com/forum/topic7633.html)
*/


ReadInteger( p_address, p_offset, p_size, p_hex=true )
{
  value = 0
  old_FormatInteger := a_FormatInteger
  if ( p_hex )
    SetFormat, integer, hex
  else
    SetFormat, integer, dec
  loop, %p_size%
    value := value+( *( ( p_address+p_offset )+( a_Index-1 ) ) << ( 8* ( a_Index-1 ) ) )
  SetFormat, integer, %old_FormatInteger%
  return, value
}
OnMessage(536, "OnPBMsg")     ;WM_POWERBROADCAST
Return

OnPBMsg(wParam, lParam, msg, hwnd) {
      If (wParam = 10) {   ;Power state change detected
 VarSetCapacity(powerstatus, 1+1+1+1+4+4)
 success := DllCall("kernel32.dll\GetSystemPowerStatus", "uint", &powerstatus)
 acLineStatus:=ReadInteger(&powerstatus,0,1,false)
 batteryFlag:=ReadInteger(&powerstatus,1,1,false)
 batteryLifePercent:=ReadInteger(&powerstatus,2,1,false)
 batteryLifeTime:=ReadInteger(&powerstatus,4,4,false)
 batteryFullLifeTime:=ReadInteger(&powerstatus,8,4,false)

 output=AC Status: %acLineStatus%`nBattery Flag: %batteryFlag%`nBattery Life (percent): %batteryLifePercent%`nBattery Life (time): %batteryLifeTime%`nBattery Life (full time): %batteryFullLifeTime%
 ;MsgBox %output% ;Debug - show full powerstatus info

 If (acLineStatus=0)
  ACPowerOff()
 Else ;If (batteryFlag>=8 | batteryLifePercent>%B_Threshold%) ;Plugged in and charging (http://msdn.microsoft.com/en-us/library/aa373232(v=vs.85).aspx)
  ACPowerOn()
 }  
   ;Must return True after message is processed
   Return True
}

Download the AHK Script

Retrieving external URL's with PHP without overloading your server

Retrieving external URLs via PHP has already gotten me kicked off a shared server in the past. A handful of visitors may be enough to incur the wrath of your admin. While redesigning my personal homepage, I wanted to scrape my recent running mileage from an Endomondo widget (login required) and embed it into the site text. The simplest way to do this, would be to retrieve and process the widget code from the Endomondo site for each page load.
This approach has two drawbacks: first - increased pageload times due to the remote retrieval, and secondly - increased server load.

To solve this problem, I decided that updating my mileage daily would be sufficient, but I still wanted the updated process to be automatic, and take place on the server.

To accomplish this, I wrote the following code. The concept is simple - scraped data is held in a file on the server, on each page load, the modification time of the file is checked, if it is over a day ago, new data is scraped and written to the file.

This way, remote fetching and it's associated slow-down and server load happen at most once a day.

The code is pretty much self explanatory,  but I'll discuss some of it's finer points below.

function howfar() {
 $rep = "many";
 if (!($mfile = @fopen('mileage.txt','r'))) {
  $latest_mod = 0;
 }
 else {
  $latest_mod = filemtime('mileage.txt');
  fclose($mfile);
 }

 $today = date(U);

 if ($today-$latest_mod > 86400 ) {
  //echo "OLD!";
  $mfile = fopen('mileage.txt','w+');
  $endo_url = "http://www.endomondo.com/embed/user/summary?id=92256&sport=0&from=20110101&measure=0&zone=Gp0200_JER";
  $endomondo = file_get_contents($endo_url);
  $loc = strpos($endomondo,'Distance:');
  $loc2 = strpos($endomondo,'</span>',$loc);
  $distance=substr($endomondo,$loc+21,$loc2-$loc-21);
  fwrite($mfile,$distance);
  fclose($mfile);
 }

 else {
  $mfile = fopen('mileage.txt','r');
  $distance=fread($mfile,4);
  fclose($mfile);
 }
 if (is_numeric($distance)) {
  $rep = $distance;
 }
 return $rep;
}

First, we attempt to open the 'mileage.txt' file, the @ suppresses any possible error messages we don't want the user to see. If the file doesn't exist, latest_mod will be set to zero, thus forcing an update.
If the file is readable, latest_mod is set to its latest update time. The times are then compared, and if the difference is greater than 86400 (a day in Unix timestamp format) - new data is fetched.
Otherwise, the file is opened, and the old data read.
You could easily modify the code to fetch nearly any for of data, and store it locally, the minimum "freshness" of the data is also easily tweakable.

I hope you find this snipplet useful, and I'd love to hear about it in the comments if you did.

Leaving Flickr - How to download all your photos

CC-BY: Dazzie D
Your "Pro" membership might be expiring, you may be nearing the 200 photo limit for free account or recurring rumors of a Yahoo!-Microsoft merger might be prompting you to consider alternative services. Either way - odd are that Flickr has all your precious photos, and you want them back! This is how I did it:

First, I'll warn you that this guide may get a bit technical, as it includes a little command line work, if you're comfortable with that - read on.

The backstory
I've been using Flickr for almost four years, and shortly after joining, I decided to upgrade to a pro status so my account could double as an image backup solution. Since then, I got my first SLR, and by 2009, I was shooting only RAW. Flickr's poor RAW support plus the fact that restoring anything larger than one photo set from Flickr would not be a simple matter - both prompted me to find an alternative backup solution.
Today, I backup my whole photo library to both a local mirror drive, and crashplan+ - a remote online backup service.
Once I no longer needed a Flickr Pro account for backup purposes, 25$ a year became rather pricey for the questionable privilege of  "Access to your original files" and "Unlimited sets and collections" - seriously Flickr, it's my data! let me have it back!

All that remained to be done before I could let my Pro account expire was to download my photostream, and make sure that I indeed had local copies of all my Flickr photos.

Downloading the photostream
CC-BY-SA: rbrwr
There are quite a few programs out there that can help you download full resolution imgaes from your Flickr account, to name a few: FlickrEditDownloadr the for-pay Bulkr and the now banned Flickrdown.
If you only have about 1,000 photos to back up - FlickrEdit is your best choice, it has a user friendly graphic interface, and works rather well.

If, on the other hand, you have thousands of photos to download (over 33,000 in my case) - your best bet it FlickrTouchr. This python script will log on to your Flickr account, and download all your images, into folders based on your Flickr sets!
The original script was set to download "Large" size images rather than originals, and seemed a bit slow on my connection, so I modified to to download originals and... (drumroll) ... use concurrent threaded downloads!

You can download my modified version - FlickrTouchrThreaded. To use it, you'll have Python installed. If your using Linux, you probably know how to do this yourself, Mac users should already have python installed by default, and windows users can find installation instructions here.
Once you have Python installed, backing up your entire photostream is a easy as typing:
python flickrtouchrthreaded.py FlickrBackupFolder 3
 Where "FlickrBackupFolder" is the name of the folder you want to back up to, followed by the number of download threads you want to run (in this case - three). This will begin downloading you whole photostream to the your selected backup folder, with sub folders based on your Flickr sets. Images not in sets will be downloaded to a "No Set" folder.

In my case I found that using more than 3 threads didn't improve my overall download speed, you can play around with the number of threads the script uses, but I wouldn't increase it over 10 so Flickr doesn't get too mad at you :)

The first time you run it, it will send you to the Flickr website and request authorization for your Flickr account, subsequent runs will start downloading immediately. You'll also note that if the script was interrupted, you can just re-run it, and it will pick up where it left off, just be sure to point it to the same folder.

A few hours later (or in my case, one week 33,640 photos and about 80GB later) you'll have your entire Flickr photostream backed up.

Finding Corrupt Images
Photo: Boaz Arad
Once you've got your whole photostream backed up, you'll want to be sure that all your images downloaded correctly. FlickrToucher does a rather good job, and will rarely corrupt any images in transit, but even one corrupt photo out of thousands could really ruin your day - especially if it happens to be your best wedding picture, or the only group of your speedskating group (see left).

To scan for corrupt JPG images, i used cPicture.
cPicture is a commercial product ($19.99 per license), but the freely available trial will allow you so scan for corrupt images without limitation. Just pick a folder, and click "Check Pictures". After churning through your photos, it will output a text file with a list of corrupt images.
If you used FlickrTouchr to download your photostream, the filenames of the images should be their Flickr photo-id's - so you can easily find them online by browsing to
http://www.flickr.com/photos/your_flickr_username/photo_id/
If anyone can reccomend a similar utility for Max and Linux users, I'd love to hear from you in the comments.

Finding duplicate photos
Photo: Boaz Arad
Some of the downloaded photos from your photostream will no doubt be duplicates of photos you already have on your hard-drive. In order to prevent wasted space - you should scan the downloaded photos for duplicates. I recommend MindGem's Fast Duplicate File Finder (FDFF) - again, a commercial product, but the trial version likely contains all the features you'll need.

Conclusion
Once you've weeded out corrupt and duplicate images, it's time to merge the backup back into your local photo library. Both Google's (free) Picasa and Adobe's (pricy!) Lightroom do a great job of keeping you pictures in order, and I recommend using one or both regularly.
It's also a good practice to always keep local copies of all your images, and never relay on online services (Flickr, Facebook etc.) as your only photo storage solution - as these can be notoriously unreliable.

FlickrTouchrThreaded - Download all your Flickr Photos FAST!

CC-BY: Agustín Ruiz
FlickrTouchr is a nifty little python script that lets you automatically download your whole Flickr photostream. Unfortunately, I found that it worked rather slowly - and traffic would plummet to zero between images.

Enter FlickrToucherThreaded! This modified new version of FlickrTouchr allows simultaneous downloading of multiple images, using concurrent download threads. The number of threads is user configurable - in order to allow optimization for each individuals connection and CPU.

FlickrToucherThreaded Version 0.1 is available for download here.

FlickrToucherThreaded is based on FlickrToucher - originally by Colm MacCarthaigh, and improved by Dan Benjamin. Both scripts are distributed under the Apache 2.0 License.

I intend to continue developing this script in the near future, coming soon:
Cleaner Thread Shutdown.
Configurable default image size.
Incorporation of improvements by tonyduckles.

So stay tuned!