Working with DBM Persistent Dictionaries

A persistent dictionary acts exactly like you'd expect. You can store name value pairs in the dictionary, which are saved to a disk, and so their data will endure between various times that your program is run. So if you save data to a dictionary that's backed by a dbm, the next time you start your program you can read the value stored under a given key again, once you've loaded the dbm file. These dictionaries work like normal Python dictionaries, which are covered in Chapter 3. The main...

The Netbeans Python Debugger

As mentioned previously, the Netbeans IDE also includes a Python debugger that is derived from JeanYves Mengant's jpydbg debugger. This section will discuss how to make use of the Netbeans Python debugger along with some examples using our HockeyRoster code that was written in the previous section. If you have used a debugger in another IDE, or perhaps the Java debugger that is available for Netbeans, this debugger will feel quite familiar. The Python debugger includes many features such as...

Using the Clipboard

PyQt provides clipboard support for text in QTextEdit, QLineEdit, QTableWidget, and the other widgets where textual data can be edited. PyQt's clipboard and drag-and-drop systems use data in MIME Multipurpose Internet Mail Extensions format, a format that can be used to store any arbitrary data. Occasionally, it is convenient to pass data to the clipboard or retrieve data from the clipboard directly in code. PyQt makes this easy. The QApplication class provides a static method that returns a...

Division Classic Floor and True

You've seen how division works in the previous sections, so you should know that it behaves slightly differently in Python 3.0 and 2.6. In fact, there are actually three flavors of division, and two different division operators, one of which changes in 3.0 Classic and true division. In Python 2.6 and earlier, this operator performs classic division, truncating results for integers and keeping remainders for floating-point numbers. In Python 3.0, it performs true division, always keeping...

What are some different frame styles

The wx.Frame class has a multitude of possible style flags. Typically, the default style is what you want, but there are several useful variations. The first set of style flags that we'll discuss governs the general shape and size of the frame. Although not strictly enforced, these flags should be considered mutually exclusive a given frame should only use one of them. Using a style flag from this group does not imply the existence of any decorators described in the other tables in this section...

Installing on Linux and Unix

If you are running Kubuntu 7.04 Fiesty Fawn and later , you already have PyQt4 installed So, you only need to install the book's examples see page 573 , and the documentation packages python-doc and python-qt4-doc. If mkpyqt.py does not work, you will have to edit the mkpyqt.py file and at least hard-code the path to pyuic4. For Linux and most other Unixes that don't have PyQt4 preinstalled, there are four tools to install the Qt C application development framework, the Python interpreter and...

Tab Widgets and Stacked Widgets

Some dialogs require so many widgets to present all the options that they make available that they become difficult for the user to understand. The most obvious way to deal with this is to create two or more dialogs and to divide the options between them. This is a good approach when it is possible since it minimizes the demands made on the user, and may also be easier from a maintenance point of view than a single complex dialog. But often we need to use a single dialog because the options we...

How can I use a font picker

The font picker dialog in wxPython is different than the file dialog, because it uses a separate helper class to manage the information it presents. Figure 9.8 displays the MS Windows version of the font dialog. Listing 9.8 displays the code used to generate figure 9.8, and should look somewhat different than previous dialog examples. Listing 9.8 Sample code for a font picker dialog box if __name__ __main__ app wx.PySimpleApp dialog wx.FontDialog None, wx.FontData if dialog.ShowModal wx.ID_OK...

Working with the support modules

The support modules provide basic functionality for the end-user programs, and can also be imported into your own programs. These modules are essentially the building blocks used to create the user-level Py programs. Table 4.4 displays a listing of the support modules that are part of the Py package, along with a brief description. Contains GUI elements unique to the PyCrust application program Provides global signal dispatching services The document module contains a very simple Document...

How do I create a multiline or styled text control

You can create a multi-line text control using the wx.te_multiline style flag. If the native widget has support for styles, you can change font and color styles within the text managed by the control, which is sometimes called rich text. For other platforms, the calls to set styles are simply ignored. Figure 7.3 displays an example of multi-line text controls. Listing 7.3 contains the code used to create figure 7.3. Typically, creating a multi-line control is handled by setting the...

Enabling and Disabling Actions

Sometimes particular actions are applicable only in certain circumstances. For example, it doesn't make much sense to allow file save on a document with no unsaved changes, or, arguably, to allow file save as on an empty document. Similarly, neither edit copy nor edit cut makes sense if there is no selected text. One way to deal with this is to leave all the actions enabled all the time, but to make sure that they do nothing in cases where they don't make sense for example, if we call...

