Java Associative Array (Sort Of)

Attached File(s): 

Ever wish that Java had associative arrays (aka assoc arrays) like in PHP?  As in, $x["name"] = "Bill" ?  Well, I created a helper class for Java which comes close to approximating it.  It can even loop through it similar to foreach().

ipad-java.jpgI call the class PseudoAssocArray, because it actually uses a HashMap to do the behind the scenes work. 

Simply include the file attached at the top of the page in your project, then use it like so:

PseudoAssocArray temp = new PseudoAssocArray(1);
temp.put("name", "April");
temp.put("age", "26");
// ...
String n = temp.get("name");

You can even make it be 2 dimensional by supplying a 2 in the constructor.  For example:

PseudoAssocArray temp = new PseudoAssocArray(2);
temp.put(0, "name", "April");
temp.put(1, "name", "Samuel");
// ...
String n = temp.get("1", "name");

Loop through like so:

temp.resetCounter(); //always do this first
while (temp.hasMore()) {
  Object obj = temp.getNext();
  // or: String s = (String) temp.getNext();
}

To loop through and get both key and value, try this:

temp.resetCounter();
while (temp.hasMore()) {
  Map<String, Object> entry = temp.getNextMap();
  String key = (String) entry.get("key");
  String value = (String) entry.get("value");
}

Enjoy!

 


Software License Fine Print

Creative Commons LicenseThis code is licensed as-is, with no warranty or guarantee, under a Creative Commons Attribution 3.0 Unported License.

You may use this code however you want, even in commercial products, but only if you include attribution to me, Richard Peacock, as the original author of this small portion of code, but not in a way that implies I endorse your project.

