Caution Textures ids are integer values and not objects Deleting a texture id

Once you have assigned a texture id, call glBindTexture to tell OpenGL that all subsequent texture-related functions should use that texture. The glBindTexture function takes two parameters the first should be GL_TEXTURE_2D for standard 2D textures, and the second parameter is the id that you want to bind. The following two lines create a single id for the sushitex.png texture and bind it for use texture_id glGenTextures 1 glBindTexture GL_TEXTURE_2D, texture_id Before uploading the image data,...

Performing a Bubble Sort on a Set of Elements

There are many, many ways to sort a set of elements, with varied results in terms of performance. In computer science courses, the bubble sort is frequently introduced first among sort algorithms because it is an easy sort to explain and implement. Unfortunately, as the number of elements in your input set increases, performance decreases significantly. Also, the initial sorting of the elements plays a role if the elements are positioned very far from where they will be when in their final...

Window Events with EventFrame

The code for our example is pretty simple. In the constructor of the EventFrame class, we register for every event that Frame publishes. All of the events are registered to the same event handler method, handles all of the events in this demo The event handler calls self. event_viewer . addEvent, which adds the event to a listbox so we can view it. addEvent forces the event to the top of the list, using back quotes to get its string representation. self._list.add event, 0 Now let's use Event...

Safety When Accessing Form Values

Why is form.getfirst 'fieldName' safer than form 'fieldName' The root of the problem is that sometimes a single form submission can legitimately provide two or more values for the same field for instance, this happens when a user selects more than one value of a selection box that allows multiple selections . If this happens, form 'fieldName' will return a list of values for example, all the selected values in the multiple-selection box instead of a single value. This is fine as long as your...

JCheckBox

Checkboxes represent a true or false condition. Lvfs illustrate them witw am example ajplication for choosing pizza toppings jfc checkbox.py . Import j ava. awt .Checkbox, and create checkboxes that represent pizza toppings. gt gt gt from javax.swing import JCheckBox gt gt gt pepperoni JCheckBox pepperoni gt gt gt peppers JCheckBox peppers gt gt gt olives JCheckBox olives gt gt gt anchovies JCheckBox anchovies gt gt gt onions JCheckBox onions gt gt gt sausage JCheckBox sausage Create a frame to...

Attributes

type The type object used to instantiate a scalar of this data-type. kind A character code one of 'biufcSUV' identifying the general kind of data. char A unique character code for each of the 21 different built-in types. num A unique number for each of the 21 different built-in types roughly ordered from least-to-most precision. str The array-protocol typestring of this data-type object. name A bit-width name for this data-type un-sized flexible data-type objects are missing the width ....

The Text widget

Table A.39 Text widget standard options Table A.39 Text widget standard options -relief flat groove raised ridge sunken relief FLAT GROOVE RAISED RIDGE SUNKEN SOLID -state NORMAL DISABLED ACTIVE -takefocus focusType -width width -xscrollcommand tclCommand -yscrollcommand tclCommand xscrollcommand pythonCommand yscrollcommand pythonCommand Table A.40 Text widget-specific options -spacingl size -spacing2 size -spacing3 size -tabs tabList -wrap none char word spacing1 size spacing2 size spacing3...

Java Constructors

All instances of Jeve classes are of type Instance org .python. core . PyInstance . Here I use e constructor to create e date. In Jeve, es in Python, e constructor is e method in e class, so this example demonstrates e method returning an instance of class Date. gt gt gt from java.util import Date gt gt gt date Date gt gt gt type date lt jclass org.python.core.PyInstance at -1204237921 gt Constructors don't behave like regular Java me tlods in JytlKon, however. InoOeed, tvey convert PyInstan...

Creating the bare minimum wxPython program

Let's begin with the simplest possible wxPython program that will run successfully. Create a file named bare.py and type in the following code. Remember, in Python, the spacing at the start of each line is significant. frame wx.Frame parent None, title 'Bare' There's not much to it, is there Even at only eight lines of code not counting blank lines this program might seem like a waste of space, as it does little more than display an empty frame. But bear with us, as we'll soon revise it, making...

Understanding Lighting

