Re: adding a simulation mode
On 12-07-04 05:42 AM, andrea crotti wrote: ... copytree(src, dest) becomes: if not PRETEND_ONLY: copytree(src, dest) import globalsub, unittest class MyTest( unittest.TestCase ): def setUp( self ): globalsub.subs( shutil.copytree ) def tearDown( self ): globalsub.restore( shutil.copytree ) You can also pass a function to subs like so: def setUp( self ): self.copied_trees = [] def fake_copytree( src, dest ): assert os.path.exists( src ) self.copied_trees.append( (src, dest )) return dest # or whatever the thing should return globalsub.subs( shutil.copytree, fake_copytree ) $ pip install globalsub HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame - importing GL - very bad...
On 13-01-02 08:53 PM, someone wrote: On 01/02/2013 10:57 PM, Michael Torrie wrote: On 01/01/2013 04:49 PM, someone wrote: On 01/01/2013 12:13 PM, Chris Angelico wrote: > You could simply > > import OpenGL.GL as GL You're right - but I forgot to write that even though this maybe should/is recommended many places then I've seen a lot of opengl code on the internet and IMHO NOBODY does that and it'll be a lot slower to type that in front of all the opengl commands... So this solution is not something I like too... But I can see some other people came up with good solutions, which I didn't knew about.. Why is this solution not to your liking? Python has namespaces for a Because the amount of opengl-functions is HUGE, many people (at least on the internet) do as I and (IMHO) it takes up too much time to change a lot of code plus sometimes I grab/modify small code pieces from the internet and it makes my development SO MUCH faster just to make an exception here with star-import for opengl-commands. I'd agree on it being rather impractical/pointless/verbose to have every single OpenGL entry point and constant have an extra gl. or glu. or glut. added to the front. OpenGL/GLU/GLUT is already namespaced, but using C-style prefix namespacing (that is gl* glu* glut* and GL_*, GLU_*, GLUT_*), so adding Python style namespacing to the front of that makes it very verbose. OpenGL-using code is *littered* with OpenGL entry points and constants (and yes, I intend the slight slight), so that's going to make it rather annoying to work with. PyOpenGL's current approach is mostly attempting to maintain backward compatibility with the older revisions. wxPython actually rewrote its whole interface to go from * imports into namespaced lookups and then wrote a little migration tool that would attempt to rewrite your code for the new version. They also provided a transitional API so that code could mix-and-match the styles. For PyOpenGL that would look something like this: from OpenGL import gl, glu, glut gl.Rotate(...) gl.Clear(gl.COLOR_BUFFER_BIT) or, if you really needed PEP-8 compliance, and don't mind making the API look nothing like the original, we might even go to: from opengl import gl, glu, glut gl.rotate(...) gl.clear(gl.COLOR_BUFFER_BIT) Either of which would *also* make it possible for us to lazy-load the entry points and symbols (that would save quite a bit of ram). But I'm not actually likely to do this, as it makes it far more annoying to work with C-oriented references (and since PyOpenGL is primarily used by new OpenGL coders who need to lean heavily on references, that's a big deal). Currently you can often copy-and-paste C code into PyOpenGL and have it work properly as far as the OpenGL part is concerned (arrays and the like need to be rewritten, but that's not something I can control, really). People are already confused by the small variations from C OpenGL, making the API look entirely different wouldn't be a good direction to move, IMO. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pylint, was Re: pygame - importing GL - very bad...
On 13-01-02 09:48 PM, Terry Reedy wrote: ... 2) self.lightDone: Invalid name "lightDone" (should match [a-z_][a-z0-9_]{2,30}$) So I can now understand that pylint doesn't like my naming convention with a capital letter in the middle of the variable name, like: "lightDone" = a boolean value. I suppose pylint wants me to use (a little longer method) an underscore to separate words in long variable names... That is more conventional in the Python community (and is in pep 8, I believe) but still a choice. That seems like a improper error message from the tool. "Invalid name" does *not* properly describe that situation. The name is *not* "Invalid" in any sense of the word, and a "checker" that tells you it is is creating needless false-positives. An error checker should be saying something like: "self.lightDone: Does not match PEP8 recommended style" making it clear that this is *not* an error, it is a *style* related *warning*. HTH, Mike -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: handling return codes from CTYPES
On 13-01-21 05:46 AM, Steve Simmons wrote: ... >>> from ctypes import * >>> sLib = cdll.slib >>> lic_key = c_char_p("asdfghjkl".encode(encoding='utf_8', errors='strict')) >>> initResult = sLib.InitScanLib(lic_key.value) >>> print("InitScanLib Result: ", initResult) InitScanLib Result: 65535 >>> I've tried declaring initResult as c_short by: inserting... >>> initResult = c_short(0) ... before the call to sLib.InitScanLib but I still get the same response (65535). That's because you've just discarded the object you created. What you wanted was, I believe: initScanLib = sLib.InitScanLib initScanLib.restype = c_short initResult = initScanLib( ... ) i.e. you tell the initScanLib function how to coerce its result-type. *Some* C functions take a pointer to a data-value to fill in their data, but not *your* function. That pattern looks like: result = c_short(0) my_ctypes_function( ..., byref(result) ) print result.value i.e. you have to pass the variable into the function (as a reference/pointer). HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: handling return codes from CTYPES
On 13-01-21 11:52 AM, Steve Simmons wrote: Mike, Thanks for your response - I was puzzled by one part of it though... On 21/01/2013 15:14, Mike C. Fletcher wrote: That's because you've just discarded the object you created I (mis?)understood from the ctypes documentation that '>>> initResult = c_short(0)' would result in the creation of a ctypes 'short' called initResult and that this object would be mutable. On that basis, I expected the following statement '>>> initResult = initScanLib( ... )' would assign the result of the call to initResult. So, I can understand that I am not using the correct approach but I don't understand how I discarded the object I created. Can you clarify please? Sure, the problem isn't here a ctypes issue, but a Python one. When you do the following: >>> initResult = c_short(0) you have bound the name "initResult" (a string key in a "namespace" dictionary) to a ctypes c_short object. The name "initResult" is in no way special, nor is there any "type" associated with that variable name. The fact that it has been assigned to a c_short *at this moment* does not affect any *future* value assigned to that name. >>> initResult = initScanLib( ... ) Here you have assigned whatever object is the result of initScanLib( ... ) to the name "initResult". The old object pointed to by "initResult" is no longer referenced by that name, so the Python intepreter is free to discard that old object immediately. Thus you have "discarded" the object you created by reassigning the single reference to it to another object, which leaves it free to be garbage collected (depending on Python implementation that might be instantly or eventually). Python does not have typed *variables*, every variable is a pointer to an object (PyObject *) under the covers. There is nothing in Python like: int i; short j; nothing which makes a variable type-enforcing or constrained. At least, nothing in core Python. In theory you can create a namespace which *does* allow such things, but that's getting pretty involved. Hope that helps, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: XSLT to Python script conversion?
On 12-02-13 06:20 AM, Matej Cepl wrote: Hi, I am getting more and more discouraged from using XSLT for a transformation from one XML scheme to another one. Does anybody could share any experience with porting moderately complicated XSLT stylesheet (https://gitorious.org/sword/czekms-csp_bible/blobs/master/CEP2OSIS.xsl) into a Python script using ElementTree's interparse or perhaps xml.sax? Any tools for this? Speed differences (currently I am using xsltproc)? Any thoughts? Thank you, Matěj I wound up rewriting the Docbook to XSL transformation for PyOpenGL's docs in Python using lxml.etree and Kid (now reworked to use Genshi). However, that was a fairly direct translation, it has only a handful of strategies for transforming nodes from docbook to xhtml. That said, it took our processing time down from so-long-I-just-didn't-want-to-work-on-the-docs down to regenerate-whenever-I-make-a-trivial-change. http://bazaar.launchpad.net/~mcfletch/pyopengl/directdocs/files <http://bazaar.launchpad.net/%7Emcfletch/pyopengl/directdocs/files> Is the repository where the project lives. It *also* does a lot of other processing, but the generate.py, model.py and templates/section.kid files are all you need to look at to understand the docbook processing. HTH, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe and OpenGL problem
Line 13:17 of OpenGL.__init__.py, replace with: try: filename = os.path.join(os.path.dirname(__file__), 'version') __version__ = string.strip(open(filename).read()) except Exception, err: __version__ = '2.0.2.02' HTH, Mike [EMAIL PROTECTED] wrote: >I am using the new py2exe and python 24. When I run my setup.py, the >dist seems to generate just fine. However run I run the resulting exe, >I get an error: > >IOError: [Errno 2] No such file or directory >'c:\\app\\dist\\library.zip\\OpenGL\\version' > >Now I've tried the recommended route with older py2exes, where I >exclude OpenGL and copy the entire directory over to my dist, but that >didn't work. I included "version" into the "OpenGL" directory via my >setup.py script, and it is there right in the library.zip, but I still >get the same error. > >Anyone have any ideas or suggections? > > -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Teenagers of busses do *what*?
Steven D'Aprano wrote: ... >He is the equivalent of one of those bored, spoiled teenagers who urinate >on public transport just to see the shocked reactions of other people. You >can't engage him in rational debate. Until we find a way to send electric >shocks through the Internet, all we can do is ignore him. To argue with >him just gives him the sick entertainment he wants. > > Rational debate? They urinate on your buses and you worry about rational debate? Call the transit police. Have them hauled home in a paddy wagon to say hello to their parents after a few dozen hours of picking up litter and scrubbing bus floors. We may not be able to do anything particularly effective to the morons who light *online* fires; but then they are easily ignored when their signal/noise ratio drops to nil. But if you're seeing this kind of behaviour in the real world, for criminney's sake, fix it with the judicious use of a billy club upside the head. No society thrives while letting people piss in the common well. The public transit system is a commons to be protected like any other. If you see people pissing on your public transit, get scared and fix your society. Entirely off-topic, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Merging sorted lists/iterators/generators into one stream of values...
Lasse Vågsæther Karlsen wrote: >I need to merge several sources of values into one stream of values. All >of the sources are sorted already and I need to retrieve the values from >them all in sorted order. > >In other words: >s1 = [10, 20, 30, 40, 50] >s2 = [15, 25] >s3 = [17, 27, 37] > >for value in ???(s1, s2, s3): > print value > >will print out 10, 15, 17, 20, 25, 27, 30, 37, 40, 50 in that order. > >The sources are cursors retrieving data from several databases, not from >the same server, and there's a potential for a large number of rows from >several of the sources. As such, any method that would load it all into >memory and sort it is no good as it would too much memory. > >Is there a function or whatnot in Python that will do what I want? I >have come up with my own method but since it uses generators I'm not >sure how much overhead there is. Additionally, since the values >retrieved from the cursors will be dictionaries of "fieldname":value >pairs, the method would either need to handle that construct (and be >told what fieldname to sort on), or be able to take a function object to >use for the comparison operation. > >Basically, I'll use my own function for this unless someone can point me >to something that is already available. Couldn't seem to find anything >in the builtin modules but I didn't find glob.glob when I was looking >for how to find filenames either so who knows what it's called :) > >Since I need to deal with a variable list of sources (that is, 2 in one >application, 3 in another and 4-5 in a third), a simple 2-source method >isn't enough but if it's better than what I do for 2 sources then I can >make a wrapper for it, since that's what I do anyway. > > I doubt you'll find a prebuilt one, it's fairly easy to create your own, after all. Generators are fairly fast constructs in Python, btw. Here's what I whipped up in a few minutes: def firstIter( value ): it = iter( value ) try: return it.next(), it except StopIteration, err: return None, None def inorder( comparision, *args ): iterators = [ [value,it] for (value,it) in [ firstIter( arg ) for arg in args ] if it is not None ] iterators.sort() while iterators: yield iterators[0][0] try: value = iterators[0][0] = iterators[0][1].next() except StopIteration, err: iterators.pop(0) else: if len(iterators) > 1 and comparision( value, iterators[1][0]) == 1: iterators.sort() continue if __name__ == "__main__": s1 = [10, 20, 30, 40, 50] s2 = [15, 25] s3 = [17, 27, 37] s4 = [] for value in inorder(cmp, s1, s2, s3, s4): print value Anyway, have fun, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Merging sorted lists/iterators/generators into one stream of values...
Lasse Vågsæther Karlsen wrote: >Ok, that one looks more sleak than what I came up with. > >Couple of things I learn from your solution, please correct me if I >misunderstood something: > >1. list containing other lists will sort itself based on first element >on lists inside ? > > Correct, comparison is recursive for lists/tuples. >2. sort(), pop() is not costly operations > > They *can* be costly, but the algorithm reduces the number of times they are called to less-than-linear for all but pathological cases (i.e. they are only called when you need to switch streams). It also only requires sorting only the number of streams, rather than the whole set. >Other than that you seem to not use the cmp operator but that's easily >fixed. > > Sorry about that, revised version below: def firstIter( value ): it = iter( value ) try: return it.next(), it except StopIteration, err: return None, None def cmpFirstWith( comparison ): def compare( a,b ): return comparison(a[0],b[0]) return compare def inorder( comparison, *args ): iterators = [ [value,it] for (value,it) in [ firstIter( arg ) for arg in args ] if it is not None ] iterators.sort() while iterators: yield iterators[0][0] try: value = iterators[0][0] = iterators[0][1].next() except StopIteration, err: iterators.pop(0) else: if len(iterators) > 1 and comparison( value, iterators[1][0]) == 1: iterators.sort( cmpFirstWith( comparison ) ) continue if __name__ == "__main__": s1 = [10, 20, 30, 40, 50] s2 = [15, 25] s3 = [17, 27, 37] s4 = [] for value in inorder(cmp, s1, s2, s3, s4): print value s1 = [{'a':'b'}, {'a':'e'}] s2 = [{'a':'d'}, {'a':'z'}] def comp( a,b ): return cmp( a['a'],b['a']) for value in inorder(cmp, s1, s2 ): print value Have fun, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Merging sorted lists/iterators/generators into one stream of values...
Alex Martelli wrote: >George Sakkis <[EMAIL PROTECTED]> wrote: > ... > > >>>manipulation of a heap to place an item in the right spot, but with 4-5 >>>or a few more sources might not make an impact at all. >>> >>> >>Unless you're talking about hundreds or thousands sources, it probably >>won't. I would still go for the heap solution since IMO the resulting >>code it's more readable and easier to understand. >> >> ... >i.e., a heap solution may be over 4 times faster than a sort-based one >(in the following implementations). Readability seems quite comparable >(skipping the rest of the infrastructure, which generates random sorted >streams and ensures a stream is exhausted and verifies it etc etc): > > One thing to keep in mind (if you care about performance) is that you one could use bisect, instead of sort, as the sorted list of streams is already in order save for the one element you are processing. Btw, nice trick with reverse to reduce memory copying, when did that get introduced? Wonder if bisect can deal with reverse-sorted elements. Anyway, should reduce the O-complexity of that part of the operation, though you'll still have to do a memcpy to shift the rest of the source list's array, and if it can't deal with reverse-sorted lists it would move you back to front-of-list popping. Oh, we're still missing use of a comparison function in both versions. I'd think you'd want that functionality *available* if you're going to make this a general tool. You'll also need to check for StopIteration on creation of sources for null sequences. Finally, why the 'i' element? It's never used AFAICS. >def merge_by_sort(streams): > sources = [[s.next(), i, s.next] for i, s in enumerate(streams)] > while sources: >sources.sort(reverse=True) >best_source = sources[-1] > yield best_source[0] >try: best_source[0] = best_source[-1]() >except StopIteration: sources.pop() > > ... Have fun, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: graphic memory & animation
Peres wrote: > Thanks a lot for your answer, Fredrik, > Slow means more than 20ms to erase the screen. After double buffering > it improved a lot , of course (16 ms) but I'll need a faster speed. > I program 2D animated sequences on a PC. Do you think OpenGL is the > correct direction to take? If so is it easy to interface with Python > (it seems PyOpenGL is not freeware...) PyOpenGL has a BSD-style license, that's about as 'free' as one can get in the freeware sense. Just a note, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: System tray Icon
I have a sample up here: http://blog.vrplumber.com/scripts/recordingdevices.py using wxPython. The sample application is Linux-specific, but it should give you a fairly good idea of how to use the system tray icon control in wxPython. HTH, Mike Mike Pippin wrote: > How would I have an app run with just a system tray Icon??? any help > would be greatly appreciated. I have no clue where to start. -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: 3d Transformation
Tyler Eaves wrote: >Got a 3d algorithmns question. Algorithmn will be implemented in python, >so a library would be great if it works on windows. Basically my function >would be defined as such. > >Problem is one of coordinate transformation. Give a 3d vector, which >reprents the +z axis in the source coordinate system, and a rotation value >around that axis for determinging the x and y axises, I wish to translate >a point from that geometry into "world" geometry, or in other words >absolute coordinates. Input data is a 3d path with banking data that will >be sampled at regular points for purposes of building other geometry. > > You can find code for doing this in the OpenGLContext project. The lowest-level code is in the vrml.vrml97.transformmatrix module, which just generates matrices for the various transformations, rotations and scales. You can find the module here: http://cvs.sourceforge.net/viewcvs.py/pyopengl/vrml/vrml97/transformmatrix.py?view=markup the module also allows for generating inverse arrays (what you use for transforming from outer coordinates to inner, instead of inner to outer), and has an accelerator C module for much of the functionality. The higher levels in OpenGLContext support compositing multiple transformations in a containment hierarchy for a scenegraph. See e.g. OpenGLContext/scenegraph/transform and OpenGLContext/scenegraph/nodepath module for that higher-level stuff. Anyway, hope this helps, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite flavor of Linux? (for python or anything else)
Brett Hoerner wrote: >I have to add another vote for Gentoo. > And another here. Portage (the Python-coded package-management system) does a very good job. I tend to use fairly conservative settings as well, Gentoo's just nice and stable as a general rule, I don't care about ultimate speed or tweaking the code much, I just find that building everything from source (but without the headaches) tends to make things work together well. As far as Python support goes, Gentoo tends to work very well for Python packages, Pygame and wxPython on AMD64, for instance, install flawlessly out of the box (where others seem to have problems)... in fact most of the major packages install reliably. There's a key note that you might miss regarding the Python updating process, namely that you have to run python-updater to rebuild all of your packages for the new Python version, but once you know that, Pythonicity in Gentoo is pretty straightforward. Anyway, just a vote that's trying very hard to keep on-topic for the python list, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: new in programing
Python iterates over "things" (objects), of which integer numbers are just one possible choice. The range built-in command produces ranges of integers which are useful for tasks such as this. lim = 3 for i in range( 1, lim+1 ): for j in range( i+1, lim+2): for k in range( j+1, lim+3): for l in range( k+1, lim+4): for m in range( l+1, lim+5): for n in range( m+1, lim+6): print i,j,k,l,m,n Would be a direct translation of your code (with a few lines to make it actually do something and a fix for the last variable name). HTH, Mike Efrain Marrero wrote: >i want to now how to do this in python >this is java > > >for(int i=1 ; i<=lim ; i++){ > > for(int j=i+1; j<=lim+1; j++){ > > ... -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing huve ge Sets() to disk
Martin MOKREJÅ wrote: Tim Peters wrote: ... I was really hoping I'll get an answer how to alter the indexes for dictionaries in python. Sorry, I don't have a guess for what that might mean. I'm not an expert, mysql for example givs you ability to index say first 10 characters of a text column, which are typically varchar. Just for curiosity I'd like to know how do it in python. When importing data from a flatfile into mysql table, there's an option to delay indexing to the very last moment, when all keys are loaded (it doesn't make sense to re-create index after each new row into table is added). I believe it's exactly same waste of cpu/io in this case - when I create a dictionary and fill it with data, I want to create index afterward, not after every key/value pair is recorded. Okay, you seem to be missing this key idea: A hash-table (dict) is approximately the same level of abstraction as a btree index. Your MySQL "index" is likely implemented as a btree. A hash-table could just as readily be used to implement the index. When you insert into either of these structures (btree or hash), you are not creating an "index" separate from the structure, the structure *is* an "index" of the type you are thinking about. These structures are both efficient representations that map from a data-value to some other data-value. Hashes with a good hash function (such as Python's dicts) are basically O(1) (worst case O(n), as Tim notes), while Btrees (such as common database indices) are O(log(n)) (or something of that type, basically it grows much more slowly than n). Once more, I expect to have between E4 or E5 to E8??? words stored in 20 dictionaries (remember words of sizes in range 1-20? Every of those 20 dictionaries should be, I believe, indexed just once. The indexing method should know all entries in a given file are of same size, i.e. 5 chars, 15 chars, 20 chars etc. I think you're making this more complicated than it needs to be. I hope the algoritm can save some logic. For example, can turn off locking support, index only part of the key etc. I'd tend to agree with Tim. You're making this all far too complex in what appears to be the absence of any real need. There's a maxim in computer programming that you avoid, wherever possible, what is called "premature optimisation". You are here trying to optimise away a bottleneck that doesn't exist (indexing overhead, and locking support are basically nil for a dictionary). It is almost a certainty that these are not *real* bottlenecks in your code (what with not existing), so your time would be better spent writing a "dumb" working version of the code and profiling it to see where the *real* bottlenecks are. For example, looking up a key with it's value only once in the whole for loop tells me I don't need an index. Yes, I'll do this 4 times for those 4 languages, but still I think it's faster to live without an index, when I can sort records. I think I like the sorted text file approach, and the dictionary approach without an index would be almost the same, especially if I manage to tell the db layout not to move the cursor randomly but just to walk down the pre-sorted data. Again, you don't really have a cursor with a dictionary (and since it's randomly ordered, a cursor wouldn't mean anything). A *btree* has an order, but not a dictionary. You could construct a sorted list in memory that would approximate what I *think* you're thinking of as a dictionary-without-an-index. Good luck, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Game programming in Python
Lucas Raab wrote: Baza wrote: I'm looking for any books or on-line resources on game programming using Python. Does anyone have any advice? -- Computer says, 'no' www.panda3d.com, www.pygame.org, www.blender3d.com ... http://www.vrplumber.com/py3d.py?category=game HTH, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Optimizing Word Search
To search for a word which is a jumble of a given set of characters in a (sizable) lexicon, see this posting: http://blog.vrplumber.com/427 your alterations would be to check for length == to length - number-of-wildcards (with the wildcards removed from the translation table, of course) and then some tweaks to the "expensive" loop to allow for up to wildcard-count ValueErrors. There's some (informal) analysis in the comments of that post regarding why its a fairly good mechanism for searching large sets of words. HTH, Mike Case Nelson wrote: ... Basically, the program needs to take in a random list of no more than 10 letters, and find all possible mutations that match a word in my dictionary (80k words). However a wildcard letter '?' is also an acceptable character which increases the worst case time significantly. So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be added to the dict of words. If the letters are ['?','?'] check a-z, aa, ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz ... Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Class introspection and dynamically determining function arguments
On Thu, 20 Jan 2005 11:24:12 -, "Mark English" <[EMAIL PROTECTED]> wrote: I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window would be returned an instance of the class. The actual application I'm interested in writing would either have simple type attributes (int, string, etc.), or attributes using types already defined in a c-extension, although I'd prefer not to restrict the functionality to these requirements. Hmm, I missed the original post, but I'll jump in anyway: This sounds a heck of a lot like a property-editing system. When creating a property-modeled system, the best approach is normally to use something that actually models the properties, rather than trying to guess at the metadata involved by poking around in an arbitrarily structured object. My BasicProperty system allows for this kind of interaction (property-sheets) using wxPython (rather than Tkinter) when using wxoo. You declare classes as having a set of data-properties (which can have defaults or not, constraints or not, restricted data-types or not, friendly names or not, documentation or not). Normally you create these classes as subclasses of a class that knows how to automatically assign __init__ parameters to properties, and knows how to tell (e.g.) wxoo about the properties of the class. Those same property classes also allow for editing properties of database rows in PyTable, but that isn't likely relevant to your case. We've also used them internally to create a rather large web-based property-editing mechanism (applied to such databases), but again, not really relevant to the case at hand. Anyway, if you aren't interested in BasicProperty for this task; another project on which I work, PyDispatcher provides fairly robust mechanism (called robustApply) for providing a set of possible arguments and using inspect to pick out which names match the parameters for a function in order to pass them in to the function/method/callable object. That said, doing this for __init__'s with attribute values from an object's dictionary doesn't really seem like the proper way to approach the problem. Good luck, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Class introspection and dynamically determining function arguments
Bengt Richter wrote: On Fri, 21 Jan 2005 20:23:58 -0500, "Mike C. Fletcher" <[EMAIL PROTECTED]> wrote: On Thu, 20 Jan 2005 11:24:12 -, "Mark English" <[EMAIL PROTECTED]> wrote: ... Does the BasicProperty base class effectively register itself as an observer of subclass properties and automatically update widgets etc., a la Delphi data-driven visual components? I've thought of doing a light-weight form extension class that would use a text (maybe CSV) definition to control contruction, and easy programmatic manipulation by python of the definition parameters, like a stripped-down version of the text view of Delphi forms. It could also be done via Tkinter, to prototype it. It would be interesting to allow dragging widgets and edges around in Tkinter and round-trip the parameter changes automatically into the text representation. A little (well, ok, a fair amount ;-) further and you'd have a drag-n-drop GUI design tool. But don't hold your breath ;-) BasicProperty itself doesn't register as an observable/observer, BasicProperty is the lowest-level of the software stack, so it allows you to override and provide notification (e.g. using PyDispatcher) on property-setting. ConflictSolver (old project to create a room scheduler) used that to do automatic updating of widgets in the wxPython UI based on Model changes (though I don't remember if it was per-property or per-object). My goal for the wxoo project was to provide hooks in the wxPython GUI designers for dropping in property sheets and/or property-aware controls such that you would have the equivalent of "data aware" controls in VB or Access (keeping in mind that BasicProperty properties can also represent fields in database rows). Aside: The VRML97 field class in OpenGLContext does notifications for every set (using PyDispatcher), btw. It's a little more limited in its scope (focus on 3D data-types), but the effect is what allows the scenegraph to cache and then rebuild its internal rendering structures with very low overhead. ... Anyway, if you aren't interested in BasicProperty for this task; another project on which I work, PyDispatcher provides fairly robust mechanism (called robustApply) for providing a set of possible arguments and using inspect to pick out which names match the parameters for a function in order to pass them in to the function/method/callable object. That said, doing this for __init__'s with attribute values from an object's dictionary doesn't really seem like the proper way to approach the problem. Sounds like a workaround for parameter passing that maybe should have been keyword-based? Not as such, that is, not a workaround, and it shouldn't be keyword based ;) . The problem with using keyword-based passing is that every method needs to be written with this awareness of the keyword-handling structures. You spread pointless implementation details throughout your codebase. PyDispatcher lets you write very natural functions for dealing with events without having every function use **named parameters. I've now written quite a few such systems, and I'm currently balanced between two approaches; that taken in PyDispatcher (define only natural parameters, have the system figure out how to deliver them to you), and that taken in OpenGLContext (define an event-class hierarchy which encapsulates all information about the events). The PyDispatcher approach is nice in that it makes simple things very simple. You want access to the "lastValue" parameter in the "environment" of the event and nothing else, you define your function like so: def handler( lastValue ): print 'got last value', lastValue which works very nicely when you're early in the development of a system, or are linking multiple systems. There's no need to do all sorts of extra work defining event hierarchies, you can often leave given handlers entirely alone during refactoring if they aren't dealing with the changed properties in the event-environment. The OpenGLContext approach is more appropriate when you have a large system (such as OpenGLContext), where defining an event class is a trivial task compared to the total system expenditure. It allows for such things as putting methods on the event objects to make debugging easy, and providing common functionality. It starts to show it's worth when you start needing to reason about the phenomena of events themselves, rather than just about the phenomena the events represent (e.g. when you need to cache, delay, or reorder events). The named argument passing approach has the disadvantage that every function must be written with knowledge of that use of named arguments: def handler( lastValue, **named ): print 'got last value', lastValue when using s
Weakref.ref callbacks and eliminating __del__ methods
I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). Looking at the docs for 2.3's weakref.ref, there's no mention of whether the callbacks are held with a strong reference. My experiments suggest they are not... i.e. I'm trying to use this pattern: class Closer( object ): """Close the OIDStore (without a __del__)""" def __init__( self, btree ): """Initialise the closer object""" self.btree = btree def __call__( self, oldObject=None ): """Regular call via self.close or weakref deref""" if self.btree: self.btree.close() self.btree = None class BSDOIDStore(oidstore.OIDStore): def __init__( self, filename, OIDs = None ): """Initialise the storage with appropriate OIDs""" self.btree = self.open( filename ) self.update( OIDs ) self.close = Closer( self.btree ) weakref.ref( self, self.close ) but the self.close reference in the instance is going away *before* the object is called. So, this approach doesn't *seem* to work (the Closer doesn't get called), so I can gather that the callbacks don't get incref'd (or they get decref'd during object deletion). I can work around it in this particular case by defining a __del__ on the Closer, but that just fixes this particular instance (and leaves just as many __del__'s hanging around). I'm wondering if there's a ready recipe that can *always* replace a __del__'s operation? I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate __del__ in 2.5 or thereabouts, so I gather there must be *some* way of handling the problem generally. The thing is, weakref callbacks trigger *after* the object is deconstructed, while __del__ triggers before... must be something clever I'm missing. Throw an old doggie a bone? Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakref.ref callbacks and eliminating __del__ methods
Alex Martelli wrote: Mike C. Fletcher <[EMAIL PROTECTED]> wrote: weakref.ref( self, self.close ) but the self.close reference in the instance is going away *before* the object is called. Uh -- what's holding on to this weakref.ref instance? I guess the weakreference _itself_ is going away right after being created... You know, you're right. I'd been thinking (not-very-clearly) that registering the callback would keep the reference alive until it was called, guess I'm too used to PyDispatcher's operation. Urgh, that's seriously annoying, requires storing the callback somewhere external. Back to __del__ I suppose. Thanks Alex, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakref.ref callbacks and eliminating __del__ methods
Richie Hindle wrote: [Tim] I'll note that one fairly obvious pattern works very well for weakrefs and __del__ methods (mutatis mutandis): don't put the __del__ method in self, put it in a dead-simple object hanging *off* of self. Like the simple: class BTreeCloser: def __init__(self, btree): self.btree = btree def __del__(self): if self.btree: self.btree.close() self.btree = None Then give self an attribute refererring to a BTreeCloser instance, and keep self's class free of a __del__ method. The operational definition of "dead simple" is "may or may not be reachable only from cycles, but is never itself part of a cycle". This is very nice - I've been wondering about just this problem recently, and this will be very useful. Many thanks! From me too :) One question: why the `self.btree = None` in the last line? Isn't `self.btree` guaranteed to go away at this point anyway? (If the answer is "it's necessary for weird cases that would take an hour to explain" then I'll be more than happy to simply use it. 8-) It's to allow the Closer object to act as a substitute for a .close() method on the object, the final full code of the Closer looks like this: class Closer( object ): """Close the OIDStore""" def __init__( self, client ): """Initialise the closer object""" self.btree = client.btree def __call__( self ): """Close and cleanup to prevent multiple calls""" if self.btree: self.btree.close() self.btree = None def __del__( self ): """Handle deletion of the closer object (close btree if necessary)""" self() and we store one of these as self.close in the OIDStore instance' dictionary. self.close = Closer( self ) If the user explicitly calls storage.close() we don't want the __del__ trying to re-close the storage later. In other words, its an explicit requirement for *this* __del__, not a general requirement. Have fun, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakref.ref callbacks and eliminating __del__ methods
Tim Peters wrote: [Mike C. Fletcher] I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). A worthy goal! Well, as of now it seems to have eliminated the last leaks in TwistedSNMP, and that's likely going to eliminate the last of our leaks in our products, so yes, I suppose it was :) . A callback is strongly referenced from the weakref(s) containing it. Thanks. It would really help to give a minimal example of self-contained executable code. I'm not sure how you're using this code, and guessing takes too long. Sorry about that. I was expecting a theoretical problem, not a practical one, so didn't think to provide a practical example. The "2" there is important, just because this is an interactive session. The point of it was to stop `_` from holding a reference to the created weakref. In your code weakref.ref( self, self.close ) the weakref itself becomes trash immediately after it's created, so the weakref is thrown away entirely (including its strong reference to self.close, and its weak reference to self) right after that line ends. Of course callbacks aren't *supposed* to be called when the weakref itself goes away, they're supposed to be called when the thing being weakly referenced goes away. So this all looks vanilla and inevitable to me -- the callback is never invoked because the weakref itself goes away long before self goes away. Alex already scooped you on this "smack yourself on the head, Mikey". I was assuming the weakref object was a proxy for a reference in an internal structure; I was expecting a list of weak references that was nothing but a series of functions to call after finalising the object. My bad. I'm pretty sure it's just because there's nothing here to keep the weakref itself alive after it's created. You could try, e.g., self.wr = weakref.ref( self, self.close ) to keep it alive, but things get fuzzy then if self becomes part of cyclic trash. Yes, so it requires an external storage mechanism and code to clean that up... ick. __del__ looks cleaner and cleaner by comparison. You'd think I would have noticed the huge tables of weakref objects in PyDispatcher as I was working in there... I can work around it in this particular case by defining a __del__ on the Closer, but that just fixes this particular instance (and leaves just as many __del__'s hanging around). I'm wondering if there's a ready recipe that can *always* replace a __del__'s operation? In the presence of cycles it gets tricky; there's a lot of more-or-less recent words (less than a year old ) about that on python-dev. It gets complicated quickly, and it seems nobody can make more time to think about it. Sigh, guess I should stop listening to rumours just because they are saying something about that for which I yearn. I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate __del__ in 2.5 or thereabouts, Python 3 at the earliest. That's the earliest everything nobody can make time for lands <0.5 wink>. Well, we darn well better solve it by then! Don't want memory leaks when we're hard-wired into someone's brain. There are unresolved issues about how to get all this stuff to work sanely. The driving principle behind cyclic-trash weakref endcases right now is "do anything defensible that won't segfault". I'll note that one fairly obvious pattern works very well for weakrefs and __del__ methods (mutatis mutandis): don't put the __del__ method in self, put it in a dead-simple object hanging *off* of self. Like the simple: class BTreeCloser: def __init__(self, btree): self.btree = btree def __del__(self): if self.btree: self.btree.close() self.btree = None Yes, this was the "work around" I'd implemented (well, with __call__ instead and del just calling it). Of course, that didn't actually eliminate any __del__ methods, but oh well, if we're not losing those until 3.x it doesn't really matter :) . The fix for the Deferred in Twisted got a little hideous (there the __del__ is poking around into lots of different attributes of the Deferred. To hack that I created a descriptor class that forwards a variable to the held object and wrapped each of the needed variables in one of those... I'm going to have to find something a little less baroque if I'm going to get it into Twisted... really, it doesn't look like any of it's necessary, it's just logging an error if the Deferred ended on a Failure. Something should be done though, leaking memory from a core object in the framework is just a PITA. When a weakref and its weak referent are both in cyclic trash, Python currently says "the or
Re: PyCon signature advertising
Steve Holden wrote: ... I appreciate that not everyone has control over their .sig, ... Take control of your sigs, my sisters and brothers! Viva la Revolution! Follow the Steve into the heat and light of PyCon. You can achieve enlightenment if only you go to the District on the Eastern Edge of the new continents when the spring arrives. It is only there that all will be revealed. It is only there that you shall find peace. Joy to the Python world! Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
Alan McIntyre wrote: ... I have a list of items that has contiguous repetitions of values, but the number and location of the repetitions is not important, so I just need to strip them out. For example, if my original list is [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I want to end up with [0,1,2,3,2,4,5]. ... Is there an elegant way to do this, or should I just stick with the code above? >>> def changes( dataset ): ... last = None ... for value in dataset: ... if value != last: ... yield value ... last = value ... >>> print list(changes(data )) which is quite readable/elegant IMO. Have fun, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
Ralf W. Grosse-Kunstleve wrote: ... >class grouping: > >def __init__(self, x, y, z): >self.x = x >self.y = y >self.z = z ># real code, finally > >This becomes a serious nuisance in complex applications with long >argument lists, especially if long variable names are essential for >managing the complexity. Therefore I propose that Python includes >built-in support for reducing the ``self.x=x`` clutter. Below are >arguments for the following approach (*please* don't get too agitated >about the syntax right here, it really is a secondary consideration):: > > ... This can be dealt with quite nicely if you take a step back and consider what you're trying to do: * define a set of properties/fields for a class, potentially with default values for any given property * define an initialisation function which, given an instance of a class with defined properties (potentially with defaults) and a mapping of name:value pairs, assigns the named values to the named properties... class Grouping( propertied.Propertied ): x = FloatProperty( "x", """Holder for the grouping node's x coordinate""", defaultValue = 0, ) y = FloatProperty( "y", """Holder for the grouping node's y coordinate""", defaultValue = 0, ) z = FloatProperty( "z", """Holder for the grouping node's z coordinate""", defaultValue = 0, ) def __init__( self, **args ): # code here to do whatever you like to args (or whatever)... super( Grouping, self ).__init__( **args ) # extra code here... where the propertied.Propertied class defines a simple init that iterates through the defined properties pulling those which are present in the **args of the __init__ function and assigning them to the appropriate property. The advantage here is that your class is now documented properly, with the information about a given property all localised in a definition of the property. Your properties can also implement the observer pattern, automatic type checking and coercion, and can provide default values that appear when you delete current values (not just during initialisation). You can also do useful things like using the defined properties of a class to auto-generate __repr__ and __str__ values. You can have your properties delegate to other objects, or have them delay loading/resolving a property's value until the last possible second (lazy loading from an object database, for instance). The fact that it's all doable in Python 2.2+ without any need for new syntax... well... that's cool too. The disadvantage is that the properties tend to be unordered (unless you explicitly order them, and that's awkward looking), and you have to pass them to the constructor as keyword arguments. But then, if you're defining a class with 50 properties, you likely aren't really wanting to pass all 50 as positional arguments anyway. You'll find patterns like this in my own OpenGLContext (3D scenegraph viewer) and BasicProperty packages, as well as in Traits (originally part of a 2D graphics package), and Zope's FieldProperty (and PEAK, though as always with PEAK, it's somewhat weird in there ;) ). All of those are largish systems (or used in largish systems), btw. Just my thoughts, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Thomas Lotze wrote: >Hi, > >I think I need an iterator over a string of characters pulling them out >one by one, like a usual iterator over a str does. At the same time the >thing should allow seeking and telling like a file-like object: > > Okay, first off, this is never going to be *fast* compared to something coded in C and wrapped with Python. You are dealing with every single character as a Python object, so let's forget fast for the moment and do a straightforward implementation: class Franken( str ): frankenIndex = 0 def __iter__( self ): while self.frankenIndex < len(self): yield self[ self.frankenIndex ] self.frankenIndex += 1 self.frankenIndex = 0 def seek( self, index ): self.frankenIndex = index def tell( self, index ): return self.frankenIndex if __name__ == "__main__": f = Franken( 'abcdefg' ) for c in f: print 'char', c if c == 'c': break f.seek( 5 ) l1 = list( f ) l2 = list( f ) assert l1 == [ 'f','g' ] assert l2 == list(str(f)) print 'first list', l1 print 'second list', l2 If you want to speed it up, you can optimise for various string sizes (eg using a slice of the string and the built-in iterator when appropriate), but in the end, it's not going to be anywhere near as fast as a C-engine tokeniser, so I'd personally spend more time on elegance than on speed... Anywho, have fun, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Fire event when variable is Set/Get
Varghjärta wrote: ... But there is something that keeps bugging me, and that keeps me from embracing Python even more as a serious alternative to C#(for me). In C# I make heavy use of Get & Set, mainly to fire an event that some property has changed so that one can act on that _if one would need to. I've grown very used to doing it and it feels like the best way to make very OO and reusuable and easy to use Classes. It's fairly straightforward to implement observability for any of the various "modeling" descriptor systems out there. Attached you'll find a quick demo of how one could use BasicProperty with PyDispatcher to produce the effect. The biggest problem is that normally the particular events you want to fire are application specific. Heck, it's a toss-up whether the property or the client should be the sender of a message (basically depends on whether you normally want to filter by one or the other). The OpenGLContext vrml scenegraph has PyDispatcher-sending fields built-in if you want to see a real-world use. (We have others which use BasicProperty + PyDispatcher, but they're not Open-Source). Have fun, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com """Demonstration of observable properties""" from dispatch import dispatcher from basicproperty import basic class Observable( basic.BasicProperty ): """Sample of creating an observable BasicProperty""" SETTING_SIGNAL = "basicproperty.observable.set" def __set__( self, client, value ): """Override to send dispatcher messages on setting""" value = super( Observable, self ).__set__( client, value ) try: dispatcher.send( signal = self.SETTING_SIGNAL, sender = self, value = value, client = client, ) except Exception, err: # you'd actually want to log here... pass return value if __name__ == "__main__": from basicproperty import propertied import random class Model( propertied.Propertied ): name = Observable( "name", """The name of the object, for some purpose""", defaultValue = "Uncle Tim", ) age = Observable( "age", """How old the object is, often just a guess""", defaultFunction = lambda prop, client: random.randint( 1, 100), ) def onName( sender, client, value ): """Process a change to a Model Object""" print 'Name', sender, client, value def onAge( client, value ): """Process a change to a Model Object""" print 'Age', client, value dispatcher.connect( onName, sender = Model.name, signal = Observable.SETTING_SIGNAL, ) dispatcher.connect( onAge, sender = Model.age, signal = Observable.SETTING_SIGNAL, ) m = Model() m.name = 'Peters' m.age # note we send a message, as the default is __set__ on retrieval m.age = 18 -- http://mail.python.org/mailman/listinfo/python-list
Re: Selection, picking with PyOpenGL?
Erik Max Francis wrote: >I was interesting in adding selection and hit testing to ZOE, and was >looking at the PyOpenGL wrappers' handling of selection and picking. I >see glSelectBuffer to specify the size of the buffer, and glRenderMode >properly returns the number of hits when put back into GL_RENDER mode, >but I don't see any way within PyOpenGL itself to access the select >buffer to actually process the hits. Is there any way to do this >without using OpenGLContext? (If not, does this make sense, given that >OpenGLContext is supposed to be an additional helper library for a >gentle introduction to OpenGL?) > > I think you're missing what's returned from the glRenderMode code (which is non-standard OpenGL, to avoid the need for Python code using and decoding structured pointers), from OpenGLContext: nameStack = list(glRenderMode(GL_RENDER)) that is, you get a stack of name records (i.e. your glSelectBuffer with (near,far,names) records) back from the glRenderMode call, *not* just a count of the records produced. In general, you shouldn't *need* OpenGLContext to do anything, as all of its OpenGL code is written directly in Python to PyOpenGL's API (that was its original purpose in life, to test those APIs). It is, however, intended to provide a source for sample code showing how to accomplish effects when using PyOpenGL, so from renderpass.py: event.setObjectPaths([ nodepath.NodePath(filter(None,[ self.selectable.get(name) for name in names ])) for (near,far,names) in nameStack ]) shows you how to deal with the glSelectBuffer result, namely that it's a near value, a far value, and a set of integer names (the name stack) for each record in the set. OpenGLContext is here creating a node-path of all selectable objects from the scenegraph root to the final selected object using the nameStack and a registered set of name:node values (self.selectable). It will use those to populate the event objects that show up in the OpenGLContext mouse-event-handling APIs. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclasses and class variables
Jan-Ole Esleben wrote: >Yes, that works, but it is unfortunately not an option (at least not a >good one). > >Is there no way to create a class variable that exists during >definition of the class? (I cannot imagine there isn't, since >technically it's possible and manually it can be done...) > >Ole > > The metaclass hook occurs *after* class definition, anything using a side-effect of a metaclass hook then, *must* occur after the execution of the metaclass hook. At the time you want to write classvar.append the "class" is only a namespace, so, if you really need this feature you'll need to look elsewhere for at least *part* of the solution. A global "classvar" that, when appended to, caches values until your metaclass is called and transfers the cache to the class should *work*, but egads that's ugly compared to just classvar = [] . I guess what I'd ask is *why* is avoiding that single line so important. It could be there's a reasonable answer, but the amount of machinery required to avoid it is going to be significant. class meta( type ): newClassVar = [] def __new__( cls, name, bases, dictionary ): dictionary[ 'classvar' ] = cls.newClassVar[:] del cls.newClassVar[:] return super( meta, cls ).__new__( cls, name, bases, dictionary ) __metaclass__ = meta classvar = meta.newClassVar or something along those lines... Um, ick, but HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: PyOpenGL
[EMAIL PROTECTED] wrote: >Hey I'm a programmer looking to port some of my opengl ...although >limited into a python app I've made... I'd like to know where to find >any python/opengl source or a tutorial etc.. whatever I'd like to get a >series of points that represent a 3d slope presented to the user. > >Thanks >Matt > > That'd a fairly simple demo; you'll find a "big brother" of it in the "dots" demo with PyOpenGL (which is a particle system composed of dots (points)). OpenGLContext has a number of demos for displaying pointsets (dots), including the basic pointset test that just creates a set of 20 points or so. If what you mean is that you want to create a *mesh* from a point-set, then you need to add some more information, particularly you need a way to figure out the topological connections between points. If it's a regular x,y grid, you can readily construct the polygons, if not, you get into something a little more fuzzy. Good luck, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator and Metaclasses Documentation
sysfault wrote: >Does anyone know of any good documentation on these topics, doesn't look >like the official python tutorial covers them. Thanks in advance. > > PyCon 2005, PyCon 2004 and PyGTA November 2004 presentations here are all on these topics: http://www.vrplumber.com/programming/ Though the don't go into extreme detail on decorators (they are basically syntactic sugar for a particular type of descriptor). HTH, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator and Metaclasses Documentation
bruno modulix wrote: >Mike C. Fletcher wrote: >(snip) > > >>Though the don't go into extreme detail on decorators (they are >>basically syntactic sugar for a particular type of descriptor). >> >> >> >Err... Could you elaborate on this ? Decorators are syntactic sugar for >function wrapping, while descriptors are a 'protocol' to hook into >attribute lookup, so I don't really see how one can describe the first >in terms of the second... > > There are two major types of descriptors, the elven and the dwarven. * Elven descriptors are things like property, BasicProperty, VRML97 fields, Zope Field Properties, or PEAK's mechanisms. They mediate access to an instance's attributes, (both setting and getting of values) and are used primarily for domain modeling. * Dwarven descriptors are things like staticmethod or classmethod; function-like things that tend to look like a function and quack like a function, but have some special property or functionality attached when accessed as an attribute of a class/instance (functions themselves return instance methods or class methods depending on how they are retrieved). As you'll read in the PyCon 2005 paper pointed to, the whole set basically grew out of a generalisation of what functions were already doing (conceptually). Functions are, in short, the proto-descriptor. That is, objects which control what result is returned by attribute access (e.g. an instance or unbound instance method). Many (most?) dwarven descriptors are implemented as simple wrapper functions around the base function to use the function's already-present descriptor hooks. Decorators are syntactic sugar for defining dwarven descriptors. In Python 2.2 and 2.3 a dwarven descriptor was instantiated like this: def function( cls ): """Do something simple with the class""" function = classmethod( function ) in Python 2.4+, they can be instantiated like this: @classmethod def function( cls ): """Do something simple with the class""" technically you *could* return something that's not a descriptor from the decorator (e.g. classmethod), but it's unlikely you'd do that very often. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python image thumbnail generator?
Chris Dewin wrote: >Hi. I run a website for my band, and the other guys want an image gallery. > >I'm thinking it would be nice and easy, if we could just upload a jpg into >a dir called "gallery/". When the client clicks the "gallery" link, a >cgi script could search the gallery/ dir, and create thumbnails of any >jpeg images that don't already have a thumbnail associated with them. The >script could then generate a page of clickable thumbnails. > >A few questions: > >(1) Can this be done with python? If so, what module do I need to look up? > > PIL can certainly handle the functionality. >(2) If it can't be done with python, is there some small utility that will >do it for me? Something I could easily install locally in my own >"public_html" dir on my website? > > The core function looks something like this: import Image # this is PIL def getThumbnail( filename, size = (32,32) ): '''Get a thumbnail image of filename''' image = Image.open(filename) rx, ry = image.size[0]/float(size[0]), image.size[1]/float(size[1]) if rx > ry: resize = int(size[0]), int(round(image.size[1]*(1.0/rx), 0)) else: resize = int(round(image.size[0]*(1.0/ry), 0)), int(size[1]) image = image.resize( resize, Image.BILINEAR ) newimage = Image.new( 'RGB', size, ) x,y = image.size newimage.paste( image, ((size[0]-x)/2, (size[1]-y)/2), ) return newimage then you call newImage.save( filename, format ) to save the result. >(3) Is this the sort of thing which, if done regularly, would hog far far >too much of my webhosts system resources? > > As long as you *only* generate images for sources that don't yet have (or are newer than) their thumbnail you should be fine. >(4) Am I talking about re inventing the wheel? > > Probably. ZPhotoSlides (a Zope product) provides thumnailing, slideshows and the like, probably closer to what you'd want for this kind of application. You'll probably find other non-Zope versions as well. Good luck, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Pointers and ctypes
F. Petitjean wrote: >Le 29 Aug 2005 06:19:17 -0700, [EMAIL PROTECTED] a écrit : > > ... >You can use the ctypes.byref() function (as it is in an argulent list): > > ReadOPort.argtypes = (c_ushort, c_ushort, ctypes.POINTER(c_ulong) ) > ReadOPort.restype = c_short > status = c_ulong() # status value to be read > number = c_ushort(1) # CardNumber = 1 > port = c_ushort(11) > rc = ReadOPort(number, port, ctypes.byref(status)) > print rc, ststus > > Just as an FYI, Thomas has recently added code which does the byref automatically. The version of ctypes in CVS HEAD will allow you to pass in a c_ulong where the argtype is ctypes.POINTER(c_ulong). Have fun, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: File parser
infidel wrote: >Angelic Devil wrote: > > ... >Some time ago I was toying around with writing a tool in python to >parse our VB6 code (the original idea was to write our own .NET >conversion tool because the Wizard that comes with VS.NET sucks hard on >some things). I tried various parsing tools and EBNF grammars but VB6 >isn't really an EBNF-esque syntax in all cases, so I needed something >else. > ... You may find this project interesting to play with: http://vb2py.sourceforge.net/index.html Have fun, Mike -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Has anybody tried to make a navigation like Google?
Lad wrote: >Hi, >I would like to make in my web application a similar navigation like >Google uses, I mean at the bottom of each page there are numbers of >returned pages after you search query. >Has anyone tried that? Is there an algorithm for that? I do not want to >re-invent the wheel. >Thank you for help >La. > > First the assumptions: * We'll assume you're using SQL queries against a database * You don't want to have to produce the whole result-set across the database interface, but you don't mind producing them on the database side * You want precise values (Google's aren't precise measures of number of records) o If you don't, you can use whatever estimation mechanism you like to get the total instead of a second query * You have a complete ordering of records (if not then your results will randomly shuffle themselves as the user pages through) Given that: * You need to construct a query that produces (just) a count of all records in the set * You then need a query that is parameterised to return a subset of the records in the set o offset -- count of records from the start of the set o limit -- number of records to display on any given page Now, when you want to retrieve the records: def search( self ): """Perform the search, retrieve records and total""" self.records = self.SEARCH_QUERY( connection, whatToSelect = self.whatToSelectSubset, limits = self.calculateLimits(), orders = self.calculateOrders(), wheres = self.calculateWheres(), **self.queryParameters ) for record in self.SEARCH_QUERY( connection, whatToSelect = self.whatToSelectCount, limits = "", orders = "", wheres = self.calculateWheres(), **self.queryParameters ): self.total = record[0] In that code the SEARCH_QUERY is a PyTable SQLQuery object, it just takes care of the cross-database substitution operations. The code to handle the whatToSelect determination looks like this (by default): keyColumnName = common.StringProperty( "keyColumnName", """Column name used to count total number of columns""", #define keyColumnName on Search!, ) whatToSelectSubset = common.StringProperty( "whatToSelectSubset", """What to select in the subset-of-records query""", defaultValue = "*", ) whatToSelectCount = common.StringProperty( "whatToSelectCount", """What to select in the count-of-records query""", defaultFunction = lambda prop,client: """COUNT(DISTINCT( %s ))"""%(client.keyColumnName), ) the wheres are the natural WHERE clauses you want to apply to the query (i.e. the search terms). The orders are normally a default set of fields with the ability for the user to move any field to the front of the set via UI interactions. The "limits" are actually both limits and orders in this example, since they are tied together as the paging functionality: def calculateLimits( self ): """Calculate the limit/offset clauses for a select""" return """LIMIT %s OFFSET %s"""%( self.limit, self.offset ) Just for completeness, here's an example of a SEARCH_QUERY: SEARCH_QUERY = sqlquery.SQLQuery("""SELECT %(whatToSelect)s FROM voip.voicemail JOIN voip.voipfeature USING (voipfeature_id) JOIN voip.voipaccount USING (voipaccount_id) %(wheres)s %(orders)s %(limits)s """) The UI then offers the user the ability to increase offset (page forward), decrease offset (page backward), and re-sort (change the ordering fields). You disable the paging if you've reached either end of the record-set (offset<0 offset >= total-1), obviously. Anyway, hope that helps, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: improvements for the logging package
[EMAIL PROTECTED] wrote: >Vinay> Well, it seems a little too late now, for unittest, threading, > logging >Vinay> and probably a few more. > >Correct, as I indicated. > > ... >Vinay> What would you suggest for threading, unittest etc. in terms of >Vinay> binding more unix_like_names and deprecating existing ones? It >Vinay> seems a lot of work for not very much benefit, beyond consistency >Vinay> for its own sake. > >No, while "consistency is the hobgoblin of little minds" I think we should >strive for consistency within the core code, simply because it tends to be >used as an informal educational tool. As for the others (and logging as >well, for that matter), maybe it's just been too long to make changes and >they should only be changed in Py3K. > > I would strongly support the assertion that changing the interfaces on deployed modules just to match the style guide is not something that should happen before Py3K (that is to say, it should not happen until we simply don't care about being able to run old Python code, which is to say, a very long time). There's no reason whatsoever to break *every* piece of code that ever used a service just to support consistency in naming. Especially when you're dealing with these modules that are used in probably the majority of projects it's just a *huge* make-work project to go removing the original service (API). If someone really wants the newly-named version, create a different entry-point (module) and allow them to use that. See how popular the renamed version is as a stand-alone module where the barrier to entry is copying it in (which is far less than revising hundreds of projects to deal with a deprecation). If it flies, consider adding it to the standard library and eventually deprecating the current version. Consistency in the standard library is good. We *should* strive for it as we improve the library. But reworking elements in the standard library *just* to support consistency, at the expense of complete API incompatibility, just doesn't have a good cost/benefit ratio for the *users* of Python. A note in the docstring and documentation noting the inconsistency in naming due to historic factors would seem to be more appropriate if we're worried about emulation by users. Anyway, I realise Skip probably was using "in Py3K" in the "some unimaginably far-off time" sense, but just in case he wasn't I felt I should pipe up... Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: 64 bit Python
Mathias Waack wrote: ... My python script allocates a bunch of strings each of 1024 characters and writes it in a cStringIO. And it fails after writing 512K of strings. Don't know how python restricts the heap size - but I'm fairly sure its not a restriction of the OS. Does cStringIO require contiguous blocks of memory? I'm wondering if maybe there's something going on where you just can't allocate more than a GB of contiguous space? What happens if you just store the strings in a list (or use StringIO instead of cStringIO)? I'd imagine there might be problems with creating an individual string of multiple GB as well, for the same reason. Just an idea, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: Probably over my head... Trying to get Font Names
If you don't have a GUI library to use, TTFQuery+Fonttools will retrieve this information: from ttfquery import _scriptregistry fonts = _scriptregistry.registry.fonts.keys() fonts.sort() for name in fonts: print name if you do have a GUI, your GUI library will almost certainly have a mechanism to retrieve the list of fonts. With wxPython, for instance, it's called wxFontEnumerator. If you just want the user to choose a font, most GUI libraries already have controls/dialogues that can handle it. TTFQuery is going out, reading the .ttf fonts with Fonttools and storing their metadata in an index for faster access, whereas your GUI library will be using a simple API call to retrieve the metadata. That means TTFQuery is going to be heavier, but it can, for instance, also give you information about fonts not installed on the system. HTH, Mike TTFQuery: http://ttfquery.sourceforge.net/ Samantha wrote: I am attempting to extract the Font Names from the installed windows fonts. I am having a heck of a time getting these rather than the file names. Examples can be seen by going to Control Panel > Fonts Any help or direction is appreciated. S ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: 3d graphics
Eric Hanson wrote: Hi, I'm interested in doing some work with 3d graphics visualizations of XML/RDF data in Python. I know Python is strong on the XML front but what about 3d graphics? Is there a graphics library out there with graphics library with a fairly gradual learning curve? Do people actually use Python for games programming and the likes? Python's got a few 3D libraries: http://www.vrplumber.com/py3d.py You'll probably be most interested in a scenegraph/retained-mode renderer, listed here: http://www.vrplumber.com/py3d.py?category=retained depending on your background, VPython (or VTK/MayaVi if you're more from a science background) might be a good starting point. Soya or Panda seem more involved, but probably take you a little further toward game-like engines. Pivy or OpenGLContext (both being Inventor-style scenegraphs) are more toolkits for developers to build applications, they generally let you load and work with objects readily, but they aren't trying to provide "jumping, shooting and exploding" features out-of-the-box. Then there are the full (normally C++) game engines with Python wrappers, likely a steeper learning curve, but once you get up and running they should give you fairly easy going for writing a game. Most (commercial) games that use Python follow that last model, a C++ engine that uses Python for scripting and extensions. AFAIK there hasn't been a (commercial) 3D game (graphics engine) written with Python as the primary implementation language (for the graphics engine). Of the retained-mode renderers on that page, only a handful are primarily Python code; it takes a lot of work to get a decently performing scenegraph engine written in Python. HTH, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: Probably over my head... Trying to get Font Names
[Samantha: your email has been bouncing, might want to clear your inbox] Samantha wrote: Thanks Mike. I must have not installed the ttfquery and font tools correctly. I get an error. This error: ... ImportError: No module named fontTools Like I said I think I am way in over my short head. S Does look as though you missed getting FontTools installed. You realise it's a separate package from TTFQuery, right? http://sourceforge.net/projects/fonttools/ You'll have to do the standard: python setup.py install to get it installed on your system. HTH, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: Probably over my head... Trying to get Font Names
Samantha wrote: Mike, Not sure why that email bounced. That last one bounced too, btw. I downloaded these files: WinTTX2.0b1.exe TTFQuery-1.0.0.win32.exe numarray-1.1.1.win32-py2.4.exe They all seemed to install. Is WinTTX2.0b1.exe not the fontTools file? I believe WinTTX is a font-editing program from which fontTools was split out into a separate project. As well, though I don't *know* that this will cause problems, I'd thought fontTools required Numeric (Numpy) rather than Numarray. Would try the fontTools package first with the Numarray you've installed, and if you then find problems with it not being able to find Numeric, install the Numpy release. HTH, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: yield_all needed in Python
Skip Montanaro wrote: ... If this idea advances I'd rather see extra syntactic sugar introduced to complement the current yield statement instead of adding a new keyword. It's a bit clumsy to come up with something that will work syntactically since the next token following the yield keyword can be any identifier. You'd thus need another keyword there. Something like: I'd agree on *not* introducing a new keyword. I run into this issue every once in a while, but new keywords for minor syntactic sugar seems a bit much. # Some code here yield from foogen1(arg3) ... It would be nicer if that was yield all from I don't really like the need to look past that (potentially long) expression to see the effect of the operation. I don't mind the yield from syntax, it nicely encapsulates the learning of "generators" so that when you see yield up front you know something generatish is going on. I'd be fine with: for yield on foogen1(arg3) or for yield from foogen1(arg3) which goes more toward the idea of being syntactic sugar for a for loop that yields each value that is produced. Of course, what happens with: [ for yield from foogen1(arg3) ] would then have to be defined... that might make it too complex an change. Oh well. Have fun all, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Thomas Bellman wrote: Torsten Bronger <[EMAIL PROTECTED]> wrote: Just to amplify Thomas' statements... ... And inflexibility will always make some situations horribly daunting to get out of. Powerful constructs like these can, in some cases, enable a skilled package writer to design an API that reduces the amount of boiler plate code needed for using the package. ... The following is from the (draft of) my paper for my pycon presentation (upcoming). We see similar patterns throughout the class-type redesign, the introduction of the __new__ method which allowed for “hooking” the creation (as distinct from initialization) of an object, the __getattribute__ method for hooking all attribute access. In each case, the operations were previously “part of the interpreter” and unavailable for customization by the Python programmer, the protocols generalized the behavior, making objects themselves responsible for what was previously implemented by the interpreter, and thus was always exactly the same. That sameness was arguably a strong advantage for Python in the early days of its life-cycle. When you were handed an object (particularly, any object defined by a class), it had simple, predictable behavior. The (one) class implementation was straightforward enough that most new users didn't particularly get lost in it. Of course, the flip side was the presence of “types”, which could behave very differently, and the need for people who wanted to customize the core behavior of an object (for instance to change how attribute traversal was handled) to write C extensions. And then there was the strange exception for attribute access for functions, but that was so natural and practical it seldom bit anyone who wasn't doing meta-programming. Effectively, there were a few bits of “magic” that the Python programmer needed to understand, but the variety and complexity of the magical patterns was limited. The magic incantations could be learned readily by the acolyte, but there was a hard cap on what could be done without becoming a “wizard” and programming in C. The limits on functionality made Python a smaller and less complex language, but it also tended to frustrate the “wizards”, who, after all, might know C, but would rather either program in Python (or spend more of their time looking at really deep C, rather than creating yet another customization to support something just beyond the reach of the acolytes). So, with Python 2.2, the wizards of Python made it possible to override and customize the behavior of objects in ways that were previously impossible. They brought things that were previously “magic” (for example, the order of attribute lookup that somehow created bound instance methods) into the realm of the understandable by rationalizing the process. metaclasses and descriptors are primarily of interest to metaprogrammers, people whose target audience is other programmers. Most programmers can get along perfectly fine ignoring them save for knowing what the particular ones they *use* do. Metaprogramming is not *necessarily* a *dark* art, but it can certainly lead the way to darkness if done improperly or wantonly. When done properly, you can build systems that seem to perfectly map a problem domain into the familiar embrace of everyday Python with just the right "lived in" touches to make it seem as though the language was designed from the start to support that domain [leaving aside any questions of syntactic variants, which is its own involved debate]. When you have metaprogramming to do, it is *such* a relief when you can get it done in Python without resorting to C. Have fun all, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: 3D plotting library / OpenGL
I've got a collection of 3D libraries here: http://www.vrplumber.com/py3d.py?category=retained http://www.vrplumber.com/py3d.py?category=science My own OpenGLContext would likely handle what you've described. It's scenegraph based, can handle fairly large-ish worlds, allows for writing mouse-over and mouse-click handlers. It has text support using either 2D or 3D text, and can load VRML97 for defining geometry (spheres, crosses, and the like). It runs under wxPython, GLUT, PyGame, or (with some limitations) Tkinter. On the other hand, scientific visualisation *isn't* it's focus, so one of the items from the science category might be more appropriate. Anyway, HTH, Mike Andrew Dalke wrote: I've been looking for a decent 3D plotting library with support for user selection that works under OpenGl, preferable with wxPython. ... What I was hoping for was a toolkit that worked cross-platform and assumed OpenGL is available, leaving me to pass it the OpenGL context and a few other essentials, or something that made a scene graph that I could render as I wish. ... ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: [Newby] Problem with compilation.
There is a work-alike cross-platform "fcrypt.py" module which can be used to replace crypt on non-unix platforms. Google to find it. HTH, Mike j vickroy wrote: The Python modules documentation indicates crypt is only available on Unix platforms. ... ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling Python 2.4 extensions with free VC++ Toolkit
Jody Burns wrote (with Peter): See Mike C. Fletcher's post and http://www.vrplumber.com/programming/mstoolkit/ for a way to do it very easily (you have to be able to use the GNU patch tool, but that's not difficult at all). --Jody ... not been able to get into hacking on the core of Python because ... -Peter Keep in mind that the recipe there is for building *extensions*, not core Python. There's a pointer from my page to a post by someone who seemed to have built core Python with the Toolkit, but my page isn't going to help Peter much with hacking on core Python. Just an FYI, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: building python extensions with .net sdk compiler?
Grumman wrote: David Fraser wrote: So using MinGW seems like the better option ... is it working for Python 2.4? ... Of course it'd be nice if msvccompiler.py just fell back to looking for the toolkit/sdk default dirs (or looked them up via environment vars, since the toolkit does include a vcvars32.bat that sets appropriate ones) if the VS lookup failed. Which is what the patch here: http://www.vrplumber.com/programming/mstoolkit/ does. Have fun, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Step by step: Compiling extensions with MS Visual C++ Toolkit 2003 - msvccompiler-patch.txt (0/1)
Martin Bless wrote: ... Two things first - not to forget: (1) In contrast to what Mike writes I had to use a different registry key (see step 9) Which is expected (even noted on the page), particularly if you have a different version of the SDKs. The keys in the patch were extracted from an English Win2K Platform SDK. Don't know of any *good* way to figure out the keys in a version-agnostic manner. Suggestions welcome... (2) I don't now what people mean when talking about "msvcr71.lib". There's no such file on my machine. BUT there IS a "msvcrt.lib" a directory "C:\Programme\Microsoft Visual Studio .NET 2003\Vc7\lib". I guess the ".\Vc7\." indicates we are talking of the expected lib. Correct? I don't know. This was sloppy on my part. msvcr71.dll is the DLL used for Visual Studio 7.1, we want the .lib for that version of the DLL, but as you note, it is actually named msvcrt.lib (same as the one for Visual Studio 6.0). Get and install the platform SDK "Windows XP SP2 SDK" (about ... It is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MicrosoftSDK\InstalledSDKs\B44C7E10-89BD-4A32-A3BF-D9D0BC4C9A05 and it is not ...\63DADB24-DC99-45EB-A748-EC93AB8A7497. Find out about the correct key in your case and adjust the crucial line 133 in msvccompiler.py: freeSDK=r"SOFTWARE\Microsoft\MicrosoftSDK\InstalledSDKs\B44C7E10-89BD-4A32-A3BF-D9D0BC4C9A05" ... Will have to figure out how to make this work across SDK versions somehow. Thanks for the report, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling Python 2.4 extensions with free VC++ Toolkit
[EMAIL PROTECTED] wrote: Hi all, I've been wondering if there's anything on the drawing board about patching distutils/msvccompiler.py so that it can compile Python extensions using the free Visual C++ toolkit instead of the entire Visual C++ development environment. I've got a patch for msvccompiler.py as part of my Toolkit recipe here: http://www.vrplumber.com/programming/mstoolkit/ it seems to work fairly well for those who have tried it, and should allow MSVC 7.1 to override MSToolkit if it's installed... i.e. it should work on non-toolkit installs as well (don't have MSVC 7.1 to test that, but the changes shouldn't alter "normal" usage). I know it's possible, because I was able to compile and install PyCrypto 2.0 for Python 2.4 today. I did this by commenting out the part of msvccompiler that checks for VS library paths and manually adding them to my LIB environment variable. If you feel like it, try with the patch/recipe above. It should avoid any extra work regarding fiddling with paths on a per-package basis (though that's just because it puts the path setup into the vc7.bat file and then tells distutils to look in the environment for them). Have fun, Mike BTW, what is with that funky 7-person garbage "From:" list in your message header? Some messed-up attempt at spam-catching? Rather annoying in Thunderbird, as it generates 7 garbage "To" headers when doing a reply-to-all to catch the mailing-list. Might want to fix that... Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: save an opengl canvas (wxPython)
There's sample code in PyOpenGL and OpenGLContext for saving canvases to PNG or JPEG formats using PIL. Saving to Postscript requires considerably more work (if you're implying saving as triangles, lines and the like). There is a GPL library which lets you do this, and I have an old SWIG wrapper for it sitting around somewhere (I think, haven't touched it in years), but even then, it's fairly poor quality compared to capturing a bitmap image. Anyway, the function for reading a buffer is glReadPixels: http://pyopengl.sourceforge.net/documentation/manual/glReadPixels.3G.xml see the end of that man page for pointers to Python sample code. Good luck, Mike Zunbeltz Izaola wrote: Hi, I've a drawing made in an OpenGL canvas. I want to save it to a file (preferibly PostScript format). Somebody knows how to do it? TIA Zunbeltz ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python & nurbs
Jelle Feringa // EZCT / Paris wrote: Is anyone aware of a python nurbs module? So far I found Runar Tenfjord's effort, which is quite interesting: http://runten.tripod.com/NURBS/ But in the end doesn't really meet my needs. Any suggestions? Hint to get a useful answer: Define your needs. Display in 3D (want to use them to define and display geometry)? Numeric analysis (writing some sort of CAD or automation system)? Modeling system (want some way to interactively define them)? OpenGLContext has a set of NURBs nodes modeled after the VRML97 NURBs extension, though they don't see all that much usage. I would imagine some of the other retained-mode systems have them as well. My collection of links to retained-mode engines is here: http://www.vrplumber.com/py3d.py?category=retained If you want something for doing numeric analysis of NURBs, don't know where you'd find it. Many 3D modelers will let you create nurbs surfaces. IIRC Rhino was the pre-eminent NURBs-focused modeler a few years ago. Good luck, Mike ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: list IndexError
Ishwor wrote: i am trying to remove an item 'e' from the list l but i keep getting IndexError. I know the size of the list l is changing in the for loop & its sort of trivial task but i found no other way than to suppress the IndexError by doing a pass. any other ways you guys can suggest? Also is this a good or bad habit in Python? someone may perhaps suggest a better way which i am unaware of?? the deletion could be invoked from user input (command line) as well so its not limited to 'e'( as in my code) Probably the most pythonic approach to this problem when dealing with small lists is this: result = [ item for item in source if item != 'e' ] or, if you're using an older version of Python without list comprehensions: filter( lambda item: item!='e', source ) or even (expanding the list comprehension): result = [] for item in source: if item != 'e': result.append( item ) The "python"-ness of the solutions is that we are using filtering to create a new list, which is often a cleaner approach than modifying a list in-place. If you want to modify the original list you can simply do source[:] = result[:] with any of those patterns. If you really do need/want in-place modification, these patterns are quite serviceable in many instances: # keep in mind, scans list multiple times, can be slow while 'e' in source: source.remove('e') or (and this is evil C-like code): for index in xrange( len(source)-1, -1, -1 ): if source[i] == 'e': del source[i] Keep in mind that, in the presence of threading, any index-based scheme is likely to blow up in your face (even the filtering solutions can produce unexpected results, but they are generally not going to raise IndexErrors due to off-the-end-of-the-list operations). Good luck, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: list IndexError
Ishwor wrote: ... I believe lamda's are unnamed functions aren't they?? Still learning... ;-) Yes. yeah actually i saw what Fedrik had to say above. I created a sliced copy of the l & did my homework within the for loop You might want to check it again before you hand it in ;) ... >>> def ishwor( source ): ... for item in source: ... if item == 'd': ... source.remove( item ) ... >>> d = ['a','b','c','d','e'] >>> ishwor( d ) >>> d ['a', 'b', 'c', 'e'] Well, that worked fine, but wait a minute... >>> d = ['a','b','c','d','d','e'] >>> ishwor( d ) >>> d ['a', 'b', 'c', 'd', 'e'] This is the same problem as you saw before. Under the covers, the Python interpreter is written such that it's keeping track of the index into the list as an integer. When you mutate the list, that integer gets out-of-sync with the value you think you're processing. The while form I provided avoids that by re-scanning the *whole* list every time it does the check. The filtering forms do it by working on a temporary list. The reverse-index form does it by only deleting from the segment of the list *after* the point where the to-be-done indices reference. This code is so clean and looks very healthy. :) Python will live a long way because its a cute language. :-) Cute is, of course, the highest praise to which any man, woman or language can aspire :) . for index in xrange( len(source)-1, -1, -1 ): if source[i] == 'e': del source[i] thanx Mike, i have tried this C-ish way as well . :-) it seemed quiete ok for my small list but dont know about huge lists. It's actually *good* for huge lists where you only want to delete a few items, that's it's main attraction, it doesn't copy the list at all (though each deletion causes a memcopy of all pointers from that element in the list onward, that's a fairly faster operation). It's going to avoid new memory allocation much of the time, and doesn't have the "scan the whole list for each deletion" overhead of the "while x in list" version. Anyway, have fun, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: list IndexError
Fredrik Lundh wrote: Mike C. Fletcher wrote: yeah actually i saw what Fedrik had to say above. I created a sliced copy of the l & did my homework within the for loop You might want to check it again before you hand it in ;) ... ... that's not the code he quoted in the mail you replied to, though... Ah, my mistake, I missed the [:] after the source argument that was taking a copy... which brings up the question, how many other people would miss it? Guess it's just a matter of how often you see the pattern, so you begin to expect the [:] and either look for it or take it for granted (hmm, another source of bugs?). Apologies for any unnecessary alarm, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: twistedSnmp and hexadecimal values ...
Francesco Ciocchetti wrote: >I'm tryng to use TwistedSnmp to make query and walk directly inside my >python code. > >The problem i'm facing is that any time there is an hexadecimal value to >be returned by the snmpwalk it is returened in a weird and useless >way... does anyone had any (successfull) experience with twistedsnmp and >hexadecimal values (as Mac Addresses)? > > TwistedSNMP returns the raw (binary) values as strings. Hexadecimal "values" are just human readable presentation logic for a binary value (stored as a string). For instance, for a MAC address, we currently display it to our users using: ":".join([ '%02x'%(ord(v)) for v in mac ]) where mac is the "weird and useful" ;) value you got back. That will give you a colon-separated hexadecimal display value, which may or may not be exactly what you want. Feel free to play with the display logic to get what you feel to be a good display format. We (Cinemon) often use string sub-classes that provide extra formatting logic and apply those to the values when we get the data-values in, but that's just an artefact of how we store and process the results of the TwistedSNMP queries, not TwistedSNMP itself. BTW, more detail in a question (what result you got, what result you expected, what you did to get the result) is generally a good idea. HTH, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbiw - PypenGL and OpenGLContext
Steve T wrote: >I have been searching for a language to help with a product I am >developing - last week I discovered PYOpenGL - looks really useful. I >found some demos which I studied to create part of what I need (a heap >of boxes) but when I try and add an image to the box faces it looks as >if I have to delve into OpenGLContext. Now from here drawing boxes is >no longer as simple. My main driver is speed of _development_ (not >graphics speed) so I would really like to be able to say >box(position_vector, size_vector,texture_file). > >Am I on the wrong track entirely here, should I pursue OpenGLContext >or am I misusing the visual.* parts of PYOpenGL? > > If you are really just drawing boxes, then raw PyOpenGL *may* be appropriate, but you'll need to figure out the wonders of texturing. You can find some pretty good code for that in the NeHe demos (I believe around the 6th or 7th). They create a rotating textured, lit box, so if that's all you need, you're golden. If your goal is to eventually produce a more involved scene, you will likely want one of the scenegraph engines. Obviously I'm biased toward OpenGLContext, but it's visual-alike package (i.e. a simplified scenegraph model) is not yet ready for prime time, so you'd have to use the full VRML97 model to create your boxes. That would look something like this: from OpenGLContext import testingcontext BaseContext, MainFunction = testingcontext.getInteractive() from OpenGLContext.scenegraph.basenodes import * class TestContext( BaseContext ): def OnInit( self ): """Initialise and set up the scenegraph""" self.sg = sceneGraph( children = [ Transform( rotation = (0,1,0,.8), children = [ Shape( geometry = Box( size=(4,4,2) ), appearance = Appearance( material = Material( diffuseColor =(1,1,1) ), texture = ImageTexture( url = "http://blog.vrplumber.com/images/ruminations.jpg";, ), ), ), ], ), ], ) def getSceneGraph( self ): """With older OpenGLContext versions need to explicitly return this""" return self.sg if __name__ == "__main__": MainFunction( TestContext ) There are other retained-mode/scenegraph engines available besides OpenGLContext, you can find a listing of some of them here: http://www.vrplumber.com/py3d.py?category=retained HTH, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting Font Outline informations
TTFQuery, built on top of FontTools, allows you to do this. You can see use of the extraction in the OpenGLContext/scenegraph/text package, which uses TTFQuery to implement 3D text rendering. http://ttfquery.sourceforge.net/ http://pyopengl.sourceforge.net/context/ HTH, Mike Gabriele *Darkbard* Farina wrote: > Hi, > > there is a Python library that makes me able to extract outline > informations from font files? I'd like to manage TrueType and FreeType > fonts ... > > I searched for som wrappers, but I didn't find anything ... > > bye ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: preallocate list
Jim wrote: > Thanks for the suggestions. I guess I must ensure that this is my > bottle neck. ... > for line in f: > factor = [] > tokens = line.split() > for i in tokens: > factor.append(float(i)) > factors.append(loadFactor) > ... You might try: factors = [ [float(item) for item in line.split()] for line in f ] avoiding the extra statements for appending to the lists. Also might try: factors = [ map(float, line.split()) for line in f ] though it uses the out-of-favour functional form for the mapping. Good luck, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Any movement on FreeBSD segfaults when using threads?
There was a post a few months ago from "snacktime" in which they described a failure when running under Twisted: http://mail.python.org/pipermail/python-list/2005-February/265137.html which they eventually narrowed down to an apparent problem with pycrypto: http://mail.python.org/pipermail/python-list/2005-February/265146.html and which generated this sourceforge bug report for Python: http://twistedmatrix.com/pipermail/twisted-python/2005-February/009475.html http://sourceforge.net/tracker/index.php?func=detail&aid=1080660&group_id=5470&atid=105470 I am seeing a similar effect, (though only after the program has been running a few days), in one of our products running on FreeBSD 5.3-RC2 with Python 2.3.4, PyOpenSSL 0.6, Twisted 2.0, and PyPgSQL 2.4 (which is somewhat different than snacktime's library collection (different OpenSSL and PostgreSQL bindings)). Note particularly, that the PyCrypto library to which the problem was apparently localised is *not* installed on the failing machine. As with snacktime, I see the failure coming from pthread_testcancel() (gdb) bt #0 0x28222f17 in pthread_testcancel () from /usr/lib/libpthread.so.1 #1 0x2821b39f in pthread_mutexattr_init () from /usr/lib/libpthread.so.1 #2 0x in ?? () I haven't been able to isolate the failures to a particular piece of code (this is showing up on a live server, so I'm hesitant to run under gdb for a couple of days to try to catch the failure). I'm *not* using RSA encryption (which was the area to which snacktime localised their problem). I *do* use SSL sockets from Twisted, however. I am running a background thread for database access, with a Queue mediating the set of items to process and reactor.callFromThread returning control to Twisted when the items are finished. Anyway, my question is really "has this been solved already"? If so, what was the solution? If not, I'll have to work at building a minimal failing test case so I can begin to debug it. Thanks for any information, Mike -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Object Systems
On 14-08-11 04:26 PM, thequietcen...@gmail.com wrote: ... Hello, has anyone created a survey of Python Object Systems? The two I am aware of are: - elk https://github.com/frasertweedale/elk - Traits http://code.enthought.com/projects/traits/ Here's the ones from my talk at Pycon 2005 (http://www.vrplumber.com/programming/descriptors-pycon2005.pdf): OpenGLContext/PyVRML97 http://bazaar.launchpad.net/~mcfletch/pyvrml97/trunk/files Observable, auto-coercing data properties w/ Numeric/numpy array support, defaults BasicProperty (now largely abandoned): http://bazaar.launchpad.net/~mcfletch/basicproperty/trunk/files Again, observable auto-coercing typed properties, defaults, introspection Zope2 FieldProperty, DublinCore, Validation, Observability PEAK Defaults, delegation, implicit feature loading Traits Delegation, typing, validation, defaults, Observability, introspection PyObjc, ctypes, JythonC, IronPython Function-like things with lots of metadata There's also a listing of the other tasks for which descriptors/object systems were expected to show up at the time, if you look for Python + that key-word you'll likely find a few dozen more "object systems" out there. You'll also likely find about a thousand metaclasses these days. HTH, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- https://mail.python.org/mailman/listinfo/python-list
Re: logging: warn() methods and function to be deprecated.
On 11-10-24 04:28 AM, Vinay Sajip wrote: >> I think that is a real shame - it seems to be gratuitous breakage for almost >> zero benefit. That issue shows that Trac makes heavy use of .warn, I've use >> .warn almost exclusively for many years, and code.google.com shows it is >> used >> extensively in the wild. > Okay, but it's easy enough to change, and people are getting a reasonable > amount of time to deal with it. I'd have to echo Mark's sentiment here. There is a *lot* of (fairly old) code around that uses .warn, and I'd wager even a lot of new code written by old programmers (such as myself) that uses it. Breaking it to avoid having an undocumented method seems wrong; suggest just adding documentation: "logger.warn(...) -- an alias to logger.warning provided for backward compatibility" >> Is there still a chance to reconsider? > I'm not dogmatic about things like this; warn() is just a hangover from a > long time ago and bit of a nit, that's all. I suppose I should have removed > it when 3.0 was released, but it went under my radar at that time. > > Hence my post here, to get feedback from logging users about this proposed > change. I actually consider .warning() a nit :) . After all, it's 3 extra characters :) , and *who* actually reads documentation instead of just poking around and finding the shortest-named method in the instance? Anyway, I personally don't see this as worth the breakage. Just my $0.02, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: logging: warn() methods and function to be deprecated.
On 11-10-26 05:12 AM, Vinay Sajip wrote: > Mike C. Fletcher vrplumber.com> writes: > >> I actually consider .warning() a nit :) . After all, it's 3 extra >> characters :) , and *who* actually reads documentation instead of just >> poking around and finding the shortest-named method in the instance? > Readability counts :-) Are you saying there's no need to bother documenting > stuff ??? ;-) More: an undocumented entry point is not "deprecated" because, after all, it shows up in PyDoc as a regular method. > >> Anyway, I personally don't see this as worth the breakage. > > What breakage are we really talking about? Remember, Python 2.x will not > change > in this area - the proposed change is for Python 3.3 and later only, and will > not be backported :-) > > As far as I know, Trac doesn't work with Python 3 anyway. Most of the code out > there (which Mark found via Google Code Search) is Python 2.x. When porting > from > 2 to 3.3, it's just one extra little thing to deal with - small compared with > other issues which come up when doing such ports. Sure, but most of *everything* is Python 2.x, and porting to Python 3.x is already enough of a pain that key-stone projects like Trac still aren't there :) . This isn't going to be easily amenable to auto-translation via 2to3 (because you generally are calling log.warn() rather than logging.warning, but sometimes you are doing getattr( log, log_level ) and then passing that method around a few times), and it will often fall into the small percentage of untested code in most projects (coverage is often poor for logging messages in corner cases), so often won't get caught by test suites. Not a 3.x user, but expecting to have to be some day in the future, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: logging: warn() methods and function to be deprecated.
On 11-10-26 10:51 AM, Vinay Sajip wrote: ... > auto-translation via 2to3 (because you generally are calling log.warn() >> rather than logging.warning, but sometimes you are doing getattr( log, >> log_level ) and then passing that method around a few times), and it > That doesn't sound like a good usage pattern to me, especially as loggers > have a > log method which takes the logging level. There shouldn't be any need to pass > a > bound method around. Bound methods also pull along to *which* log you are going to send the message, but then I suppose you could just use the logging key as well as a piece of data. I'll withdraw the suggestion that it is not a trivial thing to add to 2to3, though I'll leave the implementation to someone else. Have fun, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: memory leaks - tools and docs
On 11-11-24 10:00 PM, Aljosa Mohorovic wrote: > i've been trying to find memory leaks in a wsgi application using > gunicorn to run it and after a lot of time invested in research and > testing tools i did find a lot of useful information (most really old) > but i'm left with a feeling that this should be easier, better > documented and with tools that generate better data. > > if anybody can share some tips, links, docs or better tools with > better reports i would really appreciate it. > i'm not against paying for a good tool so any recommendation is > appreciated. > > i mostly used http://guppy-pe.sourceforge.net/#Heapy but found > http://pysizer.8325.org/ and http://code.google.com/p/pympler/ also > interesting. > > Aljosa Meliae is a similar tool wrt collecting memory-usage information. RunSnakeRun can process Meliae dumps to produce visualizations of the memory used in the process. HTH, Mike https://launchpad.net/meliae http://www.vrplumber.com/programming/runsnakerun/ -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess module and long-lived subprocesses
On 12-01-20 09:42 AM, s...@pobox.com wrote: > I'm converting some os.popen calls to use subprocess.Popen. I had > previously been ignoring stdout and stderr when using os.popen. The primary > motivation to switch to subprocess.Popen now is that I now want to check > stderr, so would have to make code changes to use os.popen[34] anyway. > Might as well go whole hog and switch to the new API. > > The library documentation doesn't talk a lot about long-lived subprocesses > other than the possibility of deadlock when using Popen.wait(). Ideally, I > would write to the subprocess's stdin, check for output on stdout and > stderr, then lather, rinse, repeat. Is it safe to assume that if the stdout > and/or stderr pipes have nothing for me the reads on those file objects (I'm > using PIPE for all three std* files) will return immediately with an empty > string for output? They won't block, will they? Will a broken pipe IOError > get raised as for os.popen() or do I have to call Popen.poll() even in error > situations? > > Thanks, > Definitely *will* block, you have to explicitly set them non-blocking to have non-blocking behaviour: def set_nb( fh ): """Set non-blocking flag on given file handle""" if isinstance( fh, int ) or hasattr( fh, 'fileno' ): flags = fcntl.fcntl(fh, fcntl.F_GETFL) fcntl.fcntl(fh, fcntl.F_SETFL, flags| os.O_NONBLOCK) on each of the 3 buffers, then you need to attempt read/write on each of them periodically, catching the EWOULDBLOCK errors, to prevent deadlocks where the buffers have filled up (e.g. because the subprocess is printing out errors on stderr, or because it is generating output, or because for some reason the process isn't reading your input fast enough). I think everyone winds up with their own wrapper around subprocess after they use it for more than a short period... HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: PyOpengl text rendering with autocad font
Marco wrote: >I must use text in Opengl, Python >This text is for architecture design then I need to use AutoCad fonts >(extension .shx). >I have two troubles: > >I don't find a guide, a good program, something for use any kind of >fonts in PyOpengl. The nehe tutorial has some bugs in translation to >Python. >I need to scale rotate the text. > > For general font rendering you can choose two major approaches, either use a built-in platform-Dependant system (such as seen in the NeHe tutorial) or code your own to render the individual characters using either one of the cross-platform GUI libraries (2D text) or TTFQuery (3D/polygonal text (i.e. you can rotate in all 3 dimensions)). There is a NeHe tutorial translation for the font-rendering demo in OpenGLContext's tests directory. To render text in general, see the OpenGLContext/scenegraph/text/* modules. However, none of those knows how to handle .shx files, they load TTF fonts instead. >I don't know anything about handling fonts, I must use this .shx but I >don't know. In which way can I take this file and put them in my >programs? > > If you can find a format specification you may be able to write an importer (IIRC SHX fonts are just series of lines, so would be very easy to render once you have the format read). You might find it easier to redefine the process as "tell autocad to use truetype, then render truetype" if whoever is asking for .shx will allow it. >If somebody wants to help me :-) >Thanks. > > HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Limiting the size of List and making it Homogeneous
Little class that does restrictions/checks on adding to a list (simply subclass and put your restrictions in the beforeAdd or beforeMultipleAdd methods). http://pytable.sourceforge.net/pydoc/basictypes.rlist.html http://cvs.sourceforge.net/viewcvs.py/basicproperty/properties/basictypes/rlist.py?view=markup Note, however, that if you goal is to create a simple C-level pointer of machine ints you'll need to use Numpy or a similar system that implements such a type. Have fun, Mike ankit wrote: >Is it possible to limit the size of list in python. >I want to make list of 5 elements. How can I achieve this thing in >python. And one more thing can we declare list to store elements of >same type as in c, C++ we can declare an >array which can have 5 elements of type int. >C, C++: > int intarr[5] >How can I achieve this kind of behavior ? > >Thanks > > -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting results from a large hotshot profile
Brian Cole wrote: ... >I did a hotshot profile. To make this profile took >about a day. However, I've been trying to extract results from the >profile for the past two days. It's eating up all the memory (2G >memory) on the machine and is slowing sucking up the swap space >(another 2G). > >I'm hesitant to kill it for I might get results out of it some day >(even if I may have to bequeath them to my grand-children), but is >there a better way to do this? > > ... >The profile is 355 MB large. Is there anything I can do to extract that data? > > You might want to try my RunSnakeRun utility: http://www.vrplumber.com/programming/runsnakerun/ It's designed to load large hotspot runs. I've never had a 355 MB one, but I regularly load 140+MB ones on a desktop 1GB machine. It does an incremental load, so you start to see results as soon as it starts running and continues loading the data-set in the background (it can take quite a while for the full data-set to load, but I don't *think* it should run out of RAM). In case you don't want the GUI, the package includes the core hotshotreader module that actually does the incremental loading, you could use that to produce a view by writing code to display the results statically. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting results from a large hotshot profile
Brian Cole wrote: >Thanks for the tip. I got the following error message when trying to >run your profiler. > > ... > File "c:\Documents and Settings\coleb2\My > Documents\software\Python24\Lib\site >-packages\runsnakerun\hotshotreader.py", line 95, in loadHotshot >localDeltas[depth] = 0 >IndexError: index out of bounds > > ... >As the traceback shows I'm running this on Windows. I'm gonna go >wrestle with installing wxPython and Numeric on my Linux box and see >if that makes a difference. > > Not likely. The hotshotreader module is creating an array of sys.getrecursionlimit() long integers to store the accumulated local times. It does the same to track the number of frames. Most likely your main program is setting sys.getrecursionlimit explicitly and as a result it winds up with a larger possible stack. You can try replacing the sys.getrecursionlimit() calls with some big number (say 40,000, or just multiply the recursion limit by 10 or 20 if you like) and see if that solves the problem. Probably should allow for setting the value on the command-line I guess. I suppose there may also be cases where a recursive call to the interpreter gets a whole separate stack... or maybe there's something going on with threads intermixing to create greater depth. Let me know if that helps, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: 3D Vector Type Line-Drawing Program
James Stroud wrote: > James Stroud wrote: > >> Hello All, >> >> I'm looking for a program to do line-drawings in 3d, with output to >> postscript or svg or pdf, etc. I would like to describe a scene with >> certain 1-3d elements oriented in 3d space with dashed or colored lines >> and filled or transparent surfaces (or maybe semitransparent). >> >> I would then like to set the camera and have the scene depicted as a >> line drawing (not ray-traced solid body, etc). >> >> Does anyone know of a library to do this? >> > > > I'm really looking for a python library. The title of the post is kind > of misleading. > At one point I created a gl2ps wrapper for use with PyOpenGL, that, combined with any of the PyOpenGL-based renderers would allow much of what you're describing, though IIRC it didn't properly support transparent or textured surfaces. You could probably recreate the wrapper using ctypes in a few hours and then hook it up in a few more. I believe there are similar OpenGL-to-SVG libraries here and there, you could likely hook one of them up to get a reasonable result that would support more graphics features (maybe). Generally what you get out of these things, however, is a quite fragmented view of your objects (that is, you get the triangles that would be rendered). That *can* be coded around, but generally people are either focused on making it look good or making it editable. Good luck, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Python OpenGL difficulties
[EMAIL PROTECTED] wrote: > I'm beginning learning Python and OpenGL in Python. > > Python fine. But difficulties with OpenGL; presumably with the > installation of OpenGL. > > OS = Linux FC5. > > Python program gl_test.py: > > from OpenGL.GLUT import * > from OpenGL.GLU import * > from OpenGL.GL import * > > name = "Hello, World" > height = 400 > etc. > > [EMAIL PROTECTED]/etc/python>$ python2 gl_test.py > > Traceback (most recent call last): > File "gl_test.py", line 1, in ? > from OpenGL.GLUT import * > ImportError: No module named OpenGL.GLUT > > [EMAIL PROTECTED]/etc/python>$ echo $PYTHONPATH > /usr/lib/python2.2/site-packages/OpenGL > You should already have site-packages in your PythonPath. You want the directory *above* OpenGL in the path, not OpenGL itself. I'm unsure why you're running a Python 2.2 instance on a modern Linux. I'd suspect that you're using an RPM for an older Linux? Not sure there, I run Gentoo, so everything builds from source for the packages that are installed. There are some Fedora Core build patches in CVS that are waiting for me to get my posterior in gear with Win32 testing to be released. Not sure if that would change anything for you, though. Good luck, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: simpleparse parsing problem
David Hirschfield wrote: > Anyone out there use simpleparse? If so, I have a problem that I can't > seem to solve...I need to be able to parse this line: > > """Cen2 = Cen(OUT, "Cep", "ies", wh, 544, (wh/ht));""" > ... > expr:= termlist, ( operator, termlist )+ > I *believe* you wanted that to be *, not + Best way to write a SimpleParse grammar is from the ground up, using test cases, so test each thing you think you're parsing. Makes it much easier to spot situations like this. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: does anybody earn a living programming in python?
walterbyrd wrote: > If so, I doubt there are many. > > I wonder why that is? > I've now used Python in every job I've had for the last 10 years. Started off with web-sites for a few months, then writing VRML-processing libraries to piece together and massage virtual worlds (not a *lot* of jobs there). After that worked on a piece of Cable-system SNMP monitoring software (again, not a *lot* of jobs in that). After that billing/provisioning systems for VoIP (you really only need one). The last two companies (one of which I own, one in which I was a partner) were python-only shops. PyGTA (Toronto Python User's Group), which is a fairly large user-group, seems to be about 60% (off-the-cuff estimate) paid Pythonistas, with some people picking it up for filling in corners and others spending all day working on it. The paid positions tend (like most programming positions in less-well-known general-purpose languages) to be programming + X for values of X which are a problem domain having an obscure nature. That is, boutique/bespoke development that requires some specialisation such that the customer is willing to go for whatever language is suitable and gets the job done. Regarding Java from one of the previous comments (and this is a cynical moment here, I'm really a far more positive person, just ignore this): There are still lots of jobs in Java, just as there are still lots of jobs in COBOL. Kids in the know (i.e. who *love* programming, rather than just wanting a job) going into university are minimising their Java exposure so that they don't box themselves into the big-old-company environments that have locked themselves into Java while everyone else moves onto the more dynamic languages/platforms. Job security and easy availability is not the be-all and end-all of happiness in life. That said, if you know anyone who "just wants a job", please, push them at Java, someone has to spend the next 30 years maintaining the Struts and J*EE sites people are putting together today in all those big institutions. Have fun, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: "fork and exit" needed?
Vincent Delporte wrote: > On Thu, 30 Nov 2006 15:38:11 +0100, Vincent Delporte <[EMAIL PROTECTED]> > wrote: > >> Here's my Python rewrite: >> http://codecomplete.free.fr/asterisk/python_cid.txt >> First line of your script should be: #! /usr/bin/env python which is how Linux knows what interpreter to use for the script. HTH, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pyopengl glShaderSourceARB error
joroy wrote: > Hi all, > > I think this is ctypes related but how can I call the glShaderSourceARB > function? > > The function have this header: > > glShaderSourceARB( GLhandleARB(shaderObj), GLsizei(count), > POINTER(arrays.GLcharARBArray)(string), GLintArray(length) ) -> None > > I call the function with someting like: glShaderSourceARB(self._object, > 1, sourceString, 1) > > The error is > "expected LP_GLcharArray instance instead of str" > > In fact I don't have any information on how to use this function. > This is the last version of pyopengl available on the CVS > (PyOpenGL-3.0.0a5-py2.5.egg) > Sorry about the lack of information available. There's a sample of usage here (known to work on Win32 and Linux with latest CVS HEAD): http://pyopengl.cvs.sourceforge.net/pyopengl/OpenGLContext/tests/shaderobjects.py?view=markup The key information you seem to be missing are that the Python version has a simpler API and that you have to pass an array (list) of strings, not just a single string to the compilation function. The count and length (array of lengths) parameters are pulled from the list-of-strings you pass. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclass uses?
Nathan Harmston wrote: > Hi, > > Recently I posted a question about the factory pattern in python. I ve > implemented this following one of the ideas posted. After some reading > I ve seem a lot of Aspect Oriented Programming mentioned but I m not > really sure what it is. > > Can anyone help me understand how metaclasses can improve the quality > of my code and let me do better things. > My presentation from three pycons ago was an attempt to address this issue (what metaclasses are useful for): http://www.vrplumber.com/programming/metaclasses-pycon.pdf HTH, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Traceback of hanged process
Klaas wrote: > Hynek Hanke wrote: > >> Hello, >> >> please, how do I create a pythonic traceback from a python process that >> hangs and is not running in an interpreter that I executed manually >> or it is but doesn't react on CTRL-C etc? I'm trying to debug a server >> implemented in Python, so I need some analog of 'gdb attach' for C. >> ... > In python2.5, you can run a background thread that listens on a port or > unix socket, and prints a formatted version of sys._current_frames() to > stderr. > You can also use the signal module to similar effect. Works well in Twisted, at least: http://blog.vrplumber.com/835 HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: OpenGL
NaeRey wrote: > If you notice the project died, being latest release Jan2 2005. Thats > over a year old. > Died, no. We have a rather small developer community, basically myself and a few people who contribute a module here or there. Most (really, all) of the time being spent on PyOpenGL these days is focusing on the OpenGL-ctypes implementation, which hopefully will let far more people work on the source-code (and add features and coverage of more extensions). Have fun, Mike -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: OpenGL
[EMAIL PROTECTED] wrote: > Does that mean PyOpenGL is based on ctypes ? > PyOpenGL, the project with releases, binaries on most platforms, and lots of history is currently written in SWIG. It was originally written in pure Python C-extension code, then Tarn rewrote it using SWIG a few years ago. OpenGL-ctypes is in the PyOpenGL CVS repository, it's a ctypes re-re-implementation of the same Python API to OpenGL. My intention is that the ctypes implementation will become the 3.0.0 release when it is finished and optimised. If there's time and enough interest I'll try to produce another maintenance release for PyOpenGL-SWIG, but I'm really quite tired of spelunking through dozens of levels of C-code macro expansions, so I'm not all that interested in working with the codebase. > I thought is was using SWIG ? > And on that note: I have some (old) SWIG typemaps for numarray arrays > that I'm using for many years. > > I was always wondering how difficult it would be for me to add them > into PyOpenGL ? > Likely difficult, for the SWIG version. You might be able to *substitute* them quite readily for the Numpy mapping, but having the APIs support two different numeric systems requires some API to switch between them, which requires rewriting the (really-deeply-embedded) typemaps to support that. The difficulty of doing that kind of change is part of what prompted me to rewrite the system in Python (using ctypes). > So far I'm just using my own (one !) OpenGL function with that typemap > to draw 6 vertices in a vector linestrip. But I would like to not > have to resort to "string conversion" when for example drawing 2D > typemaps... > > Anyway, thanks a lot for PytOpenGL - my program (image analysis > platform and microscope control) would not be possible without it. > Sebastian Haase > OpenGL-ctypes is designed with a fairly well abstracted array-handling API. Basically any array type can be registered with handlers that let you tell the system how to do basic operations; get an array's size, shape, data-type, convert to a given data-format, build an "empty" array of a given size, that kind of thing. I haven't written a numarray one yet, but it should be a fairly trivial change from the Numpy/scipy-core module. Have fun, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Collecting snmp data - threads, processes, twisted?
Antal Rutz wrote: ... > I'd like to collect snmp data from varoius network devices parallel. > ... > Could you give me some advice how can I make my script really parallel? > > My options maybe: > 1. pySNMP (as it's full in python) > 2. subprocess (I'd like to make (find) a solution as threadpool.py) > (running yapsnmp, pySNMP or even net-snmp?...) > 3. TwistedSNMP (seems too weird for me.. cannot imagine a simple > solution for my problem) > This kind of parallel mass-query operation is TwistedSNMP's primary focus (it was created for a commercial product that scans thousands of agents). If you really want all of the queries to run in parallel (i.e. send out all the queries within milliseconds of each other): agents = [ ... ] dl = [] for agent in agents: dl.append( agent.get( (oid,oid,oid) ) ) return defer.DeferredList( dl ) add a callback to the DeferredList which processes the (success,result_or_failure) list you get back. If you want to process individual results/failures before the whole set returns, add the callback for that to the agent.get() result. If you have thousands of devices you'll likely want to batch the queries into ~ 200 simultaneous queries and/or use multiple protocols (gives you more OS-level buffering). Have fun, Mike ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Where do they tech Python officialy ?
NicolasG wrote: ... > I'm planning to save some money and attend a course in any of the > universities that teach hard core Python. > > Does some one have any suggestions on which University to attend ? > In Canada, the University of Toronto is planning to switch all first-year Comp-Sci courses to Python this September. Last I heard the University of Waterloo allowed Python submissions for most assignments in most courses. But those are "learn hard-core computer science using Python" solutions, not "learn hard-core Python" solutions. If you really want to learn hard-core Python, probably your best bet is: * read everything Tim Peters has ever written in comp.lang.python (this will take a few months), start with "import this" * read everything the PyPy guys have ever written (particularly Christian and Armin) * read and try to beat the more exotic recipes in the Python cookbook * read the papers from the various PyCons on metaclasses and the like, build a couple of dozen metaclasses and descriptors But jumping into "hardcore" first might not be the best approach. Many would suggest just learning "normal" Python first, *then* moving onto the hardcore stuff. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Call for advice on how to start PyOpenGL!
math2life wrote: > I work with python for two years, are familiar with image processing, > but beginner on PyOpenGL and OpenGL. > > Any advice appreciated! > As has been mentioned, the NeHe tutorials[1] are a good starting point. There are (multiple) translations of the first 8 or so and then some cherry-picked translations further along the set. There is a set of OpenGL demo/sample code available[2] as a separate download from the 3.x series (these files are mostly included in the 2.x series, though there is new material in the 3.x set). OpenGLContext also has a large number of simple samples, though I've still got "release OpenGLContext" on my seemingly infinitely long and growing todo list, so that might not be the easiest way to start. The "Red Book" is an older standard manual for getting started with (C) OpenGL code, often you can find older editions online for free. There are hundreds of C tutorials hanging around the net that normally translate easily into Python/PyOpenGL. The PyOpenGL manual pages *try* to have links to source code, but unfortunately the (java, ick!) based system that generates the base files has been broken for a while and I haven't had time to fix it properly so I can re-run the generator to update the links. In the meantime, Google's code search helps a lot when you restrict to Python code.[3] HTH, Mike [1] http://nehe.gamedev.net [2] http://sourceforge.net/project/showfiles.php?group_id=5988&package_id=221827 [3] http://www.google.com/codesearch?q=lang%3Apython -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Question: wxpython and 3d engine example with model load ?
OpenPavilion wrote: ... > I would like to create an application, which uses wxpython tree, menu > and grid elements and embedds a 3d view of some of the listed objects > in an own detail window, so showing the object as a 3d model. > I know there is PyOpenGL as well, but I need to load complete models > (meshes done with cinema4d or blender) into the 3d view. > There's a bit of sample code in OpenGLContext/bin (yes, yes, I know, part of PyOpenGL, which you don't want) that does a VRML-97-scenegraph-rendering window + a shell (you'll need the latest CVS version to work with modern wxPythons). There's commented out code that inserted a tree (to show the scenegraph as a tree, but I haven't got that finished). Other options: * I think Pivy (Coin/Inventor wrapper) could likely be embedded in PyQt (it has a Qt-based window operation IIRC) if that's an acceptable compromise. * http://www.python-ogre.org/wiki/DownloadsPage seems to suggest there's an example for using Ogre with wxPython/wxWidgets. * http://panda3d.org/phpbb2/viewtopic.php?=&p=11555 suggests there's a way to get panda3d and wxPython working together I don't see a soya + wxPython page in a few seconds of googling, so I guess finding that is left as an exercise for the reader. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python GUI + OpenGL
Achim Domma wrote: > Hi, > > I'm developing a GUI app in Python/C++ to visualize numerical results. > Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there > are no windows binaries for Python 2.5 for quite some time now. > > I need a OpenGL context without restrictions and some settings dialogs. > Is wx + PyOpenGL the way to go? Or could somebody recommend a better set > of tools/libs? > > regards, > Achim > PyOpenGL 3.x (currently in alpha state, but reasonably usable) works on Python 2.5, there are no binaries because the system no longer requires binary versions. Install the setuptools package, then run easy_install PyOpenGL and the egg file should be downloaded and installed to your machine. The current version doesn't package GLE along with the code, however, so you'll have to find a DLL for that if you need it. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: interpreting glyph outlines from ttfquery?
Wojciech Muła wrote: > swiftset wrote: > >> I'm try to convert a glyph into a format I can easily numerically >> manipulate. So far I've figured out how to use ttfquery to get a list >> that represents the outline of a contour in a glyph: >> >> from ttfquery import describe, glyphquery, glyph >> f = describe.openFont("/usr/share/fonts/truetype/freefont/ >> FreeSans.ttf") >> n = glyphquery.glyphName(f, 'D') >> g = glyph.Glyph(n) >> c = g.calculateContours(f) >> o = glyph.decomposeOutline(c[1]) >> >> o looks like: >> >> [array([182, 82],'s'), >> (354, 82), >> (420.29, 90.014), >> (474.91, 114.0), ..., >> array([182, 82],'s'), >> array([182, 82],'s')] >> >> Is this a polyline? >> > > decomposeOutline docstring confirms -- it's a polyline. I think > elements marked with 's' starts new subpath. > > w. > Examples of rendering self.contours and self.outlines (created by self.compile on the Glyph) using OpenGL operations are in the toolsfont module in OpenGLContext: http://pyopengl.cvs.sourceforge.net/pyopengl/OpenGLContext/scenegraph/text/toolsfont.py?view=markup The outlines are simple 2D line-loops, the things with 's' are array objects (not start coordinates), you can convert the whole thing to a consistent array with numpy.array (or Numeric.array). That is, the 's' is just an artefact of how the calculation was done, the values are all 2-element coordinates, some as Python tuples, some as 2-element Numeric/numpy "short" arrays. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: PyDispatcher question
Jorgen Bodde wrote: > Hi all, > > Hopefully someone can help me. I am fairly new to Python, and I am > looking into PyDispatcher. I am familiar with the C++ sigslot variant, > and I wonder how similar PyDispatches is. I run in to the following > 'problem' (pseudo code, untested here) > Here's some real code... from pydispatch import dispatcher import gc class X(object): def __init__( self ): dispatcher.connect( self.someSignal, signal=1 ) def someSignal( self ): print 'hello world' obj = X() dispatcher.send( signal= 1 ) del obj #gc.collect() dispatcher.send( signal= 1 ) This will print out only one "hello world" on my Python 2.5 Gentoo machine (it should work the same on any recent Python). Basically your python shell will tend to keep around an extra copy of the X instance until you get rid of it explicitly, and that's what keeps the object "live" and receiving signals if you try the code in the shell. PyDispatcher is designed so that, by default, when the object goes away the registration is removed. It uses the weakref module to do this, rather than __del__ methods, to avoid garbage cycles, btw. HTH, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Python's interpreter
Steve Holden wrote: > Rafael Almeida wrote: > ... > Because they aer smarter than you, without wishing to be too rude. > Replace that with "more experienced", please. Otherwise it is a bit rude, despite your wishes. We've always been newbie positive on Python-list, and new compiler writers are just as important educational targets as new Python programmers. Have fun, Mike -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: TwistedMatrix missing OpenSSL?
Lamonte Harris wrote: > Where can I get it? Anyone got any idea? http://www.voidspace.org.uk/python/modules.shtml#pycrypto Might help. Mike > > Where do I get it? I'm currently running python 2.5 > > On 10/4/07, *Lamonte Harris* <[EMAIL PROTECTED] > <mailto:[EMAIL PROTECTED]>> wrote: -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame and python 2.5
[EMAIL PROTECTED] wrote: > Ben> Python extensions written in C require recompilation for each new > Ben> version of Python, due to Python limitations. > > Can you propose a means to eliminate this limitation? > Sure, write your wrapper-style extensions in ctypes :) . For example, pygame-ctypes[1] should work on Python 2.5. Of course, you need to get the PyGame dependencies (SDL) installed via some external mechanism, but the ctypes-based code should run in Python 2.5 today (with the caveat that it's not finished software). [1] http://www.pygame.org/ctypes/ Have fun, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Saving PyOpenGl figures as ps
Frank wrote: > Hi, > > I installed pyopengl (opengl for python) on my linux box and > everything works fine. But now I want to save the generated images as, > e.g., ps or eps. How can I do that and how can I adjust the resolution > (if necessary)? This is probably simple but for some reason I can not > find out how to do that. > > I appreciate every hint! > > Thanks, Frank > Hi Frank, Take a look at the demos in OpenGL, particularly: OpenGL-ctypes/OpenGL/Demo/GLUT/tom/conesave.py which is a little GLUT application that renders into a GLUT windows and then allows you to save it. That's raster operation though (i.e. produces a PNG or JPG). Raster operations can only save a portion of the screen as rendered, so if you want a higher resolution image you need to make a larger window. If you want to get more advanced you can try using an off-screen buffer (pbuffer or MESA) for the rendering, which may (depending on implementation) allow for higher resolutions. If you want a true vector graphic (PS, EPS) you'll need to use something like GL2PS. http://www.geuz.org/gl2ps/ HTH, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Dlls
Jason Ward wrote: > Hi. I am interested to know why python can't access DLL files directly. > It seems to me that because python can't access DLL's directly we have to > waste our time and write wrappers around libraries that have already > been written. > > So if the python developers were to implement say this. > > import MYDLL.dll > > Then we would be able to do everything with that library that we can > do in other languages. > > For eg. I want to use PyOpenGL. But the problem is the library hasn't > got all the opengl functions implemented. > So I can either develop quickly with an incomplete library or develop > slowly in assembler. > I mean really, in asm we just call the dll function directly. > > Why must python be different? Hi again, Jason, As we pointed out to you, ctypes *does* allow you to just load the DLL and start calling functions. In fact, that's how development tends to happen in the ctypes implementation. Someone just loads the DLL, hacks up a demo, I look at it and factor their code into the code-base. If there's some function missing that you need, do something like this: from OpenGL.platform import GL GL.myFunction( myParameter, myOtherParameter ) and if the parameters are of simple types, it will often "just work". If you want to pass arrays or similar data-types you'll need to make them ctypes arrays or pointers to use those "raw" functions, but they should work perfectly well. That is, you have to pass the right data-type, but then you'd have to do that in assembler too. Have fun, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: dependency algorithm
Tom Jones wrote: > Hi, > > Consider tuples of the above numbers in the form: >(a,b) > > Suppose this relation means: >a depends on b > > Given a list of tuples, I would like an algorithm to return the proper > ordering of the elements...and if the ordering has a loop (which in this > case, prevents a proper ordering), then it should return None. > You want what's called a topological sort, see: http://blog.vrplumber.com/scripts/toposort.py for a pair of old algorithms from Tim Peters and I. I believe we raise errors on loops, but that's pretty trivial to change. Have fun, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Screen Shots?
katie smith wrote: > UGH so frustrating. In my game there is a minimap. On top of the > minimap is a window showing the part of the map your viewing. The > minimap is composed of other little pictures piled of top of eachother. > > I want to know how to basically take a picture from ex.((50,50),to > (150,150)) and blit the mini window image on top of it. hard to > explain but everytime I move the window box I don't want to redo the > window with its couple hundred compiled image. I need to copy picture > and make it into a surface??.. I dont even know. > > Any help would be greatly appreciated If you are using Pygame (you don't say which GUI library you are using), you can draw the mini-map into a surface and then re-blit the surface to the screen each time you want to display it. HTH, Mike -- ____ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Diez B. Roggisch wrote: ... > I was under the impression that PyOpenGL is ctypes-based in the new > versions? > It is, but I haven't had the time to do a new release and check it on a Windows box. There are minor fixes in CVS that *should* IIRC make us run better on those Windows machines that have problems with the 3.x alphas so far. Tempus fugit, Mike -- ________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: State of the "Vaults of Parnassus"
Christoph Zwerschke wrote: > Does anybody know what happened to the "Vaults of Parnassus" site at > http://www.vex.net/~x/parnassus/? > > "Dr Dobb's weekly Python news" still claims that it "ambitiously > collects references to all sorts of Python resources." But I have the > impression that it does not do this any more since April 2005, probably > because we have the Cheese Shop now. It's strange that the site does not > mention that it is not maintained any more, and it is still possible to > submit and update entries, but these changes seem to be discarded. > That's not very nice. Also, I found no contact address on the whole > website. Who is in charge of it? > > -- Christoph > The Vaults are run by one of my colleagues, who is (as it seems we all are), rather overworked these days. Last I heard he had someone who was helping him every once in a while to review the new submissions, but that was quite a while ago. I don't *think* there's any discarding, but rather a delay so long in publishing that it would feel like a discard... Take care, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Using python for a CAD program
. That said, threading is always tricky, particularly during debugging. If you can avoid it for most operations and only put things in threads that are largely disconnected from other processes you'll likely be happier. The big win would be if you are doing all of your simulation in C with an event-based update such that the simulation generates changes as a queued list of updates to the model. You could then have the simulation yield the interpreter lock and seldom block the rest of the process (save when it touches a Python object (i.e. the updates coming from or going to the queue)). Have fun, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list