Archive for the 'Java' Category

CHAPTER 10 BATTERIES (Make web site) INCLUDED 237 SPECIAL CHARACTERS

Tuesday, June 10th, 2008

CHAPTER 10 BATTERIES INCLUDED 237 SPECIAL CHARACTERS IN CHARACTER SETS In general, special characters such as dots, asterisks, and question marks have to be escaped with a backslash if you want them to appear as literal characters in the pattern, rather than function as regexp operators. Inside character sets, escaping these characters is generally not necessary (although perfectly legal). You should, however, keep in mind the following rules: You do have to escape the caret (^) if it appears at the beginning of the character set unless you want it to function as a negation operator. (In other words, don t place it at the beginning unless you mean it.) Similarly, the right bracket (]) and the dash (-) must be put either at the beginning of the character set or escaped with a backslash. (Actually, the dash may also be put at the end, if you wish.) Alternatives and Subpatterns Character sets are nice when you let each letter vary independently, but what if you want to match only the strings ‘python’ and ‘perl’? You can t specify such a specific pattern with character sets or wildcards. Instead, you use the special character for alternatives: the pipe character (|). So, your pattern would be ‘python|perl’. However, sometimes you don t want to use the choice operator on the entire pattern just a part of it. To do that, you enclose the part, or subpattern, in parentheses. The previous example could be rewritten as ‘p(ython|erl)’. (Note that the term subpattern can also be used about a single character.) Optional and Repeated Subpatterns By adding a question mark after a subpattern, you make it optional. It may appear in the matched string, but it isn t strictly required. So, for example, the (slightly unreadable) pattern r’(http://)?(www.)?python.org’ would match all of the following strings (and nothing else): ‘http://www.python.org’ ‘http://python.org’ ‘www.python.org’ ‘python.org’ A few things are worth noting here: I ve escaped the dots, to prevent them from functioning as wildcards. I ve used a raw string to reduce the number of backslashes needed. Each optional subpattern is enclosed in parentheses. The optional subpatterns may appear or not, independently of each other.
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

236 CHAPTER 10 (Web site traffic) BATTERIES INCLUDED The Wildcard

Monday, June 9th, 2008

236 CHAPTER 10 BATTERIES INCLUDED The Wildcard A regexp can match more than one string, and you create such a pattern by using some special characters. For example, the period character (dot) matches any character (except a newline), so the regular expression ‘.ython’ would match both the string ‘python’ and the string ‘jython’. It would also match strings such as ‘qython’, ‘+ython’, or ‘ ython’(in which the first letter is a single space), but not strings such as ‘cpython’or ‘ython’ because the period matches a single letter, and neither two nor zero. Because it matches anything (any single character except a newline), the period is called a wildcard. Escaping Special Characters When you use special characters such as this, it s important to know that you may run into problems if you try to use them as normal characters. For example, imagine you want to match the string ‘python.org’. Do you simply use the pattern ‘python.org’? You could, but that would also match ‘pythonzorg’, for example, which you probably wouldn t want. (The dot matches any character except newline, remember?) To make a special character behave like a normal one, you escape it, just as I demonstrated how to escape quotes in strings in Chapter 1. You place a backslash in front of it. Thus, in this example, you would use ‘python\.org’, which would match ‘python.org’, and nothing else. Note To get a single backslash, which is required here by the re module, you need to write two back- slashes in the string to escape it from the interpreter. Thus you have two levels of escaping here: (1) from the interpreter, and (2) from the re module. (Actually, in some cases you can get away with using a single backslash and have the interpreter escape it for you automatically, but don t rely on it.) If you are tired of doubling up backslashes, use a raw string, such as r’python.org’. Character Sets Matching any character can be useful, but sometimes you want more control. You can create a so-called character set by enclosing a substring in brackets. Such a character set will match any of the characters it contains, so ‘[pj]ython’ would match both ‘python’and ‘jython’, but nothing else. You can also use ranges, such as ‘[a-z]’ to match any character from a to z (alphabetically), and you can combine such ranges by putting one after another, such as ‘[a-zA-Z0-9]’ to match uppercase and lowercase letters and digits. (Note that the character set will match only one such character, though.) To invert the character set, put the character ^ first, as in ‘[^abc]’ to match any character except a, b, or c.
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

CHAPTER 10 BATTERIES (Make web site) INCLUDED 235 This interaction

Sunday, June 8th, 2008

CHAPTER 10 BATTERIES INCLUDED 235 This interaction isn t terribly interesting. I could have done exactly the same thing with an ordinary dictionary instead of the shelf object. But now that I ve quit the program, let s see what happens when I restart it perhaps the following day? Enter command (? for help): lookup Enter ID number: 001 What would you like to know? (name, age, phone) name Name: Mr. Gumby Enter command (? for help): quit As you can see, the program reads in the file I created the first time, and Mr. Gumby is still there! Feel free to experiment with this program, and see if you can extend its functionality and improve its user-friendliness. Perhaps you can think of a version that you have use for yourself? How about a database of your record collection? Or a database to help you keep track of which friends have borrowed which of your books? (I know I could use that last one.) re Some people, when confronted with a problem, think I know, I ll use regular expressions. Now they have two problems. Jamie Zawinski The re module contains support for regular expressions. If you ve heard about regular expressions before, you probably know how powerful they are; if you haven t, prepare to be amazed. You should note, however, that mastering regular expressions may be a bit tricky at first. (Okay, very tricky, actually.) The key is to learn about them a little bit at a time just look up (in the documentation) the parts you need for a specific task. There is no point in memorizing it all up front. This section describes the main features of the re module and regular expressions, and enables you to get started. Tip In addition to the standard documentation, Andrew Kuchling s Regular Expression HOWTO (http://amk.ca/python/howto/regex/) is a useful source of information on regular expressions in Python. What Is a Regular Expression? A regular expression (also called a regex or regexp) is a pattern that can match a piece of text. The simplest form of regular expression is just a plain string, which matches itself. In other words, the regular expression ‘python’ matches the string ‘python’. You can use this matching behavior for such things as searching for patterns in a text, for replacing certain patterns with some computed values, or for splitting a text into pieces.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

234 CHAPTER 10 (Web server setup) BATTERIES INCLUDED Caution As

Saturday, June 7th, 2008

234 CHAPTER 10 BATTERIES INCLUDED Caution As you can see, the program specifies the file name C:database.dat. If you, by any chance, have a database by that name that the shelve module can use, it will and that database will be modified. So make sure that you use a file name for your database that isn t in use already. After running this program, the proper file appears. The program shown in Listing 10-8 has several interesting features: I have wrapped everything in functions to make the program more structured. (A possible improvement is to group those functions as the methods of a class.) I have put the main program in the main function, which is called only if __name__ == ‘__main__’. That means you can import this as a module and then call the main function from another program. I open a database (shelf) in the main function, and then pass it as a parameter to the other functions that need it. I could have used a global variable, too, because this program is so small, but it s better to avoid global variables in most cases, unless you have a reason to use them. After reading in some values, I make a modified version by calling strip and lower on them because if a supplied key is to match one stored in the database, the two must be exactly alike. If you always use strip and loweron what the user enters, you can allow him or her to be sloppy about using uppercase or lowercase letters and additional whitespace. Also, note that I ve used capitalize when printing the field name. I have used try and finally to ensure that the database is closed properly. You never know when something might go wrong (and you get an exception), and if the program terminates without closing the database properly, you may end up with a corrupt database file that is essentially useless. By using try and finally, you avoid that. So, let s take this database out for a spin. Here is the interaction between the program and me: Enter command (? for help): ? The available commands are: store : Stores information about a person lookup : Looks up a person from ID number quit : Save changes and exit ? : Prints this message Enter command (? for help): store Enter unique ID number: 001 Enter name: Mr. Gumby Enter age: 42 Enter phone number: 555-1234 Enter command (? for help): lookup Enter ID number: 001 What would you like to know? (name, age, phone) phone Phone: 555-1234 Enter command (? for help): quit
Check Tomcat Web Hosting services for best quality webspace to host your web application.

CHAPTER 10 BATTERIES INCLUDED 233 pid =

Friday, June 6th, 2008

CHAPTER 10 BATTERIES INCLUDED 233 pid = raw_input(’Enter unique ID number: ‘) person = {} person[’name’] = raw_input(’Enter name: ‘) person[’age’] = raw_input(’Enter age: ‘) person[’phone’] = raw_input(’Enter phone number: ‘) db[pid] = person def lookup_person(db): “”" Query user for ID and desired field, and fetch the corresponding data from the shelf object “”" pid = raw_input(’Enter ID number: ‘) field = raw_input(’What would you like to know? (name, age, phone) ‘) field = field.strip().lower() print field.capitalize() + ‘:’, db[pid][field] def print_help(): print ‘The available commands are:’ print ’store : Stores information about a person’ print ‘lookup : Looks up a person from ID number’ print ‘quit : Save changes and exit’ print ‘? : Prints this message’ def enter_command(): cmd = raw_input(’Enter command (? for help): ‘) cmd = cmd.strip().lower() return cmd def main(): database = shelve.open(’C:\database.dat’) try: while True: cmd = enter_command() if cmd == ’store’: store_person(database) elif cmd == ‘lookup’: lookup_person(database) elif cmd == ‘?’: print_help() elif cmd == ‘quit’: return finally: database.close() if __name__ == ‘__main__’: main()
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

232 CHAPTER 10 BATTERIES INCLUDED >>> import (Web design company)

Thursday, June 5th, 2008

232 CHAPTER 10 BATTERIES INCLUDED >>> import shelve >>> s = shelve.open(’test.dat’) >>> s[’x'] = [’a', ‘b’, ‘c’] >>> s[’x'].append(’d') >>> s[’x'] [’a', ‘b’, ‘c’] Where did the ‘d’ go? The explanation is simple: When you look up an element in a shelf object, the object is reconstructed from its stored version; and when you assign an element to a key, it is stored. What happened in the preceding example was the following: 1. The list [’a', ‘b’, ‘c’] was stored in s under the key ‘x’. 2. The stored representation was retrieved, a new list was constructed from it, and ‘d’was appended to the copy. This modified version was not stored! 3. Finally, the original is retrieved again without the ‘d’. To correctly modify an object that is stored using the shelve module, you must bind a temporary variable to the retrieved copy, and then store the copy again after it has been modified: >>> temp = s[’x'] >>> temp.append(’d') >>> s[’x'] = temp >>> s[’x'] [’a', ‘b’, ‘c’, ‘d’] Thanks to Luther Blissett for pointing this out. From Python 2.4 onward, there is another way around this problem: Setting the writeback parameter of the open function to true. If you do, all of the data structures that you read from or assign to the shelf will be kept around in memory (cached) and only written back to disk when you close the shelf. If you re not working with huge data, and you don t want to worry about these things, setting writeback to true (and making sure you close your shelf at the end) may be a good idea. Example Listing 10-8 shows a simple database application that uses the shelve module. Listing 10-8. A Simple Database Application # database.py import sys, shelve def store_person(db): “”" Query user for data and store it in the shelf object “”"
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

CHAPTER 10 (Affordable web design) BATTERIES INCLUDED 231 >>> from

Wednesday, June 4th, 2008

CHAPTER 10 BATTERIES INCLUDED 231 >>> from random import shuffle >>> shuffle(deck) >>> pprint(deck[:12]) [’3 of spades’, ‘2 of diamonds’, ‘5 of diamonds’, ‘6 of spades’, ‘8 of diamonds’, ‘1 of clubs’, ‘5 of hearts’, ‘Queen of diamonds’, ‘Queen of hearts’, ‘King of hearts’, ‘Jack of diamonds’, ‘Queen of clubs’] Note that I ve just printed the 12 first cards here, to save some space. Feel free to take a look at the whole deck yourself. Finally, to get Python to deal you a card each time you press Enter on your keyboard, until there are no more cards, you simply create a little while loop. Assuming that you put the code needed to create the deck into a program file, you could simply add the following at the end: while deck: raw_input(deck.pop()) Note If you try the while loop shown here in the interactive interpreter, you ll notice that an empty string gets printed out every time you press Enter because raw_input returns what you write (which is nothing), and that will get printed. In a normal program, this return value from raw_input is simply ignored. To have it ignored interactively, too, just assign the result of raw_input to some variable you won t look at again and name it something like ignore. shelve In the next chapter, you learn how to store data in files, but if you want a really simple storage solution, the shelve module can do most of the work for you. All you have to do is supply it with a file name. The only function of interest in shelve is open. When called (with a file name) it returns a Shelf object, which you can use to store things. Just treat it as a normal dictionary (except that the keys must be strings), and when you re done (and want things saved to disk) you call its close method. A Potential Trap It is important to realize that the object returned by shelve.openis not an ordinary mapping, as the following example demonstrates:
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

230 CHAPTER (Unlimited web hosting) 10 BATTERIES INCLUDED If you

Tuesday, June 3rd, 2008

230 CHAPTER 10 BATTERIES INCLUDED If you put this in a script file and run it, you get an interaction something like the following: How many dice? 3 How many sides per die? 6 The result is 10 Creating a fortune cookie program. Assume that you have made a text file in which each line of text contains a fortune. Then you can use the fileinput module described earlier to put the fortunes in a list, and then select one randomly: # fortune.py import fileinput, random fortunes = list(fileinput.input()) print random.choice(fortunes) In UNIX, you could test this on the standard dictionary file /usr/dict/words to get a random word: $ python fortune.py /usr/dict/words dodge Creating an electronic deck of cards. You want your program to deal you cards, one at a time, each time you press Enter on your keyboard. Also, you want to make sure that you don t get the same card more than once. First, you make a deck of cards a list of strings: >>> values = range(1, 11) + ‘Jack Queen King’.split() >>> suits = ‘diamonds clubs hearts spades’.split() >>> deck = [’%s of %s’ % (v, s) for v in values for s in suits] The deck you just created isn t very suitable for a game of cards. Let s just peek at some of the cards: >>> from pprint import pprint >>> pprint(deck[:12]) [’1 of diamonds’, ‘1 of clubs’, ‘1 of hearts’, ‘1 of spades’, ‘2 of diamonds’, ‘2 of clubs’, ‘2 of hearts’, ‘2 of spades’, ‘3 of diamonds’, ‘3 of clubs’, ‘3 of hearts’, ‘3 of spades’] A bit too ordered, isn t it? That s easy to fix:
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

CHAPTER 10 (Web design conference) BATTERIES INCLUDED 229 random number

Monday, June 2nd, 2008

CHAPTER 10 BATTERIES INCLUDED 229 random number in the range from 1 to 10 (inclusive), you would use randrange(1,11) (or, alternatively, randrange(10)+1), and if you want a random odd positive integer lower than 20, you would use randrange(1,20,2). The function random.choice chooses (uniformly) a random element from a given sequence. The function random.shuffleshuffles the elements of a (mutable) sequence randomly, such that every possible ordering is equally likely. The function random.sample chooses (uniformly) a given number of elements from a given sequence, making sure that they re all different. Note For the statistically inclined, there are other functions similar to uniformthat return random numbers sampled according to various other distributions, such as betavariate, exponential, Gaussian, and several others. Examples Generating a random date in a given range. In the following examples, I use several of the functions from the time module described previously. First, let s get the real numbers representing the limits of the time interval (the year 2005). You do that by expressing the date as a time tuple (using -1 for day of the week, day of the year, and daylight savings, making Python calculate that for itself) and calling mktime on these tuples: from random import * from time import * date1 = (2005, 1, 1, 0, 0, 0, -1, -1, -1) time1 = mktime(date1) date2 = (2006, 1, 1, 0, 0, 0, -1, -1, -1) time2 = mktime(date2) Then you generate a random number uniformly in this range (the upper limit excluded): >>> random_time = uniform(time1, time2) Then, you simply convert this number back to a legible date: >>> print asctime(localtime(random_time)) Mon Jun 24 21:35:19 2005 Creating an electronic die-throwing machine. For this example, let s ask the user how many dice to throw, and how many sides each one should have. The die-throwing mechanism is implemented with randrange and a for loop: from random import randrange num = input(’How many dice? ‘) sides = input(’How many sides per die? ‘) sum = 0 for i in range(num): sum += randrange(sides) + 1 print ‘The result is’, sum
From our experience, we can recommend PHP Web Hosting services, if you need affordable webhost to host and run your web application.

228 CHAPTER 10 BATTERIES INCLUDED random The (Web design rates)

Sunday, June 1st, 2008

228 CHAPTER 10 BATTERIES INCLUDED random The random module contains functions that return random numbers, which can be useful for simulations or any program that generates random output. Note Actually, the numbers generated are pseudo-random. That means that while they appear completely random, there is a predictable system that underlies them. However, because the module is so good at pretending to be random, you probably won t ever have to worry about this (unless you want to use these numbers for strong-cryptography purposes, in which case they may not be strong enough to withstand determined attack but if you re into strong cryptography, you surely don t need me to explain such elementary issues). If you need real randomness, you should check out the urandomfunction of the os module. The class SystemRandom in the random module is based on the same kind of functionality, and gives you data that is close to real randomness. Some important functions in this module are shown in Table 10-7. Table 10-7. Some Important Functions in the random Module Function Description random() Returns a random real number n such that 0 =n < 1 getrandbits(n) Returns n random bits, in the form of a long integer uniform(a, b) Returns a random real number n such that a =n < b randrange([start], stop, [step]) Returns a random number from range(start, stop, step) choice(seq) Returns a random element from the sequence seq shuffle(seq[, random]) Shuffles the sequence seq in place sample(seq, n) Chooses n random, unique elements from the sequence seq The function random.randomis one of the most basic random functions; it simply returns a pseudo-random number n such that 0 < n < 1. Unless this is exactly what you need, you should probably use one of the other functions, which offer extra functionality. The function random.getrandbits returns a given number of bits (binary digits), in the form of a long integer. This is probably mostly useful if you re really into random stuff (for example, working with cryptography). The function random.uniform, when supplied with two numerical parameters a and b, returns a random (uniformly distributed) real number n such that a < n < b. So, for example, if you want a random angle, you could use uniform(0,360). The function random.randrange is the standard function for generating a random integer in the range you would get by calling rangewith the same arguments. For example, to get a
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.