Command Line Options

It is possible to skip the GUI and start web2py directly from the command line by typing something like 1 python web2py.py -a 'your password' -i 127.0.0.1 -p 8000 When web2py starts, it creates a file called parameters_8000.py where it stores the hashed password. If you use lt ask gt as the password, web2py prompts you for it. For additional security, you can start web2py with 1 python web2py.py -a ' lt recycle gt ' -i 127.0.0.1 -p 8000 In this case web2py reuses the previously stored hashed...

Building the Brains

Game Pygame

Each ant is going to have four states in its state machine, which should be enough to simulate ant-like behavior. The first step in defining the state machine is to work out what each state should do, which are the actions for the state see Table 7-1 . Table 7-1. Actions for the Ant States Table 7-1. Actions for the Ant States Walk toward a random point in the world. We also need to define the links that connect states together. These take the form of a condition and the name of the state to...

Additional Display Flags

There are a few more flags you can use in a call to set_mode. I consider them advanced, because they can hurt performance if used incorrectly or cause compatibility problems on some platforms. It is usually best to use the value 0 for windowed displays and FULLSCREEN for full-screen displays to ensure your game will work well on all platforms. That said, if you know what you are doing you can set a few advanced flags for extra performance. There is also no harm in experimenting (it won't hurt...

Slicing Strings

In addition to extracting individual characters in a string, you can pick out groups of characters by slicing strings. Slicing works a lot like indexing, but you use two offsets separated by a colon ( ) character. The first offset is where Python should start slicing from the second offset is where it should stop slicing. Again, think of the offsets as the spaces between the characters, not as the characters themselves. > > > my_string 5 10 'sashi' The first line tells Python to slice...

Graphics Module Reference

The examples in this chapter have touched on most of the elements in the graphics module. This section provides a complete reference to the objects and functions provided in the graphics library. Experienced programmers use these sorts of guides to learn about new libraries. You will probably want to refer back to this section often when you are writing your own graphical programs. A GraphWin object represents a window on the screen where graphical images may be drawn. A program may define any...

Managed Objects

Unlike threads, processes do not support shared objects. Although you can create shared values and arrays as shown in the previous section, this doesn't work for more advanced Python objects such as dictionaries, lists, or instances of user-defined classes.The multiprocessing module does, however, provide a way to work with shared objects if they run under the control of a so-called manager.A manager is a separate subprocess where the real objects exist and which operates as a server. Other...

Restart Shell

Restarting the Shell deletes all variables, clears out all function definitions, and unloads all modules that are not automatically loaded at runtime. In addition, all memory is cleared, all breakpoints are reset, and all data in the Edit window is erased. Restarting the Shell can be very useful for a number of reasons, including not being sure what variables have been set or what functions have been modified. Restarting the Shell is much akin to shutting down the Python IDLE editor and then...

IMAPs Unique Message IDs

Complaints about imaplib's user-friendliness aside, you might have problems writing IMAP scripts if you assume that the message numbers don't change over time. If another IMAP client deletes messages from a mailbox while this script is running against it (suppose you have your mail client running, and you use it to delete some spam while this script is running), the message numbers will be out of sync from that point on. The IMAP-based SubjectLister class minimizes this risk by getting the...

Using the Matrix Class

The Game Objects library contains a class named Matrix44 that we can use with Pygame. Let's experiment with it in the interactive interpreter. The following code shows how you would import Matrix44 and start using it gt gt gt from gameobjects.matrix44 import gt gt gt identity Matrix44 gt gt gt print identity The first line imports the Matrix44 class from the gameobjects.matrix44 module. The second line creates a Matrix44 object, which defaults to the identity matrix, and names it identity. The...

OOP Is About Code Reuse

And that, along with a few syntax details, is most of the OOP story in Python. Of course, there's a bit more to it than just inheritance. For example, operator overloading is much more general than I've described so far classes may also provide their own implementations of operations such as indexing, fetching attributes, printing, and more. By and large, though, OOP is about looking up attributes in trees. So why would we be interested in building and searching trees of objects Although it...

Name Mangling Overview

Here's how name mangling works names inside a class statement that start with two underscores but don't end with two underscores are automatically expanded to include the name of the enclosing class. For instance, a name like_X within a class named Spam is changed to _Spam_X automatically the original name is prefixed with a single underscore and the enclosing class's name. Because the modified name contains the name of the enclosing class, it's somewhat unique it won't clash with similar names...

Creating a Main Window

Structure Python Pyqt Program

For most main-window-style applications, the creation of the main window follows a similar pattern. We begin by creating and initializing some data structures, then we create a central widget which will occupy the main window's central area, and then we create and set up any dock windows. Next, we create actions and insert them into menus and toolbars. It is quite common to also read in the application's settings, and for applications that restore the Figure 6.2 The Image Changer's modules,...

Canvas rectangle objects

Each rectangle is specified as two points x0, y0 is the top left corner, and x1, y1 is the location of the pixel just outside of the bottom right corner. For example, the rectangle specified by top left corner 100,100 and bottom right corner 102,102 is a square two pixels by two pixels, including pixel 101,101 but not including 102,102 . The outline lies inside the rectangle on its top and left sides, but outside the rectangle on its bottom and right side. The default appearance is a...

Canvas text objects

You can display one or more lines of text on a canvas C by creating a text object id C.create_text ( x, y, option, ) This returns the object ID of the text object on canvas C. Options include This returns the object ID of the text object on canvas C. Options include The text color to be used when the text is active, that is, when the mouse is over it. For option values, see fill below. The stipple pattern to be used when the text is active. For option values, see stipple below. The default is...

Matching stipple patterns

This may seem like an incredibly picky style point, but if you draw a graphic that has two objects with stippled patterns, a real professional will make sure that the patterns align along their boundary. Here is an example. The left-hand screen shot shows two adjacent 100x100 squares stippled with the gray12 pattern, but the right-hand square is offset vertically by one pixel. The short black line in the center of the figure is drawn along the boundary of the two figures. The second screen shot...

Naming conventions

The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent. Nevertheless, here are the currently recommended naming standards. New modules and packages (including third-party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred. Descriptive naming styles There are many different naming styles. It helps to be able to recognize what naming style is being used,...

Escape Sequences Represent Special Bytes

The last example embedded a quote inside a string by preceding it with a backslash. This is representative of a general pattern in strings backslashes are used to introduce special byte codings known as escape sequences. Escape sequences let us embed byte codes in strings that cannot easily be typed on a keyboard. The character , and one or more characters following it in the string literal, are replaced with a single character in the resulting string object, which has the binary value...

What Is a Predicate

A term you can see often in discussions about programming is predicate it just means a function (or other callable object) that returns TRue or False as its result. A predicate is said to be satisfied when it returns true. If your application needs some function such as containsAny to check whether a string (or other sequence) contains any members of a set, you may also need such variants as Check whether sequence seq contains ONLY items in aset. for c in seq if c not in aset return False...

How do I change the color or font of a grid cell

Wxpython Color Cell

As with other controls, there are a set of properties that you can use to change the display attributes for each cell. Figure 14.5 displays some of what you can do with the attribute methods. Listing 14.6 displays the code used to create figure 14.5. Notice the use of both grid methods aimed at a specific cell and of the creation of wx.grid.Grid-CellAttr objects. Figure 14.5 A sample usage of the grid attribute methods Listing 14.6 Changing the color of grid cells wx.Frame._init_ self, None,...

Drawing Ovals

Rectanble With Oval Inside

While the last statement in the above example draws an oval, you can also draw ovals using the create_oval function. Similar to drawing arcs, an oval is drawn inside the boundaries of a rectangle. For example, the following code canvas Canvas(tk, width 400,height 400) canvas.pack() canvas.create_oval(1, 1, 300, 200) This example draws an oval in the (imaginary) square drawn from pixel positions 1,1 to 300,200. If we draw a red rectangle with the same coordinates, you can properly see how the...

Plotting Performance Graphs

We've been referencing the images, but we haven't created any graphs yet. In this section, we'll look at the function that reads the data from our database and generates individual images for every possible host probe timescale combination. As you've seen, these images can be combined by multiple criteria. In this example, we group them by their timescale value and probe name. In addition to the simple data plotting, our function will also calculate some statistical parameters for the dataset...

Designing User Interfaces

Tkinter Dialog Example

Before we can begin we must start Qt Designer. On Linux, run designer amp in a console assuming it is in your path , or invoke it from your menu system. On Windows XP, click Start Qt by Trolltech Designer, and on Mac OS X launch it using Finder. Qt Designer starts with a New Form dialog click Dialog with Buttons Bottom and then click Create. This will create a new form with a caption of untitled, and with the QDialogButtonBox as shown in Figure 7.2. Figure 7.2 A dialog with buttons bottom...

Methods Are Objects Bound or Unbound

Methods in general, and bound methods in particular, simplify the implementation of many design goals in Python. We met bound methods briefly while studying_call_in Chapter 29. The full story, which we'll flesh out here, turns out to be more general and flexible than you might expect. In Chapter 19, we learned how functions can be processed as normal objects. Methods are a kind of object too, and can be used generically in much the same way as other objects they can be assigned, passed to...

Function Interfaces and Callback Based Code

As an example, the tkinter GUI toolkit (named Tkinter in Python 2.6) allows you to register functions as event handlers (a.k.a. callbacks) when events occur, tkinter calls the registered objects. If you want an event handler to retain state between events, you can register either a class's bound method or an instance that conforms to the expected interface with_call__. In this section's code, both x.comp from the second example and x from the first can pass as function-like objects this way....

Bound Methods and Other Callable Objects

As mentioned earlier, bound methods can be processed as generic objects, just like simple functions they can be passed around a program arbitrarily. Moreover, because bound methods combine both a function and an instance in a single package, they can be treated like any other callable object and require no special syntax when invoked. The following, for example, stores four bound method objects in a list and calls them later with normal call expressions > > > x Number(2) Class instance...

Packing widgets

So far we have been stacking widgets in a single column, but in most GUIs the layout is more complicated. For example, here is a slightly simplified version of TurtleWorld (see Chapter 4). This section presents the code that creates this GUI, broken into a series of steps. You can download the complete example from At the top level, this GUI contains two widgets a Canvas and a Frame arranged in a row. So the first step is to create the row. class SimpleTurtleWorld(TurtleWorld) This class is...

Testing with mocks

The point of unit testing is to test as many aspects of your code as possible in isolation from the other parts it's easier to tightly specify the behavior of your code and makes the tests run faster. In practice, life is never quite so neat. Your objects need to interact with other objects, and you need to test that interaction. Several different approaches can minimize the number of live objects your tests need to use the most useful of these approaches is creating mock objects. Working with...

History of Pygame

Pygame is built on another game creation library called Simple DirectMedia Layer (SDL). SDL was written by Sam Lantinga while he was working for Loki Software (a now-defunct game company) to simplify the task of porting games from one platform to another. It provided a common way to create a display on multiple platforms as well as work with graphics and input devices. Because it was so simple to work with, it became very popular with game developers when it was released in 1998, and has since...

Creating a multithreaded wxPython application

In most GUI applications, it's useful for long-running processes to run in the background of the application so that they don't interfere with the user's interaction with the rest of the application. The mechanism for allowing background processing is typically to spawn a thread and allow the long process to run in that thread. And that's what you'll do in a wxPython program, with a couple of specific points that we'll describe in this section. The most important point is that GUI operations...

Updating Objects on a Shelve

Now for one last script let's write a program that updates an instance (record) each time it runs, to prove the point that our objects really are persistent (i.e., that their current values are available every time a Python program runs). The following file, updatedb.py, prints the database and gives a raise to one of our stored objects each time. If you trace through what's going on here, you'll notice that we're getting a lot of utility for free printing our objects automatically employs the...

Hello World Revisited

As I mentioned in Chapter 1, there is a tradition when learning new languages that the first code you write displays the text Hello, World on the screen. Technically we have already done this with a print ' Hello, World ' statement but it is a little disappointing because as game programmers we are interested in creating appealing visuals and a line of text just does not cut it We are going to create a Hello World script with Pygame that opens a graphical window on your desktop and draws an...

Starting pygamemixer

In order to play sounds, we have to initialize pygame.mixer. Remember what initializing means It means to get something ready at the start. Getting pygame.mixer ready is very easy. We just need to add the line after we initialize Pygame. So the code at the start of a program that uses Pygame for sound Now we're ready to play some sounds. There are two main types of sounds you'll use in your programs. The first is sound effects or sound clips. These are usually short, and they're most commonly...

Summation with Recursion

To sum a list (or other sequence) of numbers, we can either use the built-in sum function or write a more custom version of our own. Here's what a custom summing function might look like when coded with recursion > > > def mysum(L) if not L return 0 return L 0 + mysum(L l ) Call myself At each level, this function calls itself recursively to compute the sum of the rest of the list, which is later added to the item at the front. The recursive loop ends and zero...

The PIL Library

Pil Library Python Logo

Python, by itself, contains no graphic capabilities. The language core is all about looping and decision-making and assignments and string handling, as we have seen in the chapters leading up to this one in this book. To implement any sort of graphic capability in your Python applications, you need an external library. This isn't unusual, as we have seen in the use of CGI functionality and relational database functionality in previous chapters. As with the MySQL library that we downloaded in...

Review Questions

A __ structure can execute a set of statements only under certain circumstances. 2. A___structure provides one alternative path of execution. 3. A n ____ expression has a value of either true or false. 4. The symbols gt , lt , and are all_operators. 5. A n _structure tests a condition and then takes one path if the condition is true, or another path if the condition is false. 6. You use a n _statement to write a single alternative decision structure. 7. You use a n _statement to write a dual...

Hardware and Software

Major Components Computer

The physical devices that a computer is made of are referred to as the computer's hardware. The programs that run on a computer are referred to as software. The term hardware refers to all of the physical devices, or components, that a computer is made of. A computer is not one single device, but a system of devices that all work together. Like the different instruments in a symphony orchestra, each device in a computer plays its own part. If you have ever shopped for a computer, you've...

Augmented Assignments

Beginning with Python 2.0, the set of additional assignment statement formats listed in Table 11-2 became available. Known as augmented assignments, and borrowed from the C language, these formats are mostly just shorthand. They imply the combination of a binary expression and an assignment. For instance, the following two formats are now roughly equivalent Table 11-2. Augmented assignment statements X + Y X & Y X - Y X Y X * Y X A Y X Y X > > Y X Y X < < Y X ** Y X Y Augmented...

Case study

Python Case Study

To tie it all together, let's build a simple command-line notebook application. This is a fairly simple task, so we won't be experimenting with multiple packages. We will, however, see common usage of classes, functions, methods, and docstrings. Let's start with a quick analysis Notes are short memos stored in a notebook. Each note should record the day it was written and can have tags added for easy querying. It should be possible to modify notes. We also need to be able to search for notes....

Indefinite Loops

Our averaging program is certainly functional, but it doesn't have the best user interface. It begins by asking the user how many numbers there are. For a handful of numbers this is OK, but what if I have a whole page of numbers to average It might be a significant burden to go through and count them up. It would be much nicer if the computer could take care of counting the numbers for us. Unfortunately, as you no doubt recall, the for loop is a definite loop, and that means the number of...

How do I create an alert box

The three simplest ways of interacting with the user via a dialog box are wx.MessageDialog, which represents an alert box, wx.TextEntryDialog, which prompts the user to enter some short text, and wx.SingleChoiceDialog, which allows the user to select from a list of available options. The next three sections discuss these simple dialogs. A message box dialog displays a short message and allows the user to press a button in response. Typically, message boxes are used to display important alerts,...

How do I add and update a status bar

In wxPython, you can add and place a status bar in the bottom of a frame by calling the frame's CreateStatusBar method. The status bar automatically resizes itself when the parent frame resizes. By default, the status bar is an instance of the class wx.StatusBar. To create a custom status bar subclass, attach it to your frame using the SetStatusBar method, with an instance of your new class as the argument. To display a single piece of text in your status bar, you can use the SetStatus-Text...

Class Hierarchy for Geometric Shapes

Oop Geometric Shapes

Our next examples concern drawing geometric shapes. We know from Chapter 4 how to draw curves y f x , but the point now is to construct some convenient software tools for drawing squares, circles, arcs, springs, wheels, and other shapes. With these tools we can create figures describing physical systems, for instance. Classes are very suitable for implementing the software because each shape is naturally associ ated with a class, and the various classes are related to each other through a...

Smart Dialogs

We define a smart dialog to be one that initializes its widgets in accordance with data references or data structures that are passed to its initializer, and which is capable of updating the data directly in response to user interaction. Smart dialogs can have both widget-level and form-level validation. Smart dialogs are usually modeless, with apply and close buttons, although they can also be live, in which case they may have no buttons, with changes to widgets reflected directly into the...

Entropy and Information Gain

As was mentioned before, there are several methods for identifying the most informative feature for a decision stump. One popular alternative, called information gain, measures how much more organized the input values become when we divide them up using a given feature. To measure how disorganized the original set of input values are, we calculate entropy of their labels, which will be high if the input values have highly varied labels, and low if many input values all have the same label. In...

How do I manage the row and column headers of a grid

In a wxPython grid control, each row and column has its own label. By default, rows are given numeric labels starting with 1 and columns are given alphabetical labels starting with A and continuing to Z, which is followed by aa, ab, and so on. If you're creating a spreadsheet, this is great, but not necessary for most other applications. For something a bit less generic, wxPython provides methods to change the labels. Figure 14.3 displays a sample grid with label headers. Figure 14.3 A sample...

How do I make a slider

Tkinter Slider

A slider is a widget that allows the user to select a number from within a range by dragging a marker across the width or height of the control. In wxPython, the control class is wx.Slider, which includes a read-only text display of the current value of the slider. Figure 7.7 displays examples of a vertical and horizontal slider. Basic slider use is fairly straightforward, but there are a number of events you can add. Figure 7.7 A vertical wx.Slider and a horizontal wx.Slider, which use the...

How can I create a list box

A list box is another mechanism for presenting a choice to the user. The options are placed in a rectangular window and the user can select one or more of them. List boxes take up less space than radio boxes, and are good choices when the number of options is relatively small. However, their usefulness drops somewhat if the user has to scroll far to see all options. Figure 7.13 displays a wxPython list box. In wxPython, a list box is an element of the class wx.ListBox. The class has methods...

Custom and Interactive Graphics Items

Pyside Move Qgraphicsitem

The predefined graphics items can be made movable, selectable, and focusable by calling setFlags on them with suitable constants. Users can drag movable items with the mouse, and they can select selectable items by clicking them, and by using Ctrl Click to select multiple items. Focusable items will receive key events, but will ignore them unless we create an item subclass with a key event handler. Similarly, we can make items responsive to mouse events by subclassing and implementing...

Word Segmentation

For some writing systems, tokenizing text is made more difficult by the fact that there is no visual representation of word boundaries. For example, in Chinese, the three-character string SHA ai4 love verb , guo3 country, ren2 person could be tokenized as SH A, country-loving person, or as S HA, love country-person. A similar problem arises in the processing of spoken language, where the hearer must segment a continuous speech stream into individual words. A particularly challenging version of...

Calculating Stack Size

At times when assessing a binary for possible vulnerabilities, it's important to understand the stack size of particular function calls. This can tell you whether there are just pointers being passed to a function or there are stack allocated buffers, which can be of interest if you can control how much data is passed into those buffers possibly leading to a common overflow vulnerability . Let's write some code to iterate through all of the functions in a binary and show us all functions that...

Counting Instances with Class Methods

Interestingly, a class method can do similar work here the following has the same behavior as the static method version listed earlier, but it uses a class method that receives the instance's class in its first argument. Rather than hardcoding the class name, the class method uses the automatically passed class object generically class Spam numlnstances 0 Use class method instead of static Spam.numlnstances + 1 def printNumlnstances(cls) print(Number of instances , cls.numlnstances)...

Using Properties to Control Attribute Access

In the previous subsection the Point class included a distance_from_origin method, and the Circle class had the area , circumference , and edge_dis-tance_from_origin methods. All these methods return a single float value, so from the point of view of a user of these classes they could just as well be data attributes, but read-only, of course. In the ShapeAlt.py file alternative implementations of Point and Circle are provided, and all the methods mentioned here are provided as properties. This...

PyCrust sets the standard for a Python shell

Minimizing Python Shell With Wxpython

When you work with Python interactively, you work in an environment that is called the Python shell which is similar to other shell environments, such as the DOS window on Microsoft platforms, or the bash command line on Unix-based systems. The most basic of all the Python shells is the one in listing 4.1, which you see when you launch Python from the command line. While it is a useful shell, it is strictly text-based, rather than graphical, and it doesn't provide all the shortcuts or helpful...

Text Corpus Structure

We have seen a variety of corpus structures so far these are summarized in Figure 2-3. The simplest kind lacks any structure it is just a collection of texts. Often, texts are grouped into categories that might correspond to genre, source, author, language, etc. Sometimes these categories overlap, notably in the case of topical categories, as a text can be relevant to more than one topic. Occasionally, text collections have temporal structure, news collections being the most common example....

Brown Corpus

The Brown Corpus was the first million-word electronic corpus of English, created in 1961 at Brown University. This corpus contains text from 500 sources, and the sources have been categorized by genre, such as news, editorial, and so on. Table 2-1 gives an example of each genre for a complete list, see Table 2-1. Example document for each section of the Brown Corpus Table 2-1. Example document for each section of the Brown Corpus Christian Science Monitor Editorials Underwood Probing the...

Iron Python and the CLR

So far, we've focused on navigating the .NET framework and the Python language, emphasizing the skills you need to make effective use of IronPython. But not all .NET concepts map easily to Python concepts certain corners of .NET can't be brought directly into Python. This section looks at some of these dusty corners and how they work in IronPython. Most of the things we explore are simple but, even if they're easy, you need to know the trick in order to use them. The first line of IronPython...

Slicing and Striding Strings

Piece 3 We know from Piece 3 that individual items in a sequence, and therefore in- 18 lt dividual characters in a string, can be extracted using the item access operator . In fact, this operator is much more versatile and can be used to extract not just one item or character, but an entire slice subsequence of items or characters, in which context it is referred to as the slice operator. First we will begin by looking at extracting individual characters. Index positions into a string begin at...

Lambda functions that take a tuple instead of multiple

In Python 2, you could define anonymous lambda functions which took multiple parameters by defining the function as taking a tuple with a specific number of items. In effect, Python 2 would unpack the tuple into named arguments, which you could then reference by name within the lambda function. In Python 3, you can still pass a tuple to a lambda function, but the Python interpreter will not unpack the tuple into named arguments. Instead, you will need to reference each argument by its...

Fibonacci Iterator

Now you're ready to learn how to build an iterator. An iterator is just a class that defines an_iter_() end with a pair of underscore (_) characters. Why is that There's nothing magical about it, but it usually indicates that these are special methods. The only thing special about special methods is that they aren't called directly Python calls them when you use some other syntax on the class or an instance of the class. More about special methods. self.a, self.b self.b, self.a + self.b return...

Using Jinja With Django

Every time I meet someone new who asks me about Django, I tell them exactly what I think. It's a great product. It does exactly what it's designed to do. Allows you to build decently structured applications rapidly, without much overhead in doing so. One of the other things I tell them, is that the first they should do is scrap the template engine, and install Jinja.Jinja is a sandboxed template engine, written in Python of course. It's created by the guys over at Pocoo.

Debugger Hooks

One very cool feature that IDAPython supports is the ability to define a debugger hook within IDA and set up event handlers for the various debugging events that may occur. Although IDA is not commonly used for debugging tasks, there are times when it is easier to simply fire up the native IDA debugger than switch to another tool. We will use one of these debugger hooks later on when creating a simple code coverage tool. To set up a debugger hook, you first define a base debugger hook class and...

Input or Raw Input

The raw_input() function is a safe method for getting input from the user because it does not allow arbitrary execution or evaluation of user input. There is another, similar command in IronPython called input. The input command, while useful, can also be very dangerous it allows the execution of IronPython commands based on user input. This can be a tremendous security risk and should be used with caution.

How Jython Finds the Jars and Classes to Scan

There are two properties that Jython uses to find jars and classes. These settings can be given to Jython using commandline settings or the registry (see Appendix A). The two properties are python.packages.paths python.packages.directories These properties are comma separated lists of further registry entries that actually contain the values the scanner will use to build its listing. You probably should not change these properties. The properties that get pointed to by these properties are more...

Logical And Physical Lines

A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line. An example of a logical line is a statement like print( 'Hello World' ) - if this was on a line by itself (as you see it in an editor), then this also corresponds to a physical line. Implicitly, Python encourages the use of a single statement per line which makes code more readable.

Implementing COM Objects in Python

Script Form Edit Delphi

In order to implement COM objects in the Python version of Windows, you need a set of extensions developed by Mark Hammond and Greg Stein. Part of the win32com package, these extensions enable you to do everything that is COM-related, including writing COM clients and COM servers. The following link takes you to the download page of these extensions All the Win32 extensions including the COM extensions are part of the win32all installation package. This package also installs the PythonWin IDE...

Calculating Permutations The Lazy Way

First of all, what the heck are permutations Permutations are a mathematical concept. There are actually several definitions, depending on what kind of math you're doing. Here I'm talking about combinatorics, but if that doesn't mean anything to you, don't worry about it. As always, Wikipedia is your friend. The idea is that you take a list of things could be numbers, could be letters, could be dancing bears and find all the possible ways to split them up into smaller lists. All the smaller...

Command pattern

The command pattern adds a level of abstraction between actions that must be done, and the object that invokes those actions, normally at a later time. In the command pattern, client code creates a Command object that can be executed at a later date. This object knows about a receiver object that manages its own internal state when the command is executed on it. The Command object implements a specific interface typically it has an execute or do_action method, and also keeps track of any...

Getting a Nodes Children

When dealing with a DOM tree, you primarily use nodes and node lists. A node list is a collection of nodes. Any level of an XML document can be represented as a node list. Each node in the list can in turn contain other node lists, representing the potential for infinite complexity of an XML document. The Node interface features two methods for quickly getting to a specific child node, as well as a method to get a node list containing a node's children. firstChild refers to the first child node...

The winserviceutil Module Manage Windows Services

Windows services are processes that run on a Windows desktop or a Windows server machine. They can be remotely started, stopped, restarted, and queried for status. To manage Windows services, there is the win32serviceutil module, found in Mark Hammond's win32all package. For information on how to get the win32all package, please see Appendix B. The following example shows how to start a service, stop a service, restart a service, or get service status through Python def service_info action,...

Why Indentation Syntax

The indentation rule may seem unusual at first glance to programmers accustomed to C-like languages, but it is a deliberate feature of Python, and it's one of the main ways that Python almost forces programmers to produce uniform, regular, and readable code. It essentially means that you must line up your code vertically, in columns, according to its logical structure. The net effect is to make your code more consistent and readable unlike much of the code written in C-like languages . To put...

Single Document Interface SDI

For some applications, users want to be able to handle multiple documents. This can usually be achieved simply by running more than one instance of an application, but this can consume a lot of resources. Another disadvantage of using multiple instances is that it is not easy to provide a common Window menu that the user can use to navigate between their various documents. There are three commonly used solutions to this. One is to use a single main window with a tab widget, and with each tab...

Formulating Algorithms with Top Down Stepwise Refinement Case Study Nested Control Structures

Let us work another complete problem. We once again formulate the algorithm using pseudocode and top-down, stepwise refinement and we develop a corresponding Python program. Consider the following problem statement A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, several of the students who completed this course took the licensing examination. Naturally, the college wants to know how well its students did on the exam. You have...

Formulating Algorithms with Top Down Stepwise Refinement Case Study Sentinel Controlled Repetition

Let us generalize the class-average problem. Consider the following problem Develop a class-averaging program that processes an arbitrary number of grades each time the program is executed. In the first class-average example, the program knows the number of grades 10 to be entered by the user. In this example, no indication is given of how many grades will be entered. The program processes an arbitrary number of grades. How can the program determine when to stop the input of grades How will it...

Using the abstractmethod and abstractproperty decorators

In Java, for example, an abstract class by definition can't be instantiated under any circumstances. As with many features, in Python the abstractness of abstract base classes isn't so much an enforced rule as it is a gentleman's agreement. Python will allow you to create instances of generic abstract base classes without complaint as long as the base class doesn't contain an abstract method > > > from abc import ABCMeta > > > class MyABC(metaclass ABCMeta) > > > my_myabc...

Registering Callback Handler Objects

In examples thus far, C has been running and calling Python code from a standard main program flow of control. That's not always the way programs work, though in some cases, programs are modeled on an event-driven architecture where code is executed only in response to some sort of event. The event might be an end user clicking a button in a GUI, the operating system delivering a signal, or simply software running an action associated with an entry in a table. In any event (pun accidental),...

Introduction to SNMP

Snmp Architecture

SNMP Simple Network Management Protocol is a UDP-based protocol used mostly for managing network-attached devices, such as routers, switches, computers, printers, video cameras, and so on. Some applications also allow access to internal counters via the SNMP protocol. SNMP not only allows you to read performance statistics from the devices, it can also send control messages to instruct a device to perform some action for example, you can restart a router remotely by using SNMP commands. There...

Initializing OpenGL Features

The resize function is enough to start using OpenGL functions to render to the screen, but there are a few other things we should set to make it more interesting (see Listing 9-5). Listing 9-5. Initializing OpenGL def init() glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0)) The first thing that the init function does is call glEnable with GL_DEPTH_TEST, which tells OpenGL to enable the Z buffer. This ensures that objects that are far from the camera aren't drawn over objects that are near to the...

Note You may have to flip the normals on the faces of the cube which makes them point inward rather than outward The

Skybox Rendering Opengl

Generating the skybox textures may require a little more effort because each texture must seamlessly align with the four other textures it shares an edge with. If you are artistically inclined, you may be able to draw or paint these textures, but it is probably easier to use 3D modeling software to render six views of a scene for each face of the skybox. An excellent choice for rendering skyboxes is Terragen www.planetside.co.uk terragen , which creates remarkably realistic-looking images of...

Python Design Pattern Command Object

Absolute imports 46 abstract factory pattern about 271 examples 272 implementing 273-275 UML class diagram 272 abstraction 16 access control 50, 51 adapter pattern about 257, 259 benefits 258 structure 258 UML diagram 258 add_child method 279 add_point method 127 Agent class 90 aggregation 19 all method 352 API SQLite 348 append method 170 append method 98 anchor 356 expand 356 fill 356 ipadx 356 ipady 356 padx 356 pady 356 side 357 assertDictEqual method 320 assertEqual method 318 assertFalse...