Tidy JSON Formatting with TextWrangler

This script can be used to format JSON. Place the script in your TextWrangler Text Filters folder. For me the path was /Library/Application Support/TextWrangler/Text Filters. You can name the script whatever you want, just make sure to give it a .py extension. I called mine TidyJSON.py.

#!/usr/bin/python

import fileinput
import json

if name == "main":
jsonStr = ''
for aline in fileinput.input():
jsonStr = jsonStr + ' ' + aline.strip()
jsonObj = json.loads(jsonStr)
print json.dumps(jsonObj, sort_keys=True, indent=2)

After saving the file, restart TextWrangler and go to Text -> Apply Text Filter -> TidyJSON. Your garbage-looking JSON will look like a million bucks!

Twitter Share - Android

Been working on a twitter share using the ACTION_SEND intent rather than the more cumbersome Twitter APIs. [css]

// Call find twitter client to get the twitter clients to post to 
Intent shareIntent = findTwitterClient();
shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
startActivity(Intent.createChooser(shareIntent, "Share"));

findTwitterClient will call this method, which will search the phone for various Twitter clients, and launch the tweet through the first client it successfully matches:

public Intent findTwitterClient() {
final String[] twitterApps = {
// package // name - nb installs (thousands)
"com.twitter.android", // official - 10 000
"com.twidroid", // twidroid - 5 000
"com.handmark.tweetcaster", // Tweecaster - 5 000
"com.thedeck.android" }; // TweetDeck - 5 000 };
Intent tweetIntent = new Intent();
tweetIntent.setType("text/plain");
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(
tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

for (int i = 0; i < twitterApps.length; i++) {
for (ResolveInfo resolveInfo : list) {
String p = resolveInfo.activityInfo.packageName;
if (p != null && p.startsWith(twitterApps[i])) {
tweetIntent.setPackage(p);
return tweetIntent;
}
}
}
return null;
}

Changing the default page when you open a new tab in Firefox

I've been super frustrated with firefox lately because somehow my default page when you open a new tab got changed from blank to a bing search.  Can't tell you how annoying this is when I'm used to a quick ctrl+t, ctrl+v to get where I want to go.  And the worst part is there's nowhere to change it when you go to the firefox options! It turns out the perpetrator is Microsoft (of COURSE) and that I somehow installed an extension that was doing it.  I'm still mad at firefox.

To disable the madness you need to restart firefox in safe mode: Firefox -> Help -> Restart Firefox with Add-ons Disabled.  Wait for it to restart, then select Disable all add-ons and whatever else you want to select.

Hit Make Changes and Restart and you should be all set.  No more pesky bing search stealing the cursor location.

Use LogCat to Debug for Android

To use LogCat you need to import the Log library in the java code import android.util.Log;

Then, where you would normally print something, replace “System.out.println(“HERE”);” with:

Log.d(“LOGCAT”, “HERE”);

Now when you run your app on the emulator or a device it'll print out to logcat, which can be viewed right in Eclipse (might need to go to Tools and click LogCat or something similar) or in the terminal in the directory where the android sdk has been installed, in the <sdk>/platform-tools/ folder.

Run adb logcat from that directory location to view the logs.

This prints out a log of everything that's happening, so if it's on the phone there's probably going to be a lot of stuff going on continuously, which is why it's helpful to use good tags so you can just browse or search for "LOGCAT" and you'll find what you're looking for.

Geotagging

  I read an article this week titled Could Geotagging Pose a Threat to Your Security.  I felt like it was a relevant topic to data communications and general tech because geotagging is essentially using a smartphone's GPS features to tag the latitude and longitude of the pictures that are taken.  This significant advancement in data communications is an incredible tool and creates a wide array of creative possibilities with the geologically tagged images.  However, it also poses some serious security threats.

The article contains comments from several officials that explains why geotags can be so dangerous.   "Geotagging can be dangerous when you don't intend to share that information with someone else, when someone else has a vested interest in knowing what that location is of the picture you took," says Jeremiah Johnson of the National White Collar Crime Center.  This poses a major threat, because predators can potentially analyze your photos off your blog, website, or social network and use the embedded geotag to identify the exact locations of some of your most routine daily tasks.  And worse yet, your children's common locations.  The article concludes by referring to a video on several ways to disable geotags on your smart phone.

I see the ability to geographically tag my images as a wonderful tool that, as with all technology, with proper use within well-established boundaries, can be a great way to manage and collect your digital media.  My personal decision (and recommendation) is to use geotagging in all cases on my phone, but from here on out the change I will make is that I will remove the geotag information before posting any potentially "private" images on the Internet.

I feel like there are too many advantages of this technology to do something drastic like shut it off completely.  I loved being able to see all my photos by location on a map on my iPhone.  Without geotagging that wouldn't be possible.

Years down the road, I'd like to be able to take a look at my personal history by looking at a map and seeing collections of pictures in all the locations I’ve lived or traveled.  What amazing technology!  Sure, you could manually specify the location of each photo, but if we're talking hundreds or thousands of pictures, the geotag is such a innovative (and creative) feature that enables wonderful creativity.

As with any technology, we must make sure we understand the technology and approach it correctly.  Similar skepticism at the risks of new technologies occurred with AOL instant messenger and other messaging clients that came out 10-15 years ago.  Look at the widespread use of these technologies today... where would we be without them!  Geotagging must be handled safely and responsibly, and it can be an incredible tool that takes advantage of years of technological innovation in computer hardware and data communications!

Using PHP and LDAP to Authenticate Against BYU's Servers

Been working on a BYU project at the law school where I only want to let BYU students post on a message board.  I needed an authentication solution and decided to give LDAP a try since I've heard it's relatively simple.  Here's the two step process: 1) Create a form that accepts a username and password as follows.

<form action=login.php method=post name=Auth>

Please log in using your NetID and password:<p>

<table cellspacing=3 cellpadding=3> <tr> <td>Username: </td> <td><input type=text name=username size=16 maxlength=15></td> </tr> <tr> <td>Password: </td> <td><input type=password name=password size=16 maxlength=15></td> </tr> <tr> <td colspan=2><input type=submit value=Authenticate style='width:100'></td> </tr> </table> </form>

 2) Create a login.php file.  This file accepts the username and password from the form, then connects to BYU's LDAP server (ldap://ldap.byu.edu - port 389).  After connecting, it binds the connection using the username (NetID) and if successful returns true.  Below, the authenticate function is called and if successful sets the 'loggedin' session variable to 'true' (not a boolean).  It then redirects back to the previous page, which, in this example is the message board I'm working on.

