Archive

Posts Tagged ‘function’

Display JavaScript Source Programatically

March 23rd, 2009 2 comments

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

<script type="text/javascript">//<![CDATA[
 function displaySource(name) {
  $('<code>'
   + $('#display-' + name).prevAll('script').eq(0).html()
   .replace(/^\s*|\s*$/g, '')
   .split('\n').slice(1, -1).join('\n')
   .replace(/(^|\n) /g, '$1')
   .replace(/('[^']*')/g, '<em>$1</em>')
  + '</code>')
  .insertAfter('#display-' + name);
 }
//]]></script>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

<script type="text/javascript" id="display-test">displaySource("test");</script>

Getting Started With PHPDoc

January 26th, 2009 No comments

If you followed the tutorial on installing PHPDoc then you are probably wondering how to get started actually writing the documentation. PHPDoc will parse all the files given to it and look for comment blocks, it will then use these blocks to create the documentation for your application. A valid PHPDoc comment block must start with a '/**', have a '*' on every line and finish with '*/'. The comment must appear before the section that is being commented upon and any lines within the comment without a '*' will be ignored by the parser.

To create some sample documentation we will use the following useless class.

<?php
include('another_file.php');
 
class MyClass
{
 
  public $publicVariable = 123;
  private $privateVaraible;
 
  public function aFunciton($parameter)
  {
    // some code here...
  }
 
}

The first thing we need to do is create a file comment, this comment is intended to tell people what this file contains. In this example the file contains a single class definition and an include statement.

/**
 * MyClass File (short description about the file)
 *
 * This file contains the definition of the file MyClass (a longer description about the file).
 * @author A.N. Other
 * @version 1.0
 * @package MyPackage
 */

Notice the use of the @ symbol. This is called a tag and allows PHPDoc to assign values to internal variables. So when we use @version, we are setting the version variable for our file.

define() statements, functions, classes, class methods, and class vars, include() statements, and global variables can all be documented. So the next step is to document what the include statement includes. PHPDoc will attempt to find any files referenced through include or require statements and generate documentation for those files. If present, a link will be created from this file to that file in the documentation.

/**
 * Include the another_file.php file.
 */
include('another_file.php');

Next is our class definition, which consists of two forms of description(short and long) as well as some tags relating to things like what package the class is in.

/**
 * This is a short description about the class.
 *
 * This is a longer description which should detail exactly what the class does.
 * @package test
 * @author A.N. Other
 * @version 1.0
 * @copyright A copyright notice, if any.
 */
class MyClass
{
}

The two variables within the class must also be documented.

/**
 * A description of the variable.
 * @var integer
 */
public $publicVariable = 123;
 
/**
 * This variable will only appear in our documentation is we set the --parseprivate attribute on the command line or it has been set up in the INI file.
 * @access private
 * @var string
*/
private $privateVaraible;

Finally, we document the function. The functions are documented using the two tags of @param and @return. The @param can be defined multiple times and is a descriptive list of the parameters that the function takes. The @return value can only be defined once and describes what the function returns. If more than one datatype is returned from the function then they can be separated by a pipe (|).

/**
 * This class either returns an integer or a string.
 * @param A description about the parameter $parameter
 * @return string|int This function returns a string or an integer.
 */
public function aFunciton($parameter)
{
  // some code here...
}

To add more than one parameter just add another line in that starts with @param.

You can run PHPDoc on this file by using the following command (assuming that your project is kept in a folder called "MyProject" and that you want the documentation to go in "docs" within that directory.

C:\MyProject>phpdoc -t "C:\MyProject\docs" -o HTML:frames:default -d "C:\MyProject"

Randomising The Middle Of Words In PHP

November 18th, 2008 No comments

I was sent an email the other day that contained some text were the start and end letter of each word were left alone, but the middle of each word was randomized. The weird part was that the text was still readable, which is due to the way in which the brain processes words.

I wondered if I could replicate this using a PHP script. All I would need to do is split apart the sentence into the component words and loop through those words, randomizing the middle of them. Clearly, it is not possible to mix up the order of letters in a word less than four characters long so a check would be needed for this. This is what I cam up with:

function mixWordMiddle($string)
{
 $string = explode(' ',$string);
 foreach ( $string as $pos=>$word ) {
  $tmpArray = array();
  if ( strlen($word) > 3 ) {
   $chars = preg_split('//', $word, -1, PREG_SPLIT_NO_EMPTY);
   for ( $i = 1 ; $i < count($chars)-1 ; ++$i ) {
    $tmpArray[] = $chars[$i];
    shuffle($tmpArray);
   }
   $string[$pos] = $chars[0].implode($tmpArray).$chars[count($chars)-1] .' ';
  }
 }
 echo implode(' ',$string);
}

I then tried plugging in the following text about evolution.

$string = 'In biology, evolution is the changes in the inherited traits of a population of organisms from one generation to the next. These changes are caused by a combination of three main processes: variation, reproduction, and selection.';

And came up with something like the following.

In bliygoo, eoutivoln is the cganhes in the iethirned titras of a piaplouotn of oargnsims form one gneoeatirn to the nxte. Thsee cagnhes are ceusad by a cmibitoonan of there main persocses: voaitanri, rteunodpoirc, and stoneleic.

Which is actually quite difficult to read. I thought that this might be because I had used a bit of text with too many long words, so I selected another:

$string = 'A giant Saudi oil tanker seized by pirates in the Indian Ocean is nearing the coast of Somalia, the US Navy says.';

This produced the following text.

A ganit Suadi oil taeknr seezid by ptaiers in the Ianidn Oecan is nraneig the cosat of Smiolaa, the US Navy syas.

This is just a test script, so it doesn’t take into account any punctuation. However, the text it produces is still difficult to read, which leads me be skeptical of the claims of that the email I received.

Categories: PHP Strings Tags: , , , , , ,

Generate Password Function In PHP

November 17th, 2008 No comments

I have talked about generating random passwords before. Although that function generated some nice passwords, they perhaps aren’t as unique as they ought to be.

This function, take from Webtoolkit creates passwords of different length with varying levels of complexity.

function generatePassword($length=9, $strength=0) {
  $vowels = 'aeiu';
  $consonants = 'bdghjmnpqrstvxyz';
  if ( $strength & 1 ) {
    $consonants .= 'BDGHJLMNPQRSTVWXYZ';
  }
  if ( $strength & 2 ) {
    $vowels .= 'AEU';
  }
  if ( $strength & 4 ) {
    $consonants .= '23456789';
  }
  if ( $strength & 8 ) {
    $consonants .= '@#$%';
  }
 
  $password = '';
  $alt = time() % 2;
  for ($i = 0; $i < $length; $i++) {
    if ($alt == 1) {
      $password .= $consonants[(rand() % strlen($consonants))];
      $alt = 0;
    } else {
      $password .= $vowels[(rand() % strlen($vowels))];
      $alt = 1;
    }
  }
  return $password;
}

The first parameter is the number of characters that the function should return. The second parameter is a number up to 8 which converts into complexity. The least complex password consists of only lower case consonants. The most complex password consists of upper and lower case letters,

You might notice that some of the letters and numbers are missing, this is deliberate. When passwords are generated many of the characters can be very similar. Zero can look like an upper case O and I can look like the number one or a lower case L. Removing these letters stops people getting their passwords wrong and having to reapply for them in the future. Also, many people write down their passwords, even though you shouldn’t, and in doing this many characters can also look the same. For example, in a mix of upper and lowercase letters it is difficult to see the difference between an upper and lower case W.

You can run the function like this.

echo generatePassword(8,1); // LareSuSy
echo generatePassword(8,2); // hUsuserU
echo generatePassword(8,3); // MEdEgYze
echo generatePassword(8,4); // tanapa3a
echo generatePassword(8,5); // ary2ugeR
echo generatePassword(8,6); // uqUtebyq
echo generatePassword(8,7); // yRysuNEV
echo generatePassword(8,8); // ygyqyha%

This is just the output that I got from these parameters, a different password is run each time. You should be using level 8 for any system administrator passwords.

The Script Element, Adding An Action To A Button And Functions In Flex

November 5th, 2008 No comments

Yesterday I talked about creating some simple Flex elements in your application. Today I will introduce a new element called Script.

The Script element, if you haven’t already guessed is used to run your application function and should be contained within the Application element. You can either put script inline like this.

<mx:Script>
// some code here
</mx:Script>

Or you can use the source attribute and link it with an external ActionScript source file.

<mx:Script source="myactionscriptfile.as">
</mx:Script>

The simplest thing you can do is use the function trace(). This is a debugging function that will output information into the debugging Window in your Flex IDE. To print out a message when your application is first run do the following.

<mx:Script>
trace('Flex program running.');
</mx:Script>

To capture a mouse click on a Button element you need to use the attribute click, the value of which can be either come code or a callback to a function. To use inline code using the following, which will print out a trace.

<mx:Button id="abutton" label="A button" click="trace('Button clicked');" />

To use a callback function do the following.

<mx:Button id="abutton" label="A button" click="clicked();" />

In your script section you can now add the function that you want, and perhaps do more than just a simple trace() call. The following script will send a trace message to your output and then open a browser window to the talk in code page. If you embed this application within a web page then the current browser window will redirect to the URL.

<mx:Script>
public function clicked():void
{
 trace('Button clicked');
 navigateToURL(new URLRequest('http://www.talkincode.com'));
}
</mx:Script>

To create a function you need to use the following syntax:

scope function functionName():return type
{
}

The scope is how the application will see the function. For a function like this that is outside the scope of a class (which is another topic) it should have public scope. The return type is the type of value that is returned by the function, and if no value is to be returned then void is used. If the function adds two numbers together and returns the result then the return type would be Number.

Categories: Flex Tags: , , , , , , ,