Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. Show all posts

Saturday, April 12, 2008

8 Essential MySQL Queries

Here's a list of queries that I found myself using very often and that save me a lot of development time. I hope you can benefit from them as well.

1. Create a quick backup

Before testing a new piece of code you suspect might mess up data in one or more tables it's always a good practice to create a backup. To quickly create a backup copy of a table, use this query:

CREATE TABLE backup SELECT * FROM TABLE original;

The query creates a table backup which is a copy of the original table and includes both structure and content.

2. Create/change/restore a password

Many applications store MD5-crypted passwords in the database. If you want to quickly create a new MD5-ed password, or you have forgotten your password, use the following query to get a new one:

SELECT MD5('somepasshere');

This statement will give you "b5bab206cc8002bf7c10d47b24a2d0e6" which is the encrypted version of the string "somepasshere". There are other function that crypt stings in MySQL using different algorithms, most notably

PASSWORD()
which is using MySQL's own crypting algorithm.

3. Working with Unix timestamps

To convert from human-readable MySQL date/time format into Unix timestamp, use: SELECT UNIX_TIMESTAMP(); Without parameters, this will give you the timestamp of the current date and time. With parameters, you can get timestamp for any date. For example: SELECT UNIX_TIMESTAMP('2006-12-31'); This statement gives you the timestamp 1167541200. To get a date back from a timestamp, use: SELECT FROM_UNIXTIME(1167541200); This results in "2006-12-31 00:00:00"

4. Quick increment

To increment an integer stored in a table (useful for stats for example), use: UPDATE sometable SET counter=counter+1 WHERE …; Here "counter" is the name of the field that stores the integer value.

5. Toggle a value

If you have a field that stores a Boolean type of value, like 0/1 or yes/no, you can easily toggle the value with one if-statement:

UPDATE sometable SET flag=(IF(flag='no','yes','no'));

6. Find/replace

Say you want to update a piece of text if all records in a table field. REPLACE() comes to the rescue:

UPDATE sometable SET field = REPLACE(field, 'black','white');

This statement will replace all occurrences of the string "black" with the string "white" in all records of the "field" column. Apart from the string "white" the rest of the text contained in the field will be left as is.

7. Get a random record

If you want to select a random row in your table, you can use the statement:

SELECT * FROM table ORDER BY RAND();

8. Upper/lower case

If you want to modify a value and make it upper or lowercase, use the UPPER or LOWER functions, like this:

SELECT LOWER("Value"); // gives you "value"

SELECT UPPER("Value"); // gives you "VALUE"

About the Author
Stoyan Stefanov is a web developer from Montreal, Canada, Zend Certified Engineer, book author and contributor to the international PHP community. His personal blog is at http://www.phpied.com.

How to Create a MySQL Database

Whether you are an experienced web programmer or a complete novice attempting to provide data interactivity with your web site, MyQSL is an easy to use and free database solution that can allow you to store and configure data to be displayed on your web site.

The best way to create and manage a MySQL database is to download an open source (free) program called PhpMyAdmin. PHPMyAdmin allows you to manage all aspects of both your database structure and data from one easy to use interface. This tool is intended to handle the administration of MySQL over the Web.

This tool provides an interface that allows you to create and drop databases, create, drop, or alter tables, delete, edit, or add fields, execute any SQL statement, manage keys on fields, manage privileges, and import and export data into various formats. That sounds like a complicated set of activities, but the easy to use graphical tools make things quite simple and easy to understand. If you make a mistake, the software even provides instructions on where you made your error.

For a complete demo see: http://www.phpmyadmin.net/phpMyAdmin/
For documentation visit: http://www.phpmyadmin.net/home_page/docs.php

Most Linux based web hosting companies provide PhpMyAdmin as a standard feature with their packages. It is also available in a “Windows” IIS version. If your hosting provider does not already have this product installed they will often install it for you, or even allow you to install it yourself. Setup is quick and easy if you follow the step-by-step installation documentation.

Step One: Creating your new database

When you log in to your PhpMyAdmin welcome page, the first step is to enter a name for your new database in a text box provided. You can name your database anything that you wish, however if you are creating the database to use with a script or software package that you purchased somewhere, the script provider will often suggest a “preferred” database name. You should always create your database using the following format:

username_ databasename
Example: myusername_mydatabase

Your complete database name should always begin with your username followed by an underscore, then followed by the database name. This allows the server to know which user is in control of the new database, and it will also provide permission to access the database to only specific users. This also allows different users on the same server to use the same name for their own database, as you did, without interfering with your data – that is helpful if more than one user on your server bought similar software for their own site. They can then also use the software providers “preferred” database name.

Step Two: Creating a table for your new database

After you have created a database, the next step is to create a table, or even multiple tables, for you to store data. A table is the part of your new database that actually stores data.

You create a table by selecting the database that you created from the drop box list of databases. Once a database is selected a new form appears and asks for you to create a new table.

You must decide what you want to name your table and enter that name into the name box. Try to choose a name that reflects the type of data that will be stored in the table, such as orders, users, or inventory.

You then must decide how many “fields” or columns of data that you want to store for each record. If you need for the table to store five (5) different items, such as username, users email address, users telephone number, users account number, and the users age, than you would need five (5) fields. Simply enter the number 5 in the appropriate box. Once you hit create, the system will create a table and will add those fields into the table for you. Don’t worry about the number of fields you might need right now, as you can always add or delete fields later.

Step Three: Defining Fields

Once you have created your table you will be prompted to tell the database what features that you want each field to have. This looks complicated, but it’s not if you select your data type from the information below. You basically have to decide between three common data types and select the best choice for storing your data. If you make a mistake you can go back and edit the field.

If the field is to be used to store numbers, here are some choices:

TINYINT – A very small integer. The signed range is -128 to 127.
SMALLINT - A small integer. The signed range is -32768 to 32767.
MEDIUMINT - A medium-size integer. The signed range is -8388608 to 8388607.
INT - A normal-size integer. The signed range is -2147483648 to 2147483647.
BIGINT – A very large integer.

Some other less common number options include:

FLOAT- A floating-point number.
DOUBLE – A double-precision floating-point number.
DECIMAL - A packed exact fixed-point number.

If the field is to be used to store text or both text and numbers combined, here are some choices:

VARCHAR is for varying characters and can be up to 255 characters in length.
TEXT is a column with a maximum length of 65,535 characters – easy to search.
BLOB is a column with a maximum length of 65,535 characters – case-sensitive.

If the field is to be used to store dates, here are some choices:

DATE - A date.
DATETIME - date and time combination.
TIMESTAMP - useful for recording the date and time of an INSERT or UPDATE operation.
TIME - A time.

Once you have selected the data type for your fileds you will need to let the system know how many characters that you will need to store in the field.

Example: if you are storing a username, you might want to select VARCHAR as your data type and allow up to 100 characters for that field. If you are creating a User Identification number you might want to select INT and allow up to six characters – that would allow you to have up to 999,999 users.

The last step to creating your data fields is to select any special attributes that you may find helpful. Some examples are:

Auto Increment: Auto-Increment fields are useful for assigning unique identification numbers for users, products, and customers, etc. By default, fields are incremented using number characters (like "1", "2").

Primary Key: The primary key is a data column that uniquely identifies a specific instance of that data. At least one of your fields must be a Primary Key. Username is an example of a good primary key. You do not want to have more than one individual having the same username.

Index Key: Allows you to speed up searches by designating a field as a preferred data source, especially when combining data from multiple tables.

Congratulations, once you have completed these steps you are ready to import data into your new database.

About the Author
Don Beavers lives in Bryan/College Station, Texas and is an enterprise level PHP-MySQL programmer at both the Shopping Elf Shopping Guide and the Datavor Web Directory.

Tuesday, April 8, 2008

Developing and deploying an application on Google App Engine

This video introduces developers to building apps on Google App Engine using Python.

Saturday, March 22, 2008

Introduction to Glass Panes in Swing

In the Java Swing classes JFrame and JApplet, the glass pane provides a unique and powerful feature. The glass pane is a layer above all other controls within the JFrame and JApplet. It allows you to paint above all other controls.

In addition to drawing graphics over the contents of a JFrame or JApplet, the glass pane can also be used to handle mouse events. Be aware that adding a mouse listener to the glass pane will prevent any mouse events from being sent to the controls below it.

