Re: a basic bytecode to machine code compiler
> > > That's quite an interesting idea. I do think a lot of production Python > code implicitly depends on the GIL and would need rework for multicore. > For example, code that expects "n += 1" to be atomic, because the > CPython bytecode interpreter won't switch threads in the middle of it. > -- > Yes it will. The interpreter may switch threads between any of these bytecode instructions. In [8]: dis.dis(compile('n += 1', '', 'single')) 1 0 LOAD_NAME0 (n) 3 LOAD_CONST 0 (1) 6 INPLACE_ADD 7 STORE_NAME 0 (n) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE Proof: In [15]: n = 0 In [16]: class Foo(threading.Thread): : def run(self): : global n : for i in range(1): : n += 1 : : In [17]: threads = [Foo() for i in range(5)] In [18]: for thread in threads: : thread.start() : : In [19]: n Out[19]: 37433 -- http://mail.python.org/mailman/listinfo/python-list
Re: Terrible FPU performance
On Tue, Apr 26, 2011 at 8:40 AM, Mihai Badoiu wrote: > Hi, > > I have terrible performance for multiplication when one number gets very > close to zero. I'm using cython by writing the following code: > > You should ask this question on the Cython users mailing list. -- http://mail.python.org/mailman/listinfo/python-list
relative imports with the __import__ function
I have package tree that looks like this: main.py package __init__.py configuration.ini server __init__.py xmlrpc_server.py controller.py reco segmentation __init__.py red_objects.py main.py launches an instance of xmlrpc_server.py which, in turn, imports controller.py. controller.py reads configuration.ini to determine which module/function to import from the segmentation directory and subsequently use. that config file specifies the module as 'red_objects' and the function as 'segment_red'. I am trying to dynamically import that module and func using the __import__ statement but keep getting empty module errors. In the following code segment, the failing code is uncommented, but the commented code works fine: seg_mod = 'red_objects' smod = __import__('..segmentation.%s' % seg_mod, fromlist=[seg_func], level=-1) #from ..segmentation import red_objects #smod = red_objects I have tried all sorts of values for the 'level' kwarg as well as everywhich variation of the dotted relative notation. I'm assuming i'm missing something fundamental on the import resolution... As an aside, I would like to move main.py inside of the package directory, but I dont know if that is possible with what i'm trying to do here. Thanks for any help. Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: relative imports with the __import__ function
On Tue, Dec 8, 2009 at 5:48 PM, Peter Otten <__pete...@web.de> wrote: > Chris Colbert wrote: > >> I have package tree that looks like this: >> >> main.py >> package >> __init__.py >> configuration.ini >> server >> __init__.py >> xmlrpc_server.py >> controller.py >> reco >> >> segmentation >> __init__.py >> red_objects.py >> >> >> >> main.py launches an instance of xmlrpc_server.py which, in turn, >> imports controller.py. >> controller.py reads configuration.ini to determine which >> module/function to import from the segmentation directory and >> subsequently use. >> >> that config file specifies the module as 'red_objects' and the >> function as 'segment_red'. >> >> I am trying to dynamically import that module and func using the >> __import__ statement but keep getting empty module errors. > > >> I'm assuming i'm missing something fundamental on the import resolution... > > After some experimentation it turns out you have to provide some context for > __import__() to determine the absolute location of the requested module. The > required bit of information is the current module's __name__ attribute which > you can provide via the globals parameter: > > def import_segmentation(name): > return getattr(__import__("segmentation." + name, level=2, > globals=globals()), name) > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > Many thanks Peter! Almost like a charm! It seems the relative import level is dependent on the location of the main entry module. I thought the whole idea of relative imports was to make the import independent of the entry point? here is the import function i'm using def import_segmentation(self): # get the segmentation function defined in configuration.ini parent_dir = os.path.split(os.path.dirname(__file__))[0] prsr = ConfigParser.ConfigParser() prsr.read(os.path.join(parent_dir, 'configuration.ini')) seg_mod = prsr.get('segmentation', 'module') seg_func = prsr.get('segmentation', 'function') print __name__ smod = __import__('segmentation.%s' % seg_mod, globals=globals(), fromlist=[seg_func], level=2) sfunc = getattr(smod, seg_func) return sfunc for that import level of 2 to work the tree must look like this: main.py package __init__.py configuration.ini server __init__.py xmlrpc_server.py controller.py reco segmentation __init__.py red_objects.py but if I rearrange the package structure like this (just moving the location of main.py): package main.py __init__.py configuration.ini server __init__.py xmlrpc_server.py controller.py reco segmentation __init__.py red_objects.py I have to change the import to level=1 or I get this error: ValueError: Attempted relative import beyond toplevel package I don't understand why the location of my main.py should have ANY bearing on relative import resolution. But again, i'm probably just being dense and need someone to explain it to me in newb speak ;) Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
a python downloader for the Amazon mp3 store
So, I wasn't happy with the Amazon mp3 downloader for linux (because it sucks). And clamz is written in C with a bunch of dependencies. Thus, I've created a python downloader for .amz files using the crypto keys figured out by Ben Moody (clamz author). Its just command line only right now, but I will add a pyqt front end in the future. The only external dependency is PyCrypto, which is in the ubuntu repos. I always appreciate feedback! GPL licensed http://code.google.com/p/pymazon/ Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
doing cool stuff with Python and Industrial Robots....
Im just finishing up some research work during a stint as a visiting researcher in Germany. I've made a short clip showing a KUKA robot performing object reconstruction using a single camera mounted on the robot. The entire system is written in Python (control, math, everything) and related infrastructure (Cython/NumPy/Scipy/Mayavi/etc...) I cant give any technical details yet, as I have a few papers still pending publication. But I thought you all might enjoy the video. Everyone likes big robots!!! ~60MB www.therealstevencolbert.com/dump/reco_demo.mpg The video begins by showing the ground-truth of the object rendered as a wireframe. The robot then captures three images of the object from various vantages. The software then reconstructs the shape of the object, and overlays the wireframe with the results. Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
ANN: Pymazon 0.1beta released.
I'm happy to announce the first beta release of Pymazon: a Python implemented alternative to the Amazon mp3 downloader. Pymazon was created specifically to alleviate the issues surrounding the Linux version of the Amazon mp3 downloader (though it should run just fine in Windows too). Pymazon can be used from the command line, or a gui interface if PyQt4 is installed. You can get Pymazon from the cheeseshop using pip (easy_install is not supported as it breaks the bin script): $ pip install pymazon You can read more about Pymazon (screenshots, installation, usage, source code) at http://code.google.com/p/pymazon/ Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Pymazon 0.1beta released.
On Mon, Jan 4, 2010 at 11:43 AM, Tim Wintle wrote: > On Tue, 2009-12-29 at 19:44 +0100, Chris Colbert wrote: > > I'm happy to announce the first beta release of Pymazon: a Python > > implemented alternative to the Amazon mp3 downloader. > > > > Pymazon was created specifically to alleviate the issues surrounding > > the Linux version of the Amazon mp3 downloader (though it should run > > just fine in Windows too). > > Thanks! > > I've been complaining to them for not providing 64-bit binaries (or > source) for ages! (Although hats off to them for even providing the > number of linux variants they do support) > Youre completely right, and my language on the google code site was a little harsh towards Amazon in that respect. I've fixed that now. Cheers! -- http://mail.python.org/mailman/listinfo/python-list
how to change when the logging module creates the log file?
I have an application the writes to a log file when specific exceptions are handled. However, if no exceptions are encountered, I don't want to create a log at all. The problem I am running into is that the stdlib logging module creates the log file immediately upon logger instantiation. Thus: >>> logger = logging.basicConifg('testlog.txt') already creates the file 'testlog.txt'. So, at program close, I am reading the size of the log file, and if it is empty I remove it with os.remove(). This works fine on Linux, but throws a permission denied exception on Windows. There has to be a better way to do this than using a hack like that. Is there a way to make the logging module hold-off on file creation until the first log is generated? I could do it by wrapping logger in a class, but that would remove the beauty of having any module import logging from the stdlib and being able to write to the log. Thanks for any pointers! Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: how to change when the logging module creates the log file?
i was able to fix the exception by calling logging.shutdown() before the call to os.remove(). However, I still think there is probably a more elegant solution. On Wed, Jan 6, 2010 at 12:57 PM, Chris Colbert wrote: > I have an application the writes to a log file when specific exceptions are > handled. However, if no exceptions are encountered, I don't want to create a > log at all. > > The problem I am running into is that the stdlib logging module creates the > log file immediately upon logger instantiation. > > Thus: > >>> logger = logging.basicConifg('testlog.txt') > > already creates the file 'testlog.txt'. > > So, at program close, I am reading the size of the log file, and if it is > empty I remove it with os.remove(). This works fine on Linux, but throws a > permission denied exception on Windows. > > There has to be a better way to do this than using a hack like that. Is > there a way to make the logging module hold-off on file creation until the > first log is generated? I could do it by wrapping logger in a class, but > that would remove the beauty of having any module import logging from the > stdlib and being able to write to the log. > > Thanks for any pointers! > > Chris > -- http://mail.python.org/mailman/listinfo/python-list
Re: lightweight encryption of text file
PyCrypto is already pretty easy to use by itself. I dont know why you want a wrapper on top of it. On Fri, Jan 8, 2010 at 11:02 PM, Irmen de Jong wrote: > On 8-1-2010 22:39, Daniel Fetchinson wrote: > >> >>>http://www.nightsong.com/phr/crypto/p3.py >>> >> >> Thanks a lot, currently I'm having trouble using this code on python >> 2.6 but probably some small tweaking will fix it. >> > > If you keep having issues with this module, maybe you can try this: > > http://www.freenet.org.nz/ezPyCrypto/ > > It provides a very easy compact api on top of PyCrypto. So you'll need to > install that as well to be able to use this. > > -irmen > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQwt installation
On Mon, Jan 18, 2010 at 6:15 PM, Gib Bogle wrote: > Should there be a problem installing PyQwt5.2.0 with PyQt4.4.4 and > Python2.6 on Windows? My student is saying she can't get the Windows > installer to work, and she points out that the download site says "Binary > installation of PyQwt-5.2.0 on Windows for Python-2.6.x, PyQt-4.5.4" > -- > http://mail.python.org/mailman/listinfo/python-list > It's a sad day when the professor can't google. from http://pyqwt.sourceforge.net/doc5/installation.html#windows-binary-installer Windows Binary Installer Make sure that you have installed: python-2.6.2.msi numpy-1.3.0-win32-superpack-python2.6.exe PyQt-Py2.6-gpl-4.5.4-1.exe before installing PyQwt5.2.0-Python2.6-PyQt4.5.4-NumPy1.3.0-1.exe. So I would say, yes, they are probably not compatible. The PyQt4.5 brought many changes from 4.4. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE for MacOS-X
On Tue, Jan 19, 2010 at 2:09 AM, Jean Guillaume Pyraksos wrote: > What's the best one to use with beginners ? > Something with integrated syntax editor, browser of doc... > Thanks, > >JG > -- > http://mail.python.org/mailman/listinfo/python-list > I whole-heartedly recommend WingIDE. It's commercial and the only piece of commercial Linux software I use, but it is worth every penny. And support emails are answered within hours, if not minutes...they are great guys over there. **I am not affiliated with Wingware in any way. Just a happy customer.** -- http://mail.python.org/mailman/listinfo/python-list
Re: html code generation
use a deque with a 'junk' as each element http://docs.python.org/library/collections.html On Wed, Jan 20, 2010 at 4:03 PM, George Trojan wrote: > I need an advice on table generation. The table is essentially a fifo, > containing about 200 rows. The rows are inserted every few minutes or so. > The simplest solution is to store row data per line and write directly html > code: > line = "value1value2>... " > each run of the program would read the previous table into a list of lines, > insert the first row and drop the last one, taking care of table header and > trailer. > Is there a more classy solution? > > George > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: html code generation
On Wed, Jan 20, 2010 at 4:52 PM, Chris Colbert wrote: > use a deque with a 'junk' as each element > > http://docs.python.org/library/collections.html > > On Wed, Jan 20, 2010 at 4:03 PM, George Trojan wrote: > >> I need an advice on table generation. The table is essentially a fifo, >> containing about 200 rows. The rows are inserted every few minutes or so. >> The simplest solution is to store row data per line and write directly html >> code: >> line = "value1value2>... " >> each run of the program would read the previous table into a list of >> lines, insert the first row and drop the last one, taking care of table >> header and trailer. >> Is there a more classy solution? >> >> George >> -- >> http://mail.python.org/mailman/listinfo/python-list > > In [1]: from collections import deque In [2]: a = deque(['foo', 'bar']) In [3]: ''.join(a) Out[3]: 'foobar' In [4]: a.popleft() Out[4]: 'foo' In [5]: a.append('baz') In [6]: ''.join(a) Out[6]: 'barbaz' -- http://mail.python.org/mailman/listinfo/python-list
Re: html code generation
ah ok, i misread your post. Store each 'junk' as an item in the deque. the idea is the same though. On Wed, Jan 20, 2010 at 4:55 PM, Chris Colbert wrote: > > > On Wed, Jan 20, 2010 at 4:52 PM, Chris Colbert wrote: > >> use a deque with a 'junk' as each element >> >> http://docs.python.org/library/collections.html >> >> On Wed, Jan 20, 2010 at 4:03 PM, George Trojan wrote: >> >>> I need an advice on table generation. The table is essentially a fifo, >>> containing about 200 rows. The rows are inserted every few minutes or so. >>> The simplest solution is to store row data per line and write directly html >>> code: >>> line = "value1value2>... " >>> each run of the program would read the previous table into a list of >>> lines, insert the first row and drop the last one, taking care of table >>> header and trailer. >>> Is there a more classy solution? >>> >>> George >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> > In [1]: from collections import deque > > In [2]: a = deque(['foo', 'bar']) > > In [3]: ''.join(a) > Out[3]: 'foobar' > > In [4]: a.popleft() > Out[4]: 'foo' > > In [5]: a.append('baz') > > In [6]: ''.join(a) > Out[6]: 'barbaz' > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Mastering Python 3 I/O - Special Preview - Feb 5, 2010 (Chicago)
oops :) On Fri, Jan 22, 2010 at 9:41 PM, Steve Holden wrote: > Dave: > > New York classes went well this week, and there appears to be some > demand for Chicago training. How can we satisfy this demand to our > common profit? > > regards > Steve > > David Beazley wrote: > > Mastering Python 3 I/O > >** PyCON'2010 Tutorial Preview in Chicago ** > > > > with David Beazley > > February 5, 2010, 12pm - 5pm > > http://www.dabeaz.com/chicago/index.html > > > > Can't make it to PyCON, but want to attend a cutting-edge tutorial on > > the latest Python features? Join David Beazley, author of the Python > > Essential Reference, in Chicago for a preview of his new tutorial > > "Mastering Python 3 I/O." The goal of this tutorial is to take a top > > to bottom tour of the Python 3 I/O system and to focus on essential > > features that you must know if you are ever going to port existing > > applications to Python 3 or use it for real applications. This > > tutorial promises to go far beyond what you find in the documentation > > and books (Dave's included). You'll learn about tricky gotchas, see > > interesting practical examples, and get a better grasp of how Python 3 > > is put together. > > > > This tutorial preview includes a free copy of the "Python Essential > > Reference, 4th Ed.", lunch at one of Chicago's finest new restaurants, > > artisinal pastries and more--all for the same price as a tutorial at > > PyCON. However, it's strictly limited to 8 attendees. > > > > More information is available at: > > > > http://www.dabeaz.com/chicago/index.html > > > > Cheers, > > Dave > > > > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ > Holden Web LLC http://www.holdenweb.com/ > UPCOMING EVENTS:http://holdenweb.eventbrite.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: list.pop(0) vs. collections.dequeue
On Mon, Jan 25, 2010 at 5:09 PM, Steve Howell wrote: > On Jan 25, 1:32 pm, Arnaud Delobelle wrote: > > Steve Howell writes: > > > > [...] > > > > > My algorithm does exactly N pops and roughly N list accesses, so I > > > would be going from N*N + N to N + N log N if switched to blist. > > > > Can you post your algorithm? It would be interesting to have a concrete > > use case to base this discussion on. > > > > I just realized you meant the Python code itself. It is here: > > https://bitbucket.org/showell/shpaml_website/src/tip/shpaml.py > > -- > http://mail.python.org/mailman/listinfo/python-list > looking at that code, i think you could solve your whole problem with a single called to reversed() (which is NOT the same as list.reverse()) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, PIL and 16 bit per channel images
On Mon, Jan 25, 2010 at 5:04 PM, Peter Chant wrote: > Does anyone know whether PIL can handle 16 bit per channel RGB images? > PyPNG site (http://packages.python.org/pypng/ca.html) states PIL uses 8 > bits > per channel internally. > > Thanks, > > Pete > > > -- > http://www.petezilla.co.uk > > -- > http://mail.python.org/mailman/listinfo/python-list > Mode The mode of an image defines the type and depth of a pixel in the image. The current release supports the following standard modes: - *1* (1-bit pixels, black and white, stored with one pixel per byte) - *L* (8-bit pixels, black and white) - *P* (8-bit pixels, mapped to any other mode using a colour palette) - *RGB* (3x8-bit pixels, true colour) - *RGBA* (4x8-bit pixels, true colour with transparency mask) - *CMYK* (4x8-bit pixels, colour separation) - *YCbCr* (3x8-bit pixels, colour video format) - *I* (32-bit signed integer pixels) - *F* (32-bit floating point pixels) http://www.pythonware.com/library/pil/handbook/concepts.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: For loop searching takes too long!
if you're open to other libraries, this could be done extremely fast in numpy. On my machine summing that whole array takes 75ms. On Thu, Jan 28, 2010 at 8:00 PM, Steven D'Aprano < st...@remove-this-cybersource.com.au> wrote: > On Thu, 28 Jan 2010 15:52:14 -0800, elsa wrote: > > > Now, what I need to do is randomly choose one myList[i], however the > > distribution of my random choice needs to be proportional to the values > > of myList[i][0]. So, for this list above, I'd have a much higher chance > > of choosing myList[0] than myList[1]. > > > > Here is how I'm doing it at the moment: > > > > def chooseI(myList): > > mySum=0 > > choice = random.choice(range(1,sum([i[0] for i in myList])+1)) > > for i in range(len(myList)): > > mySum+=myList[i][0] > > if mySum>=choice: > > return i > > break > > This isn't related to your problem, but you don't need the break after > the return -- the return will leave the loop and the function, and the > break will never be reached. > > You could probably speed the code up a little by changing all the calls > to range into xrange. range actually generates a list of integers, which > is time consuming, while xrange is a lazy generator which just produces > each integer one at a time. (You can ignore this if you are using Python > 3.0 or 3.1.) > > Another small optimization you could use is to use a generator expression > instead of a list comprehension inside the call to sum. That should > generate the sum lazily, instead of calculating a giant list first and > then adding it up. > > But I'd try something like this: > > # Untested. > def chooseI(myList): >total = sum(i[0] for i in myList) >mySum = 0 >choice = random.randrange(total) >for i in myList: >mySum += i[0] > if mySum >= choice: >return i > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: easy question, how to double a variable
I come from a scientific background, so my approach to the solution of this problem is a little different. It makes use of some numerical approximations, but that's not necessarily a bad thing, because it helps avoid singularities. So it could be a little more robust than other solutions presented here. It also has a little more functionality: Say you wanted to return three times a variable, you wouldnt want to write another function to do that for you, so now you just pass in how many times you want the variable repeated as the first parameter. Hope this helps! Cheers! import math def repeat(how_many_times, x): def f(n): return 1./(2**n) def summation(func, howmany): if howmany == 1: return func(1) else: return func(howmany) + summation(func, howmany-1) def eulerify(num): return abs(math.cos(math.pi) + 1j*(math.sin(math.pi))) * num def get_coefficient(multiplier): return eulerify(multiplier * summation(f, 100)) return int(eulerify(get_coefficient(how_many_times) * x)) On Fri, Oct 2, 2009 at 2:08 PM, Albert van der Horst wrote: > In article > , > daggerdvm wrote: >>you brain needs error checking! > > Whose brain? At least I know this: > > Your brain is beyond repair. Go for a brain transplant. > > Groetjes Albert > > -- > -- > Albert van der Horst, UTRECHT,THE NETHERLANDS > Economic growth -- being exponential -- ultimately falters. > alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python shared lib
thats because the standard way to build python packaged is to use distutils, and not make files. Blame Yafaray for not supplying a setup.py... ..M, Aahz wrote: > In article , > namekuseijin wrote: >> >>and then I realize that, for whatever reason, the super popular and >>trendy python DOESN'T FRIGGIN BUILD SHARED LIBS BY DEFAULT! > > I've got a dim memory that there's a reason for this -- you might try > searching the python-dev archives and/or bugs.python.org. > -- > Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ > > "Normal is what cuts off your sixth finger and your tail..." --Siobhan > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Is there a way to specify a superclass at runtime?
I have an application that needs to run different depending on whether the input data is being simulated, or provided from instrumentation. I am trying to abstract this machinery in a single class called Controller which I want to inherit from either SimController or RealController based on whether a module level flag SIMULATION is set to True or False. so I have something like this: SIMULATION = False class SimController(object): "do sim stuff here" class RealController(object): " do real stuff here" class Controller(SuperKlass): pass so if SIMULATION == False I want to be able to instance a Controller object that inherits from RealController and vice-versa. I thought this might be possible with metaclasses, but I didnt find anything useful in the docs or on google. Thanks for any help! Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to specify a superclass at runtime?
because when i import this module, the classes will already be determined by the intitial flag setting. i.e. SIMULATION = False class SimController(object): def foo(self): print 'bar' class RealController(object): def foo(self): print 'baz' if SIMULATION: SuperKlass = SimController else: SuperKlass = RealController class Controller(SuperKlass): pass In [2]: import testcontroller In [3]: testcontroller.SIMULATION Out[3]: False In [4]: c = testcontroller.Controller() In [5]: c.foo() baz In [6]: testcontroller.SIMULATION = True In [7]: c = testcontroller.Controller() In [8]: c.foo() baz On Mon, Oct 5, 2009 at 3:32 PM, MRAB wrote: > Chris Colbert wrote: >> >> I have an application that needs to run different depending on whether >> the input data is being simulated, or provided from instrumentation. >> >> I am trying to abstract this machinery in a single class called >> Controller which I want to inherit from either SimController or >> RealController based on whether a module level flag SIMULATION is set >> to True or False. >> >> so I have something like this: >> >> >> SIMULATION = False >> >> class SimController(object): >> "do sim stuff here" >> >> class RealController(object): >> " do real stuff here" >> >> class Controller(SuperKlass): >> pass >> >> >> so if SIMULATION == False I want to be able to instance a Controller >> object that inherits from RealController and vice-versa. >> >> I thought this might be possible with metaclasses, but I didnt find >> anything useful in the docs or on google. >> >> Thanks for any help! >> > Why not just: > > SIMULATION = False > > class SimController(object): > "do sim stuff here" > > class RealController(object): > " do real stuff here" > > if SIMULATION: > SuperKlass = SimController > else: > SuperKlass = RealController > > class Controller(SuperKlass): > pass > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to specify a superclass at runtime?
I dont think so, because that would require logic outside of the controller class to determine which controller to instantiate. My whole purpose for Controller is to encapsulate this logic. So, if the data should be simulated, then i just need to pass -simulate True as a command line argument, and the controller takes care of it... On Mon, Oct 5, 2009 at 3:44 PM, Richard Brodie wrote: > > "Chris Colbert" wrote in message > news:mailman.868.1254748945.2807.python-l...@python.org... > >> I am trying to abstract this machinery in a single class called >> Controller which I want to inherit from either SimController or >> RealController based on whether a module level flag SIMULATION is set >> to True or False. > > At first sight, that seems kind of odd. Wouldn't it be simpler to have > SimController and RealController inherit from Controller? > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to specify a superclass at runtime?
I suppose i can just move the SIMULATION flag to another module, and then import it and check it before intstantiation. So, the arg parser will have to set the flag before any other processing begins... On Mon, Oct 5, 2009 at 3:49 PM, Chris Colbert wrote: > I dont think so, because that would require logic outside of the > controller class to determine which controller to instantiate. > > My whole purpose for Controller is to encapsulate this logic. > > So, if the data should be simulated, then i just need to pass > -simulate True as a command line argument, and the controller takes > care of it... > > On Mon, Oct 5, 2009 at 3:44 PM, Richard Brodie wrote: >> >> "Chris Colbert" wrote in message >> news:mailman.868.1254748945.2807.python-l...@python.org... >> >>> I am trying to abstract this machinery in a single class called >>> Controller which I want to inherit from either SimController or >>> RealController based on whether a module level flag SIMULATION is set >>> to True or False. >> >> At first sight, that seems kind of odd. Wouldn't it be simpler to have >> SimController and RealController inherit from Controller? >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to specify a superclass at runtime?
that's a good idea. Thanks! On Mon, Oct 5, 2009 at 4:18 PM, MRAB wrote: > Chris Colbert wrote: >> >> because when i import this module, the classes will already be >> determined by the intitial flag setting. >> >> i.e. >> SIMULATION = False >> >> class SimController(object): >> def foo(self): >> print 'bar' >> >> class RealController(object): >> def foo(self): >> print 'baz' >> >> if SIMULATION: >> SuperKlass = SimController >> else: >> SuperKlass = RealController >> >> class Controller(SuperKlass): >> pass >> >> >> >> >> >> In [2]: import testcontroller >> >> In [3]: testcontroller.SIMULATION >> Out[3]: False >> >> In [4]: c = testcontroller.Controller() >> >> In [5]: c.foo() >> baz >> >> In [6]: testcontroller.SIMULATION = True >> >> In [7]: c = testcontroller.Controller() >> >> In [8]: c.foo() >> baz >> > [snip] > You could put the Controller class inside a factory function: > > def Controller(): > if SIMULATION: > SuperKlass = SimController > else: > SuperKlass = RealController > class Controller(SuperKlass): > pass > return Controller() > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use WSGI applications with apache
if you want to use it with apapache, you need mod_wsgi. If you want a pure python solution, you can use the wsgi server that comes with CherryPy. Personally, I use the wsgi server in CherrPy on my website. My site is not large by any means and the ease of deployment completely erased any benefit I would have gained from apache. On Tue, Oct 6, 2009 at 11:34 PM, wrote: > Hi folks, > > I'm not quite sure where to ask this, but this is my closest guess. > > I've written a web service based on the newf micro-framework and it uses > wsgiref.simple_server. I'm noticing that it's not returning response > codes properly (after fixing a bug in newf). Instead, it just > closes the TCP connection silently. > > I am assuming that I need to run it with a more sophisticated server, > and I eventually want to run it under apache, but I can't seem to > figure out how to do this. Someone once showed me how, and it was > a simple line in the apache config. But I can't figure it out how > to do again. > > Any help? > -- > Obama Nation | My emails do not have attachments; it's a digital signature > that your mail program doesn't understand. | > http://www.subspacefield.org/~travis/ > If you are a spammer, please email j...@subspacefield.org to get blacklisted. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
does anyone know how to use libjeg from within memory in python
Say I use python to talk to a wireless webcamera that delivers images via http requests. I request an image and read it into a buffer, but the image is in jpeg format. I would like to convert this to a simple RGB format buffer to pass to numpy. Has anyone managed this using libjpeg or any other lib? Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: does anyone know how to use libjeg from within memory in python
In answering my own question, this can be done trivially with PIL. Here is a self contained example: In [1]: import httplib In [2]: from PIL import ImageFile In [3]: import numpy as np In [4]: conn = httplib.HTTPConnection('www.therealstevencolbert.com') In [5]: conn.request('GET', '/dump/IMG_0408_rs.JPG') In [6]: r1 = conn.getresponse() In [7]: r1.status Out[7]: 200 In [8]: data = r1.read() In [9]: parser = ImageFile.Parser() In [10]: parser.feed(data) In [11]: img = parser.close() In [12]: img.show() In [13]: numpyimg = np.asarray(img) In [14]: numpyimg.shape Out[14]: (768, 1024, 3) In [15]: numpyimg.dtype Out[15]: dtype('uint8') On Tue, Oct 13, 2009 at 11:51 AM, Chris Colbert wrote: > Say I use python to talk to a wireless webcamera that delivers images > via http requests. > > I request an image and read it into a buffer, but the image is in jpeg format. > > I would like to convert this to a simple RGB format buffer to pass to > numpy. Has anyone managed this using libjpeg or any other lib? > > Cheers! > > Chris > -- http://mail.python.org/mailman/listinfo/python-list
Re: does anyone know how to use libjeg from within memory in python
Heh, for whatever reason, your post is dated earlier than my response, but wasn't here when I sent mine. But yeah, PIL worked. On Tue, Oct 13, 2009 at 12:04 PM, Stefan Behnel wrote: > Chris Colbert wrote: >> Say I use python to talk to a wireless webcamera that delivers images >> via http requests. >> >> I request an image and read it into a buffer, but the image is in jpeg >> format. >> >> I would like to convert this to a simple RGB format buffer to pass to >> numpy. Has anyone managed this using libjpeg or any other lib? > > According to the docs, the stdlib jpeg module has been removed in Py3: > > http://docs.python.org/library/jpeg.html > > But since you are processing images anyway, what about using an image > processing library like PIL or ImageMagick? > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: does anyone know how to use libjeg from within memory in python
My emails must not be making it to list... I posted a solutions about 10 minutes after I posted the questions. Thanks! On Tue, Oct 13, 2009 at 12:35 PM, Dave Angel wrote: > Chris Colbert wrote: >> >> Say I use python to talk to a wireless webcamera that delivers images >> via http requests. >> >> I request an image and read it into a buffer, but the image is in jpeg >> format. >> >> I would like to convert this to a simple RGB format buffer to pass to >> numpy. Has anyone managed this using libjpeg or any other lib? >> >> Cheers! >> >> Chris >> >> > > You probably want to use PIL > > http://www.pythonware.com/products/pil/ > > > DaveA > -- http://mail.python.org/mailman/listinfo/python-list
Re: What IDE has good git and python support?
it depends on what i'm doing. quick and dirty test script: ipython a larger problem with code I am likely to use later: spyder a multi-module large project (like wrapping opencv): Wing Chris On Tue, Oct 27, 2009 at 5:04 PM, Mick Krippendorf wrote: > Aweks schrieb: >> what do you use? > > Either of the following: > -> Vim + Eclim + Rope + pylint + PyDev + Eclipse + cygwin + WindowsXP > -> Vim + Linux > > Mick. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE python shell freezes after running show() of matplotlib
This is a threading issue that is very common when using gui toolkits with the interactive interpreter. You're better off just using ipython, which already has builtin support for matplotlib when you start it via "ipython -pylab" On Wed, Oct 28, 2009 at 7:41 PM, OKB (not okblacke) wrote: > Forrest Sheng Bao wrote: > >> I am having a weird problem on IDLE. After I plot something using show >> () of matplotlib, the python shell prompt in IDLE just freezes that I >> cannot enter anything and there is no new ">>>" prompt show up. I >> tried ctrl - C and it didn't work. I have to restart IDLE to use it >> again. >> >> My system is Ubuntu Linux 9.04. I used apt-get to install IDLE. > > I believe this is the intended behavior. Look in matplotlib > documentation on the difference between interactive and non-interactive > modes. > > -- > --OKB (not okblacke) > Brendan Barnwell > "Do not follow where the path may lead. Go, instead, where there is > no path, and leave a trail." > --author unknown > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: calling server side function
I second the suggestion for XML-RPC... It also solves the security issue in your example, by only exporting functions you specifically register... look at xmlrpclib in the standard python library. On Wed, Oct 28, 2009 at 8:59 AM, Gabriel Genellina wrote: > En Wed, 28 Oct 2009 04:04:50 -0300, Paul Hartley > escribió: > >> I have a socket set up between a client and server program. Let's say >> that I serialize (pickle) some data in the client and send it to the server >> with the intention of calling a function in the server to process the data. >> How would one execute the function? This is not for a web-based >> application, BTW -- it's a desktop based application >> My current thought process is (using a generalized example): >> I have a list of numbers in the client and want to find the length of the >> list using the server. There exists a function find_len() in the server >> code. I have a list of numbers [1,2,3]. On the client side, I create the >> tuple ("find_len", [1,2,3]), and serialize it. I pass this serialized >> object via a socket to the server, which unpickles it. The server takes the >> key (find_len) and uses a getattr call to get the find_len function. The >> server then calls find_len([1,2,3]) to get the sum. >> def find_len(list_): return >> Are there better ways of accomplishing this (I'm aware that there are >> security pitfalls here...) > > xmlrpc does more or less the same thing, but serializing in xml instead of > pickling. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to guard against bugs like this one?
This is kinda akin to creating your own libc.so in a folder where your compiling and executing c programs and then wondering why your program bugs out On Mon, Feb 1, 2010 at 9:34 PM, kj wrote: > > > I just spent about 1-1/2 hours tracking down a bug. > > An innocuous little script, let's call it buggy.py, only 10 lines > long, and whose output should have been, at most two lines, was > quickly dumping tens of megabytes of non-printable characters to > my screen (aka gobbledygook), and in the process was messing up my > terminal *royally*. Here's buggy.py: > > > > import sys > import psycopg2 > connection_params = "dbname='%s' user='%s' password='%s'" % > tuple(sys.argv[1:]) > conn = psycopg2.connect(connection_params) > cur = conn.cursor() > cur.execute('SELECT * FROM version;') > print '\n'.join(x[-1] for x in cur.fetchall()) > > > (Of course, buggy.py is pretty useless; I reduced the original, > more useful, script to this to help me debug it.) > > Through a *lot* of trial an error I finally discovered that the > root cause of the problem was the fact that, in the same directory > as buggy.py, there is *another* innocuous little script, totally > unrelated, whose name happens to be numbers.py. (This second script > is one I wrote as part of a little Python tutorial I put together > months ago, and is not much more of a script than hello_world.py; > it's baby-steps for the absolute beginner. But apparently, it has > a killer name! I had completely forgotten about it.) > > Both scripts live in a directory filled with *hundreds* little > one-off scripts like the two of them. I'll call this directory > myscripts in what follows. > > It turns out that buggy.py imports psycopg2, as you can see, and > apparently psycopg2 (or something imported by psycopg2) tries to > import some standard Python module called numbers; instead it ends > up importing the innocent myscript/numbers.py, resulting in *absolute > mayhem*. > > (This is no mere Python "wart"; this is a suppurating chancre, and > the fact that it remains unfixed is a neverending source of puzzlement > for me.) > > How can the average Python programmer guard against this sort of > time-devouring bug in the future (while remaining a Python programmer)? > The only solution I can think of is to avoid like the plague the > basenames of all the 200 or so /usr/lib/pythonX.XX/xyz.py{,c} files, > and *pray* that whatever name one chooses for one's script does > not suddenly pop up in the appropriate /usr/lib/pythonX.XX directory > of a future release. > > What else can one do? Let's see, one should put every script in its > own directory, thereby containing the damage. > > Anything else? > > Any suggestion would be appreciated. > > TIA! > > ~k > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
determining which value is the first to appear five times in a list?
I'm working on a naive K-nearest-neighbors selection criteria for an optical character recognition problem. After I build my training set, I test each new image against against the trained feature vectors and record the scores as follows: match_vals = [(match_val_1, identifier_a), (match_val_2, identifier_b) ] and so on.. then I sort the list so the smallest match_val's appear first (indictating a strong match, so I may end up with something like this: [(match_val_291, identifier_b), (match_val_23, identifier_b), (match_val_22, identifer_k) ] Now, what I would like to do is step through this list and find the identifier which appears first a K number of times. Naively, I could make a dict and iterate through the list AND the dict at the same time and keep a tally, breaking when the criteria is met. such as: def getnn(match_vals): tallies = defaultdict(lambda: 0) for match_val, ident in match_vals: tallies[ident] += 1 for ident, tally in tallies.iteritems(): if tally == 5: return ident I would think there is a better way to do this. Any ideas? Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Read PGM's with more than 256 range in PIL1.1.7
According the pil manual it handles PGM files with "'1', 'L', or 'RGB' data" which leads me to believe 16bit data is not supported. You CAN write your own decoder for that though: http://www.pythonware.com/library/pil/handbook/decoder.htm It would be trivial to write a decoder for the pgm format. On Mon, Feb 8, 2010 at 4:47 PM, Davo wrote: > I have a PGM format image file with 4096 range. When I reads it with > PIL, I get an image with 8-bit values and alternate columns are zero. > Does PIL support reading and writing PGM's with more than 8-bits? > > Davo > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: obfuscate
I always though a double rot13 followed by a rot26 was the best? On Mon, Feb 8, 2010 at 9:19 PM, Tim Chase wrote: > Steven D'Aprano wrote: > >> obfuscate is a pure-Python module providing classical encryption >> algorithms suitable for obfuscating and unobfuscating text. >> >> obfuscate includes the following ciphers: >> - Caesar, rot13, rot5, rot18, rot47 >> - atbash >> - Playfair, Playfair6 and Playfair16 >> - Railfence (encryption only) >> - Keyword >> - Affine >> - Vigenere >> - frob (xor) >> > > I prefer the strength of Triple ROT-13 for my obfuscation needs, but I > don't see it listed here. I guess I'll have to roll my own despite the dire > warnings against amateur cryptographers authoring their own unvetted > implementations. ;-) > > -tkc > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: fork vs threading.Thread
dont call the .run() method, call the .start() method which is defined the Thread class (and should NOT be overridden). tftpserv.start() xmlserv.start() On Fri, Feb 12, 2010 at 10:57 PM, Jordan Apgar wrote: > I'm trying to run two servers in the same program at once. Here are > the two: > class TftpServJ(Thread): >def __init__(self, ip, root, port=69, debug = False ): >Thread.__init__(self) >setup stuff here > >def run(self): >try: >self.server.listen(self.ip, self.port) >except KeyboardInterrupt: >pass > > and > class XMLServer(Thread): >def __init__(self, host, port, hostid, rsa_key): >Thread.__init__(self) > setup stuff > >def run(self): >self.server.serve_forever() > > > I call them as: > tftpserv = TftpServJ(host, "/home/twistedphrame/Desktop/xmlrpc_server/ > server") > tftpserv.run() > xmlserv = XMLServer(host, port, HostID, key) > xmlserv.run() > > > it seems that tftpserv runs but wont go on to spawn xmlserv as well. > do I need to fork if I want both these to run at the same time? It > was my impression that by using Thread execution in the main program > would continue. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: working with laptop battery
You'll need acpi installed: In [6]: import subprocess In [7]: p = subprocess.Popen('acpi', stdout=subprocess.PIPE) In [8]: output, errors = p.communicate() In [9]: print output --> print(output) Battery 0: Full, 100%, rate information unavailable On Sat, Feb 13, 2010 at 8:43 PM, Daniel Dalton wrote: > On Sat, Feb 13, 2010 at 05:26:02PM -0800, Chris Rebert wrote: > > It's probably gonna depend on which OS you're running. Which would be...? > > Sorry, forgot to mention this. I'm running debian linux. > > Thanks, > Dan > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to use AWS/PAA nowadays? PyAWS / pyamazon outdated?
This one works for the product API. http://pypi.python.org/pypi/python-amazon-product-api/0.2.1 On Thu, Feb 18, 2010 at 5:09 AM, Snaky Love wrote: > Hi, > > is anybody aware of any updated and / or maintained library for > accessing AWS/PAA with Python? I found the dusty pyamazon and a > derivate of it, pyaws, but both of them do not seem to support request > signatures which must be used by August 15, 2009 to use the Amazon > Services, and generally seem to be a little bit outdated... > > Is there a better way doing signed requests to AWS/PAA nowadays? How > are you doing it? > > I found a good PHP Library here: http://getcloudfusion.com/docs - but > I would like to program stuff with python - is there anything pythonic > that is close to that? > > Thank you very much for your attention, > have a nice day, > Snaky > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to pyjamas?
it's working for me. On Thu, Feb 18, 2010 at 1:16 PM, Daniel Fetchinson < fetchin...@googlemail.com> wrote: > Does anyone know what happened to pyjs.org ? > > Cheers, > Daniel > > > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to pyjamas?
ah, yep, i was viewing the page chrome had cached. It's down for me too. I lose the trace in Washington: 3 G3-0-873.TAMPFL-LCR-08.verizon-gni.net (130.81.110.222) 14.399 ms 17.917 ms 18.040 ms 4 so-6-1-0-0.TPA01-BB-RTR2.verizon-gni.net (130.81.29.242) 18.666 ms 18.890 ms 19.232 ms 5 ge-1-0-0-0.ATL01-BB-RTR2.verizon-gni.net (130.81.17.48) 36.460 ms 38.546 ms 38.707 ms 6 0.so-2-2-0.XT2.ATL5.ALTER.NET (152.63.86.73) 41.357 ms 33.709 ms 35.851 ms 7 * 0.so-7-0-0.XT2.ATL4.ALTER.NET (152.63.86.109) 34.522 ms 37.320 ms 8 0.xe-10-1-0.BR3.ATL4.ALTER.NET (152.63.82.13) 37.558 ms 32.756 ms 35.533 ms 9 xe-11-2-0.edge4.Atlanta2.Level3.net (4.68.62.17) 37.715 ms 100.222 ms 102.317 ms 10 ae-71-52.ebr1.Atlanta2.Level3.net (4.68.103.60) 40.227 ms 34.315 ms 36.647 ms 11 ae-73-70.ebr3.Atlanta2.Level3.net (4.69.138.20) 42.695 ms 39.589 ms 41.666 ms 12 ae-2-2.ebr1.Washington1.Level3.net (4.69.132.86) 52.152 ms 54.256 ms 54.540 ms 13 ae-61-61.csw1.Washington1.Level3.net (4.69.134.130) 61.982 ms 62.316 ms 62.460 ms 14 ae-14-69.car4.Washington1.Level3.net (4.68.17.6) 55.660 ms 55.645 ms 56.943 ms 15 CO-LOCATION.car4.Washington1.Level3.net (4.79.170.254) 59.423 ms 58.914 ms 50.872 ms 16 * * * 17 * * * 18 * * * 19 * * * 20 * * * 21 * * * 22 * * * 23 * * * 24 * * * 25 * * * 26 * * * 27 * * * 28 * * * 29 * * * 30 * * * On Thu, Feb 18, 2010 at 1:58 PM, sstein...@gmail.com wrote: > Down from here (NH, US). > > S > > > On Feb 18, 2010, at 1:44 PM, Chris Colbert wrote: > > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Avoid converting functions to methods in a class
this is somewhat hackish: In [1]: def test(): ...: print 'spam' ...: ...: In [20]: class Ham(): : target = {'target': test} : def test_eggs(self): : self.target['target']() : : In [21]: h = Ham() In [22]: h.test_eggs() spam On Fri, Feb 19, 2010 at 10:33 PM, Steven D'Aprano < st...@remove-this-cybersource.com.au> wrote: > I have a convention when writing unit tests to put the target of the test > into a class attribute, as follows: > > class MyTest(unittest.TestCase): >target = mymodule.someclass > >def test_spam(self): >"""Test that someclass has a spam attribute.""" >self.failUnless(hasattr(self.target, 'spam')) > > > It works well until I write a test for stand-alone functions: > > class AnotherTest(unittest.TestCase): >target = mymodule.function > >def test_foo(self): >self.assertEquals(self.target('a', 'b'), 'foo') > > The problem is that target is turned into a method of my test class, not > a standalone function, and I get errors like: > > TypeError: function() takes exactly 2 arguments (3 given) > > The solution I currently use is to drop the target attribute in this > class, and just refer to mymodule.function in each individual test. I > don't like this solution because it violates Once And Only Once: if the > function changes name, I have to make many edits to the test suite rather > than just one. > > Are there any better solutions? > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: DreamPie - The Python shell you've always dreamed about!
http://dreampie.sourceforge.net/download.html reading is a wonderful thing. On Sun, Feb 21, 2010 at 11:32 AM, Mensanator wrote: > On Feb 21, 10:30�am, Mensanator wrote: > > On Feb 21, 3:42 am, Noam Yorav-Raphael wrote:> I'm > pleased to announce DreamPie 1.0 - a new graphical interactive > > > Python shell! > > > > What versions of Python does it suuport? > > What OS are supported? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: DreamPie - The Python shell you've always dreamed about!
This is bloody fantastic! I must say, this fixes everything I hate about Ipython and gives me the feature I wished it had (with a few minor exceptions). I confirm this working on Kubuntu 9.10 using the ppa listed on the sites download page. I also confirm that it works interactively with PyQt4 and PyGtk (as to be expected since these toolkits use the PyOS_inputhook for the mainloop). However, it does not work interactively with wx (again, this is as expected since wx doesn't use the PyOS_inputhook). In short, the gui toolkit support is the same as in Ipython if you dont use any of the magic threading switches, which are now deprecated anyway. Matplotlib does not work interactively for me. Is there a special switch that needs to be used? or should a pick a non-wx backend? (i'm thinking the latter is more likely) A couple of things I would like to see (and will help implement if I can find the time): 1) A shortcut to show the docstring of an object. Something like Ipython's `?`. i.e. `object.foo?` translates to `help(object.foo)` 2) How do I change the color of the blinking cursor at the bottom? I can't see the damn thing! 3) line numbers instead of the `>>>` prompt 4) a plugin facility where we can define our own `magic` commands. I use Ipython's %timeit ALL the time. 5) Double-click to re-fold the output section as well. Thanks for making this Cheers, Chris On Sun, Feb 21, 2010 at 4:42 AM, Noam Yorav-Raphael wrote: > I'm pleased to announce DreamPie 1.0 - a new graphical interactive > Python shell! > > Some highlights: > > * Has whatever you would expect from a graphical Python shell - > attribute completion, tooltips which show how to call functions, > highlighting of matching parentheses, etc. > * Fixes a lot of IDLE nuisances - in DreamPie interrupt always works, > history recall and completion works as expected, etc. > * Results are saved in the Result History. > * Long output is automatically folded so you can focus on what's > important. > * Jython and IronPython support makes DreamPie a great tool for > exploring Java and .NET classes. > * You can copy any amount of code and immediately execute it, and you > can also copy code you typed interactively into a new file, with the > Copy Code Only command. No tabs are used! > * Free software licensed under GPL version 3. > > Check it out at http://dreampie.sourceforge.net/ and tell me what you > think! > > Have fun, > Noam > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: formatting a number as percentage
>>> print('%.0f%%' % (0.7*100)) 70% On Sun, Feb 21, 2010 at 12:53 PM, vsoler wrote: > I'm trying to print .7 as 70% > I've tried: > > print format(.7,'%%') > .7.format('%%') > > but neither works. I don't know what the syntax is... > > Can you help? > > Thank you > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: DreamPie - The Python shell you've always dreamed about!
Do you have gtk and PyGTK installed? Sounds like a missing dependency to me. On Tue, Feb 23, 2010 at 6:56 AM, Alan Harris-Reid < aharrisr...@googlemail.com> wrote: > gorauskas wrote: > >> I installed it on a Windows 7 machine with CPython 2.6.4 and I get the >> following error: >> >> Traceback (most recent call last): >> File "dreampie.py", line 3, in >> File "dreampielib\gui\__init__.pyc", line 73, in >> File "dreampielib\gui\load_pygtk.pyc", line 49, in load_pygtk >> ImportError: DLL load failed: The specified module could not be found. >> >> What am I doing wrong? >> >> Thanks, JGG >> > And I installed it on WinXP sp3 and Python 3.1 - when launched a window > flashes before my eyes, then disappears! Has the installation package been > checked for all common Windows versions? > > Regards, > Alan > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Spam from gmail (Was: fascism)
this image is appropriate: http://4.bp.blogspot.com/_pS7sKjlzwFg/SwhG1S901pI/Eiw/XSm93RIY2WE/s400/kelso-burn.jpg On Tue, Feb 23, 2010 at 6:06 PM, Daniel Fetchinson < fetchin...@googlemail.com> wrote: > >> >> Is it just me or has the spew from gmail on this list radically > >> >> increased in the last week? Anyone else considering blocking all > gmail > >> >> posts to this list? > >> > > >> > I did that a long time ago for all of the Usenet groups I read > >> > and all but one of the mailing lists I read. > >> > >> Wait, I misread the posting. I block everything from > >> google.groups, not everything from gmail. > > > > Yes, I did that a long time ago as well. But now there seems to be > > more and more actual spam coming from gmail.com itself. It may just be > > a minor blip on the spam graph but I'm keeping my eye on it. > > > > Most mailing lists that I am on are pretty good at filtering spam > > before it gets to the list. The only spam I ever see on my NetBSD > > lists are the ones that I moderate and I block them before anyone else > > sees them. A little more pain for me in return for a lot less pain for > > everyone else. I guess that's not possible on a list that is gatewayed > > to UseNet like this one is. > > > > Hmm. I wonder if all the spam is coming from the NG side. I'll have > > to look at that. One of the reasons that I stopped reading UseNet over > > ten years ago was because of the diminishinig S/N ratio. I have always > > felt that it was a mistake to gateway this group. > > And this has to do with python programming in what way? > > You, sir, are incredibly funny :) > > Just 5 minutes ago you declared in a nearby thread that > > > It isn't about the Python programming language so it is off topic. So > > what if some members have an interest? We have interest in a lot of > > things. We all have interest in the hardware that our programs run on > > but questions about hardware are also off topic. > > > > Perhaps you don't quite grasp the point of topical discussion groups. > > They are a way of letting individuals decide for themselves what kind > > of discussions they want to be involved in. By spamming the group this > > way you take away that freedom of choice. It's ironic when it is done > > in the name of freedom. > > Touche! > > Cheers, > Daniel > > > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: loop over list and process into groups
Man, deja-vu, I could have sworn I read this thread months ago... On Thu, Mar 4, 2010 at 2:18 PM, nn wrote: > > > lbolla wrote: > > On Mar 4, 3:57 pm, Sneaky Wombat wrote: > > > [ {'vlan_or_intf': 'VLAN2021'}, > > > {'vlan_or_intf': 'Interface'}, > > > {'vlan_or_intf': 'Po1'}, > > > {'vlan_or_intf': 'Po306'}, > > > {'vlan_or_intf': 'VLAN2022'}, > > > {'vlan_or_intf': 'Interface'}, > > > {'vlan_or_intf': 'Gi7/33'}, > > > {'vlan_or_intf': 'Po1'}, > > > {'vlan_or_intf': 'Po306'}, > > > {'vlan_or_intf': 'VLAN2051'}, > > > {'vlan_or_intf': 'Interface'}, > > > {'vlan_or_intf': 'Gi9/6'}, > > > {'vlan_or_intf': 'VLAN2052'}, > > > {'vlan_or_intf': 'Interface'}, > > > {'vlan_or_intf': 'Gi9/6'},] > > > > > > I want it to be converted to: > > > > > > [{'2021':['Po1','Po306']},{'2022':['Gi7/33','Po1','Po306']},etc etc] > > > > > > I was going to write a def to loop through and look for certain pre- > > > compiled regexs, and then put them in a new dictionary and append to a > > > list, but I'm having trouble thinking of a good way to capture each > > > dictionary. Each dictionary will have a key that is the vlan and the > > > value will be a list of interfaces that participate in that vlan. > > > Each list will be variable, many containing only one interface and > > > some containing many interfaces. > > > > > > I thought about using itertools, but i only use that for fixed data. > > > I don't know of a good way to loop over variably sized data. I was > > > wondering if anyone had any ideas about a good way to convert this > > > list or dictionary into the right format that I need. The solution I > > > come up with will most likely be ugly and error prone, so I thought > > > i'd ask this python list while I work. Hopefully I learn a better way > > > to solve this problem. > > > > > > Thanks! > > > > > > I also have the data in a list, > > > > > > [ 'VLAN4065', > > > 'Interface', > > > 'Gi9/6', > > > 'Po2', > > > 'Po3', > > > 'Po306', > > > 'VLAN4068', > > > 'Interface', > > > 'Gi9/6', > > > 'VLAN4069', > > > 'Interface', > > > 'Gi9/6',] > > > > > > > > === > > > > from itertools import groupby > > > > data = \ > > [ {'vlan_or_intf': 'VLAN2021'}, > > {'vlan_or_intf': 'Interface'}, > > {'vlan_or_intf': 'Po1'}, > > {'vlan_or_intf': 'Po306'}, > > {'vlan_or_intf': 'VLAN2022'}, > > {'vlan_or_intf': 'Interface'}, > > {'vlan_or_intf': 'Gi7/33'}, > > {'vlan_or_intf': 'Po1'}, > > {'vlan_or_intf': 'Po306'}, > > {'vlan_or_intf': 'VLAN2051'}, > > {'vlan_or_intf': 'Interface'}, > > {'vlan_or_intf': 'Gi9/6'}, > > {'vlan_or_intf': 'VLAN2052'}, > > {'vlan_or_intf': 'Interface'}, > > {'vlan_or_intf': 'Gi9/6'},] > > > > def clean_up(lst): > > return [d.values()[0] for d in data if d.values()[0] != > 'Interface'] > > > > out = {} > > for k, g in groupby(clean_up(data) , key=lambda s: > > s.startswith('VLAN')): > > if k: > > key = list(g)[0].replace('VLAN','') > > else: > > out[key] = list(g) > > > > print out > > === > > > > hth, > > L. > > Good use of groupby. Here is what I ended up coming up: > > from itertools import groupby > laninfo=[ 'VLAN4065', > 'Interface', > 'Gi9/6', > 'Po2', > 'Po3', > 'Po306', > 'VLAN4068', > 'Interface', > 'Gi9/6', > 'VLAN4069', > 'Interface', > 'Gi9/6',] > > def splitgrp(s, f=[False]): > f[0]^=s.startswith('VLAN') > return f[0] > lanlst=(list(g) for k,g in groupby(laninfo,key=splitgrp)) > out={item[0][4:]:item[2:] for item in lanlst} > print(out) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: execute bash builtins in python
On Wed, Mar 17, 2010 at 11:44 AM, Nobody wrote: > On Fri, 12 Mar 2010 08:15:49 -0500, Steve Holden wrote: > > > For shell=True I believe you should provide the command as a single > > string, not a list of arguments. > > Using shell=True with an argument list is valid. > > On Unix, it's seldom what you want: it will invoke /bin/sh to execute the > first argument with $1, $2, ... set from the remaining arguments. > > On Windows, a list is converted to a string in the same manner regardless > of the value of the "shell" argument. Specifying shell=True causes the > command string to be executed via "cmd /c ...". This allows the "program" > to be a script, whereas shell=False requires the program to be a binary > executable. > > -- > http://mail.python.org/mailman/listinfo/python-list > if you can work interactively, save yourself the headache and just use Ipython: brucewa...@broo:~$ ipython Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: alias Total number of aliases: 15 Out[1]: [('cat', 'cat'), ('clear', 'clear'), ('less', 'less'), ('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('cp', 'cp -i'), ('lc', 'ls -F -o --color'), ('ldir', 'ls -F -o --color %l | grep /$'), ('lf', 'ls -F -o --color %l | grep ^-'), ('lk', 'ls -F -o --color %l | grep ^l'), ('ll', 'ls -lF'), ('ls', 'ls -F'), ('lx', 'ls -F -o --color %l | grep ^-..x'), ('mv', 'mv -i'), ('rm', 'rm -i')] In [2]: -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to open a file for shared write mode under Windows?
you could also just have one process do the writing for both processes via pipes. On Thu, Mar 18, 2010 at 12:20 AM, Gabriel Genellina wrote: > En Wed, 17 Mar 2010 23:42:46 -0300, escribió: > > > Is there a way to open a file for shared write mode under >> Windows? >> >> I have 2 processes that will write to different regions of this >> shared file. >> > > Using the pywin32 package at sourceforge, you have access to the CreateFile > function: http://msdn.microsoft.com/en-us/library/aa363858(v=VS.85).aspx > You want dwShareMode=FILE_SHARE_WRITE > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to open a file for shared write mode under Windows?
It's not too difficult: # subp.py import sys import time for i in range(10): sys.stdout.write('I am subprocess\n') sys.stdout.flush() # this may not be necessary time.sleep(1) # writer.py import subprocess import time subp = subprocess.Popen(['/usr/bin/python', '-u', './subp.py'], stdout=subprocess.PIPE) while True: time.sleep(1) print('I am main process.') # write this to one section of the file if subp.poll() != None: # the subprocess has terminated break stdout = subp.stdout.readline() print(stdout) # write this to the other section brucewa...@broo:~/Documents$ python ./writer.py I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. I am subprocess I am main process. On Thu, Mar 18, 2010 at 12:52 AM, Steve Holden wrote: > Chris Colbert wrote: > [top-posting switched to bottom-posting] > > > > On Thu, Mar 18, 2010 at 12:20 AM, Gabriel Genellina > > mailto:gagsl-...@yahoo.com.ar>> wrote: > > > > En Wed, 17 Mar 2010 23:42:46 -0300, > <mailto:pyt...@bdurham.com>> escribió: > > > > > > Is there a way to open a file for shared write mode under > > Windows? > > > > I have 2 processes that will write to different regions of this > > shared file. > > > > > > Using the pywin32 package at sourceforge, you have access to the > > CreateFile function: > > http://msdn.microsoft.com/en-us/library/aa363858(v=VS.85).aspx > > You want dwShareMode=FILE_SHARE_WRITE > > > > you could also just have one process do the writing for both processes > > via pipes. > > You could, but then you'd have to work out how to avoid blocking on one > pipe when data was available form the other. Or is this trivially easy, > and I just don't know enough about pipes? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ > Holden Web LLC http://www.holdenweb.com/ > UPCOMING EVENTS:http://holdenweb.eventbrite.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: C++ code generation
I think Stefan was telling you, in a nice way, to stop spamming every thread about code generation with a plug for your project. 2010/3/17 CHEN Guang > >> - Original Message - > >> From: "Dan Goodman" > >> > >>> I'm doing some C++ code generation using Python, and would be > interested > >>> in any comments on the approach I'm taking. > >> > >> PythoidC ( http://pythoidc.googlecode.com ) is a C code generator (not > C++) > > > > It would be nice if you could start reading the posts before you answer, > > and then try to give an answer that fits the question. > > > > Stefan > > I have read the post, may be I lost some words and made you misunderstand. > I meant: > PythoidC ( http://pythoidc.googlecode.com ) is a C code generator (but not > C++), if you find it useful, > welcome to take a look. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
ANN: Pymazon 0.1.1 Released
I'm happy to announce the release of Pymazon 0.1.1! This release brings a big enhancement in the form of PyGtk support in addition to the PyQt4 and Command line interfaces already available. A special thanks to Ray Meyers for his gtk commits! Pymazon Changelog 0.1.1 - - Added support for command line options and configuration file - Added support for save name templates - Added a threaded downloader which runs a user-specified simultaneous threads when in gui mode - Added a PyGtk Gui (Submitted by Raymond Myers) - Rewrote the QT Gui with Qt Designer and pyuic4 - this simplified and cleaned up a bunch of stuff - Added graphical progress bars to the Gui's - Removed a check that asserted the downloaded file size was the same as specified in the amz file as Amazon was misreporting file size and it was causing Pymazon to erroneously fail - Cleaned up code all over the place: logging, settings, etc... Pymazon is available in the cheeseshop and google code. Pymazon is a Python implemented downloader for the amazon mp3 store. You can read more about Pymazon at http://code.google.com/p/pymazon/. I always appreciate comments and bug reports. Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: nested threading
Spawning a thread from within a thread works just fine. Calling thread.start() is a non-blocking function and returns immediately. On Thu, Mar 25, 2010 at 11:23 AM, Omer Ihsan wrote: > is there anything as "nested threading"that is, call a thread from > within a thread. > in this case how will thread locking take place. > > for example initially there were two functions that were called using > threading.Thread. these wont get unlocked unless both of them are done > with whatever they need to do. if say function 2 calls another thread. > then what?? > > inquisitive:-| > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes as namespaces?
i use them in Pymazon to encapsulate program wide settings and enforce valid values for these settings. http://code.google.com/p/pymazon/source/browse/pymazon/settings.py On Fri, Mar 26, 2010 at 11:50 AM, Jean-Michel Pichavant < jeanmic...@sequans.com> wrote: > kj wrote: > >> What's the word on using "classes as namespaces"? E.g. >> >> class _cfg(object): >>spam = 1 >>jambon = 3 huevos = 2 >> >> breakfast = (_cfg.spam, _cfg.jambon, _cfg.huevos) >> >> >> Granted, this is not the "intended use" for classes, and therefore >> could be viewed as a misuse ("that's what dictionaries are for", >> etc.). But other than this somewhat academic objection[*], I really >> can see no problem with using classes in this way. >> >> > You cannot see the problem because there's no problem using classes as > namespaces. > > And yet, I've come across online murky warnings against using >> classes as "pseudo-namespaces". Is there some problem that I'm >> not seeing with this technique? >> >> ~K >> >> > import this > [snip] > Namespaces are one honking great idea -- let's do more of those! > > Modules and dictionaries are no more namespaces than classes. So any > container is potentially a namespace. > > JM > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Have you embraced Python 3.x yet?
On Fri, Mar 26, 2010 at 4:07 PM, Mensanator wrote: > On Mar 26, 8:23 am, Harishankar wrote: > > Have you people embraced Python 3.x or still with 2.5 or 2.6? > > 3.1. > > The only module I use regularly is gmpy and that's one that has > been updated. > -- > http://mail.python.org/mailman/listinfo/python-list > I won't switch until NumPy and SciPy make the jump. -- http://mail.python.org/mailman/listinfo/python-list
Re: GIF89A and PIL
since the images only use a couple colors each, just run length encode it. Depending on the image, you may be able to get a super small size that way, and avoid the whole mess. On Sat, Mar 27, 2010 at 11:32 PM, Harishankar wrote: > On Sat, 27 Mar 2010 19:44:54 -0700, Stephen Hansen wrote: > > > On 2010-03-27 08:17:46 -0700, Alain Ketterlin said: > > > >> Stephen Hansen writes: > > > >>> If not, are there any decent other image libraries out there that > >>> anyone's familiar with? The only one I could find was PythonMagick, > >>> which seems completely undocumented. Or I'm blind. > >> > >> I don't know PythonMagick, but it is based on ImageMagick, which is > >> kind of a swiss-knife in image manipulation and conversion. You could > >> try the standalone tools first, to see if you get what you want/need. > > > > Well, I know it -can- do what I need, except the subprocess business > > isn't something I want to deal with. And the library seems utterly > > undocumented. :( > > > >> Hmm, a 16x16 image. Don't expect much from the most sophisticated > >> formats (e.g, PNG), because their overhead (headers etc.) may well be > >> above the size of the data. Compression isn't usually targeted at small > >> files. > > > > Yeah, I don't expect much from PNG. The images are very small but I > > might be sending a LOT of them over a pipe which is fairly tight, so > > 50-60 bytes matters. That's why I selected GIF. > > > >> (BTW: "slight tweaking" may have an effect on file-size if it > >> introduces new colors, because GIF uses a color-table. I guess you know > >> all this.) > > > > Yeah, I know this is possible, which is why the tweaking was to be very > > careful: these images all have only a couple indexed colors each, and I > > should be able to do the tweaks and not increase the size excessively. > > > > However, the problem is: I left out all the tweaks and it still exploded > > in size. > > > > Just opening, and then saving the same file with no changes at all, > > resulted in a 72 byte file growing to 920. > > > > I thought it was GIF87a vs GIF89a... but have since come to determine it > > doesn't appear to be. I decided to give PNG a try again, since those > > extra 50 bytes *matter*, but if I can't get GIF to work, 50 is better > > then 900. Unfortunately, I hit the same wall there. > > > > If I convert these itty-bitty images into PNG, they're about 120 bytes > > or so. Opening one in PNG, making no changes, and saving, results in the > > new file being 900 bytes too :( > > > > So I wonder if there's just some hyper-optimization Photoshop does that > > PIL can't round-trip. > > > >> GIF uses the LZW algorithm, and so does zip and gzip (the latter with > >> an additional layer of Huffmann coding). If your images are of fixed > >> size, you _may_ be better off compressing the raw data with a general > >> purpose compressor (i.e., gzip). Check the packages gzip and zlib. > > > > Hm. I hadn't thought of compressing the saved version. I could do that, > > I suppose: it just seems there is so much extra stuff which shouldn't be > > needed that's being saved out. > > This might not be of much use to you, but I've found by experience that > PNGs are almost always bigger or equal to GIFs of the same resolution, > colour depth and so on. I've never yet seen a PNG file that is smaller > than a GIF for the same set of pixels. > > As mentioned above, compressing raw data stream might be more beneficial > in this situation. > > Also try the pngcrush utility and see what size it gives you. > http://pmt.sourceforge.net/pngcrush/ > > -- > Harishankar (http://harishankar.org http://literaryforums.org) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: "Usability, the Soul of Python"
not really, the int will eventually overflow and cycle around ;) On Tue, Mar 30, 2010 at 8:11 AM, Xavier Ho wrote: > Did no one notice that > > > for(i = 99; i > 0; ++i) > > Gives you an infinite loop (sort of) because i starts a 99, and increases > every loop? > > Cheers, > > Ching-Yun Xavier Ho, Technical Artist > > Contact Information > Mobile: (+61) 04 3335 4748 > Skype ID: SpaXe85 > Email: cont...@xavierho.com > Website: http://xavierho.com/ > > > > On Tue, Mar 30, 2010 at 9:40 PM, Alf P. Steinbach wrote: > >> * Jean-Michel Pichavant: >> >>> John Nagle wrote: >>> Jonathan Hayward wrote: > I've posted "Usability, the Soul of Python: An Introduction to the > Python Programming Language Through the Eyes of Usability", at: > > http://JonathansCorner.com/python/ > No, it's just a rather verbose introduction to Python, in dark brown type on a light brown background. One could write a good paper on this topic, but this isn't it. John Nagle >>> Why is it bad ? >>> >> >> Consider >> >> >> >> >From a usability standpoint, the braces go with the lines to print out >> the stanza rather than the for statement or the code after, so the following >> is best: >> >> for(i = 99; i > 0; ++i) >>{ >>printf("%d slabs of spam in my mail!\n", i); >>printf("%d slabs of spam,\n", i); >>printf("Send one to abuse and Just Hit Delete,\n"); >>printf("%d slabs of spam in my mail!\n\n", i + 1); >>} >> >> >> >> This is just unsubstantiated opinion, but worse, it makes a tacit >> assumption that there is "best" way to do indentation. However, most >> programmers fall into that trap, and I've done it myself. In fact, when I >> worked as a consultant (then in Andersen Consulting, now Accenture) I used >> the style above. Petter Hesselberg, author of "Industrial Strength Windows >> Programming" (heh, I'm mentioned) asked my why on Earth I did that, like, >> nobody does that? It was a habit I'd picked up in Pascal, from very naïve >> considerations of parse nesting levels, a kind of misguided idealism instead >> of more practical pragmatism, but since I realized that that was an >> incredibly weak argument I instead answered by pointing towards Charles >> Petzold's code in his "Programming Windows" books. And amazingly I was >> allowed to continue using this awkward and impractical style. >> >> I may or may not have been responsible for the similarly impractical >> compromise convention of using three spaces per indentation level. At least, >> in one big meeting the question about number of spaces was raised by the >> speaker, and I replied from the benches, just in jest, "three!". And that >> was it (perhaps). >> >> >> Cheers, >> >> - Alf (admitting to earlier mistakes) >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: (a==b) ? 'Yes' : 'No'
On Tue, Mar 30, 2010 at 1:08 PM, John Nagle wrote: > Chris Rebert wrote: > >> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone >> wrote: >> >>> Hi, how can I write the popular C/JAVA syntax in Python? >>> >>> Java example: >>> return (a==b) ? 'Yes' : 'No' >>> >>> My first idea is: >>> return ('No','Yes')[bool(a==b)] >>> >>> Is there a more elegant/common python expression for this? >>> >> >> Yes, Python has ternary operator-like syntax: >> return ('Yes' if a==b else 'No') >> >> Note that this requires a recent version of Python. >> > >Who let the dogs in? That's awful syntax. > >John Nagle > > -- > http://mail.python.org/mailman/listinfo/python-list > I wouldn't say that. It reads exactly how one would say it. I prefer this over the ? semantics. Whenever I see that, my mind goes "Does a equal b? If so, return this, otherwise return that". "Return this if a equals b, otherwise return that" is much more direct and declaritive IMHO. -- http://mail.python.org/mailman/listinfo/python-list
Re: sort array, apply rearrangement to second
On Tue, Mar 30, 2010 at 7:25 PM, Victor Eijkhout wrote: > I have two arrays, made with numpy. The first one has values that I want > to use as sorting keys; the second one needs to be sorted by those keys. > Obviously I could turn them into a dictionary of pairs and sort by the > first member, but I think that's not very efficient, at least in space, > and this needs to be done as efficiently as possible. > > I could use a hand. > > Victor. > -- > Victor Eijkhout -- eijkhout at tacc utexas edu > -- > http://mail.python.org/mailman/listinfo/python-list > I'm not quite sure what you are asking, but there is probably an efficient way to do it in pure numpy. You can either post an example of what you want here, or better, take it to the NumPy mailing list and I will help you there. -- http://mail.python.org/mailman/listinfo/python-list
Re: sort array, apply rearrangement to second
On Tue, Mar 30, 2010 at 9:59 PM, Chris Colbert wrote: > > > On Tue, Mar 30, 2010 at 7:25 PM, Victor Eijkhout wrote: > >> I have two arrays, made with numpy. The first one has values that I want >> to use as sorting keys; the second one needs to be sorted by those keys. >> Obviously I could turn them into a dictionary of pairs and sort by the >> first member, but I think that's not very efficient, at least in space, >> and this needs to be done as efficiently as possible. >> >> I could use a hand. >> >> Victor. >> -- >> Victor Eijkhout -- eijkhout at tacc utexas edu >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > I'm not quite sure what you are asking, but there is probably an efficient > way to do it in pure numpy. You can either post an example of what you want > here, or better, take it to the NumPy mailing list and I will help you > there. > > This seems to be what you want: http://stackoverflow.com/questions/1903462/how-can-i-zip-sort-parallel-numpy-arrays -- http://mail.python.org/mailman/listinfo/python-list
Re: Python + OpenOffice Calc
On Wed, Mar 31, 2010 at 4:21 PM, bobicanprogram wrote: > On Mar 31, 2:47 am, Tracubik wrote: > > Hi all! > > i'm giving away to a friend of mine that have a garage (he repair car) my > > old computer. He will use it essentialy to create estimates of the work > > via an ods file (i've made a simple ods file to be filled with the cost > of > > materials and a description of the work). > > He's totally new with computer and have difficult to fill the ods file, > so > > i'ld like to create a simple python program that help him to introduce > the > > data in to the ods file via a simple gui. > > So what i'm looking for is a way in python to insert data in a particular > > cell of the ods file and possibly to save it and print it when it's full > > filled with data. > > > > the guy is similar to this: > > > > 3 fields: quantity - description of the piece bought - price > > > > a way to add a new "line" if needed (for a new piece entry) similar to > the > > "add rule" in evolution > > > > 1 text field for the description of the work + 1 field for the price of > > the work > > > > and off course a way to insert this data in to the ods file via python > > > > Any hints/tutorial/info? > > > > thanks > > Nico > > > OOcalc supports a little known feature whereby data can be > automatically sync'd between the spreadsheet and an HTML table. A > few years ago I did up a demo of this in action using Tcl/Tk (http:// > www.icanprogram.com/hosug). It should not be too hard to port this > idea to Python. > > bob > -- > http://mail.python.org/mailman/listinfo/python-list > if he cant click on a cell in oocalc, what makes you think he'll be able to use your program? -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm not sure you understand
On Fri, Apr 2, 2010 at 11:35 AM, A Serious Moment wrote: > Do you really not see the complete absurdity of posting an entire paper in this forum as plain text? Not only are you completely off-topic for this group, but the paper as you posted it is completely unreadable; regardless of whether it is plagiarized or not. -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie/2.5.1.1] Computing value of a word?
On Wed, Feb 16, 2011 at 4:27 AM, Chris Rebert wrote: > On Wed, Feb 16, 2011 at 1:17 AM, Gilles Ganault wrote: > > Hello, > > > > For a game, I need to go through a wordlist, and for each word, > > compute its value, ie. a=1, b=2, etc. > > > > So for instance, NewYork = 14 + 5 + 23 + 25 + 15 + 18 + 11 = 111. > > > > Before I write the obvious While loop to go through each line in the > > input text file, I was wondering if Python didn't already have some > > function to perform this type of computation. > > A = ord('a') - 1 > for line in your_file: >word = line.strip().lower() >score = sum(ord(letter)-A for letter in word) > > Or a one-liner (import not included): In [26]: import numpy as np In [27]: (np.frombuffer(buffer('NewYork'.lower()), dtype='uint8') - 96).sum() Out[27]: 111 -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance of list vs. set equality operations
the proof is in the pudding: In [1]: a = range(1) In [2]: s = set(a) In [3]: s2 = set(a) In [5]: b = range(1) In [6]: a == b Out[6]: True In [7]: s == s2 Out[7]: True In [8]: %timeit a == b 1000 loops, best of 3: 204 us per loop In [9]: %timeit s == s2 1 loops, best of 3: 124 us per loop On Tue, Apr 6, 2010 at 2:11 PM, Gustavo Narea wrote: > Hello! > > Could you please confirm whether my understanding of equality > operations in sets and lists is correct? This is how I think things > work, partially based on experimentation and the online documentation > for Python: > > When you compare two lists, *every* element of one of the lists is > compared against the element at the same position in the other list; > that comparison is done by the __eq__() method (or the equivalent for > builtin types). This is interrupted when a result is False. > > When you compare two sets, there's a loop over all the elements of the > first set, where the hash for that element is looked up in the second > set: > - If this hash matches the hash for one or more elements in the > second set, the element in the first set is compared (with __eq__ or > equivalent) against the elements in the second set which have the same > hash. When a result is True, nothing else is done on that element and > the loop takes the next element in the first set; when all the results > are False, the loop ends and the two sets are not equivalent. > - If the hash doesn't match that of an element in the second set, > then the loop ends and the two sets are not equivalent. > > So this means that: > 1.- When you have two collections which have the same elements, the > equality operation will *always* be faster with lists. > 2.- When you have two collections with different elements, the > equality operation *may* be faster with sets. > > For example, if you have two collections of 1,000 elements each and > 998 of them are equivalent, comparing both collections as sets will be > slower than doing it with lists. But if you have two collections of > 1,000 elements each and 998 of them are not equivalent, then comparing > both collections as lists will be slower than doing it with sets. > > The performance of equality operations on sets is directly > proportional to the amount of different elements in both sets, while > the performance of equality operations on lists is simply proportional > to the cardinality of the collection. > > In other words: The more different elements two collections have, the > faster it is to compare them as sets. And as a consequence, the more > equivalent elements two collections have, the faster it is to compare > them as lists. > > Is this correct? > > This is why so many people advocate the use of sets instead of lists/ > tuples in similar situations, right? > > Cheers, > > - Gustavo. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance of list vs. set equality operations
:slaps forehead: good catch. On Tue, Apr 6, 2010 at 5:18 PM, Gustavo Narea wrote: > On Apr 6, 7:28 pm, Chris Colbert wrote: >> the proof is in the pudding: >> >> In [1]: a = range(1) >> >> In [2]: s = set(a) >> >> In [3]: s2 = set(a) >> >> In [5]: b = range(1) >> >> In [6]: a == b >> Out[6]: True >> >> In [7]: s == s2 >> Out[7]: True >> >> In [8]: %timeit a == b >> 1000 loops, best of 3: 204 us per loop >> >> In [9]: %timeit s == s2 >> 1 loops, best of 3: 124 us per loop > > > I think you meant to set "s2 = set(b)": > = > In [1]: a = range(1) > > In [2]: b = range(1) > > In [3]: s1 = set(a) > > In [4]: s2 = set(a) > > In [5]: s3 = set(b) > > In [6]: %timeit a == b > 1 loops, best of 3: 191 us per loop > > In [7]: %timeit s1 == s2 > 1 loops, best of 3: 118 us per loop > > In [8]: %timeit s1 == s3 > 1000 loops, best of 3: 325 us per loop > = > > Cheers. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: python as pen and paper substitute
you may have a look at sage: http://www.sagemath.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: get objects from image
lookup "connected component labeling" in a machine vision book. On Thu, Apr 8, 2010 at 9:57 AM, Chris Hulan wrote: > On Apr 8, 9:17 am, Jannis Syntychakis wrote: >> Hallo Everybody, >> >> Maybe you can help me with this: >> >> i have a picture. The picture is black, with some white objects. >> >> Is there any way i can detect the automatically? Something like: >> if there white objects bigger than 3 pixels draw a box there or get >> their >> position! >> >> getting their position is more important for me. >> >> One more question:" >> >> can i let the user tell the software there the white object is? like a >> square >> this moves with the mouse and the user will be able to click on the >> white objects. >> >> Maybe somebosy could help? with an example maybe? >> >> Thank you very much in advance >> >> Ioannis > > Sounds like a job for an image lib, like say Camellia (http:// > camellia.sourceforge.net/index.html) > Their info Mentions a Ruby interface, so a python interface should be > fairly easy > > cheers > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to open and read an unknown extension file
On Thu, Apr 8, 2010 at 11:42 AM, Kushal Kumaran wrote: > On Thu, Apr 8, 2010 at 9:00 PM, varnikat t wrote: >> I am trying to do this >> if os.path.exists("*.*.txt"): >> file=open("*.*.txt") >> self.text_view.get_buffer().set_text(file.read()) >> else: >> file=open("*.*.html") >> self.text_view.get_buffer().set_text(file.read()) >> >> It gives error *.*.txt not existingThere are two files in the folder >> testing.pnm.txt >> and testing.pnm.html >> How to make it open any name and extension file and read it? >> > > os.path.exists does not do pattern matching like that. Take a look at > the glob module. > > -- > regards, > kushal > -- > http://mail.python.org/mailman/listinfo/python-list > In [4]: files = [f for f in os.listdir(os.getcwd()) if os.path.splitext(f)[-1]=='.txt'] In [5]: files Out[5]: ['pip-log.txt', 'extended_abstract.txt', 'testlog.txt', 'pymazon_error_log.txt', 'hny.txt'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating a rainbow?
On Thu, Apr 8, 2010 at 12:46 PM, Tobiah wrote: > I'm having a difficult time with this. I want > to display a continuous range of hues using HTML > hex representation (#RRGGBB). How would I go > about scanning through the hues in order to > make a rainbow? > > Thanks, > > Toby > -- > http://mail.python.org/mailman/listinfo/python-list > In [43]: possible = [] In [44]: for i in range(2**8): : h = hex(i).lstrip('0x') : while len(h) < 2: : h = '0' + h : possible.append(h) : : In [45]: full = [r + g + b for r in possible for g in possible for b in possible] In [46]: len(full) Out[46]: 16777216 In [47]: 2**24 Out[47]: 16777216 -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating a rainbow?
On Thu, Apr 8, 2010 at 1:14 PM, Tobiah wrote: >> Look at the colorsys module. >> >> http://docs.python.org/library/colorsys.html?highlight=colorsys#module- > colorsys > > That so rocks. Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > How does that answer your original question? -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating a rainbow?
On Thu, Apr 8, 2010 at 2:34 PM, Tobiah wrote: >> How does that answer your original question? > > I was able to do this: > > import colorsys > > sat = 1 > value = 1 > length = 1000 > for x in range(0, length + 1): > hue = x / float(length) > color = list(colorsys.hsv_to_rgb(hue, sat, value)) > for x in range(3): > color[x] = int(color[x] * 255) > hexval = ("#%02x%02x%02x" % tuple(color)).upper() > print "" > % hexval > > > http://tobiah.org/rainbow.html > -- > http://mail.python.org/mailman/listinfo/python-list > I see. It appears I misunderstood the question. The link doesn't work in Chrome btw. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get text from a html file?
On Tue, Apr 13, 2010 at 1:58 PM, varnikat t wrote: > > Hi, > Can anyone tell me how to get text from a html file?I am trying to display > the text of an html file in textview(of glade).If i directly display the > file,it shows with html tags and attributes, etc. in textview.I don't want > that.I just want the text. > Can someone help me with this? > > > Regards > Varnika Tewari > > -- > http://mail.python.org/mailman/listinfo/python-list > > You should look into beautiful soup http://www.crummy.com/software/BeautifulSoup/ -- http://mail.python.org/mailman/listinfo/python-list
ANN: Pymazon 0.9 released!
I am happy to announce the 0.9 release of Pymazon. http://code.google.com/p/pymazon/ Pymazon is a Python implemented downloader for the Amazon MP3 store. This release is a near-full rewrite which brings a brand new GUI design and a host of new features: Notably: - Pymazon now supports MP3 downloads which contain digital booklets and video attachments. - The GUI now has a settings dialog. No more having to manually edit the .pymazonrc file - An improved command line downloader interface. - A much much cleaner code-base. I wasn't happy with Pymazon the first time around, hence the rewrite. - Some convenience functionalities to mimic the official Amazon downloader. Pymazon can run on PyQt4, PyGtk, and the command line. This release is serving as the beta before the 1.0 release. I have done a fair bit of testing on this release, show it should be pretty stable. However, please report any bugs so I can fix them and tag the official 1.0 version. Aside from google code, Pymazon is also available in the cheese shop. Cheers! -- http://mail.python.org/mailman/listinfo/python-list
Permanently adding to the Python path in Ubuntu
I'm having an issue with sys.path on Ubuntu. I want some of my home built packages to overshadow the system packages. Namely, I have built numpy 1.3.0 from source with atlas support, and I need it to overshadow the system numpy 1.2.1 which I had to drag along as a dependency for other stuff. I have numpy 1.3.0 installed into /usr/local/lib/python2.6/dist-packages/. The issue is that this directory is added to the path after the /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my version of numpy. I have been combating this with a line in my .bashrc file: export PYTHONPATH=/usr/local/lib/python2.6/dist-packages So when I start python from the shell, everything works fine. Problems show up when python is not executed from the shell, and thus the path variable is never exported. This can occur when I have launcher in the gnome panel or i'm executing from within wing-ide. Is there a way to fix this so that the local dist-packages is added to sys.path before the system directory ALWAYS? I can do this by editing site.py but I think it's kind of bad form to do it this way. I feel there has to be a way to do this without root privileges. Any ideas? Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Permanently adding to the Python path in Ubuntu
I don't want to have to modify the path in each and every application. There has to be a way to do this... Personally, I don't agree with the Debian maintainers in the order they import anyway; it should be simple for me to overshadow system packagers. But that's another story. P.S. my first name is Steven! Cheers, Chris On Sat, Aug 29, 2009 at 11:51 PM, Sean DiZazzo wrote: > On Aug 29, 5:39 pm, Chris Colbert wrote: >> I'm having an issue with sys.path on Ubuntu. I want some of my home >> built packages to overshadow the system packages. Namely, I have built >> numpy 1.3.0 from source with atlas support, and I need it to >> overshadow the system numpy 1.2.1 which I had to drag along as a >> dependency for other stuff. I have numpy 1.3.0 installed into >> /usr/local/lib/python2.6/dist-packages/. The issue is that this >> directory is added to the path after the >> /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my >> version of numpy. >> >> I have been combating this with a line in my .bashrc file: >> >> export PYTHONPATH=/usr/local/lib/python2.6/dist-packages >> >> So when I start python from the shell, everything works fine. >> >> Problems show up when python is not executed from the shell, and thus >> the path variable is never exported. This can occur when I have >> launcher in the gnome panel or i'm executing from within wing-ide. >> >> Is there a way to fix this so that the local dist-packages is added to >> sys.path before the system directory ALWAYS? I can do this by editing >> site.py but I think it's kind of bad form to do it this way. I feel >> there has to be a way to do this without root privileges. >> >> Any ideas? >> >> Cheers, >> >> Chris > > I think you can modify sys.path inside your application. > > Maybe this will work (at the top of your script): > > > import sys > sys.path[0] = "/usr/local/lib/python2.6/dist-packages" > > import numpy > > > PS. Say hi to Steven for me! > > ~Sean > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Permanently adding to the Python path in Ubuntu
Great! That was the solution I was looking for. Thanks! Chris On Sun, Aug 30, 2009 at 12:29 PM, Christian Heimes wrote: > Chris Colbert wrote: >> Is there a way to fix this so that the local dist-packages is added to >> sys.path before the system directory ALWAYS? I can do this by editing >> site.py but I think it's kind of bad form to do it this way. I feel >> there has to be a way to do this without root privileges. >> >> Any ideas? > > Have you read my blog entry about my PEP 370? > http://lipyrary.blogspot.com/2009/08/how-to-add-new-module-search-path.html > > Christian > -- http://mail.python.org/mailman/listinfo/python-list
Re: IDE for Python
I'm a big fan of wing. Pay for the non-free version and you get all the goodies, plus PHENOMENAL support. Really. They answer support emails within a few minutes. Its has the best code completion i've seen in any python editor/ide and is also the most stable, fastest (for ide's), and customizable. I am not affiliated with Wingware or their parent company in any way. On Mon, Aug 31, 2009 at 11:32 AM, Che M wrote: > On Aug 31, 10:53 am, Mike Driscoll wrote: >> On Aug 29, 1:08špm, ivanko@gmail.com wrote: >> >> > 29.08.2009 4:14 ÐÏÌØÚÏ×ÁÔÅÌØ "Thangappan.M" š >> > ÎÁÐÉÓÁÌ: >> >> > > Dear all, >> > > Please suggest some good IDE for python.I am working in linux platform. >> > > -- >> > > Regards, >> > > Thangappan.M >> >> > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta >> > and š >> > Code:Blocks, but they are designed mainly for C++ (but still can be used). >> >> Don't forget Wingware IDE. Admittedly, it's not free (except for a >> limited version), but it's pretty good. There's also SPE (Stani's >> Python Editor). If you want a nigh-complete list, check the Python >> wiki: >> >> http://wiki.python.org/moin/PythonEditors > > Not sure when an editor gets to be called an IDE, but while on the > site > that OP should check out this related page: > > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing objects at runtime.
why not just pawn your processing loop off onto a child thread and give yourself a hook (function) that you can call that return whatver info you what. Run the script in ipython, problem solved. On Mon, Sep 14, 2009 at 7:57 AM, jacopo wrote: > >> You might consider running a BaseHTTPServer in a separate thread >> which has references to your objects of interest and exporting the >> data through a web interface. Using a RESTful approach for mapping >> URLs to objects within your system, a basic export of the data can >> be as simple as printing out HTML strings with interpolated data. > > > Thank you Gary, > > just to be sure I understood correctly: > with this solution, in order to inspect an object I would have to load > a web page at a specific URL. That URL, > through a separate thread, would access the object on the fly and > display the content in a web page?! > Is there a reason to link objects to different URLs or I could link > many of them to the same URL? > > Thanks, Jacopo > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Why use "locals()"
Given that python is devoid of types: "Is the variable 'a' an int or a float at runtime?", explicit can only be taken so far. Personally, I use locals() when I work with Django. On Mon, Sep 14, 2009 at 7:42 AM, Sean DiZazzo wrote: >> If you are willing to open your mind to the possibility that some >> Pythonic things don't adhere to every Zen, then I would suggest that >> Gabrielle's examples are perfectly Pythonic shortcuts. But if you >> don't want to use them, you don't have to, nobody is forcing you. > > It's a pretty small domain, but I see the use (and the Pythonicity). > > Thanks all for your advice. > > ~Sean > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
if you have numpy installed: ln[12]: import numpy as np In [13]: k = np.array([('a', 'bob', 'c'), ('p', 'joe', 'd'), ('x', 'mary', 'z')]) In [14]: k Out[14]: array([['a', 'bob', 'c'], ['p', 'joe', 'd'], ['x', 'mary', 'z']], dtype='|S4') In [15]: k[:,1] Out[15]: array(['bob', 'joe', 'mary'], dtype='|S4') -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
by your definitions, Python is just a wrapper around a C library. If none of the solutions work for you, roll your own. On Thu, Sep 17, 2009 at 11:38 AM, Giacomo Boffi wrote: > John Nagle writes: > >> gerlos wrote: >>> John Nagle ha scritto: >>> I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. >>> Did you look at matplotlib? In their examples page there are some >>> charts like the ones you asked for. I guess it could work for you, >>> and it seems to work flawlessy in MS Windows as in gnu/linux. >> >> That's a wrapper for Antigrain ("http://www.antigrain.com/";), which is >> a C++ library. > > come on, you can configure matplotlib to use one of too many different > backends > > from http://matplotlib.sourceforge.net/users/customizing.html > > CONFIGURATION BEGINS HERE > > # the default backend; one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg > # MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template > # You can also deploy your own backend outside of matplotlib by > # referring to the module name (which must be in the PYTHONPATH) as > # 'module://my_backend' > backend : GTKAgg > > -- > Yes you who must leave everything that you cannot control. > It begins with your family, but soon it comes around to your soul. > Well I've been where you're hanging, I think I can see how you're pinned: > When you're not feeling holy, your loneliness says that you've sinned. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: palindrome iteration
;) In [29]: s = 'bannab' In [30]: a = np.frombuffer(s.lower(), dtype='uint8') In [31]: np.all(a == a[::-1]) Out[31]: True In [32]: s = 'bannac' In [33]: a = np.frombuffer(s.lower(), dtype='uint8') In [34]: np.all(a == a[::-1]) Out[34]: False -- http://mail.python.org/mailman/listinfo/python-list
why do I get this behavior from a while loop?
This seems strange to me, but perhaps I am just missing something: In [12]: t = 0. In [13]: time = 10. In [14]: while t < time: : print t : t += 1. : : 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 In [15]: t = 0. In [16]: time = 10. In [17]: while t < time: : print t : t += 0.1 : : 0.0 0.1 0.2 0.3 <--snip--> 9.4 9.5 9.6 9.7 9.8 9.9 10.0 I would think that second loop should terminate at 9.9, no? I am missing something fundamental? Cheers! Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: why do I get this behavior from a while loop?
What a newbie mistake for me to make. I appreciate the replies everyone! Cheers, Chris > On Fri, 27 Nov 2009 17:06:44 +0100, S. Chris Colbert wrote: > > I would think that second loop should terminate at 9.9, no? > > > > I am missing something fundamental? > > "What Every Computer Scientist Should Know About Floating Point" > http://docs.sun.com/source/806-3568/ncg_goldberg.html > -- http://mail.python.org/mailman/listinfo/python-list
ANN: Pymazon 0.1.0 released!
Hello, I'm happy to announce the first non-beta release of Pymazon: a python implemented downloader for the Amazon mp3 store. Improvements from the beta: - Running download status indicator - Various fixes for Windows - Some code cleanup Pymazon was created to be a simple and easy alternative for the Linux version of the Amazon downloader, and alleviate the pain of getting it to work with 64bit Linux. You can read about Pymazon at http://pymazon.googlecode.com You can download from googlecode or the cheeseshop: $ pip install pymazon or $ easy_install pymazon It also works on Windows. Dependencies: PyCrypto (it's in the ubuntu repos and the cheeseshop) PyQt4 >= 4.5 (optional, only needed for GUI) GPLv3 License Cheers! SCC -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary used to build a Triple Store
> Definitely a newbie question, so please bear with me. > > I'm reading "Programming the Semantic Web" by Segaran, Evans, and Tayor. > > It's about the Semantic Web BUT it uses python to build a "toy" triple > store claimed to have good performance in the "tens of thousands" of > triples. > > Just in case anybody doesnt know what an RDF triple is (not that it > matters for my question) think of it as an ordered 3 tuple representing > a Subject, a Predicate, and an Object eg: (John, loves, Mary) (Mary, > has-a, lamb) {theSky, has-color,blue} > > To build the triple store entirely in Python, the authors recommend > using the Python hash. Three hashes actually (I get that. You > want to have a hash with the major index being the Subject in one hash, > the Predicate in another hash, or the Object for the third hash) > > He creates a class SimpleGraph which initializes itself by setting the > three hashes names _spo, _pos, and _osp thus > > class SimpleGraph; >def __init__(self); > self._spo={}; > self._pos=(); > self._osp={}; > > So far so good. I get the convention with the double underbars for the > initializer but > > Q1: Not the main question but while I'm hereI'm a little fuzzy on > the convention about the use of the single underbar in the definition of > the hashes. Id the idea to "underbar" all objects and methods that > belong to the class? Why do that? > > But now the good stuff: > > Our authors define the hashes thus: (showing only one of the three > hashes because they're all the same idea) > > self._pos = {predicate:{object:set( [subject] ) }} > > Q2: Wha? Two surprises ... > 1) Why not {predicate:{object:subject}} i.e. > pos[predicate][object]=subjectwhy the set( [object] ) construct? > putting the object into a list and turning the list into a set to be the > "value" part of a name:value pair. Why not just use the naked subject > for the value? > because the argument has to be iterable. In [1]: set(1) --- TypeError Traceback (most recent call last) /home/brucewayne/ in () TypeError: 'int' object is not iterable > 2) Why not something like pos[predicate][object][subject] = 1 > .or any constant. The idea being to create the set of three indexes. > If the triple exists in the hash, its "in" your tripple store. If not, > then there's no such triple. > I can't really answer that, I imagine there is a better way to code what is trying to be accomplished. But I'm no Steven D'Aprano and I'm already a few beers in ;) -- http://mail.python.org/mailman/listinfo/python-list