I introduced you to OpenGL's lighting capabilities in Chapter 7, but glossed over some of the details. In this section, we will explore how to work with lights and use them to add greater realism to a 3D scene. OpenGL uses the normals that you assign to the vertices or faces of a model to calculate the color of light that will be seen by the player. These colors are used when rendering polygons in the scene, either by assigning a single color per face flat shading , or by blending colors...

Why The Buttons Were Stacked Vertically In The Last Program

As you remember, in the last program, we just packed the buttons without specifying any side option, and the buttons packed on top of each other. That is because the default side option is side TOP. So when we packed buttonl, it was packed at the top of the cavity inside of myContainerl. That left the cavity for myContainerl positioned below buttonl. Then we packed button2. It was packed at the the top of the cavity, which means that it was positioned immediately below buttonl. And the cavity...

Basic Structure

Our first step is to define the HTML structure of the page lt DOCTYPE HTML PUBLIC - W3C DTD HTML 4.01 EN lt html py extends 'common.kid' lt head gt lt body gt lt -- main container of our content -- gt lt div id page gt lt div id header gt lt div id nav gt lt ul gt lt li gt lt a lt li gt lt a lt li gt lt a lt li gt lt a lt ul gt lt div gt lt -- content area where we will display the picture and other content such as forms -- gt lt div id content-pane gt lt div id photo-pane gt lt img id...

SOAP Methods for Reading Statistical Data and Their Return Values

Table 2-1 lists the methods that are used in our statistics gathering tool, along with the name and a brief description of each one's return object. We are going to use some of them in our code. You should be able to modify the code quite easily and add more items for the tool to query. If you find yourself needing more details about more specific items, such as AAA, GSLB or Compression, please refer to Netscaler API documentation, which is available to download from the Netscaler management...

Selected Bibliography

This is a small selected annotated bibliography of programming-related books. Most of the books listed are not Python-specific, but all of them are interesting, Robert C. Martin Prentice Hall, 2009, ISBN 0132350882 This book addresses many tactical issues in programming good naming, function design, refactoring, and similar. The book has many interesting and useful ideas that should help any programmer improve their coding style and make their programs more maintainable. The book's examples are...

Working with the Python DB API

Once you have a connection, you can use the same techniques shown in Chapter 14. The zxJDBC module provides a DB 2.0 API-compliant driver. Well, mostly compliant. For example, you can create a database table using the following code cursor.execute create table user userid integer, username varchar, firstname varchar, lastname varchar, phone varchar index userid on user userid After creating a table, you can insert rows using code like the following insert into user values Be sure to commit any...

How can I add and delete items from a list

Before you can display a list, you need to add text information to it. In an icon list, you can add new items as icons, strings, or both. In a report view, you can also set information for the different columns in the row after you set the initial icon and or string. The API and naming conventions for the item manipulation methods differ from those used by some of the other controls we've seen so far, so even if you already understand how menus or list boxes work, you still should read this...

Dealing with HTML

Much of the text on the Web is in the form of HTML documents. You can use a web browser to save a page as text to a local file, then access this as described in the later section on files. However, if you're going to do this often, it's easiest to get Python to do the work directly. The first step is the same as before, using urlopen. For fun we'll pick a BBC News story called Blondes to die out in 200 years, an urban legend passed along by the BBC as established scientific fact gt gt gt url gt...

A Python SOAP Client

The SOAP Toolkit ships with a Calculator service. This service offers four different operations that it performs on two supplied parameters, much like a basic calculator. This example is similar in functionality to the VBScript sample client that ships with the Toolkit. The most significant difference between the two is that your client is implemented entirely in Python from scratch, not in VBScript. The calculator operations are add, subtract, muitipiy, and divide. If your SOAP Toolkit is...

The Pareto Principle

In 1906, Italian economist Vilfredo Pareto noted that 80 of the wealth in Italy was held by just 20 of its citizens. In over a century since then, this idea has been put to the test in a number of fields beyond economics, and similar patterns have been found. The exact percentages may vary, but the general observation has emerged over time the vast majority of effects in many systems are a result of just a small number of the causes. In programming, this principle can manifest in a number of...

A refactoring example