The first example will demonstrate drawing graphics over all controls in the JFrame.

//Create a panel to use as the glass pane
JPanel panel = new JPanel()
{
public void paintComponent(Graphics g)
{
g.setColor(Color.red);

//Draw an oval in the panel
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
};

//Turn off the opaque attribute of the panel
//This allows the controls to show through
panel.setOpaque(false);

//Set the glass pane in the JFrame
setGlassPane(panel);

//Display the panel
panel.setVisible(true);
The results of the glass pane:


By setting the opaque attribute on the JPanel to false, it turns of the background of the JPanel. When the panel is painted, only the graphics in the paintComponent will be drawn without the background.

By simply modifying the paintComponent you can create a completely different effect. In the next example, we set the alpha level for the color. This allows a color to be painted while allowing the controls below it to be shown.
//Create a panel to use as the glass pane
JPanel panel = new JPanel()
{
public void paintComponent(Graphics g)
{
//Set the color to with red with a 50% alpha
g.setColor(new Color(1, 0, 0, 0.5f));

//Fill a rectangle with the 50% red color
g.fillRect(10, 10, this.getWidth() - 20, this.getHeight() - 20);
}
};

The results of glass pane:


This tutorial only covers the basics of using the glass pane. There are a number of interesting possible uses of the glass pane. Below are some ideas of things to try with the glass pane:
  • Create a transition effects between screens.
  • Display a progress screen within the glass pane.
  • Display debug information within the glass pane.
Related Links
Swing Hacks -Chapter 6 has some cool examples for creating a progress indicator in the glass pane.

Sunday, March 16, 2008

Improve The Performance Of Your MySQL Server

MySQL is a rock solid, lighting fast database server which has been designed for two factors speed and performance. It is the Ferrari of databases: Light weight, fast and Built for the high speed tracks!

I still hear an awful lot of stories from owners whose databases are running two slow. In my experience, the three main places to look for problems are:

1. Faulty Database Design
2. Bad Queries
3. Server factors

Faulty Database Design
Proper database design is the single most important factor for the ensuring performance and maintainability of the database. Here is what you need to answer when designing a table: Can I reduce the size of data that each row will have? Here is what you can do:

1. Use unsigned numeric values when the application will not store negative numbers. Like the “quantity ordered” of an item in an ecommerce application is never going to be -$125.

2. Use Variable length values instead of fixed length value i.e. used varchar instead of char.

3. Do not use unnecessarily large field sizes. For most ecommerce application “unsigned smallint” is more than enough to store inventory count. A field described as “unsigned smallint” can store a max value of 65535.

4. Don’t ignore normalization; its helps prevent unnecessary repetition of data. The part B of this is, don’t overuse normalization. If the table will not grow in size significantly, there is no point in normalization. For example, if the user table has just 20 rows (i.e. 20 employees in a company), all attempts of normalization are wasted.

5. Use Keys. Don’t decide keys by “The customer id has to be indexed in the order table”. If the order table is being searched 90% of the times by “order date”, it makes more sense to index “order date”.

Remember, how a table will be used should determine how it is designed. Spending time here will save years of frustration.

Bad Queries
It sounds too good to be true but you wont believe the number of developers out there who completely suck at writing queries. There are two types of bad queries:

a) Unnecessary Queries: These are the queries that shouldn’t have been made in the first place. The only way to avoid this is asking, “Do I really need this data?”

b) Inefficient Queries: These are the queries that do not use the underlying table structure or MySQL functions in the correct way.

Here is a starting point to start looking at problem areas:

1. Unnecessary usage of “Select * “statements when the entire processing is being done on a single column. The more data is fetched from the server the more work MySQL has to do and more bandwidth it takes.

2. Using sub-query instead of a join. On a properly designed database, joins are incredibly fast. Using sub-queries just shows a lack of knowledge.

3. Improper use of Keys. This is especially valid for range checks. Remember to use the “Explain” statement to check the usage of keys and then use the “use key” statement in your “where” clauses to force key usage.

Server Factors
Everything done correctly, there still may be some server factors that may be causing the system to be slow. These are:

1. Hardware related
2. Server configuration related

Here is what you can do about the hardware:

1. The more RAM is on the system the better it is. MySQL frequently fetches data from the RAM and more the RAM is on the system, the better it is.

2. Buy the fastest possible RAM! A slower RAM is just irony.

3. Once you are settled with the RAM size and speed, look for processing speed. MySQL can use multiple processors.

Once you are satisfied with the hardware, there are a set of variables in “my.cnf” that you must look at:

a) key_buffer_size: This describes the memory available to store the index keys. The default is 8 MB but you can set it to 25% of the RAM.

b) query_cache_size: This value is by default 0. if you have a lot of repeating queries like in reporting applications etc, make sure you set this value high.

c) table_open_cache: This determines the number of table descriptors that MySQL will keep in the cache. The default value is 64. But, if you have 100 users accessing a table concurrently then this value should atleast be 100. You also have to take into considerations joins etc. Thus, this value should also be kept high.

I hope this article will take one step further in unlocking the mystery of slow servers and help solve some of the problems.

About Author:
Mukul Gupta is the CMO of Indus Net Technologies, an India based Internet Consulting firm which specializes in Opensource solutions. You can reach him at script@script2please.com or visit http://www.script2please.com

Hiding and Displaying the Mouse Cursor in Visual Basic

Pesky, isn't it? I hate that little cursor sometimes, and now I'm armed and ready to kill it. The scourge of mice everywhere, the bane of the arrow, it's the ShowCursor function!

Private Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long

This tutorial is not for the faint of heart, or the verbose... this promises to be quite short. There are only two things you need to know about this API call, how to hide the cursor, and how to show the cursor. Notice I said "hide" not destroy. The ability to click is still there, even though we remove the cursor, there is simply no longer a graphical representation.

To remove the cursor, pass 0 (that's a zero not the letter 'o') as the bShow argument. To replace the cursor, pass 1 as the bShow argument, that's it! Here's an example in case you're a slow learner :)
ShowCursor 0

That would remove the cursor! How quaint. Anyway, I have written a small program that toggles the cursor on and off, so download it if you're still confused.

About this Tutorial
This tutorial is from The Game Progamming Wiki which is published under the GNU Free Documentation License 1.2.

Simple Solution for Php Includes - IFrames

I have recently created my first Php program. I wanted to share with others some of the problems that I encountered, and how I finally overcame these obstacles.

My Reason for needing a Php Include
To start, my most recent website features a free classified advertising solution, a modified version of PhpBB stripped to function as an Article Bulletin Board (No replying), and a link directory. The business model of my Website offers free Classified Advertising, but charges a small fee for enhanced advertisements (Featured, Bolded, and Better Placement). The Classifieds were purchased from a developer, so I had little experience with the application. The link directory was a free resource of an old program that I modernized a bit. I choose the old link directory because the links are clean. They are not replaced with coding to count outbound traffic. I figured this would increase the value of links, to sites who exchanged links with me.

To increase revenue on the new site, I realized that I needed to increase the value of, “Featured Advertisements”. To do this I wanted to randomly rotate featured advertisements, from the classifieds, across my Bulletin Board and Link Directory. Bare in mind, all three are run from a unique table, and I wanted to leave it that way. In addition, I had little experience with the development for all three applications.

I started reading tutorials and utilizing Forums to create a Php program for external pages on the site. The program would pull a random featured ad from the classified table. This program only took me about 32 hours to create, while performing research. I didn't intend to get into the schematics of the program with this post, so forgive me if you are looking for a Random generator. But I would be more than happy to share my code upon request.

The code I created was simple, it worked just the way I wanted, but I ran into one cumbersome obstacle; how do I implement this easily across two unique table driven applications? The answer was to use a Php Include.

I started reading tutorials on, "Php includes and functions and classes". I realized quickly that this was a bit more confusing than creating the actual coding. In addition, I ran into parsing errors if I included the new coding in only one application.

My solution to using the, "Include ()," Php function.

I found that very few people were willing to provide any feedback for such a problem, even in the most resourceful forums for Php Coding and information resources. I fumbled with the coding for over 72 hours. I thought this was a bit ridiculous, as the code itself took less time to create.