<head> <?php session_start(); ?> </head>

<?php

echo "test"; echo "</br>";

// get username and password from form $username = $_POST['username']; $password = $_POST['password'];

/* * checks the credentials against the LDAP server * $user - RouteY * $pass - password */ function authenticate($user,$pass){

echo "</br>"; echo "Authenticating..." . $user;

// prevents guest account access if($pass == ""){ return false; }

try{

$Yldap_location = "ldap://ldap.byu.edu"; $ldap_port = 389;

// call the ldap connect function $Ydatabase = ldap_connect($Yldap_location, $ldap_port);

// bind the connection $good = @ldap_bind($Ydatabase, "uid=".$user.",ou=People,o=BYU.edu", $pass);

if($good){ // valid credentials return true; } else{ // invalid credentials return false; }

} catch(Exception $e){ return false; } }

// call authenticate function if(authenticate($username,$password)){

// authenticate successful echo "</br>"; echo "SUCCESS";

// set session $_SESSION['loggedin'] = 'true';

// redirect echo $_SESSION['loggedin']; $url = "http://www.law2.byu.edu/page/messageboard.php"; //$url = "http://www.law2.byu.edu/page/messageboard.php"; header("Location: ".$url); } else{

// authenticate fails echo "</br>"; echo "FAIL";

// redirect to login header("Location: http://www.law2.byu.edu/page/messageboard.php"); } ?>

java.util.Date to java.sql.Date conversion error

For a database project (building a full retail store system) I've tried passing a java.util.Date to a Java prepared statement.  The problem is that the prepared statement expects java.sql.date, and converting it isn't working for me.  Here's the errant code: ps.setDate(2, emp.getDate()); which results in this error: no suitable constructor found for Date(java.util.Date) constructor java.sql.Date.Date(long) is not applicable (actual argument java.util.Date cannot be converted to long by method invocation conversion) constructor java.sql.Date.Date(int,int,int) is not applicable (actual and formal argument lists differ in length) The fix is to create an SQL Date using the java.util.Date as follows: java.sql.Date sqlDate = new java.sql.Date(emp.getDate().getTime()); Then, the prepared statement accepts the date. ps.setDate(2, sqlDate);

Super Wi-Fi - The Dawn of a New Era

Vocab Lesson to start - SUPER WI-FI - Super Wi-Fi is essentially Wi-Fi as we already know it, but on a new, unused block of unlicensed spectrum (thanks FCC!).  This spectrum ranges from 50 MHz to 700 MHz and is at a much lower frequency than Wi-Fi is now, which will allow for better travel of data signals. I recently read on article on Super Wi-Fi.  The article makes some great points about Super Wi-Fi, which is supposedly the direction we're all heading.  Should it pan out, Americans will have the ability to get Wi-Fi access all across town, or campus, or park, or whatever it may be.  This makes me think of two futuristic possibilities: (1) the possibility of every human being having some kind of ever-connected bracelet, or ring, or even chip in them and (2) the fall of cell phone providers.

The article begins by shedding light on the first "Super Wi-Fi" network in Wilmington, North Carolina. With the first efforts relatively successful, are we ready to move everyone over to "Super Wi-Fi"? Not so fast, the article argues. "New Hanover County IT Director Leslie Chaney says that the network is being used primarily as backhaul technology for the time being and won't be available for residential subscribers in the county for at least a year."

The article goes on to describe some of the problems that Super Wi-Fi will still need to overcome. Some of the problems include establishing network standards that have yet to be worked out and mass-producing chipsets that will work on the spectrum. Overall though, Super Wi-Fi is impressive. Having taken advantage of unused TV frequencies, Super Wi-Fi is at an overall lower frequency, which means less interference from rain and walls. The county estimates that the networks will be ready for Super Wi-Fi in a year, and the country will be ready in 2-3 years.

The first impact mentioned has to do with monitoring human life.  I was telling my wife last week that I thought embedded heart-rate, temperature, and other health/performance measuring sensors in the everyday wedding ring will be an amazing technology in the future (and that we should build it).  With Wi-Fi access anywhere, and data-to-Wi-Fi transmitting chips embedded on small items such as a camera's SD card, I have to wonder when this technology will become an every day part of human life for health monitoring.  Sure, there's still years of technology and scores of legal issues to get through, but we're moving that direction.

The second, and more pressing issue is what to do with cell-phone carriers once Wi-Fi becomes commonplace.  Think of the impact nationwide Wi-Fi (are we really that far away from it?) will have.  I've already thought of ditching my phone's phone plan, data plan, and text messaging plan and using a free service like google voice, skype, heytell, facebook messenger or some combination of those as my replacement for AT&T.  What will happen when we realize that we don't need to pay AT&T for their text messaging data (thank you WiFi), "data" data (thank you WiFi), and even cellular phone data.  With Google being one of the first to venture into providing these services, I see a whole need business model with google creeping in, charging 10 bucks a month for all the above, and the whole U.S. flocking to Google Voice.  Because seriously, why I am pay $100/month for AT&T when I can get the same data using my home/school/work Wi-Fi and soon enough... Super Wi-Fi.

For these, and many other reasons, I think Super Wi-Fi will have an enormous impact on the world.

Protest SOPA on your Website (JavaScript)

Join hundreds of thousands in protesting SOPA and PIPA by writing to your congressmen, telling them how you feel about these bills.  To take it a step further and join in the #blackoutSOPA cause, paste this handy javascript into the <head> tags of your webpage or blog.  It will 'blackout' your website for January 18th only, redirecting users to sopastrike.com

<script type="text/javascript"> var a=new Date,b=a.getUTCHours(); if(0==a.getUTCMonth()&&2012==a.getUTCFullYear()&&((18==a.getUTCDate()&&13<=b)||(19==a.getUTCDate()&&0>=b)))window.location="http://sopastrike.com/strike"; </script>

Stop SOPA & PIPA

To my congressman, Jason Chaffetz, representing Utah's Third District, I oppose SOPA and PIPA. Please do not support these misguided proposals for combating online piracy. I am a web developer and mobile app developer and businesses like the one I started will be severely threatened by SOPA and PIPA. This is not freedom and liberty, it is an unjust proposal to a web-related problem. This issue must be reassessed and readdressed with greater sensitivity to freedom of speech, due process of law, and business and technological innovation.

Kyle Clegg

Android Thoughts

Recently a friend decided to upgrade from an Android device to an iPhone 4s. I commented on her facebook post:

You're crossing to the dark side??

Kyle youll be back to the dark side iphone is taking over the world!!!! and i want to be on team apple when that happens.

Touche. can't argue. iphone is by far the best. Android is decent but given iOS and apple hardware as an alternative it's almost a no brainer. unless windows phone 8 makes a splash...

Someone else chimes in:

Almost a no-brainer... but not quite. Compared to budget Android devices, the iPhone is definitely superior. But there is literally no hardware spec on the iPhone that isn't matched or beaten by higher end Androids. If you favor features over price point, it comes down to preference, not superiority. The user experience on Android 4.0 is absolutely amazing, and the open source nature of Android puts it light years ahead of iOS in terms of development opportunities.

Again, it's about preference. iOS is clean, simple, and beautiful. Android is powerful, customizable, and versatile. It's all about what you're looking for in a phone. But let us be wary of granting to Apple some of these unearned superlatives.

My latest thoughts on Android:

I haven't used Android 4.0, but given the improvements between 2.2, 2.3, 3.0, and similarly positive and 'groundbreaking' reviews for 4.0, I can't imagine it being something I get too excited about. I switched from an iPhone 4 to Android (dual core Motorola Atrix) for many of the reasons listed but have ultimately been let down.

Google delivers power, customizability, and a sense of freedom on Android devices, however I find the power comes with some catches - weak battery life, unexpected FCs, laggy display (WHY?? the Atrix's processor should kill the iphone 4). The customization options are confusing and inconsistent across different hardware makers. Even having developed two Android apps, I haven't seen (or maybe just haven't utilized) any features that I feel are compelling. Lastly, the freedom I feel due to the open source nature of Android is refreshing, but honestly, I'd be fine giving up this flexibility for a superior WP7 or iOS device.

To me, bottom line is the Android ecosystem is discombobulated and inconsistent. It's a decent OS and beats any feature phone on the market, but having seen both Android and iOS up close and personal, I'm ready to switch back to iOS or try something new in WP7/WP8.

The Palate Whistle

I was wondering how the guy whistles in this youtube video: Home - Edward Sharpe and The Magnetic Zeros Acoustic Cover (Jorge & Alexa Narvaez).  He does some crazy no lip whistle.  Googling "whistle without lips" led me to this little bit of info.

How to whistle with your mouth:

  1. This whistle may require some practice and exercise because it takes strength in your tongue, jaw, and other parts of the mouth.
  2. Draw your lips and the corners of your mouth as far back as you can. Your bottom teeth should not be visible, but it is okay if your top teeth show.
  3. Pull the tongue taut and draw it back.
  4. Broaden and flatten the tip of the tongue.
    • Be sure there is a space between your teeth and tongue.
    • Your tongue should float in your mouth more or less at the level of your bottom row of teeth.
  5. Blow air gently out.
  6. Direct your breath downwards towards your lower teeth. You should be able to feel the downward force of the air on your tongue.
    • The sound is created by the tongue working with the upper teeth to force air over the surface of the tongue and into the lower teeth.
  7. Experiment with the position of your tongue, cheek muscles, jaw, and anything else for a wide variety of whistle sounds.

AnyDVD Not Ripping DVDs to English

Working on a video editing project, I've started using AnyDVD to decode and rip DVDs to my machine.  It's been a great tool,  works efficiently and just as I would expect it to, however on a couple of the DVDs I've ripped it's, seemingly randomly, ripping one or two of the video files in French. The problem is that the language settings on AnyDVD have been set to "Automatic" by default.  To fix this, open AnyDVD and select "Language Selection" from the settings bar on the left, and change the language to English (or whichever language you want).

I'd also like to find a painless way to string the outputted VOB files back together, however for this project it's not critical, since I've only ripped these DVDs for the sake of taking two or three 30 second clips from each.  Once I do find an easy tool to string link the VOB files back up into a semi-production level looking file I'll post it here as a comment.

Candy Jar Estimator Launches

unnamed

Yesterday Bryce (my business partner) and I launched "Candy Jar Estimator" on the Android Market.  It's designed to help you win candy guessing competitions - it takes your candy, the jar type, any custom jar measurements, and computes the expected number of candies in the jar.  Basically it means automatic WIN if you use it the next time a candy estimating competition rolls around at work, church, holiday festivities, etc.  so... it's pretty awesome.

Anyway we've also entered our app in the BYU mobile app competition.  The competition runs through November 16 and there are several prizes that we could potentially take home, including $6000 grand prize, $3000 judge's prize, and a local company's choice: brand new iPads for all team members.  If you'd like to help our team out here a few things you could do.

unnamed
  1. If you have an Android phone, download the app (yes it costs a dollar), l eave a 5 star rating and a SUPER AWESOME comment.
  2. Tell your Android friends to download it and leave some awesome reviews for us.  Say "my brother is entering his android app into BUY's mobile app competition. check...it...OUT! http://bit.ly/tmlitR" (and then make sure they download it and not just look at it)
  3. Even if you don't have an Android, you can help us by +1-ing our app on the Android Market. go here (http://bit.ly/tmlitR) and click the +1 button on the top right of the screen.

The biggest help will probably be sharing, so if you want to tweet it, Facebook it, or blog it that would be very helpful.  Also - if you have friends that are big blogger's a little spotlight from their blog goes a LONG way.

Available in Android Market

Dropdown Menu in PHP

Browsing around the web you'll notice tons of drop-down menus that let you navigate to different areas of that web site.   Drop down menu navigation is great because it lets you add a lot of navigation options, without taking up much space.  I know, for the web dev buffs out there you would probably never want to do this in PHP alone, but I found a cool tidbit of info on this and wanted to share.  So if you're looking for how to do this on a large-scale you probably want to turn to JavaScript.

With that said, one way to replicate a drop down menu with PHP is to setup an HTML form somewhere on your page and have it pass the site's URL to a PHP page when you submit it.  For example:

<form action="jump.php" method="post"> <select name=url> <option value="http://php.about.com">About PHP</option> <option value="http://www.identity.st">Identity</option> </select> <input type="submit" value="Go"> </form>

Then have the PHP file jump.php use basic redirection to send them to the right page.  For example:

<?php $url = $_POST["url"]; header("Location: $url"); ?>

Give it a shot!

Using LogCat in NetBeans

The best way to debug in Android is to use LogCat.  I've yet to figure out an easy way to do this though -- using NetBeans -- but it can be done.  LogCat should be installed with your Android SDK and AVD (android virtual device) kits, however the problem is that NetBeans doesn't display logcat in a "console"-like format.  I was looking at this tonight and figured out how you can still get your LogCat printout -- it just prints straight to a text file and not in a nice built-in display window like Eclipse has.
USING LOGCAT IN NETBEANS
1) First, you'll have to add the adb tools path the Windows global variable (if you're on a mac you'll have to google how to do this).  See http://www.shahz.net/android/adb-installation-and-how-to-logcat.html
2) Then, whenever you run your app and it crashes (or anytime you want to debug), open the command prompt and enter:
adb logcat -v time > logcat.txt
This will create a file in the current folder with the current LogCat logs.  You'll have a lot of stuff in there so it's important that you've used LogCat properly in your code so that you know what to look for.  Run "start logcat.txt" to take a look.
3) To to use LogCat in your code you'll first need to import the Log library:
import android.util.Log;
Then, down where you would normally print something out, you'll replace "System.out.println("HERE");" with:
Log.d("LOGCAT", "HERE");
4) Now, run the logcat command again, then open the text file with the start command:
adb logcat -v time > logcat.txt
start logcat.txt
5) Now, use CTRL-F "LOGCAT" to look through all your LOGCAT debugging statements.
Also - If your app is crashing try searching for "E/AndroidRuntime"... this will take you to the information on what caused the error.
I know it's a little complicated, but it works!  And it'll let you debug crash errors too.  The problem with using toasts for debugging is that the app may crash before you ever reach the toast.  Which... ends up not really helping you at all.  So if you can bear the pain of these steps for your debugging, it should help out a lot!   And if you find a better way to use LogCat in NetBeans please let me know.  It would be awesome if they let you view the LogCat logs directly in NetBeans.  Man that would be sweet.  Good luck!
Let me know if you find any mistakes with the info above.