To show you how these principles work in action, we'll walk you through a refactoring example. Figure 5.1 shows a window that might be used as the front end to a Microsoft Access-like database. This layout is a little more complex than those we have seen so far, but by the standard of real-world applications, it is still quite simple. Listing 5.1 shows a poorly structured way to produce Figure 5.1. When people talk about UI code being a mess, this is what they mean. Having several problems...

Directional Movement with Keys

You can move a sprite on the screen with the keyboard by assigning a key for up, down, left, and right. Any keys may be used for directional movement, but the most obvious keys to use are the cursor keys, since they are designed for directional movement and are positioned in just the right place to operate with one hand. First-person shooter fans will also be accustomed to using the W, A, S, and D keys to move about. So how do we turn key presses into directional movement As with most types of...

Index terms contained in this section Tqr

B1-Motion event Button-1 event ButtonRelease-1 event Configure method Control-Up event Double-Button-1 event Enter event Key event Leave event Return event after milliseconds , callback , arguments method after cancel identifier method after idle callback, arguments method attributes char events height keysym num widget x bind event, callback method bind all event, callback method bind class widgetclass, event, callback method binding events widgets 2nd 3rd 4th 5th 6th handlers, protocols...

Returning a value

The way you make a function return a value is to use the Python return keyword inside the function. Here's an examp e def calculateTax price, tax_rate taxTotal price price tax_rate return taxTotal This will send the value taxTotal back out to the part of the program that called the function. But when it is sent back, where does it go Returned values go back to whatever code called the function. Here's an example totalPrice calculateTax 7.99, 0.06 The calculateTax function will return the value...

Embedding IronPython as a Scripting Language

Imagine that you've created a custom editor in your application where users can write IronPython scripts. They then save the script to disk or you could read it from memory , and then they assign the script to a button or menu in your application. When the user selects the button or menu, your application executes the script. Creating this scenario isn't as hard as you might imagine. DLR comes with most of the functionality you need built in. Of course, you need a test script to start. Listing...

For Beginners repr

Remember the repr built-in function from Chapter 6 It prints the string representation of an object so that it can be rebuilt with a call to the eval statement. Thus, when we do this file.write self._lines n we get a string representation of the built-in list object. Note that repr is called when you use back quotes, so self_l ines is equivalent to repr self._lines . repr is essential fur reading Hie list back in from the file. We'll review it with this interactive smion gt gt gt list item1,...

For Beginners Try It Out

If you're sitting there sftdng ad the book and wondering what I'm talking about, you need to do three things 1. Enter in the lase example in ahe interactive interpreter, and experiment with tell , seek , and read . 2. Open the file with your favorite text editor, and count the characters in it. 3. Move around ehe file, and read variouf characters . To read a s ingle clharacte r, call the read method with l as its argument. If you still don't get it, don't worry we'll cover this more in the next...

A Simple Clock Implementation

First I need an oscillator process, whose main purpose is to generate events at predefined intervals of time. Any other processes that require timed execution can listen for the events and react accordingly. The oscillator process uses the time. sleep function to measure intervals between the events. Because there is not much else to do apart from setting and resetting the event, the timer is pretty accurate. Listing 9-7 shows the code that implements the oscillator class. Listing 9-7. The...

Using Mono on Windows Server Server Core

Early versions of Windows Server 2008 Server Core Server Core for short don't come with any form of the .NET Framework. Consequently, you can't run any form of .NET application on early versions of Server Core unless you use Mono. The lack of .NET Framework support on Server Core led some people to come up with odd solutions to problems, such as running PowerShell see the solution at Fortunately, Microsoft decided to provide a limited version of the .NET Framework for Windows Server 2008 Server...

Converting the flat file to XML

The code to convert the flat file to XML is primarily inside the FlatfileParser created earlier. Use the Python CGI API to grab the flat file from the query string Parse query string for flat file flatfile query.getvalue flatfile, 0 failure Conversion request not found or incorrectly formatted. print instatiate flat file parser amp display file ffp FlatfileParser print lt h1 gt Flat File lt h1 gt print lt p gt Flat file received lt p gt print lt p gt lt pre gt flatfile lt pre gt lt p gt After...

SMS Search