I finally came across a helpful solution that may prove beneficial, if you are in the same situation with Php Includes. The code was uploaded onto my server as a file (something.php). I removed the standard, "Php Include ()," function from all links and the PhpBB coding. I then called the Php file (page) using an Iframe tag, on pages I wanted it to appear. This proved to be a successful replacement for the Php Include.

Search Engine Results Using Iframe for Php Include
I waited until Google came around to see how the Iframe affected my sites search rankings. Finally, the other day this happened. The conclusion, my search rankings still increased due to recent link exchanges. The code is working to my needs, and it is easily included on any page that I want, even externals outside my site can call on the code, which opens more doors for advancement.

Here is the simple Iframe code I used to replace the Php Include:

<iframe align=top valign=right width=600 height=105 marginwidth=0
marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no
src="http://your.com/file-to-include.php" width=600
height=105></iframe>
Using the Iframe tag for Php Include Conclusion
I have encountered no problems with including my PHP code on pages across external servers, using the iframe as a Php Include. As you can see, it is totally customizable. You can specify the width, height, alignment, border, scrolling, margins and more. The only obstacle that I have encountered, is the style sheet that the site, or page, with the, "Php Include," is not utilized. The page that the code is on seems to need its own unique style sheet.

I hope this proves beneficial to anyone having trouble with running a "Php Include" across various unique online applications.

About The Author
Michael J. Medeiros is the owner of http://www.mjmls.com/. He has worked as an Independent Real Estate Agent for three years, in New Jersey. He has an extensive background in Business and Marketing. Michael’s latest research and attention has been devoted to online business development and the Internet.

More Dockable Forms in Delphi

In this Delphi training guide we look further into Form Docking. In particular we look at the ManualFloat and ManualDock methods to dock and undock forms in code (rather than Drag & Dock).

Saturday, March 8, 2008

Dockable Forms in Delphi

This is an introduction to using Dockable Forms with Delphi. In it we create some multi-coloured forms and dock them into a TPageControl and a TPanel.

Thursday, March 6, 2008

Convert a String to Lower Case in Java

This tutorial will show you how to convert a string to lower case in Java. To convert a string to lower case, call the toLowerCase() method on the string.

Below is an example:

String original = "HELLO";

String lowerCase = original.toLowerCase();

Convert a String to Upper Case in Java

This tutorial will show you how to convert a string to upper case in Java. To convert a string to upper case, call the toUpperCase() method on the string.

Below is an example:

String original = "hello";

String upperCase = original.toUpperCase();

Get the List of Files in a Directory using Java

This tutorial shows how to get the list of files that are in a specific directory using Java. This tutorial will also show you how to filter the files to get only the files you are interested in.

To get the list of files, you need to create a File object for the directory. Next, you can call the listFiles() method on this File object to get the list of files contained in this directory.

File directory = new File("c:\\");
File[] files = directory.listFiles();

for (int index = 0; index < files.length; index++)
{
//Print out the name of files in the directory
System.out.println(files[index].toString());
}

If you don't want to get all the files in a directory, you can create a class that implements the FileFilter (java.io package) interface. The accept() method that you implement will specify the criteria to be used to determine if the file is returned. In our example below, the filter will only return files with "txt" for the extension.

class Filter implements FileFilter
{
public boolean accept(File file)
{
return file.getName().endsWith("txt");
}
}

To use apply this filter, pass an instance of it to the listFiles() method. Below is an example:

files.listFiles(new Filter());

Tuesday, March 4, 2008

Basic PHP Includes

Lets say you have a Web site with 10 or so pages, and you want to update the navigation. You don't want the hassle of updating every single page. That's where PHP includes come in handy.

Your basic include will look like this.

<?php include ( 'includes/navigation.php' ); ?>

That's it! What I typically do is design a page as usual, then begin breaking sections up into includes. To use this effectively:

1) Find sections or tables that will repeat throughout the site.
2) Cut the section of code out and paste it into another file.
3) Save this file into an includes folder.
4) Where the original section was, insert your PHP inclue code, referencing the file name.

Let's say I want to use the highlighted code on multiple pages.

<table>
<tbody>
<tr>
<td>
This table will be on every page.
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>
This is some other content.
</td>
</tr>
</tbody>
</table>
I'll include it like this.