For example, on a Help/Credits screen:  Portions of this project were based on work freely obtained from these developers: Richard Peacock (http://richardpeacock.com), NAME HERE, etc.  These outside developers neither endorse nor support this software.

If you use this code, feel free to email me to let me know!  I'll include a link to your project here.

Easy to Remember, Yet Unique, Passwords

So we all know we're supposed to have a different password for every site we go to, but of course no one does that.  Instead you end up using the same password for everything because its easier to remember.  The problems occur when your favorite website, knittin-for-kittens.org, gets hacked and your password stolen, and its the same password you use for your bank account.

password.jpgWhat you need is a password scheme that lets you use a different password for every site you go to, so even if one gets stolen, it won't comproise all your other sites.

Here's the system I use:

Chose a random, nonsense "base" with both numbers and letters. Include at least one capital letter.  For example:  zh2Ms
This is just something you will have to dedicate to memory.  If you base it on a phrase, that can help.  Example: zebra have 2 Many stripes = zh2Ms

Next, add on the name of the site or service you are using.  For example...

gmail:         zh2Msgmail
facebook:   zh2Msfacebook
bank:          zh2Msbank

and so on.  Now you have unique passwords for every site you use, but you will always be able to remember them.

PS:  for the best security, you should really be using lastpass!  It's wonderful and free.
 

Amazon.com - The Best Place to Buy Computer Cables, Convertors, Etc

Amazon.com has quickly become my favorite, secret spot to buy things like spare USB extension cables, iPod cables, USB convertors, HDMI cables & convertors, and so on.

amazon_logo1.jpgI used to use sites like Newegg.com, and that's a great site too, but you just can't beat the prices on Amazon.com.  And no, I'm not being paid anything or getting any kind of reward for sending people their way.

I'll give you an example from a recent purchase I made.  This is a DVI to HDMI convertor.  You can use it to connect your PC to a TV, so you can use your nice big TV as a monitor:

dvi_hdmi_convertor.jpg

At BestBuy, a similar convertor costs $30.  At Amazon, it costs less than $3 with free shipping.

Speaking of HDMI, a 3 foot standard HDMI cable costs about $4 on Newegg, with free shipping.  On Amazon it's less than $2, free shipping.  And from a store it can be as much as $20 - $50!

iphone_cable.jpgApple iPhone cables-- at Target they're $20.  At Amazon they're as low as $1, free shipping.

The examples go on and on.  For the most part, any cable or convertor I've ever looked for has been cheaper on Amazon than anywhere else, though, there is a little bit of a secret to the ordering process.

I usually don't just click "add to cart" from the main page.  I usually click on the "XX new from $xx" link at the top of the page, and look at all of the available sellers.

Make sure you order from a seller in the US (or whatever country is closest to you).  Some of the really cheap ones come from Hong Kong, and take literally 18 - 30 days to come in!  I've had this happen to me before. 

So when you order, spend the extra $0.50 and go with a closer seller.

Draw a Box Around a Coordinate In Google Maps Based on Miles or Kilometers

Attached File(s): 

This post explains how, given latitude and longitude coordinates in Google Maps (specifically, in the Static API), how one can draw a bounding box around them, based on a distance in either miles or kilometers.

gmap_bounding.pngLet's say you already know the lat/long of a particular point on the map, and now you want to draw a box around it, or maybe you just need to know the lat/long coordinates of another point, so many km or miles away?  Well, this is the script for you!

Based on a script retrieved from here:
http://www.sitepoint.com/forums/showthread.php?656315-adding-distance-gps-coordinates-get-bounding-box

The trick is that Google Maps wants you to provide it with the lat/long coordinates for each corner of the box.  After several hours of searching, I finally found a script which I was able to modify to give me what I needed.

Simply download the script linked at the top of the page, and then use the following code to create the image you see here. 

Enjoy!


    $lat = -33.872986011907216;
    $lng = 150.90904516601563;

    // Create the static map api image.
    $static_maps_url = "http://maps.googleapis.com/maps/api/staticmap";
    $static_maps_url .= "?center=$lat,$lng";
    $static_maps_url .= "&zoom=15";
    $static_maps_url .= "&size=300x300";
    $static_maps_url .= "&maptype=roadmap";
    $static_maps_url .= "&sensor=false";
    $static_maps_url .= "&markers=color:blue|$lat,$lng";

    // Figure out the corners of a box surrounding our lat/lng.
    $d = 0.3;  // distance
    $path_top_right = bpot_getDueCoords($lat, $lng, 45, $d);
    $path_bottom_right = bpot_getDueCoords($lat, $lng, 135, $d);
    $path_bottom_left = bpot_getDueCoords($lat, $lng, 225, $d);
    $path_top_left = bpot_getDueCoords($lat, $lng, 315, $d);
   
    $static_maps_url .= "&path=color:334433|weight:5|fillcolor:0xFFFF0033|";
    $static_maps_url .= "$path_top_left|$path_top_right|$path_bottom_right|";
    $static_maps_url .= "$path_bottom_left|$path_top_left";
     
    // Now, draw the image from Google Maps API!
    print "<img src='$static_maps_url'>";


 

 


Software License Fine Print

Creative Commons LicenseThis code is licensed as-is, with no warranty or guarantee, under a Creative Commons Attribution 3.0 Unported License.

You may use this code however you want, even in commercial products, but only if you include attribution to me, Richard Peacock, as the original author of this small portion of code, but not in a way that implies I endorse your project.

For example, on a Help/Credits screen:  Portions of this project were based on work freely obtained from these developers: Richard Peacock (http://richardpeacock.com), NAME HERE, etc.  These outside developers neither endorse nor support this software.

If you use this code, feel free to email me to let me know!  I'll include a link to your project here.

Encode Any String to Only Alphanumeric Chars - Better Than URLEncode

Have you ever been faced with a situation where you need to encode a string with all sorts of problem characters into a URL-safe string, but, for whatever reason, urlencode() just won't do the job? 

What you need is a function that will give you nothing but numbers and letters-- no %'s or &'s, spaces, or any other non-alphanumeric character.

Well, look no further that PHP's bin2hex() function, and its pack() function.

It can convert this tricky string:

(!X>4Ob=h/&hN\'

Into this much nicer string, which can easily pass through a URL, MySQL query, XML tags, etc, since it is guaranteed to only ever be letters and numbers:

2821583e344f623d682f26684e5c27

And then decoding is a snap.  Here are the functions you need:

function hex_encode($input) {
  return bin2hex($input);
}

function hex_decode($input) {
  return pack("H*", $input);
}

Enoy!

Android Tip: Preferences - Easier Than Using a Database - With Code Sample!

Attached File(s): 

If you have done any programming for an Android phone, you've probably already used (or at least heard of) Android's built-in database option of SQLite.  SQLite is a fine system, but it can be cumbersome to work with, especially if you only need to store a few values. 

samsung-omnia-hd-android.jpgEnter your new best friend: Preferences.

Think of "Preferences" as a way to save data (like Strings) outside of your application.  It's like a database in that way, but it is much easier to put data in and get data out.  If you build a Preferences Activity at some point, then it will actually be using this very system-- but that's another blog post.

I have included my own class for working with Preferences.  It is linked at the top of the post.  To use it, instantiate a Prefs object like so:

Prefs prefs = new Prefs(context);
// Prefs prefs = new Prefs(this) will work 
// if you are within an Activity

Now, to store a String value, all you have to do is this:

String mUserNameString = "rpeacock";
prefs.setPreference("username", mUserNameString);

To retrieve that value later, even after the app has closed and restarted, all you have to do is this:

String temp = prefs.getPreference("username");

Isn't that easy?  More to the point, isn't that much easier than creating an SQLite object, constructing a query, executing the query, then closing the connection?  That's why I use Preferences everywhere I can.  It's also great for accessing values between Activities, services, etc.

The code I attached only does Strings, but you can easily extend it to work with any value.  Enjoy!

 


Software License Fine Print

Creative Commons LicenseThis code is licensed as-is, with no warranty or guarantee, under a Creative Commons Attribution 3.0 Unported License.

You may use this code however you want, even in commercial products, but only if you include attribution to me, Richard Peacock, as the original author of this small portion of code, but not in a way that implies I endorse your project.

For example, on a Help/Credits screen:  Portions of this project were based on work freely obtained from these developers: Richard Peacock (http://richardpeacock.com), NAME HERE, etc.  These outside developers neither endorse nor support this software.

If you use this code, feel free to email me to let me know!  I'll include a link to your project here.

Top Web Sites Running Linux

Last year, I posted an article detailing the OS of choice for the top 10 web sites, finding that most of them were running some flavor of Linux. 

Linux.jpgWell, since a year has passed, I thought it might be nice to check again, not just the top 10, but some other well-known sites.

Here are my results, retrieved April 3, 2011:

Ranking from http://www.alexa.com/topsites
Results from http://uptime.netcraft.com/up/

Ranking Site OS
1 Google Linux
2 Facebook Linux
3 YouTube

Linux

4 Yahoo! Linux
5 Blogger Linux
6 Baidu unknown, running apache
7 Windows Live Windows-based
8 Wikipedia Linux
9 Twitter Linux
10 QQ Linux

 As you can see, 8 of the top 10 are running some flavor of Linux, which speaks volumes about the reliability of the OS.  Many of the top 11+ sites are just foreign variations on these sites.  For example, Google India is #14, Yahoo.jp is #12. 

So, I have decided to select several other sites which English-speakers are more likely to have used... 

Is Your Laptop Overheating?

Recently, my laptop started running hotter and hotter, to the point that it would shut itself down out of protection.  Speedfan reported my core temperature (under load) above 100C (the temperature of boiling water)!  It idled around 60 - 70C.  I almost went out a bought a new laptop, assuming my processor or power supply or something must be breaking down.

laptopfire.jpgWell, I'm glad I didn't, because I fixed it with one simple trick after some googling.  All you need to do is break out your vacuum cleaner, and clear the dust from the laptop's cooling system.

On most laptops, that means two points:  an intake vent, and an exhaust vent.  The idea is that air is sucked into the laptop through the intake vent, passes over your hot components, and then blows out of the exhaust vent, cooling everything down in the process.  This is all done with 1 or 2 fans, which can get very dusty over time.

It's that dust that causes the laptop to overheat.  It chokes the fans and creates a blanket over your components.

So, just take your vacuum cleaner's hose attachment and go over both vents really well.  The intake vent is probably on the bottom of the laptop, and the exhaust is probably on the side or back. On some laptops, to really get rid of all the dust, you might have to take the cover off and blow out the fans/vents with compressed air.  I didn't have to with mine, though.

After doing this, my laptop idles around 52-54C, and under load it gets to around 60-65C.  It's still a little hotter than I want it to be, but that's nothing compared to 100C!

So if you've got a dangerously overheating laptop (use Speedfan to check) then give this tip a try.  If it doesn't work, it probably means you have a more serious-- and more expensive-- problem.

 

Dropbox and Programming - A Match Made in Heaven

For those that don't know, Dropbox is a free service which lets you share a folder across multiple computers, even with different OSes like Mac, Windows, and Linux.  It's great for keeping all your personal files with you on both your work and home PC (without the need for a USB drive).  But where it really shines for me is when it comes to programming.

Dropbox-Review-2.jpgProgramming from multiple computers is always a bit of a pain.  What I normally do is I keep all my files on a USB drive, and just have to remember to carry it with me every where I go.  I'm always worried about breaking or losing it, so I have to back it up like crazy.

Another option is to use a version control system like Subversion or Git.  They work (usually), but you've got to remember to commit changes before moving to another computer.  For newbies they can be complicated to set up, and might be overkill for smaller one-man projects. Plus my IDE for Android development, Eclipse, just doesn't want to play nice with Subversion.

Enter Dropbox, my new hero.

Using Synergy With a Null Modem Cable

If you've never heard of Synergy, check out there website here.  In a nutshell, it's a program you run on two computers, which lets you use the keyboard and mouse of one to control the other.  Think of it a little bit like a KVM switch in software.  The connection is made over your network or the Internet.  To switch machines you just slide your mouse off the side of one screen and onto another, as if you just had a second monitor set up.

null-modem-cable.jpgRecently at my day job, I used Synergy to connect my main work computer to a spare computer I set on my desk but did not want to make room for another keyboard and mouse.  I also did not want to connect our company network to the spare computer, for security reasons.  Now, I could have just used a cross-over ethernet cable, but did not have a spare ethernet port on my main computer.

Enter my savior: an ancient serial Null Modem cable.

In the good old days, these little serial cables were used to connect two computers together at a relatively low speed for file transfers and the like.  And if you happen to have one laying around (possible with an extra "null modem" block attached, possibly not), then this guide will help you set up two Windows computers to use it to work with Synergy.

Syndicate content