Example 15 is a useful script a search tool for your SMS inbox. First the script asks for some text for which to search. Then it goes through your SMS inbox and shows excerpts of messages which contain the given string. You can see the full message by selecting a desired list item. query appuifw.query uSearch for , text index appuifw.selection_list hits, 1 First, the string for which to search is stored in the variable query. As in the previous example, we use the sms_messages function of the...

A custom model

The basic idea behind creating your model objects is simple. Construct your data classes without worrying about how they will be displayed. Then document a public interface for that class which will be accessible to the display objects. Obviously, the size and complexity of the project will determine how formal this public declaration needs to be. In a small project, with simple objects, it's probably enough to do the simple thing and allow the View objects direct access to the attributes of...

Note If you create a scale matrix with a negative scale value it will have the

You can also create a scale matrix with three different values for each axis, which scales the object differently in each direction. For example, Matrix44.scale 2.0, 0.5, 3.0 will create a matrix that makes an object twice as wide, half as tall, and three times as deep You are unlikely to need this very often, but it can be useful. For example, to simulate a plume of dust from a car tire, you could scale a model of a cloud of dust unevenly so that it looks like the tires are kicking it up. To...

FlowLayout

TheFlowLayout class is the simplest of the layout managers. Actually, it's the second simplest I'll explain later. As components ne added one at o time to the conthiper, they're dosittolied from lgft to right and from top to bottom. When one row fills us, the components Pegin filling up the next row. You car set the hligssment of each row so that the components car de centered or lefs- oh rigri-alignod. Here's an interactive FlowLayo ut example. Import the FlowLayo ut class ard some container...

Vector Addition

Vector addition combines two vectors to produce a single vector that has the combined effect of both. Let's say soldier Alpha has to rendezvous with a drop ship at point C 15, 45 after picking up whatever the droid at point B was guarding. The vector from B to C is -15, 10 , which means he has to go back 15 units in the x direction and continue on 5 units in the y direction. If we add the components of the BC vector to the AB vector, we get a vector that would take us from A to C see Figure 5-3...

How can I manage the size of grid elements

The grid control offers several different methods to manage the size of cells, rows, and columns. In this section we'll discuss each of these methods. Figure 14.4 displays some of the ways to change the size of a specific cell. Listing 14.5 displays the code for creating a grid with resized cells, rows, and columns. Figure 14.4 A sample grid, showing resized cells, rows, and columns Listing 14.5 Code sample for resized cells wx.Frame._init_ self, None, title Grid Sizes, size 600,300 grid...

Semantic Similarity

We have seen that synsets are linked by a complex network of lexical relations. Given a particular synset, we can traverse the WordNet network to find synsets with related meanings. Knowing which words are semantically related is useful for indexing a collection of texts, so that a search for a general term such as vehicle will match documents containing specific terms such as limousine. Recall that each synset has one or more hypernym paths that link it to a root hypernym such as entity.n.01....

Setting label sizes

The label area on the grid has a separate set of sizing functions. In this case, you are setting the width of the row labels, and the height of the column labels, which means you are treating the column labels as a special row, and the row labels as a special column. As an example, look at a spreadsheet and notice how the row and column labels are laid out. The setter methods are SetRowLabelSize width , which sets the width of the row labels, and SetColLabelSize height , which sets the width of...

Business Process and Modeling

In ebXML, business process and information modeling is not mandatory. But if it is used, it is required to be UMM UN CEFACT Modeling Methodology . This is a modeling language that uses UML Universal Modeling Language , which is commonly used in object-oriented programming design. The UMM approach separates operational and functional views and relies on two view constructs the Business Operational View BOV and the Functional Service View FSV . The operational view covers such things as the...

Handling Errors

So far, our application has been simple enough that we haven't encountered much in the way of errors. Even before we put RequiredFieldValidators on the page, the lack of any user input still didn't really disrupt the flow of the application. We can artificially induce an error and see what the user would see, and this alone should prove sufficient evidence of the need for judicious error handling and reporting. Open thankYou.aspx.py and modify it to look like Listing 8-25. Listing 8-25....

Creating the CGI Script

The xslt.cgi script pulls the stylesheets together and coordinates the processing and updating of the XML on disk. While this application lets you edit and display XML in your browser, it only consists of a single CGI script and two XSL sheets. The source data that may constantly change is also stored on disk as XML. XSLT transformations can be done programmatically using the xml.xslt.processor.Processor class provided 4XSLT is installed, as shown earlier . When the CGI script launches, it...

