programming posts

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.

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.

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.

Oracle_query() and Other Oracle Convenience Functions

Attached File(s): 

If you're used to using MySQL with PHP, you already know of the simple and easy to use mysql_query(), mysql_fetch_object(), mysql_affected_rows() and so forth functions.  Well, if you've ever dipped your toes into the tepid waters of Oracle, you know that it lacks the friendly PHP functions that MySQL has.  So, I created a set of convenience functions designed to mirror the MySQL ones.

Just download the attached file at the top, and use it like so:

<?php
  
  include_once("oracle_common_functions.php");

  oracle_connect($username, $pass, $host, "TEST");
  $res = oracle_query(" SELECT * FROM $table_name ") or echo(oracle_error());
  while ($cur = oracle_fetch_array($res)) {
    var_dump($cur);
  }  
  
  oracle_close();
  
?>

Just remember that to use any of this, you also need PHP to be compiled with the necessary oci libraries.

Complete list of functions in the file:

oracle_connect()
oracle_query()
oracle_fetch_array()
oracle_fetch_object()
oracle_affected_rows()
oracle_close()
oracle_error()
oracle_errno()
oracle_escape_string()

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.

Transparent iframe Background in IE

When setting background-color: transparent for an iframe in IE, it just doesn't work.  It shows up as white instead.  Of course, it works in every other browser, but not IE.  So what's the deal? How do you fix it?

This one may not come up very often for everyone, but it did for me, and took me an hour of googling to find the answer:

<iframe src='example.html' allowtransparency='true'></iframe>

You see what I did there?  allowtransparency='true'.  Apparently in IE you have to explicitly state it or it will just ignore the CSS attribute.  Thanks IE!

And while I'm on it, if you want to get rid of the border that IE places on iframes, you have do to this:

<iframe src='example.html' frameborder='0'>

That's right.  frameborder='0'.  I've said it before: IE is the best, most logical browser around.

Find the True URL of Something, Following Redirects

Have you ever wanted to know the definitive URL to something on the Internet, following any 301 redirects?  I am working on a podcast-related site right now, and recently had to keep track of a multitide of podcast URL's, even when they change.  The following PHP code saved the day:

function get_final_url($url) {
 
  $ch = curl_init($url);
  curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  curl_exec($ch);
  $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  curl_close($ch);  
 
  return $url;
}

To use, let's say you have a url of "http://example123.com/index.html"  but, unbeknownst to you, that URL actually has a 301 redirect to "http://example123.com/welcome.html". 

You can use the function this way:

$url = get_final_url("http://example123.com/index.html");

And $url will now contain "http://example123.com/welcome.html".

Enjoy!

Amazon S3 Logs - Drupal 6 Module

Note!  This project is now an official Drupal project.  You may download it by going here: http://drupal.org/project/amazon_s3_logs

as3l-sc1.pngUsing an Amazon S3 account is ideal for web sites with lots of content, but unfortunately Amazon doesn't make it easy for you to track traffic and visitors to your site.  That is where this drupal 6 module comes in.  Assuming you have correctly set up a log bucket on your account, this module makes it easy to get basic usage stats at a glace for all your files.

You're site doesn't even need to be a drupal site to use this.  If you want, you can always have a drupal installation whose only purpose is to run this module.

See this module's project page on drupal.org for instructions on installing and setting it all up.

Arrange Fields - Drupal 6 Module

 Note!  This project is now an official Drupal project.  You may download it by going here: http://drupal.org/project/arrange_fields

 ar-screen1.pngHave you ever used CCK or Webform with Drupal, and found yourself wishing you could easily arrange the fields in a horizontal style, or just easily resize textfields and areas on the fly?  Then this module is for you.  It gives you a simple drag-and-drop interface to to arrange fields on your forms.

Tab indexing is also respected, so no matter how you arrange your fields, you can still tab through them in a logical order.

Features

  • Drag and drop fields into any arrangement you want. Makes CCK and webforms look more like pen-and-paper forms.
  • Resize textfields and textareas by dragging.
  • Edit CCK configurations for each field (required, help text, allowed values, etc) in a popup without having to leave the page.
Syndicate content