The Original Jelani Harris The one and only

11Jun/120

How to check if a jquery plugin is installed or available

Most Jquery plugins act a lot like functions. They are attached to the main Jquery object, so essentially all we have to do is check that the function exists and is defined.

if ($.pluginFunction) {
  // Function exists, do your plugin stuff here.
} else {
  // Plugin does not exist, use alternatives or do nothing in here.
}
Tagged as: , No Comments
8Dec/100

How to read remote files using PHP

When I was implementing pingback functionality in my custom blogging software, I needed to read files from a remote server.

As long as allow_url_fopen is enabled in your php.ini configuration you can use HTTP and FTP urls with a majority of the functions that use a filename as a parameter.

I found that there are 3 ways to read remote files using PHP.

Fopen

if ($filepointer = fopen("http://banditrevolvers.com", "r")) {
     $site_content = "";
 
     //While we still have content to read, append it
     //1k at a time
     while ($line = fread($filepointer, 1024) {
          $site_content .= $line;
     }
 
} else {
     //Error occured while trying to read the url
}
 
fclose($filepointer);

Another example using fgets instead of fread

if ($filehandle = fopen("http://banditrevolvers.com", 'r') {
 
     while(!feof($filehandle)) {
          $readline = fgets($filehandle, 1024);
          if (eregi("<title>(.*)</title>", $readline, $output) {
               $title = $output[1];
               break;
          }
     }
} else {
     //Error occured while trying to read the url
}
 
echo "Title of the page is: " . $title;
 
fclose($filehandle);

Wait what's the difference between fgets and fread?

Glad you noticed that. The truth is that fread is the more preferable function to use when reading (or in this case streaming) data from a remote file. The reason is because the fgets function reads a line at a time. For example, if you had a 2000 line file that was only 35k in size, it would loop 2000 times with fgets. However it would only loop 35 times with fread (assuming a 1k buffer).

Then again, if you need to read a file one line at a time fgets is the function you'll need.

File_get_contents

This function will return the contents of a file in a string. To use it just specify a URL as a parameter. Be sure to check the return value to see if it was successful or not.

$content = file_get_contents("http://banditrevolvers.com");
 
if ($content !== false) {
     //Do something with the content
} else {
     //An error occurred
}

CURL

Not all web hosts have the CURL library in their installation. Thus we have to check to see if the function exists before we attempt to use it.

if (function_exists('curl_init')) {
     //Initialize a new resource for curl
     $ch = curl_init();
 
     //Set the url the retrieve
     curl_setopt($ch, CURLOPT_URL, 'http://banditrevolvers.com');
 
     //Return the value instead of outputting to the browser
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
     $contents = curl_exec($ch);
     curl_close($ch);
 
     if ($contents) {
          //Do stuff with the contents
     } else {
          //Show error message
     }
 
}
Filed under: Code Gems No Comments
1Dec/101

Changing the pointer into the hand cursor in AS3

One of the problems that I ran into while migrating from Actionscript 2 (AS2) to ActionScript 3 (AS3) was the fact that not only was setting a mouse event of a MovieClip different, so does how the mouse cursor acts.

In AS2, setting the onPress event for a MovieClip would automatically cause the cursor to switch the hand whenever you hovered over the element. However in AS3 I discovered that in order to get the same functionality it has to be done manually to get the same effect:

//These are properties of the MovieClip class
targetMc.buttonMode = true;
targetMc.useHandCursor = true;

Upon discovering this bit of code, I noticed that I had already created more than a dozen of clickable instances that could use this code and not all of them had classes for them. I had searched for some kind of global variable that I could set to see if I could get this working with all of them the easy way. Alas, I came up with nothing. So instead I decided to create a base class to implement this functionality for me.

import flash.display.MovieClip
 
package com.jelaniharris {
     class ButtonMovieClip extends MovieClip {
          //Override the default constructor and make this movieclip indicate it's a button to the user
          public function ButtonMovieClip (): void {
               this.buttonMode = true;
               this.useHandCursor = true;
          }
     }
}

Then all I needed to do was to go to my library and set the Base Class of all of my button-like elements to the ButtonMovieClip class.

I hoped this helped someone out there.

Tagged as: , 1 Comment
16Jul/1012

Using Jquery to disable the enter key

There are times that you do not want a form to automatically submit when a user hits the enter key. Or if you want to do some validation via javascript before you allow the submit to go through.

//Bind this keypress function to all of the input tags
$("input").keypress(function (evt) {
//Deterime where our character code is coming from within the event
var charCode = evt.charCode || evt.keyCode;
if (charCode  == 13) { //Enter key's keycode
return false;
}
});

By returning false in the keypress function it tells the browser not to allow the enter key event.

4May/101

Removing empty elements from an array

When dealing with tag inputs from users, I find myself having to make sure they they don't enter in any blank or empty tags. Then I realized that I needed to find out how to remove undesirable elements not only from the Php side, but also from the Javascript side as well. Thus, here are some functions that may help some other people out if they're searching for similar functionality.

In PHP

    foreach ($my_array as $key => $value) {
      //We check to make sure that the value is either null or just an empty string
      if (is_null($value) || $value=="") {
        unset($my_array[$key]);
      }
    }

An easier way to clean arrays is to use php's array_filter function without a callback parameter. By default that function is set to remove elements that contain a false (or a 0), null or a "". I mean seriously, look at how much cleaner it is:

   //This prunes out 'false', '0', 'null' or ''
   $my_array = array_filter($my_array);

In JavaScript

We can mimic the functionality of Php's array_filter in Javascript by using the Array.filter function.

   var my_array = [1,2,3,'4','', 0, null, 'false'];
   function emptyElement(element) {
	//Removes nulls, zeros (also falses), text version of false, and blank element
	if (element == null || element == 0 || element.toString().toLowerCase() == 'false' || element == '')
		return false;
		else return true;
	}
 
	var my_array = [0,'false',1,null, 2,'',3,'4',false];
	my_array = my_array.filter(emptyElement);
   }

Then my_array will include 1,2,3,4.

I hope this was somewhat useful.

Tagged as: , 1 Comment
16Sep/090

Increasing performance of Adobe CS3 Flash in Vista

When I first started to use Flash CS3 in Vista I noticed that all of my flash movies were performing very very slowly.

Honestly .. I'm not sure why. But, here's how you can make it perform better.

Here's how to speed up flash CS3 for vista

Here's how to speed up flash CS3 for vista

  1. Navigate to your Program Files -> Adobe folder(s) -> Adobe Flash CS3 and find the Flash.exe.
  2. Right click on that file and goto the Compatibility tab.
  3. Check "run this program in compatibility mode", and voila, suddenly it's running as fast as it did on XP. Happy coding!
Tagged as: , , , No Comments
10Sep/0913

Case-insensitive replaceAll in Java

The replaceAll function in the java.lang.String class replaces each substring found in that matches the regular expression to replace.

String sentence = "The sly brown fox jumped over the lazy fox.";
String result = sentence.replaceAll("fox", "doggie");
System.out.println("Input: " + sentence);
System.out.println("Output: " + result);

Would output:

Input: The sly brown fox jumped over the lazy fox.
Output: The sly brown doggie jumped over the lazy doggie.

However there are cases where we want to replaceall substrings and ignore the case, or make it case insensitive.

String sentence = "The sly brown Fox jumped over the lazy foX.";
String result = sentence.replaceAll("fox", "dog");
System.out.println("Input: " + sentence);
System.out.println("Output: " + result);

Input: The sly brown Fox jumped over the lazy foX.
Output: The sly brown Fox jumped over the lazy foX.

To create the case sensitive version of replaceAll we do not need to create a new wrapper function or create a utility class somewhere. All we need to do is prepend the Case-insensitve pattern modifier (?i) before our regex to indicate that we don't care about the case sensitivity of the regex.

String sentence = "The sly brown Fox jumped over the lazy foX.";
String result = sentence.replaceAll("(?i)fox", "dog");
System.out.println("Input: " + sentence);
System.out.println("Output: " + result);

Input: The sly brown Fox jumped over the lazy foX.
Output: The sly brown dog jumped over the lazy dog.

Tagged as: , 13 Comments