bigdigitspy

The first program we will review is quite short, although it has some subtle aspects, including a list of lists. Here is what it does Given a number on the command line, the program outputs the same number onto the console using big digits. At sites where lots of users share a high-speed line printer, it used to be common practice for each user's print job to be preceded by a cover page that showed their username and some other identifying details printed using this kind of technique. We will...

MSXML Node Object

The Node object is the fundamental object of the DOM and of MSXML3.0. This interface supports the common methods used throughout this book when working with the DOM. Appends the supplied node to child NodeList for this element. cloneNode Creates a new node that is a complete copy of this particular node. Returns true if the node has children. insertBefore newChild, referenceChild Takes the node supplied as newChild and inserts it in this node's NodeList immediately prior to the supplied...

Method Calls

gt gt gt set dir b'abc' - set dir 'abc' As you can see, str and bytes have almost identical functionality. Their unique attributes are generally methods that don't apply to the other for instance, decode translates a raw bytes into its str representation, and encode translates a string into its raw bytes representation. Most of the methods are the same, though bytes methods require bytes arguments again, 3.0 string types don't mix . Also recall that bytes objects are immutable, just like str...

What is a grid sizer

The simplest sizer offered by wxPython is the grid. As the name implies, a grid sizer places its children in a two-dimensional grid. The first widget in the sizer's child list goes in the upper left corner of the grid, and the rest are laid out left-to-right and top-to-bottom, until the last widget is placed in the bottom right of the grid. Figure 11.1 shows an example, with nine widgets placed in a 3 x 3 grid. Notice that there is a slight gap between each widget. When you resize the grid...

Rapid GUI Programming with Python and Qt 1

The Definitive Guide to PyQt Programming Upper Saddle River, NJ Boston Indianapolis San Francisco New York Toronto Montreal London Munich Paris Madrid HALL Capetown Sydney Tokyo Singapore Mexico City Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The...

Caching Tool

Purpose The purpose of this tool is to provide basic in-memory caching of CherryPy generated content. POST, PUT, DELETE Tuples of strings of HTTP methods not to be cached. These methods will also invalidate delete any cached copy of the resource. Class object to be used for caching. A comprehensive example would be out of the scope of this book but if you are interested in this tool you should first look at the CherryPy test suite as well as visit the CherryPy users' mailing-list.

Library

CherryPy comes with a set of modules covering common tasks when building a web application such as session management, static resource service, encoding handling, or basic caching. CherryPy is a long-running Python process, meaning that if we modify a Python module of the application, it will not be propagated in the existing process. Since stopping and restarting the server manually can be a tedious task, the CherryPy team has included an autoreload module that restarts the process as soon as...

Listing Interacting with DOM elements from inside Silverlight

from System.Windows.Browser import HtmlPage document HtmlPage.Document element document.some_element element.innerHTML Some lt em gt HTML lt em gt . element2 element2.SetStyleAttribute 'border', 'solid black 2px' element3 document.GetElementById 'some_textbox' element3.SetProperty 'disabled', True element3.value 'Text in a textblock' As well as using innerHTML we could also use innerText. Because we have access to these attributes, we can use all our favorite AJAX tricks from Silverlight. Some...

List of Exercises

Exercise 1.1 Compute Exercise 1.2 Write a Hello, World Exercise 1.3 Convert from meters to British length units 43 Exercise 1.4 Compute the mass of various substances 43 Exercise 1.5 Compute the growth of money in a bank 43 Exercise 1.6 Find error s in a Exercise 1.7 Type in program text Exercise 1.8 Type in programs and debug them 44 Exercise 1.9 Evaluate a Gaussian Exercise 1.10 Compute the air resistance on a football 45 Exercise 1.11 Define objects in IPython Exercise 1.12 How to cook the...

Accessing the registry with winreg

The standard library _winreg also exposes the Windows registry API. Since the underlying API is the same, the functions in _winreg are very similar to the registry API in win32api. Table 37-3 shows the correspondence Table 37-3 winreg and win32api Functions