<?php include ( 'includes/table.php' ); ?>
<table>
<tr>
<td>
This is some other content.
</td>
</tr>
</table>
Now if I change table.php later, it will change on every page automatically. It's just like using image tags, but instead of image files, you are including pieces of html. This can save you hours and hours.

About the Author
Alan Hettinger is a freelance designer available for print, web, and multimedia projects.

Array Variables in Perl

This tutorial walks through using array variables in Perl.

Simple Arrays
You’ve already seen simple arrays. We used them for the “command line” variables. Simple arrays begin with the “@” symbol. If you want a specific value from the array, you index that value using its number in the array. If you want the first item from the array, you ask for “$ARGV[0]”. If you want the third item, use “$ARGV[2]”.

Arrays always use the “@” symbol. Scalar variables always use the “$” symbol. A piece of an array is always a scalar. (You can’t have arrays inside of arrays in simple Perl.) That's why you use “@” to refer to the entire array, and “$” to refer to items within the array. If you want to know how many values are in an array, use the scalar variable $#ARRAY. This is actually the index of the last element, so for the count, you’ll need to add one. For example:

@Names = ("John","Jerry","Steve","Hsiao-Ping","Daniel");
$NameCount = $#Names+1;
print "There are $NameCount names in the array.\n";
foreach $Counter (0..$#Names) {
$HumanCounter = $Counter+1;
print "Name number $HumanCounter is $Names[$Counter].\n";
}
@Names = sort(@Names);
foreach $Name (@Names) {
print $Name;
if ($Name eq $Names[$#Names]) {
print ".\n";
} else {
print ", ";
}
}

The above program should produce the following:

/u5/jerry> arraytest
There are 5 names in the array.
Name number 1 is John.
Name number 2 is Jerry.
Name number 3 is Steve.
Name number 4 is Hsiao-Ping.
Name number 5 is Daniel.
Daniel, Hsiao-Ping, Jerry, John, Steve.

Can you spot a possible problem in the above program? You’d better, because fixing it is going to be an exercise!

Shifting Array Values
You will often shift array values when you are pulling command line options from a command line that can also include filenames. In general on Unix, when a command takes both options and filenames as arguments, the filenames come last. The ‘shift’ function allows you to slide the first element of the array out from under the rest of the elements. It completely removes that element from the array.

while ($ARGV[0] =~ /^-/) {
$currentArg = shift(@ARGV);
#figure out which option this is
#blah blah
}
#go ahead and do the rest on the filenames
while (<>) {
print;
}

Getting a Numeric Array
Suppose you want an array of numbers from 5 to 1000. You could construct it by hand, but Perl will make it for you. We‘ve already done it once with “foreach”:

@Counters = (5..1000);
This numeric construction always counts up by one. If you want to count down instead of up, you can reverse the array:
@Counters = reverse(@Counters);

or, you could combine it into one line with

@Counters = reverse(5..1000);

Sorting Arrays
You can sort arrays using simple or complex methods. The simplest way to sort an array is to use the sort function:

@Names = sort(@Names);

Sort always sorts in alphabetical order. If you want to sort in numerical order, you need to use the more complex version:

@Numbers = sort numerically @ARGV;
sub numerically {
return $a <=> $b;
}

In this case, we’re telling ‘sort’ to use the ‘subroutine’ numerically to determine how to sort the array. A ‘subroutine’ is a bit of code that can be reused without having to retype it. In this case, a sort subroutine is a special subroutine that has its arguments automatically put into $a or $b. The subroutine must return an integer. If this integer is less than zero, sort assumes that $a comes before $b. If this integer is greater than zero, sort assumes that $b comes before $a. If the integer is zero, sort assumes it doesn’t matter.

The operator ‘<=>‘ returns -1 if the item on the left is less than the item on the right, zero if they’re equal, and 1 if the item on the right is less than the item on the left. Go ahead and test it:

print $ARGV[0] <=> $ARGV[1];
print "\n";

You can do whatever you want in your subroutine, as long as it returns predictable integer values based on $a and $b.

The equivalent to ‘<=>‘ for strings is ‘cmp’. Go ahead and replace ‘<=>‘ above with ‘cmp’ and try different strings on the command line.

Other Array Functions

join(@array,$string)
returns the elements of array using string as a delimiter

pop(@array)
returns and removes the last element of array

push(@array,$string)
puts string onto the end of array. Does not return ‘array’.

shift(@array)
returns and removes the first element of array

split($string1,$string2)
returns string2 split into an array wherever string1 occurs

Associative Arrays
Associative arrays start tapping into the database functions of Perl. An associative array is a list of elements, but each element in the array is accessed by an index value that does not have to be a number.

$LastNames{'Jerry'} = 'Stratton';
$LastNames{'John'}='Paul';
$LastNames{'Steve'}='Spear';
print $LastNames{$ARGV[0]};
print "\n";
This array stores the values “Stratton”, “Paul”, and “Spear”. In order to access those values, I need to know the value they’re associated with:
20: lastname Jerry
Stratton
21: lastname Steve
Spear

You’ll use the “delete” function to delete an element of an associative array:

$deletedName = delete $LastNames{'Steve'};

If you need to get a list of all the keys in an associative array, use the keys function:

@FirstNames = keys(%LastNames);
foreach $key (@FirstNames) {
print "$key: $LastNames{$key}\n";
}

Like scalar variables and simple arrays, associative arrays have their own prefix, the “percent” sign. Like simple arrays, you’ll only use the percent sign when referring to the associative array as a whole. When referring to individual elements, you’ll continue to use the dollar sign.

Let’s take a look at a simple program for viewing the passwd file in Unix:

$PASSWDFILE = '/var/yp/passwd';
open PASSWDFILE;
while (<PASSWDFILE>) {
@lineItems = split(':');
$username = $lineItems[0];
$passwords{$username} = $lineItems[1];
$userids{$username} = $lineItems[2];
$groupids{$username}=$lineItems[3];
$names{$username}=$lineItems[4];
$homes{$username}=$lineItems[5];
$shells{$username}=$lineItems[6];
}
close PASSWDFILE;
foreach $User (@ARGV) {
$User = lc($User);
print uc($User);
print ":\n";
print "\tPassword: $passwords{$User}\n";
print "\tUser ID: $userids{$User}\n";
print "\tGroup ID: $groupids{$User}\n";
print "\tReal Name: $names{$User}\n";
print "\tHome Directory: $homes{$User}\n";
print "\tDefault Shell: $shells{$User}\n";
print "\n";
}

This script uses usernames as the ‘key’ for this associative array. It could just as well have used user id. The key has to be something that will be unique for each ‘record’.

Note that in the ‘split” line, we’ve left out the $_. Perl will often assume that that’s what you meant, and in this case it works just fine.We’ve also explicitly opened a file here for the first time. We’ll have more on that later, but we put the filename into a scalar variable, and made sure that scalar variable was in all capitals. This allowed us to use the simple form for opening the filename contained in that variable. And don’t forget that we closed it at the end! If you look at the ‘while’, you’ll see that it looks pretty much the same as when we used the <STDIN> filehandle.

About this Tutorial
This tutorial is written by Jerry Stratton and is published under the GNU Free Documentation License.

Sunday, March 2, 2008

Displaying a TIFF in a Web Page

This tutorial will show you how to display a TIFF in a web page. Web browsers can display standard image formats such as GIF, JPG, and PNG files. Unfoturnately, web browsers won't display TIFF images.

Luckily for us, we have a secret weapon called QuickTime. Beyond having the ability to play QuickTime movies, QuickTime also supports a number of image formats including TIFF, Photoshop (PSD), PICT, Targa, and more. Visit the QuickTime Tech Specs page for a complete list of supported files.

Apple's QuickTime player is available for both Windows and Mac. Foturnately, QuickTime is installed on most computers. If the plugin isn't installed on the computer, we can take advantage of the auto install feature.

Below is a sample embed tag that will load the sample TIFF image (car.tif):

<OBJECT CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" WIDTH="100%" HEIGHT="100%"
CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
<PARAM name="SRC" VALUE="car.tif">
<PARAM name="SCALE" VALUE="aspect">
</OBJECT>

The WIDTH and HEIGHT of the QuickTime plugin is set to 100%. This will make the plugin the same size as the web page in the browser.

The SRC attribute specifies the file to load. In our example, the file is in the same directory as the html file. If the file is in a different directory, specify the complete URL.

The SCALE parameter will specify how to scale the image. In our example, we set it to "aspect". This will maintain the aspect ratio. If you specify "1", the image will displayed in it original size.

NOTE: Because of the "Click to Activate" issue with Active X controls (ie QuickTime plugin), the image will not load until the plugin is clicked on. There is a solution for this problem. In short, the <OBJECT/> tags must be written in an external JavaScript file. Our example files below take care of this problem. To understand more about this issue, visit Apple's tutorial "Including QuickTime In A Web Page".

Demo:
Click to View Demo
Download Files (Right Click - Save Target As):

Resources:

Saturday, March 1, 2008

Convert a String to Number in Java

This tutorial will show you how to convert a string to different number types. Each number type in Java has a parse method that allows you convert a string into the primitive type.

When converting a string to a number, the parse method may throw a NumberFormatException if the string is null or an invalid representation for that type.

Convert a String to an int
To convert a String to an int, call the static method parseInt() on the Integer class. Below is an example:

String string = "123";
int value = Integer.parseInt(string);
Convert a String to a long
To convert a String to a long, call the static method parseLong() on the Long class. Below is an example:
String string = "123";
long value = Long.parseLong(string);

Convert a String to a float
To convert a String to a float, call the static method parseFloat() on the Float class. Below is an example:
String string = "123.4";
float value = Float.parseFloat(string);

Convert a String to a double
To convert a String to a double, call the static method parseDouble() on the Double class. Below is an example:
String string = "123.4";
double value = Double.parseDouble(string);

Split a String into Words in Java

This tutorial shows how to split a string into multiple words.

In Java 1.4, Sun added a split() method to the String class. The split method allows you to specify a regular expression that is used to split the string into a string array. To split a string where there words are separated by a space, simply specify a space (" ") as the parameter to the split() method.

The following code example shows how to split a sentence into words:

String sentence = "This is a sentence.";
String[] words = sentence.split(" ");

for (String word : words)
{
System.out.println(word);
}
Below is output from the example code:
This
is
a
sentence.

Convert a BMP to a PNG in Java

This tutorial shows how to use the ImageIO API to convert a BMP to a PNG image in Java. The ImageIO API provides methods to read the source image and to write the image in the new file format.

To read the image, simply provide the ImageIO.read() method a File object for the source image. This will return a BufferedImage.

//Create file for the source
File input = new File("c:/temp/image.bmp");

//Read the file to a BufferedImage
BufferedImage image = ImageIO.read(input);

Once you have the BufferedImage, you can write the image as a PNG. You will need to create a File object for the destination image. When calling the write() method, specify the type string as "png".

//Create a file for the output
File output = new File("c:/temp/image.png");

//Write the image to the destination as a PNG
ImageIO.write(image, "png", output);

Convert a BMP to a JPG in Java

This tutorial shows how to use the ImageIO API to convert a BMP to a JPG image in Java. The ImageIO API provides methods to read the source image and to write the image in the new file format.

To read the image, simply provide the ImageIO.read() method a File object for the source image. This will return a BufferedImage.

//Create file for the source
File input = new File("c:/temp/image.bmp");

//Read the file to a BufferedImage
BufferedImage image = ImageIO.read(input);

Once you have the BufferedImage, you can write the image as a JPG. You will need to create a File object for the destination image. When calling the write() method, specify the type string as "jpg".

//Create a file for the output
File output = new File("c:/temp/image.jpg");

//Write the image to the destination as a JPG
ImageIO.write(image, "jpg", output);

Convert a PNG to a BMP in Java

This tutorial shows how to use the ImageIO API to convert a PNG to a BMP image in Java. The ImageIO API provides methods to read the source image and to write the image in the new file format.

To read the image, simply provide the ImageIO.read() method a File object for the source image. This will return a BufferedImage.

//Create file for the source
File input = new File("c:/temp/image.png");

//Read the file to a BufferedImage
BufferedImage image = ImageIO.read(input);

Once you have the BufferedImage, you can write the image as a BMP. You will need to create a File object for the destination image. When calling the write() method, specify the type string as "bmp".

//Create a file for the output
File output = new File("c:/temp/image.bmp");

//Write the image to the destination as a BMP
ImageIO.write(image, "bmp", output);