Android Toast Example

Android lets you "toast" a display message that pops up on top of the current window. This usually occurs on some condition and is generally simple in nature, something like "OK", or "File submitted", etc. The code below can be plugged into any android class to launch a toast.

    Toast toast = Toast.makeText(getApplicationContext(), "Invalid Parameter", Toast.LENGTH_SHORT);
    toast.show();

This bit of code will launch a short toast that displays the text "Invalid Parameter". The length of the toast is 2 seconds, and can be changed to a longer 3.5 second toast by changing the duration(Toast.LENGTH_SHORT) to Toast.LENGTH_LONG.

Toast away!

Getting Started Project as a "Web Specialist"

Starting my new job as a web specialist for the BYU Law School this week.  The getting started project is as below... super stoked. Create a page using php, mysql and html where users can login or sign up and fill in forms about themselves (first name, last name, age, email address). Provide a spot for them to upload a document of type pdf, reject other types of uploads. Also, create a field that uses CKeditor to get a quick "user blurb" or description of themselves. After they are logged in, have a page in which all users are listed and linked to their profiles which will appear in a Colorbox when clicked upon. Be sure to style everything using CSS. Things you will need to know to do this:

    • How to create a form and use php post variables
    • How to upload and check uploaded documents
    • Session variables in php
    • How to create and use a correctly structured MYSQL database
    • How to use Colorbox
    • How to use CKeditor
    • How to do CSS styling

Tip: We highly recommeded thoroughly completing Lynda.com's PHP with MySQL Essential Training course to assist in preparing for the training exercise.

 

Dec 2011 update: See my mini content management system - still a work in progress.