Why the CLI hang using pyjwt ?
Not sure why the CLI command "pyjwt decode --no-verify ..." will hang at sys.stdin.read() even though I provided all the input. Any ideas on how to work around the problem? $ pyjwt -v pyjwt 1.5.3 $ pyjwt decode --no-verify eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg ^CTraceback (most recent call last): File "/usr/local/bin/pyjwt", line 11, in sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/jwt/main.py", line 157, in main output = arguments.func(arguments) File "/usr/local/lib/python2.7/dist-packages/jwt/main.py", line 58, in decode_payload token = sys.stdin.read() $ pyjwt decode --no-verify eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg ^CTraceback (most recent call last): File "/Users/v612996/anaconda/bin/pyjwt", line 11, in sys.exit(main()) File "/Users/v612996/anaconda/lib/python3.6/site-packages/jwt/main.py", line 157, in main output = arguments.func(arguments) File "/Users/v612996/anaconda/lib/python3.6/site-packages/jwt/main.py", line 58, in decode_payload token = sys.stdin.read() KeyboardInterrupt $ python --version Python 3.6.0 :: Anaconda custom (x86_64) But the same token decoded perfectly under python 2.6 interpreter: jwt.decode(encoded,verify=False) {u'some': u'payload'} What is the work around of "pyjwt decode --no-verify" hang in the CLI? -- https://mail.python.org/mailman/listinfo/python-list
Python added to PATH, cannot be directly accessed, cannot install pip
Hello team at python.org, I've asked this question on a forum and tried to figure it out myself, but I'm at a dead end. I don't know if you guys answer questions like this but I have no where else to turn to. I am using a Lenovo Laptop using Windows. I'm trying to install get-pip.py, and when I enter "python get-pip.py" into the Command Prompt, it says "Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases." So for a week, I've been trying to add Python to PATH, so I can install get-pip.py to Python. I've added the exact file location for Python to Path in both User Variables and System Variables. I've executed Manage App Execution Aliases, turned off both App Installer python.exe and App Installer python3.exe. Still can't install pip, Python was still not found. I've tried different keywords ("py get-pip.py", python3 get-pip.py", etc.). Still doesn't work. Python is added to PATH and I can still run Python scripts, but I can't find Python directly through the Command Prompt, and I cannot install get-pip.py to Python. For reference, I have Python version 3.9.6 and I installed Python directly from the site (I did not use Anaconda). Can you guys help me with this? Or do I need to delete Python and reinstall it? Sincerely, Will -- https://mail.python.org/mailman/listinfo/python-list
subprocess exiting in an incomprehensible fashion
I have this bit of code: #!/usr/bin/python import subprocess calc = subprocess.Popen("dc", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) max = 5 for value in range(1, max): calcout, calcerr = calc.communicate("%d\n" % value) print("Post Communicate Value %d: %s (%s) [%d]" % (value, calcout, calcerr, calc.returncode)) if value > 1: calcout, calcerr = calc.communicate("*\n") calcout, calerr = calc.communicate("p\n") print("Value: %d = %d" % (calcout, reduce(lambda x,y: x * y, range(1, max calc.communicate("q\n") status = calc.wait() print "Exited with: %d" % status ### End Code After the first number is input, the subprocess is exiting after the first communicate. I do not understand why. I have tried to accomplish the same thing with os.popen and popen2.Popen. I can't get anything to work and I am having a difficult time finding examples that include both redirected input and output from a subprocess. I am wanting to do work with a more complicated program, but was looking to get something simple working first. Any help would be much appreciated. I have been hunting quite a bit for he answer to no avail. Will Holcomb -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess exiting in an incomprehensible fashion
Well, I'll be damned... Thank you very much. I'm still getting a little tripped up with blocking IO and whatnot, but I think I can work that out. This was a real help, thanks again. #!/usr/bin/python # -*- coding: UTF-8 -*- import subprocess import random import re import os import time import select calc = subprocess.Popen("dc", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) max = random.Random().randint(10, 100) for value in range(1, max): calc.stdin.write("%d\n" % value) if value > 1: calc.stdin.write("*\n") calc.stdin.write("p\n") select.select([calc.stdout.fileno()], [], []) time.sleep(.1) # Still not always getting the result string = os.read(calc.stdout.fileno(), 500) print "String: ", string dcproduct, repcount = re.subn("\\\|\\s", "", string) dcproduct = int(dcproduct) pyproduct = reduce(lambda x,y: x * y, range(1, max)) if dcproduct == pyproduct: print "Π(1,%d):" % (max - 1) else: print "Products don't match: n = %d" % (max - 1) print " %d" % dcproduct print " %d" % pyproduct calc.stdin.write("q\n") status = calc.wait() print "Exited with: %d" % status -- http://mail.python.org/mailman/listinfo/python-list
Re: Game programming in Python
Hi Baza, On Tue, 11 Jan 2005 18:32:50 +, Baza <[EMAIL PROTECTED]> wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? You're probably beyond this book, however, for other newbies like moi checking this thread in future, I started with: "Python Programming for the absolute beginner" By Michael Dawson (Premier Press- www.premierpressbooks.com. ISBN: 1-59200-073-8) It's a great read and easy to follow, but more importantly in this instance, one learns Python by creating games (and then you can put this knowledge to use elsewhere). It comes with a CD that has Python 2.2.3, Pygame 1.5.6 and Livewires 2.0, the source code for the projects in the book, & useful links (as well as The Gimp for Windows and a demo version of the Cool Edit Pro multitrack recording studio). HTH. L8r, Will # Living & loving in Aotearoa, New Zealand. Kia ora Kiwis! -- http://mail.python.org/mailman/listinfo/python-list
Re: PUG in Melbourne Australia?
Hi , On Mon, 17 Jan 2005 14:50:34 GMT, Emiliano Molina <[EMAIL PROTECTED]> wrote: > Does anyone here know if there is a Python Users Group in Melbourne > Australia? I'm from NZ, but the closest thing to what you're after that I know of is over at Ozzope - Zope in Australia (Zope being built in Python). Have a look at http://www.ozzope.org and you'll find a couple of contacts there who'll be able to refine your search even further. HTH, Will :) ** From the shameless propaganda file: Need a Saatchi-quality copywriter, art director and concepts person, without their price tag? If so, email me and I'll send you the URL of my website. ** -- http://mail.python.org/mailman/listinfo/python-list
Any affordable Python-based CRM & ERP solutions?
Hi all, Please excuse the longish post. I'm new to Python (and programming), but love what I see and believe it to be an important language. I have (at least) one retail client (with single outlet at present) that requires a total business solution for their operation, preferably open source. They need: - an ecommerce website providing sales, customer service, order tracking and an opt-in newsletter - system for tracking inventory - full accounting system, tied-into the ecommerce website-- so full front-end and back-end system integration - possibly even point of sale tied-into the above. They've been using Windows up until now, but are happy to consider Linux, BSD, Mac, etc, as long as there's not a huge learning curve (they merely want a solution that works and is cost-effective). Other than standard accounting reporting requirements, they need the ability to add tax to local transactions. I have Googled with not a lot of contenders (Compiere-- http://www.compiere.org/index.html -- not Python and an Oracle license is required to run it; and I've just started reading about Bizar Shop-- http://www.bizarshop.com.au/). Anything else I've seen is either really expensive, doesn't fit the bill, or are not Python-based (which I'd ultimately like to promote). Because of the above requirements I was thinking something quite modular (that could be added to in future) would be the way to go. I like what I have seen with Plone and Zope but am unsure at present (given limited experience with these products) how one would integrate something into those solutions (if package didn't come from one 'vendor'), so that at least on the surface, everything appeared pretty seamless. Is this wishful thinking in Python at present? If so, have you encountered any other open source solutions that cover part of the above with Python handling the rest (and being easily integrated)? I look forward to any feedback. Thanks very much in advance. Cheers, Will :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on Vista installation issues
Vista is a 64 bit OS and there is no port of pywin32 for either Vista or 64-bit XP -- http://mail.python.org/mailman/listinfo/python-list
IDLE
Hi, I hope you are having a good day. I have a small IDLE problem and can’t seem to fix it. I have a .py file that I want to open using IDLE but there is no option I have even tried totally wiping python and reinstalling it nothing seems to work. Please help. Will Anderson [1]andersonwill...@gmail.com [2]Website References Visible links 1. mailto:andersonwill...@gmail.com 2. https://sites.google.com/view/willanderson/home -- https://mail.python.org/mailman/listinfo/python-list
proposal for slice hashing
I recently ran into a situation where I needed to hash a slice and found this to be unsupported. This seems silly as there is little benefit of slices not supporting hashing and large downsides. This coupled with the fact that one cannot subclass slices is a significant and needless annoyance. It seems to me a hash of a slices would simply be a hash of a slice would (in python) be: def __hash__(self): return hash((self.start, self.stop, self.step)) I can see no reason why this is not the case Context: I have an object that presents itself as a multidimensional array in the numpy style but is computes it's values on __getitem__ calls as it represents an infinite field of numbers. However this operation is expensive. In many cases the same slice of the field will be needed repeatedly. This lends itself to using an lru cache on __getitem__() however this does not work as slices cannot be stored in the dictionary key used for the lru_cache.* The only options as of now are: 1. use 3 layers of wrappers to pack the slices into a custom type that supports hashing pass this mangled version of the arguments through lru_cache wrapper into a function that reverses the process of the first wrapper and passes through to the underlying implementation. (see below "code for workaround" as example) - This is kinda jank and arguably slow. Though in my case the cost of the calculation operation dwarfs this cost by an several orders of magnitude. - mapping may be unreliable and is a rather long and impenetrable mess. 2. implementing my own custom caching for this situation which does not scale well and is a heck of a lot of work. 3. implement a special case for slices in the lru_cache function. However, this is just moving the problem into the functools library. * While I do realize that further efficiency gains would be found by caching results in a sparse and tracking what is and is not filled in the field thus keeping what is essentially a by cell cache that would be significantly more work and unlikely to yield much better results in my case and still doesn't solve the general use case. Code for Workaround: from functools import lru_cache class _hashable_slice(object): __slots__ = ['slice'] def __init__(self, s: slice): self.slice = s def __hash__(self): return hash((self.slice.start, self.slice.stop, self.slice.step)) def __eq__(self, other): return other == self.slice def slice_lru_cache(*lru_args, **lru_kwargs): lru_wrapper = lru_cache(*lru_args, **lru_kwargs) def decorator(f): @lru_wrapper def inner(*args, **kwargs): def unpack(x): if isinstance(x, _hashable_slice): return x.slice if isinstance(x, (tuple, list)): return type(x)(unpack(v) for v in x) else: return x return f(*(unpack(v) for v in args), **{k: unpack(v) for k, v in kwargs.items()}) def wrapper(*args, **kwargs): def pack(x): if isinstance(x, slice): return _hashable_slice(x) if isinstance(x, (tuple, list)): return type(x)(pack(v) for v in x) else: return x return inner(*(pack(v) for v in args), **{k: pack(v) for k, v in kwargs.items()}) wrapper.__getattr__ = lambda name: getattr(inner, name) return wrapper return decorator -- https://mail.python.org/mailman/listinfo/python-list
Re: proposal for slice hashing
On Monday, May 11, 2020 at 4:10:56 PM UTC-4, Chris Angelico wrote: > On Tue, May 12, 2020 at 6:01 AM Will Bradshaw wrote: > > The only options as of now are: > > 1. use 3 layers of wrappers to pack the slices into a custom type that > > supports hashing pass this mangled version of the arguments through > > lru_cache wrapper into a function that reverses the process of the first > > wrapper and passes through to the underlying implementation. (see below > > "code for workaround" as example) > >- This is kinda jank and arguably slow. Though in my case the cost > > of the calculation operation dwarfs this cost by an several orders of > > magnitude. > >- mapping may be unreliable and is a rather long and impenetrable > > mess. > > 2. implementing my own custom caching for this situation which does not > > scale well and is a heck of a lot of work. > > 3. implement a special case for slices in the lru_cache function. > > However, this is just moving the problem into the functools library. > > > > 4. Implement __getitem__ as a wrapper around a caching lookup function > that simply takes the three arguments. > > def __getitem__(self, slice): > return generate_values(slice.start, slice.stop, slice.step) > > @lru_cache > def generate_values(start, stop, step): > ... > > Not sure if this makes it easy enough to not worry about the hashability. > > ChrisA does not work in the case of multi dimensional __getitem__ calls in the numpy style which happens to be my case as the number of dimensions in the indexes changes by case and all of the following are supported for each axis: slice, array of indexes, int index, and other custom index object types which I am hesitant to disclose) -- https://mail.python.org/mailman/listinfo/python-list
Re: proposal for slice hashing
On Monday, May 11, 2020 at 4:45:55 PM UTC-4, Chris Angelico wrote: > On Tue, May 12, 2020 at 6:31 AM Will Bradshaw wrote: > > > > On Monday, May 11, 2020 at 4:10:56 PM UTC-4, Chris Angelico wrote: > > > On Tue, May 12, 2020 at 6:01 AM Will Bradshaw > > > wrote: > > > > The only options as of now are: > > > > 1. use 3 layers of wrappers to pack the slices into a custom type > > > > that supports hashing pass this mangled version of the arguments > > > > through lru_cache wrapper into a function that reverses the process of > > > > the first wrapper and passes through to the underlying implementation. > > > > (see below "code for workaround" as example) > > > >- This is kinda jank and arguably slow. Though in my case the > > > > cost of the calculation operation dwarfs this cost by an several orders > > > > of magnitude. > > > >- mapping may be unreliable and is a rather long and > > > > impenetrable mess. > > > > 2. implementing my own custom caching for this situation which does > > > > not scale well and is a heck of a lot of work. > > > > 3. implement a special case for slices in the lru_cache function. > > > > However, this is just moving the problem into the functools library. > > > > > > > > > > 4. Implement __getitem__ as a wrapper around a caching lookup function > > > that simply takes the three arguments. > > > > > > def __getitem__(self, slice): > > > return generate_values(slice.start, slice.stop, slice.step) > > > > > > @lru_cache > > > def generate_values(start, stop, step): > > > ... > > > > > > Not sure if this makes it easy enough to not worry about the hashability. > > > > > > ChrisA > > > > does not work in the case of multi dimensional __getitem__ calls in the > > numpy style which happens to be my case as the number of dimensions in the > > indexes changes by case and all of the following are supported for each > > axis: slice, array of indexes, int index, and other custom index object > > types which I am hesitant to disclose) > > > > Ah, fair enough. Was just looking for a solution that would work on > existing Python versions rather than demanding an upgrade to 3.10 :) I have a solution to the issue in current python, it was given in my first post at the bottom. I implemented a variant of it for my work. Just because there is a hack does not mean a fix should not be implemented. > Your use-case isn't common, but on the other hand, making slice > objects hashable doesn't seem like it'd break anything. Obviously > they'd only be hashable if start/stop/step are all hashable, but > that's no different from tuples. +0.5. I'm certain that my use case is not common. However, there are certainly many uncommon use cases in which being able to have a slice in a dictionary key or otherwise hashing a slice could be useful. > > BTW, your third option (moving the problem to functools) might > actually be easier than you think. You'd ultimately just be changing > the behaviour of _make_key. Unfortunately there's no easy way to > replace that function for a specific lru_cache, but that might itself > be a useful feature. Imagine this: > > @lru_cache(make_key=hashable_slices) > def __getitem__(self, item): > ... This is a good idea as it would allow for quite a bit of tuning by the user and allow trade offs to be made between cache lookup complexity and potentially unnecessary re-computes. -- https://mail.python.org/mailman/listinfo/python-list
Re: proposal for slice hashing
On Tuesday, May 12, 2020 at 5:51:37 PM UTC-4, Paul Rubin wrote: > Terry Reedy writes: > > Slice objects are similar to named tuples > > In that case making them hashable sounds like good sense. I mean I've already made and tested a patch it wasn't hard. I did same day as I made the post. I've also done a bit of work on the proposal to make the key function changeable in functools.lru_cache though that is a bit more complex and will take a bit of refactoring to do right. -- https://mail.python.org/mailman/listinfo/python-list
Re: Getting a number out of a string
Claudio Grondi wrote: > what about: > >>>>lst = [digit for digit in '06897'] >>>>lst > > ['0', '6', '8', '9', '7'] Or.. >>> list('06897') ['0', '6', '8', '9', '7'] Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
New Python chess module
Hi folks, I've written a Python chess module that does the following. * Reads / Writes PGN files * Write FEN files * Validates moves * Lists legal moves * Detects check / mate / stalemate / 50 move rule / threefold repetition Its still rough around the edges and not fully tested. I'll eventualy release a more polished version and possibly put it on Sourceforge. In the meantime I would be grateful for any feedback.. http://www.willmcgugan.com/chess.zip I am aware of the chess module by Erik Max Francis. It may have been more sensible to work on his version, but I did this mainly for the fun of it. I wrote a chess game in C++ a while back (http://www.chesscommander.com) and I thought it would be interesting to re-implement the chess library part in Python. Regards, Will McGugan -- http://www.willmcgugan.com -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python chess module
Pekka Karjalainen wrote: > > I have one minor point. It looks like your test whether the location is on > the board is needlessly complex. Python understands multiple comparisons > like in mathematical notation, and not like in e.g. C language. This > snippet shows what I mean: > > >>>>[x for x in range(10) if 2 > [3, 4, 5, 6] > > Read about it in the reference: > http://www.python.org/doc/2.4.2/ref/comparisons.html > Thanks. I was aware of that, I've just never got in to the habbit of using it.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python chess module
There is a new version if anyone is interested... http://www.willmcgugan.com/chess.py It contains optimizations and bugfixes. Can anyone suggest a name for this module? pyChess is already taken... Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: ASCII
Tuvas wrote: > Is there a function that will take a char. and return the ascii value? > Thanks! > ord Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
James A. Donald wrote: > I am contemplating getting into Python, which is used by engineers I > admire - google and Bram Cohen, but was horrified to read > > "no variable or argument declarations are necessary." > > Surely that means that if I misspell a variable name, my program will > mysteriously fail to work with no error message. > > If you don't declare variables, you can inadvertently re-use an > variable used in an enclosing context when you don't intend to, or > inadvertently reference a new variable (a typo) when you intended to > reference an existing variable. > > What can one do to swiftly detect this type of bug? A variable has to be assigned to before it is used, otherwise a NameError exception is thrown.. >>> a + 1 Traceback (most recent call last): File "", line 1, in ? NameError: name 'a' is not defined >>> a = 1 >>> a + 1 2 Typos in variable names are easily discovered unless the typo happens to exist in the current context. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Contest snub?
[EMAIL PROTECTED] wrote: > Notice anything strange here? The Python entry seems to have edged the PHP > entries, but is not declared the victor. Source is missing as well (the > archive > is empty.) > > http://www.apress.com/promo/fractal/seesource.html > > H... an irrational fear of snakes perhaps? Its not irrational if you are a gator! Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython question
vpr wrote: > Hi > > Does anyone have some example code to create a wx dialog that apears > off screen on the bottom right hand corner and slides up into the > screen ? > Andrea Gavana does.. http://xoomer.virgilio.it/infinity77/eng/freeware.html#toasterbox Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: 1-liner to iterate over infinite sequence of integers?
Neal Becker wrote: > I can do this with a generator: > > def integers(): > x = 1 > while (True): > yield x > x += 1 > > for i in integers(): > > Is there a more elegant/concise way? > import itertools for i in itertools.count(): print i Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: 1-liner to iterate over infinite sequence of integers?
Will McGugan wrote: > Neal Becker wrote: > >> I can do this with a generator: >> >> def integers(): >> x = 1 >> while (True): >> yield x >> x += 1 >> >> for i in integers(): >> Is there a more elegant/concise way? >> > > import itertools > for i in itertools.count(): > print i > Actualy itertools.count(1) to start at 1.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython question
vpr wrote: > I've had some problems, it seems that they dont render well in Linux. I > tried it with Ubuntu Breezy. I suspect that the animation may cause problems because of all the refreshes. Perhaps you can render the window first then save it as a bitmap. A simple blit should be better for the animation. HTH, Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a List into a String
[EMAIL PROTECTED] wrote: > I have a List > > list = ['f', 'e', 'd', 'c', 'b', 'a'] > > How can i convert it into a string so the output is > > fedcba > > i used > > for a in list: > print a, > > the output is > > f e d c b a > > How can i remove the spaces b/w each letter? print "".join(list) BTW list isnt a good name for a list, it hides the built in type. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Piecewise-cubic lookup table generator
I needed to generate some C code for a fast lookup table using piecewise-cubic interpolation. If anybody else needs this, the Python code for it is at http://tinyurl.com/92zcs (alt.source, Google Groups). Will Ware -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie q
I understand you want to do it in an applicative programming style? Not recommended in general. But here goes: .# c.l.p. question: .# "using map, lambda, reduce, filter and List Comprehensions [x for .# x in []] just don't get how to add string to all elements of list" . .## .# A function that returns a function, taking a function as argument. .def allapply(fn): .def f(seq): return map(fn, seq) .return f . .def add_string_to_element(stringval): .def f(x): return x + stringval .return f . .add_string_to_all = allapply(add_string_to_element('mystring')) . .print add_string_to_all(['d:', 'c:\windows\\','something/']) this outputs: ['d:mystring', 'c:\\windows\\mystring', 'something/mystring'] -- look Ma, no for and no lambda! -- Will Stuyvesant -- http://mail.python.org/mailman/listinfo/python-list
delay and force in Python
Here is a question for people who are more comfortable than I am with new Python stuff like generators. I am having fun implementing things from the Wizard book (Abelson, Sussman, "Structure and Interpretation of Computer Programs") in Python. In chapter 3.5 it is about streams as delayed lists. Streams are interesting because they are to lists like xrange is to range. Could save a lot on memory and computations. Below is my straight translation from Scheme code in the Wizard book to Python. It works, but now I want to rewrite the delay and force functions using Python's new stuff, generators or iterators or what-have-you. I have the feeling that that is possible, can you do it? The program below creates a stream with the numbers 1..995 and then filters the stream, keeping only the even numbers, and then prints the second number in the stream (implemented as the first number of the tail, just like in the 3.5 Section in the Wizard book). . # file: teststreams.py . . def delay(exp): return lambda: exp . . def force(o): return o() . . def cons_stream(a,b): return [a, delay(b)] . . def stream_hd(s): return s[0] . . # we use tl for cdr . def tl(x): . if len(x) == 2: return x[1] . else: return x[1:] . . def stream_tl(s): return force(tl(s)) . . def stream_enumerate_interval(low, high): . if low > high: . return None . else: . return cons_stream( . low, . stream_enumerate_interval(low+1, high)) . . def stream_filter(pred, s): . if s is None: . return None . elif pred(stream_hd(s)): . return cons_stream( . stream_hd(s), . stream_filter(pred, stream_tl(s))) . else: . return stream_filter(pred, stream_tl(s)) . . def isEven(n): return n % 2 == 0 . . print stream_hd(stream_tl(stream_filter( . isEven, . stream_enumerate_interval(1,995 . # 4 Something else: this crashes with a "maximum recursion reached" . print stream_enumerate_interval(1,998) while this does not crash . print stream_enumerate_interval(1,900) this means Python has a maximum of something like 900 recursions? -- http://mail.python.org/mailman/listinfo/python-list
Re: delay and force in Python
Yes you are right, if you just want to carry an expression around then lambda does it; but delay was not intended as a top-level function. Perhaps you think that my silly stream implementation in the original post builds the whole list, but it does not: >>> o = stream_enumerate_interval(11,121) >>> print o [11, at 0x00BA8670>] >>> f = o[1] >>> r = f() >>> print r [12, at 0x00BA86B0>] instead it builds a list of lambda's, and that is so desirable Others suggested generators indeed, and I can imagine now a usage pattern like >>> s = stream_generator(initValue, next, stop, other_params) >>> stream_hd(stream_tl(stream_filter(isEven,s))) where the idea is to pass a generator to a function all the time. What I don't like though is that I then, as I understand it, have to code some for-loop inside that function, I try to avoid for-loops. But a functional form defined with a for-loop does not seem all that bad. Anyway I have some reading-up to do, about things some posters use and I forgot to keep up with since I have been coding Python 1.5.2 style for ages now: properties, itertools, ...printed some stuff already, thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: a question
Andrew Koenig wrote: > how about writing this instead? > > ('this is a ' > 'long string') Yes, nice. And to make that possible we have to write ('one-string-item',) instead of ('one-string-item') if we want a tuple with one string inside. Sometimes that feels like a wart to me, but now I know it, sometimes not. -- http://mail.python.org/mailman/listinfo/python-list
Funny Python error messages
Add your funny or surprising Python error messages to this thread. A requirement is that you should also show (minimal) code that produces the message. Put the code below, so people can think about how to generate the message first, a little puzzle if you like. Perhaps this will even be a useful thread, to brighten the life of the brave people doing the hard work of providing us with error messages. My first one (i'm learning, i'm learning) is TypeError: 'callable-iterator' object is not callable # # # # # >>> it = iter(lambda:0, 0) # >>> it() # TypeError: 'callable-iterator' object is not callable -- http://mail.python.org/mailman/listinfo/python-list
Re: delay and force in Python
Just for the record, an implementation without using generators, somewhat like in Sect. 3.5 of the Wizard book, and without recursion limit problems. . . def stream_hd(s): # the head of the stream . return s[0] . . def stream_tl(s): # the tail of the stream . return s[1]() . . ## . # The low argument is required: the first element of the stream. . # You either use high= or stop_f= to define the end of the . # stream. Omit both for an infinite stream. stop_f is a function . # that takes low as argument and returns True or False. . # The next_f function takes one argument (an element of the stream, . # same type as the low argument has) . # The stop_f function takes one argument (same type as low) . # @param low object . # @param high object . # @param next_f function . # @param stop_f function . # @return list, a stream . def make_stream(low, high=None, next_f=None, stop_f=None): . if next_f is None: next_f = lambda x: x + 1 . if high is not None:# using high . if low > high: . return None . else: . return [low, lambda: make_stream( . next_f(low), high=high, next_f=next_f)] . elif stop_f is not None:# using stop_f . if low > stop_f(low): . return None . else: . return [low, lambda: make_stream( . next_f(low), next_f=next_f, stop_f=stop_f)] . else: # infinite stream . return [low, lambda: make_stream( . next_f(low), next_f=next_f)] . . ## . # iterative version of filter . # @param pred function, (stream-element) -> bool . # @param s list, a stream . # @return list, a stream . def stream_filter(pred, s): . if s is None: return [] . while True: . elem = stream_hd(s) . if pred(elem): . return [elem, lambda: stream_filter(pred, stream_tl(s))] . else: . s = stream_tl(s) . if s is None: return [] . . . if __name__ == '__main__': . . def is100some(x): return x % 100 == 0 . assert(stream_hd(stream_tl(stream_tl(stream_filter( . is100some, . make_stream(1, 11) == 300) . . def add_33(x): return x + 33 . assert(stream_hd(stream_tl(stream_filter( . is100some, . # stream 1,34,67,100,... . make_stream(1,9, next_f = add_33 == 3400) . . assert(stream_hd(stream_tl(stream_filter( . is100some, . # infinite stream 1,2,... . make_stream(1 == 200) . . def mod_2(x): return x % 2 == 0 . # this will need more evaluations than the recursion limit count . infinite_filter = stream_filter(mod_2, make_stream(1)) . assert( stream_hd(stream_tl(infinite_filter)) == 4 ) . -- http://mail.python.org/mailman/listinfo/python-list
Re: Help With Python
Judi Keplar wrote: I am currently taking a course to learn Python and was looking for some help. I need to write a Python statement to print a comma- separated repetition of the word, "Spam", written 511 times ("Spam, Spam, … Spam"). Can anybody help me get started? I am completely new to programming! Thanks in advance! >>> print "Spam, " * 510 + "Spam" Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Help With Python
>>> print "Spam, " * 510 + "Spam" Or if you have 2.4.. >>> print ", ".join( "Spam" for _ in xrange( 511 ) ) Although, the replys with links will ultimately be more helpful! Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: stop program in komodo
[EMAIL PROTECTED] wrote: Hello, How can we stop this peace of code in KOMODO: while 1: print "helo" I can't stop it, even using Ctrl+C Are you sure that is what is happening? When I tried it, it appeared as though nothing had happened after pressing the break button. But it was just that the buffer had filled up with a squillion "helo"'s and was busy scrolling away.. Regards, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Database recommendations for Windows app
Hi, I'd like to write a windows app that accesses a locally stored database. There are a number of tables, the largest of which has 455,905 records. Can anyone recommend a database that runs on Windows, is fast / efficient and can be shipped without restrictions or extra downloads? I have googled and found plenty of information on databases, its just that I dont have enough experience with databases to know which one is best for my task! Thanks in advance, Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Database recommendations for Windows app
Thanks for the replies. I think I'm going to go with sqllite for now. For the curious, Im writing an interface to a nutritional database. So you can type in a foodstuff and it will tell you whats in it.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL question: keeping metadata
> Is there any way of keeping this info in PIL? I don't think so... when I investigated in the past, I think I discovered that the PIL can't write EXIF data (I might be wrong, though, or my information might be outdated). > Alternatively, is there a simple image > processing package that does it? Try jpegtran: http://sylvana.net/jpegcrop/jpegtran/ You might also be interested in jhead: http://www.sentex.net/~mwandel/jhead/ Will. -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphs/statistics using wxPython
Jan Danielsson wrote: Hello all, I wanted to plot some statistics, so I wrote a simple wxPython class to do it. Then I realized that I would like to draw bar graphs, so I added that too. Since I'm a complete Python newbie, I haven't done much of it the "Python way", I suspect. So, I'm wondering if someone would like to show me some of the tricks I should have used. You can find the code at: http://user.it.uu.se/~jada3673/drawtest.py It's not finished[*], but it is usable. Oh, you can do whatever you want with it. Since I had never touched wxPython before working with this, I used some doodle application as a starting point. Btw... Has anyone already written statistics classes for wxPython? If so, where can I find them? If nothing similar exists, I'll probably add support for loading data from a file, and a few other features. Feel free to make requests or enhancements. [*] There are some size/offset bugs which I am aware of, but they are easily fixed. I just haven't got around to it yet. If you ever want to add an extra dimension, then using OpenGL with wxWindows is a breeze. See attached file for a 3d pie char.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") # Pie Chart Window # 2005 Will McGugan ([EMAIL PROTECTED]) import wx from wx import glcanvas from OpenGL.GL import * import math import time sin = math.sin cos = math.cos PI = math.pi def DegToRad(deg): return deg*PI/180. class PieSegment(object): def __init__(self, radius, angle1, angle2, colour, depth): self.display_list = glGenLists(1) glNewList(self.display_list, GL_COMPILE) self.angle1 = angle1 self.angle2 = angle2 self.explode_angle = DegToRad( (angle2 + angle1) / 2.) DrawPieSegment(radius, angle1, angle2, colour, depth) glEndList() def __del__(self): glDeleteLists(self.display_list, 1) def Draw(self, angle1, angle2, explode): glPushMatrix() glRotate(angle1, 1.0, 0.0, 0.0); glRotate(angle2, 0.0, 0.0, 1.0); glTranslatef( sin(self.explode_angle)*explode, cos(self.explode_angle)*explode, 0. ) glCallList(self.display_list) glPopMatrix() def DrawPieSegment(radius, angle1, angle2, colour, depth): angle1 = DegToRad(angle1) angle2 = DegToRad(angle2) # Number of divisions in 360 degrees RES = 100. fan2D = [] step_degree = ((2*PI)/RES) step_count = int( (angle2 - angle1) / step_degree ) + 1 step_degree = ( angle2 - angle1 ) / float(step_count) # Precalculate the trig sina1 = sin(angle1) cosa1 = cos(angle1) sina2 = sin(angle2) cosa2 = cos(angle2) # Calculate the points in an arc for p in xrange(step_count+1): a = angle1 + p * step_degree x = sin(a) y = cos(a) fan2D.append( (x,y) ) z1 = +depth/2. z2 = -depth/2. glMaterial(GL_FRONT, GL_DIFFUSE, [colour[0], colour[1], colour[2], 1.0]) # Create a fan for the top and bottom of the pie segment glNormal(0, 0, +1.) glBegin(GL_TRIANGLE_FAN) glVertex(0, 0, z1) for x, y in fan2D: glVertex(x*radius, y*radius, z1) glEnd() glNormal(0, 0, -1.) glBegin(GL_TRIANGLE_FAN) glVertex(0, 0, z2) for x, y in fan2D: glVertex(x*radius, y*radius, z2) glEnd() # A strip for the curved edge glBegin(GL_TRIANGLE_STRIP) for x, y in fan2D: glNormal(x, y, 0.) xr = x * radius yr = y * radius glVertex(xr, yr, z1) glVertex(xr, yr, z2) glEnd() n1 = -cosa1, sina1, 0. n2 = cosa2, -sina2, 0. x1, y1 = sina1 * radius, cosa1 * radius x2, y2 = sina2 * radius, cosa2 * radius # Two quads for the radius edges glNormal(n1) glBegin(GL_QUADS) glVertex(0, 0, z1) glVertex(x1, y1, z1) glVertex(x1, y1, z2) glVertex(0, 0, z2) glEnd() glNormal(n2) glBegin(GL_QUADS) glVertex(0, 0, z1) glVertex(x2, y2, z1) glVertex(x2, y2, z2) glVertex(0, 0, z2) glEnd() class PieChartWindow(glcanvas.GLCanvas): def __init__(self, parent): attriblist = None glcanvas.GLCanvas.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize, 0, "GLCanvas", attriblist, wx.NullPalette) self.init = False self.segments = [] self.animating = False self.angle = 0. self.explode = 0. self.downx = 0 self.rot = 0. self.captured_mouse = False self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftButtonDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftButtonUp) self.Bind(wx.EVT_MOTION, self.OnMouseMove) self.Bind(
frozenset question
Hi, Are there any benefits in using a frozenset over a set, other than it being immutable? Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: frozenset question
Qiangning Hong wrote: > On 7/6/05, Will McGugan <[EMAIL PROTECTED]> wrote: > >>Hi, >> >>Are there any benefits in using a frozenset over a set, other than it >>being immutable? > > > A frozenset can be used as a key of a dict: Thanks, but I meant to imply that. I was wondering if frozenset was faster or more efficient in some way. Thinking back to the dark ages of C++, you could optimize things that you knew to be constant. Will -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: frozenset question
Steven D'Aprano wrote: > There is no significant speed difference between immutable and mutable > sets, at least for queries. Regardless of whether it is successful or > unsuccessful, mutable or immutable, it takes about 0.025 second to do > each test of item in set. Why would you need to optimize that? > > If you tell us what you are trying to do, and under what circumstances it > is too slow, we'll see if we can suggest some ways to optimize it. > > But if you are just trying to optimize for the sake of optimization, > that's a terrible idea. Get your program working first. Then when it > works, measure how fast it runs. If, and ONLY if, it is too slow, > identify the parts of the program that make it too slow. That means > profiling and timing. Then optimize those parts, and nothing else. > > Otherwise, you will be like the car designer trying to speed up his sports > cars by making the seatbelts aerodynamic. No need for the 'premature optimization is the root of all evil' speech. I'm not trying to optimize anything - just enquiring about the nature of frozenset. If typing 'frozenset' over 'set' gave me a saving in time or memory (even if tiny) I would favour immutable sets, where appropriate. Thanks for the info. Will -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
dictionary that discards old items
Hi folks, I need a collection class that behaves like a dictionary but when it reaches 'n' items it discards the oldest item so that the length never goes above 'n'. (Its for caching search results) I have a vague memory of a module that does this, but I cant remember where I read about it. Can anyone enlighten me? Regards, Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary that discards old items
Michael Hoffman wrote: > Will McGugan wrote: > >> I need a collection class that behaves like a dictionary but when it >> reaches 'n' items it discards the oldest item so that the length never >> goes above 'n'. (Its for caching search results) >> >> I have a vague memory of a module that does this, but I cant remember >> where I read about it. Can anyone enlighten me? > > > You want a Least Recently Used, or LRU, cache. Here's one: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524 > > Google for to find others. Thanks. I found the one I saw originally in the Python Cookbook. Only they call it a FIFO cache. -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: First app, thanks people
Jan Danielsson wrote: . > >Oh, I do have one more question though. I'm using wxPython, and when > I check for keys I use the evt.GetKeyCode() call, and compare it with > integers which I have found by printing what event.GetKeyCode() returns. > I would prefer a more portable way, since I assume that F1 doesn't have > the same code on a Sparc Ultra10. (?) Is there a way to get "key codes" > in wxPython in a portable manner? Hi, You should use the keycode constants. http://www.wxwidgets.org/manuals/2.6.1/wx_keycodes.html#keycodes Will -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Idempotent XML processing
> In my current project, I am working with XML data in a protocol that has > checksum/signature verification of a portion of the document. > ... > the server sends me XML with empty elements as full open/close tags, > but toxml() serializes them to the XML empty element (), so > the checksum winds up not matching. (This is a horrible response to your question, so I apologize in advance.) Does it even make sense to use a checksum to verify XML, since there are basically[1] infinite ways to validly write equivalent XML data? I would think the only way that a checksum would be a viable way to verify a document is if you had some sort of standard normalized format, and made sure the data was normalized both before you computed and before you calculated the checksum. That way, you would be sure that, for instance, all insignificant whitespace was removed and all empty elements were represented uniformly. Again, I'm sorry because I didn't provide any real useful information, I just tried to poke holes in your current project. Will. [1] Unless all of your whitespace is significant -- http://mail.python.org/mailman/listinfo/python-list
Re: Idempotent XML processing
> Read up on XML canonicalization (abrreviated as c14n). lxml implements > this, also xml.dom.ext.c14n in PyXML. You'll need to canonicalize on > both ends before hashing. I said normalization but I think canonicalization is the word I was looking for. I wasn't aware that lxml implented it (or that it had an abbreviation), so that's good to know. Thanks! Will. -- http://mail.python.org/mailman/listinfo/python-list
Re: Doubt C and Python
praba kar wrote: > Dear All, >I want to know the link between c and python. >Some people with C background use Python instead > of programming in C.why? > Because I can create software many times faster. And its more fun. Will McGugan -- http://www.kelpiesoft.com -- http://mail.python.org/mailman/listinfo/python-list
Re: aproximate a number
billiejoex wrote: > Hi all. I'd need to aproximate a given float number into the next (int) > bigger one. Because of my bad english I try to explain it with some example: > > 5.7 --> 6 > 52.987 --> 53 > 3.34 --> 4 > 2.1 --> 3 > Have a look at math.ceil >>> import math >>> math.ceil(5.7) 6.0 Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: how to join two Dictionary together?
DENG wrote: > dict1={...something...} > > dict2={...somethind else ..} > > dict1 + dict2 > > > that's does works ..:(, it's not like List... I think you want.. dict1.update(dict2) Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Replacing large number of substrings
Hi, Is there a simple way of replacing a large number of substrings in a string? I was hoping that str.replace could take a dictionary and use it to replace the occurrences of the keys with the dict values, but that doesnt seem to be the case. To clarify, something along these lines.. >>> dict_replace( "a b c", dict(a="x", b="y") ) "x y c" Regards, Will McGugan -- http://www.kelpiesoft.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Has anybody tried to make a navigation like Google?
Lad wrote: > Hi, > I would like to make in my web application a similar navigation like > Google uses, I mean at the bottom of each page there are numbers of > returned pages after you search query. > Has anyone tried that? Is there an algorithm for that? I do not want to > re-invent the wheel. > Thank you for help I did something like that recently. http://www.foodfileonline.com Its not so complicated, you just need to know how many search results you have returned and how many are shown on each page. You will also need a search page that can start at a particular position in the results. Will McGugan -- http://www.kelpiesoft.com -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more 'pythonic' / 'better' ?
gabor wrote: > hi, > > there are 2 versions of a simple code. > which is preferred? > > > === > if len(line) >= (n+1): > text = line[n] > else: > text = 'nothing' > === > > > === > try: > text = line[n] > except IndexError: > text = 'nothing' > === > > > which is the one you would use? I would actualy use the following for this particular case.. text = line[n:n+1] or 'nothing' But in general I think it is best to use exceptions like that only where you expect the code to _not_ throw the exception the majority of times. Otherwise the simple condition is better. Although I expect there is not much difference either way.. Will McGugan -- http://www.kelpiesoft.com -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more 'pythonic' / 'better' ?
Pierre Barbier de Reuille wrote: >> >>I would actualy use the following for this particular case.. >> >>text = line[n:n+1] or 'nothing' > > > ... and you would get either a list of one element or a string ... > I think you wanted to write : > > text = (line[n:n+1] or ['nothing'])[0] I was assuming that 'line' would be a string, not a list. Seems more likely give the name and context. Will McGugan -- http://www.kelpiesoft.com -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more 'pythonic' / 'better' ?
Steve Holden wrote: > I'd say it's much more likely that line is a list of lines, since it > seems improbable that absence of a character should cause a value of > "nothing" to be required. You may be right. I always use plural nouns for collections. To me 'line' would suggest there was just one of them, so I assumed it was string. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
Rubinho wrote: > I've a list with duplicate members and I need to make each entry > unique. > > I've come up with two ways of doing it and I'd like some input on what > would be considered more pythonic (or at least best practice). > > Method 1 (the traditional approach) > > for x in mylist: > if mylist.count(x) > 1: > mylist.remove(x) > > Method 2 (not so traditional) > > mylist = set(mylist) > mylist = list(mylist) > > Converting to a set drops all the duplicates and converting back to a > list, well, gets it back to a list which is what I want. > > I can't imagine one being much faster than the other except in the case > of a huge list and mine's going to typically have less than 1000 > elements. I would imagine that 2 would be significantly faster. Method 1 uses 'count' which must make a pass through every element of the list, which would be slower than the efficient hashing that set does. I'm also not sure about removing an element whilst iterating, I think thats a no-no. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
Steven D'Aprano wrote: > > > Don't imagine, measure. > > Resist the temptation to guess. Write some test functions and time the two > different methods. But first test that the functions do what you expect: > there is no point having a blindingly fast bug. Thats is absolutely correct. Although I think you do sometimes have to guess. Otherwise you would write multiple versions of every line of code. > > > But count passes through the list in C and is also very fast. Is that > faster or slower than the hashing code used by sets? I don't know, and > I'll bet you don't either. Sure. But if I'm not currently optimizing I would go for the method with the best behaviour, which usualy means hashing rather than searching. Since even if it is actualy slower - its not likely to be _very_ slow. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Search Engine app
Alan Meyer wrote: > I'm not aware of such a thing. > > I stand ready to be corrected, but I think Python would not be a > good language for writing search engines. In the ones I've written > for custom projects - in C or PL/1, it has been necessary to > perform very high speed operations on highly compressed binary > structures - which is not Python's forte. > > You might be able to put a Python interface over an engine written > in another language. Wasn't Google's first search engine actualy written in Python? Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Create and display an email
Adam Endicott wrote: > I've got a wxPython based windows GUI application that takes some input > and creates a PDF file output. At the end, I need to create an email > message with this pdf file attached ready for the user to just hit > "send". I don't want to actually send the email automatically, I just > want to pop up a message in the default mail program that's ready to go > (partially because the person might not be online when the email is > created, this way they could just put it in their Outlook outbox). > > I can't figure out how to do this. I've tried using > webbrowser.open('mailto:...'), which works, except that I can't add an > attachment that way (at least I haven't been successful). And I don't > know any other way to open up a message in the default mail program. > > There has to be something obvious that I'm missing here. Any > suggestions? > I dont think there is anything in the standard library to help you here. Windows has an api called 'MAPI' which does this sort of thing. There may be bindings to it somewhere, or you could create your own with ctypes. I sure you will find something now you know what to google for.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
Thierry Lam wrote: Let's say I have the following data: 500 objects: -100 are red -300 are blue -the rest are green Is there some python package which can represent the above information in a pie chart? I wrote a wxPython control to render pretty 3D pie charts (see attached piechartwindow.py). It can also be used to pre-generate images such as this.. http://www.foodfileonline.com/static/piecharts/pie01009.jpg Code is public domain. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") # Pie Chart Window # 2005 Will McGugan ([EMAIL PROTECTED]) import wx from wx import glcanvas from OpenGL.GL import * import math import time sin = math.sin cos = math.cos PI = math.pi def DegToRad(deg): return deg*PI/180. class PieSegment(object): def __init__(self, radius, angle1, angle2, colour, depth): self.display_list = glGenLists(1) glNewList(self.display_list, GL_COMPILE) self.angle1 = angle1 self.angle2 = angle2 self.explode_angle = DegToRad( (angle2 + angle1) / 2.) DrawPieSegment(radius, angle1, angle2, colour, depth) glEndList() def __del__(self): glDeleteLists(self.display_list, 1) def Draw(self, angle1, angle2, explode): glPushMatrix() glRotate(angle1, 1.0, 0.0, 0.0); glRotate(angle2, 0.0, 0.0, 1.0); glTranslatef( sin(self.explode_angle)*explode, cos(self.explode_angle)*explode, 0. ) glCallList(self.display_list) glPopMatrix() def DrawPieSegment(radius, angle1, angle2, colour, depth): angle1 = DegToRad(angle1) angle2 = DegToRad(angle2) # Number of divisions in 360 degrees RES = 100. fan2D = [] step_degree = ((2*PI)/RES) step_count = int( (angle2 - angle1) / step_degree ) + 1 step_degree = ( angle2 - angle1 ) / float(step_count) # Precalculate the trig sina1 = sin(angle1) cosa1 = cos(angle1) sina2 = sin(angle2) cosa2 = cos(angle2) # Calculate the points in an arc for p in xrange(step_count+1): a = angle1 + p * step_degree x = sin(a) y = cos(a) fan2D.append( (x,y) ) z1 = +depth/2. z2 = -depth/2. glMaterial(GL_FRONT, GL_DIFFUSE, [colour[0], colour[1], colour[2], 1.0]) # Create a fan for the top and bottom of the pie segment glNormal(0, 0, +1.) glBegin(GL_TRIANGLE_FAN) glVertex(0, 0, z1) for x, y in fan2D: glVertex(x*radius, y*radius, z1) glEnd() glNormal(0, 0, -1.) glBegin(GL_TRIANGLE_FAN) glVertex(0, 0, z2) for x, y in fan2D: glVertex(x*radius, y*radius, z2) glEnd() # A strip for the curved edge glBegin(GL_TRIANGLE_STRIP) for x, y in fan2D: glNormal(x, y, 0.) xr = x * radius yr = y * radius glVertex(xr, yr, z1) glVertex(xr, yr, z2) glEnd() n1 = -cosa1, sina1, 0. n2 = cosa2, -sina2, 0. x1, y1 = sina1 * radius, cosa1 * radius x2, y2 = sina2 * radius, cosa2 * radius # Two quads for the radius edges glNormal(n1) glBegin(GL_QUADS) glVertex(0, 0, z1) glVertex(x1, y1, z1) glVertex(x1, y1, z2) glVertex(0, 0, z2) glEnd() glNormal(n2) glBegin(GL_QUADS) glVertex(0, 0, z1) glVertex(x2, y2, z1) glVertex(x2, y2, z2) glVertex(0, 0, z2) glEnd() class PieChartWindow(glcanvas.GLCanvas): def __init__(self, parent): attriblist = None glcanvas.GLCanvas.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize, 0, "GLCanvas", attriblist, wx.NullPalette) self.init = False self.segments = [] self.animating = False self.angle = 0. self.explode = 0. self.downx = 0 self.rot = 0. self.captured_mouse = False self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftButtonDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftButtonUp) self.Bind(wx.EVT_MOTION, self.OnMouseMove) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) def Animate(self): self.animating = True self.start_animate = time.clock() self.timer.Start(1000/20) def OnTimer(self, event): if self.IsShown(): self.Refresh() if not self.animating: self.timer.Stop(); def SetSegments(self, segments, angle=0., radius=150., depth=50.): self.segments = [] First = True if len(segments): angle = -(segments[0][0]/2. *360./100.) for seg in segments: seg_percent, colour = seg if seg_percent == 0: continue
Re: Britney Spears nude
Tim Peters wrote: > [john basha] > >>send me the britney nude photos > > > Because they're a new feature, you'll have to wait for Python 2.5 to > be released. She has just spawned a child process. Give her to Python 2.6 to get back in shape. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
Markus Weihs wrote: > Hi! > > I tried your script and got the following error: > > Traceback (most recent call last): > File "pie_chart.py", line 302, in OnPaint > self.OnDraw() > File "pie_chart.py", line 336, in OnDraw > segment.Draw(self.angle, self.rot, self.explode) > File "pie_chart.py", line 46, in Draw > glPopMatrix() > OpenGL.GL.GLerror: [Errno 1281] invalid value > > What am I doing wrong? I'm not sure. Thats a strange place for it to fail. Do you have the latest version of pyOpenGL / wxPython? Its only been tested on Windows, but it just uses basic OpenGL so there is not that much to go wrong.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list
Creating properties with decorator like syntax
Hi, Is there any way of making properties using a decorator? The current way of creating a property seems inelegant. Something like this imaginary snippit would be nice, IMHO. class C(object): @make_property def x(self): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x Regards, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating properties with decorator like syntax
Will McGugan wrote: Hi, Is there any way of making properties using a decorator? The current way of creating a property seems inelegant. Something like this imaginary snippit would be nice, IMHO. class C(object): @make_property def x(self): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x Posted too soon. Played with the above and got something which works. def make_property( func ): return property( *func() ) class C(object): def __init__(self): __x= 1 @make_property def x(): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x return getx,setx,delx c= C() c.x= 5 n= c.x + 5 Good idea, or bad? Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
namespace collisions
Hi, I'm accumulating a number of small functions, which I have sensibly put in a single file called 'util.py'. But it occurs to me that with such a generic name it could cause problems with other modules not written by myself. Whats the best way of handling this? If I put it in a common location in my Python path, should I call it willsutil.py? TIA, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL Expand Canvas
Daniel Bowett wrote: I'm new to the PIL module but think it would be useful for dealing with all the product images for the sites I work on. I can see how to do most things I need apart from expanding the canvas. By that I mean if I have an image which is 200 pixels high and 180 pixels wide - I will want to pad it left and right by 10 pixels with white space to make it a 200x200 square. Is this possible? You could create a new canvas of the larger dimensions, then copy the smaller one to the centre of it.. Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Online Programming Contest
> [Varun] > For details about samhita http://www.samhita.info/ "The Madras Institute of Technology (MIT)" it says there. The MIT acronym is taken already guys.. -- no scheme no glory -- http://mail.python.org/mailman/listinfo/python-list
Googlewhacker
Hi folks, Has anyone seen 'Googlewhack Adventure'? http://www.davegorman.com/googlewhack.htm I wrote a script to generate Googlewhacks - thought I'd share it with you. I'd better stop running it as I fear Google may ban my IP for making 20 searches a seconds.. Will McGugan import random import urllib2 import threading WHACKER_THREADS = 20 random.seed() wordlist = [ line.rstrip() for line in file("word.lst") ] whacks = file( "whacks.txt", "a" ) class WhackerThread( threading.Thread ): excluded = "/dict .lst word.lst .txt words".split() def run(self): def check_word( word ): url = """http://dictionary.reference.com/search?q=%s"""; % word dict_page = urllib2.urlopen( url ).read() return "Did You Mean" not in dict_page def is_excluded(page): for word in WhackerThread.excluded: if word in page: return True return False while( True ): word_a = random.choice( wordlist ) #word_a = "haggis" word_b = random.choice( wordlist ) words = word_a + " " + word_b google_url = """http://www.google.com/search?hl=en&q=%s+%s&btnG=Google+Search"""; % ( word_a, word_b ) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] google_page = opener.open(google_url).read() if is_excluded( google_page ): print words + " (probably a word list)" continue if "Results 1 - 1 of 1" in google_page: if not check_word( word_a ): print "%s (%s is not in dicionary.com)" % (words, word_a) elif not check_word( word_b ): print "%s (%s is not in dicionary.com)" % (words, word_b) else: print words + " WHACK!" print >> whacks, words whacks.flush() else: print words + "(no whack)" Threads= [ WhackerThread() for _ in xrange(WHACKER_THREADS) ] for whacker_thread in Threads: whacker_thread.start() -- http://mail.python.org/mailman/listinfo/python-list
Re: Googlewhacker
Will McGugan wrote: Hi folks, Has anyone seen 'Googlewhack Adventure'? http://www.davegorman.com/googlewhack.htm I wrote a script to generate Googlewhacks - thought I'd share it with you. I'd better stop running it as I fear Google may ban my IP for making 20 searches a seconds.. Oops, wrong script.. Will import random import urllib2 import threading WHACKER_THREADS = 20 random.seed() wordlist = [ line.rstrip() for line in file("word.lst") ] whacks = file( "whacks.txt", "a" ) class WhackerThread( threading.Thread ): excluded = "/dict .lst word.lst .txt words".split() def run(self): def check_word( word ): url = """http://dictionary.reference.com/search?q=%s"""; % word dict_page = urllib2.urlopen( url ).read() return "No entry found" not in dict_page def is_excluded(page): for word in WhackerThread.excluded: if word in page: return True return False while( True ): word_a = random.choice( wordlist ) #word_a = "haggis" word_b = random.choice( wordlist ) words = word_a + " " + word_b google_url = """http://www.google.com/search?hl=en&q=%s+%s&btnG=Google+Search"""; % ( word_a, word_b ) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] google_page = opener.open(google_url).read() if is_excluded( google_page ): print words + " (probably a word list)" continue if "Results 1 - 1 of 1" in google_page: if not check_word( word_a ): print "%s (%s is not in dicionary.com)" % (words, word_a) elif not check_word( word_b ): print "%s (%s is not in dicionary.com)" % (words, word_b) else: print words + " WHACK!" print >> whacks, words whacks.flush() else: print words + "(no whack)" Threads= [ WhackerThread() for _ in xrange(WHACKER_THREADS) ] for whacker_thread in Threads: whacker_thread.start() -- http://mail.python.org/mailman/listinfo/python-list
Re: Text To Speech with pyTTS
Peter Hansen wrote: Mike P. wrote: I was wondering if anyone has had any luck with the python text to speech (pyTTS) module available on Sourceforge: http://sourceforge.net/projects/uncassist I saw the following blog entry by Joey deVilla: http://farm.tucows.com/blog/Platforms/Windows/_archives/2005/1/19/266813.html and immediately tried it out. All I did was download the PyTTS package for Python (2.4, not 2.3), and install it, then ran Joey's sample above. It worked as advertised. This was on Windows XP SP2. I experience the same thing as Mike P. Im running on Windows 2K. Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Faster way to do this...
Harlin Seritt wrote: I've got the following code: nums = range(0) for a in range(100): nums.append(a) Is there a better way to have num initialized to a list of 100 consecutive int values? Isn't that equivalent to simply.. nums= range(100) Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Faster way to do this...
Warren Postma wrote: Will McGugan wrote: Isn't that equivalent to simply.. nums= range(100) I remember the day I first realized that 900 lines of some C++ program I was working on could be expressed in three lines of python. Ahh. Lately I've found myself commenting C++ code with the equivalent Python code. I find it clearer and more terse than simply commenting in English! Will -- http://mail.python.org/mailman/listinfo/python-list
Hash of integers for use in Random module
Hi, If I retrieve the hash of an integer, will it always return the same value across platforms? This reason I ask is that I want to produce a sequence of pseudo random numbers using the random module, that I can re-create later on. So I'll need to store the seed value, but Random.seed takes a hashable object rather than an integer directly. Which brings another question to mind. Are hashes of builtin objects in general consistent across platforms, or are they an implementation detail that could change? TIA, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Hash of integers for use in Random module
Will McGugan wrote: Hi, If I retrieve the hash of an integer, will it always return the same value across platforms? This reason I ask is that I want to produce a sequence of pseudo random numbers using the random module, that I can re-create later on. So I'll need to store the seed value, but Random.seed takes a hashable object rather than an integer directly. Which brings another question to mind. Are hashes of builtin objects in general consistent across platforms, or are they an implementation detail that could change? *sigh* Didnt read the docs closely enough. It does say that ints and longs are used directly.. Will -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating desktop icons for Innosetup file
Harlin Seritt wrote: I have a test app that I am creating an Innosetup script for. Everything works great except for the fact that my icons (start menu and desktop) are not starting the executable in the appropriate directory. This is causing problems because it can't find "icon.ico" and other stuff. When I go and manually change the startpath on the icon's property box, everything works fine. How do I ensure that the icon starts in the apppath? You need to set the working dir for the icon in the [Icons] sections. Adding the following to your icons should do the trick.. WorkingDir: {app}; HTH, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: computing a weighted sum
[EMAIL PROTECTED] wrote: Suppose I have a list of n floats x and a list of n floats w and I want to compute x[0]*w[0] + .. + x[n-1]*w[n-1]. Is there some elegant expression (perhaps using lambda) to have it done in one statement ? As in : y = lambda x,w : ... I ask because the way I am doing it now : y = 0 for i in range(0,n): y += x[i]*w[i] doesn't seem very pythonic :) I'll take a stab at that! In Python 2.3 sum( [ _x * _w for _x, _w in zip( x, w ) ] ) or in 2.4 sum( _x * _w for _x, _w in zip( x, w ) ) You may want to use itertools.izip in place of zip if the lists are large. Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
html escape sequences
Hi, I'd like to replace html escape sequences, like and ' with single characters. Is there a dictionary defined somewhere I can use to replace these sequences? Thanks, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: html escape sequences
Leif K-Brooks wrote: Will McGugan wrote: I'd like to replace html escape sequences, like and ' with single characters. Is there a dictionary defined somewhere I can use to replace these sequences? How about this? import re from htmlentitydefs import name2codepoint _entity_re = re.compile(r'&(?:(#)(\d+)|([^;]+));') def _repl_func(match): if match.group(1): # Numeric character reference return unichr(int(match.group(2))) else: return unichr(name2codepoint[match.group(3)]) def handle_html_entities(string): return _entity_re.sub(_repl_func, string) muchas gracias! Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL and antialiasing problem
Laszlo Zsolt Nagy wrote: I tried to posterize or darken the images but I could not find a good solution. (I also tried to count the number of colors in the image and use this info.) Can you suggest an image filter and/or method that creates darker black lines from the original thin lines? Also it would be great to have it working with those colorful smudged images. It will be terribly slow to separate them by hand. There are almost 15000 of them... Try running ImageFilter.MinFilter on the image before you thumbnail it. This should make dark lines thicker. HTH, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL and antialiasing problem
Laszlo Zsolt Nagy wrote: Try running ImageFilter.MinFilter on the image before you thumbnail it. This should make dark lines thicker. HTH, Will McGugan You are my man! It worked perfectly! Statement: Sometimes PIL is better than Adobe Photoshop. :-) Happy to help :) I also found these with the aid of the wonderful dir() function: MinFilter, MaxFilter, MedianFilter, ModeFilter, RankFilter, BuiltInFilter MinFilter replaces each pixel with the darkest pixel within the filter area. MaxFilter replaces each pixel with the brightest of the surrounding pixels. MedianFilter sorts the surrounding pixels by brightness and selects the middle value. I think ModeFilter selects the most common pixel if occurs more than a certain threshhold. RankFilter is like Median, but it selects the colour at a specific point within the ordered list. Not sure about BuiltInFilter, my guess is its an implementation detail of some kind.. Regards, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Python compared with Xen (for XML)
Here is a comment on the paper "Programming with Circles, Triangles and Rectangles" by Erik Meijer, Wolfram Schulte and Gavin Bierman. Google will find it quickly if you try. In the paper they introduce Xen, an extension to C# for better XML support. They show how Lifting, Filtering and Apply-to-all can be done so much better in C# with Xen. How is Python, my favorite programming language, doing in this respect? Let's see: Python for XML == Lifting --- The example: "bib.books.title" [[an expression for all titles of books in bib]] (stuff in double quotes "..." is suggested Xen code from the article by E.Meijer et al., stuff in double square brackets [[...]] is the intended meaning. Python code is shown after >>> , the prompt from the Python interactive interpreter.) We can do this "Lifting" in Python with list comprehension: >>> [b.title for b in bib.books] Filtering - The example: "bib.books[it.year >= 1998]" [[An expression for the books from 1998 or later]] This can also be done with Python list comprehensions. >>> [b for b in bib.books if b.year >= 1998] Apply-to-all The example: "bib.books.{print it}" [[print all books: execute a code block for every book in .books.]] I would do it like this in Python: for b in bib.books: print b looks much clearer to me than the .{...} stuff. Oh and maybe the new generator expressions can be used for this, but they are new to me and I can hardly imagine clearer syntax. Anyone? All that is needed for this to work in Python is that you collect XML attributes in object attributes; and that you give a name to the XML children of an XML element and put them as a list into an object attribute with that name. Go wild and even define new classes for it dynamically, or beforehand if you have the XML DTD or Schema. Not too hard a programming exercise; who is first? As for the other content of the article it is my opinion that they pay way too much attention to data-models and types, and then strangle themselves trying to fit one data-model onto another one, and a statically typed one too for that! (C#, Java, even Visual Basic is mentioned for laughing out loud). Better try to get the job done first. They did this work paid by microsoft.research. I think microsoft.research better pay some more attention to Python. Or are they? Are the "competitive edge" rumors true? -- http://mail.python.org/mailman/listinfo/python-list
Re: Fun with Outlook and MAPI
Chris wrote: I'm trying to send an e-mail through outlook. So far I've gotten it to work with the mail script at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149461 My only problem is that when I call Resolve() and Send(), I get confirmation dialogs. I will be sending out quite a few e-mails at a time, and would rather not have the user have to click yes for every single one. Does anyone know a workaround? I know about smtplib, but I would prefer to simply make what I have work. Thanks. Alas, I dont think that there is much you can do to prevent the confirmation dialogs with Outlook's MAPI dll. MS added them in a service pack as an anti-virus measure, so no work-around. Not all clients show these anoying dialogs though. Thunderbird definately doesn't. Regards, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Fun with Outlook and MAPI
David Fraser wrote: Alas, I dont think that there is much you can do to prevent the confirmation dialogs with Outlook's MAPI dll. MS added them in a service pack as an anti-virus measure, so no work-around. Not all clients show these anoying dialogs though. Thunderbird definately doesn't. There is actually a workaround. You're using Simple MAPI which has a I stand corrected. Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: handy stacktrace class
Oh. Never mind, then. -- http://mail.python.org/mailman/listinfo/python-list
do you master list comprehensions?
Here is a question about list comprehensions [lc]. The question is dumb because I can do without [lc]; but I am posing the question because I am curious. This: >>> data = [['foo','bar','baz'],['my','your'],['holy','grail']] >>> result = [] >>> for d in data: ... for w in d: ...result.append(w) >>> print result ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail'] puts all the words in a list, like I want. How to do this with [lc] instead of for-loops? I tried funnies like [[w for w in L] for L in data], that is correct syntax, but you'd never guess. I know, silly! No need for [lc]! So there's my question. I am sure a one-liner using [lc] will be very enlightening. Like studying LISP. -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called `brightness', but it doesn't work. -- Gallagher -- http://mail.python.org/mailman/listinfo/python-list
Re: do you master list comprehensions?
Okay that was fun. Enlightening as I hoped. unroll() in Python, for arbitrary depth, _flatten in Tkinter (what else is in Tkinter!), sum() abuse. The sum(data,[]) was funniest, it works like ((['foo','bar'] + []) + ['my','your']) + ['holy','grail']. Before I think of such things I have already coded an algorithm in imperative style. Guess I have not been exposed to functional programming enough. -- http://mail.python.org/mailman/listinfo/python-list
handy stacktrace class
I was fooling with some Python code, and starting to miss the Exception.printStackTrace() feature in Java. Here is a stab at something roughly analogous, which puts together a stacktrace as an XML document. import xml.dom.minidom class Stacktrace(xml.dom.minidom.Document): def __init__(self): import sys xml.dom.minidom.Document.__init__(self) stacktrace = self.createElement("stacktrace") self.appendChild(stacktrace) try: raise Exception except: tb = sys.exc_traceback x = tb.tb_frame.f_back while x != None: f = x.f_code frame = self.createElement("frame") frame.setAttribute("func", f.co_name) frame.setAttribute("file", f.co_filename) frame.setAttribute("line", repr(f.co_firstlineno)) stacktrace.appendChild(frame) x = x.f_back def __repr__(self): import xml.dom.ext class MyStream: def __init__(self): self.str = "" def write(self, x): self.str += x stream = MyStream() xml.dom.ext.PrettyPrint(self, stream) return stream.str[:-1] # trim trailing newline The rational for doing this as an XML document was, uh, gee, I thought I had a good reason at the time. I think I've seen XML sequences of stacktraces elsewhere and it looked like a good idea. My brief time of muddling about with xml.dom.minidom makes me think that elements are inherently tied to a particular document and can't just be lifted and moved to another document, as one might want to do to, say, build a sequence of stacktraces while debugging something. But I'm sure there's some kind of workaround for that. -- http://mail.python.org/mailman/listinfo/python-list
Python Cookbook 2nd Ed
Hi, Is the second edition of the Python Cookbook worth getting if you have the first edition? How much new material is there in the 2nd edition? Thanks, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
BF interpreter in Python
Hi, Python is my favorite language, but I rarely get the opertunity to use it at work, so I find myself actively looking for problems to solve with it. Consequently while waiting for C++ build to finish, I wrote a BrainF*** interpreter. If you are not familiar with the BF language see the following example, which calculates the mandlebrot set.. http://esoteric.sange.fi/brainfuck/bf-source/prog/mandelbrot.b My BF interpreter is here.. http://www.willmcgugan.com/brainfuck.py Release to the public domain! I imagine somebody has already done this in Python, and I fully expect some Python expert to give a one line generator expression with the same functionality.. Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Retrieve Icons Associated To An Extension?
[EMAIL PROTECTED] wrote: Hello NG, I have searched everyweher, and I am not able to find a solution... basically, I am constructing a GUI with wxPython, in which I have a list. In this list control, I have some file. I would like to associate (to every file) its icon (on Windows). I have searched about the use of Mark Hammond's win32all extensions and also ctypes, but I didn't find a solution. Could anyone please provide a very simple example on how to retrieve an icon associated to a file extension on Windows? Check out MimeTypesManager in the wxPython demo app (under More Windows/Controls). That seems to do what you want.. Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: BF interpreter in Python
Do Re Mi chel La Si Do wrote: Hi ! Good idea. I take this interpreter with jubilation. Can I add your URL at http://mclaveau.com/esolang ? Certainly, be my guest. Other question : do you know PATH ? (http://pathlang.sourceforge.net) Yes, a wonderfully expressive language! Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: Counting iterations
Derek Basch wrote: Is there a better way to count iterations that this?: pets = 0 for i in pets: pets += 1 print "pet" + "#" + pets You can use 'enumerate' to get the index, but the code above wont work - you are trying to iterate over a non-sequence. Will McGugan -- "".join( [ {'@':'@','.':'.'}.get(c,None) or chr(97+((ord(c)-97)+13)%26) for c in "[EMAIL PROTECTED]" ] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: World First Cancer Immune Booster
Health wrote: Most people with Cancer or AIDS have no immune system left. We've developed a world first "natural immune booster" which helps people fight their disease. Our totally natural product comes from the fresh Arctic Ocean. www.protecura.com Spam rarely offends me, but this is really low. Scamming money out of people with potentially fatal illnesses. I hope there's a level of hell devoted to spammers like this! Will McGugan -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Codig style: " or """
Sara Khalatbari wrote: Hi! Suppose you're writing a module & writing the definition of each function in that module in " or """. for example: a) "This function does this & that" or: b) """This function does blah blah blah""" What are the differences between " and """ ? I'm using gedit & I wanna know a bit about coding style. To be very honest: I have a very strict boss who looks for bugs in my codes & he insists to know exactly which 'CODING STYLE AUTHORITATIVE SOURCE' I've based my coding style on when using " or """. Can anybody out there give me some hint? Can anybody tell me where to find a document on python coding style. Triple quotes allow you to have quotes inside the string. I tend to use triple quotes if I'm writing text of any length, that way I dont need to change anything if I do need to insert a quote. I dont think its a matter of coding style, its purely a practical issue. If your PHB insists on consistency, I would just use """ Will McGugan -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Supercomputer and encryption and compression @ rate of 96%
[EMAIL PROTECTED] wrote: Supercomputer and encryption and compression @ rate of 96% The bit sent would be 0 and the key code would be F1-24,k 1-24, I 1-24,K 1-24,j24,j1,j12,j1,j6,j1,j3,j1,j2,j1 and would unzip or be new encryption you could encrypt or compress 100 terabits down to 1 bit of information. Now if you take this idea from my web site you could make this allot more complex and unbreakable. Data encryption 360 degrees rotation document 90 degrees and encrypt on every angel then 45 degrees change it two binary code do it again and again and fold it over like a piece of paper then having the one's and zero cancel each other out. In theory you could send a 100 terabit program to someone's computer and have it unzip and run and install or make A computer processor like the new 64 bit AMD have the bit unzip into a large ram drive and buffer use one half of the 64 bit processor decode the message and the main 64 bit run the numbers. Another way of doing this is to have a parallel computers with using one of the processes run the compressed 1 bit of information give the uncompressed a address on the ram drive to change and not even go threw the processor and then with different information on each machine compare and run statistics on information on a 45 tflops supercomputer and turn that 45 tflops computer into a 1 bit = 100,000 terabits to infinite as long as you have the ram for storage! with my calculations 45 tflops wouldn't matter any more it would be how much data you have on a 32bit operating system changing that to a 1 bit system it would be 32 * 45tflops would = 1440 tflops Matter moves so fast that it intergreats and deintergreats faster then any speed we can see it like water from a hose at real close speed it moves in lines. Please implement this as a Python module. I would like to compress my mp3 collection to single bits. Will McGugan -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Supercomputer and encryption and compression @ rate of 96%
Fredrik Lundh wrote: Will McGugan wrote: Please implement this as a Python module. I would like to compress my mp3 collection to single bits. here's the magic algorithm (somewhat simplified): def algorithm(data): m = 102021 # magic constant d = [int(c) for c in str(1*2*3*4*5*m+5+4+2+1)] x = [ord(c) for c in hex(1+2+4+5+m*5*4*3*2*1)] x[d[0]*d[1]*d[2]] = x[d[-1]] + sum(d) - d[d[-d[-1]-1]] + d[0] x = __import__("".join(chr(c) for c in x[d[0]*d[1]:])).encodestring return "".join(x(data).split("\n")).rstrip("="), sum(d)-sum(reversed(d)) and here's a driver for your MP3 collection: import glob def compress(filename): data = open(filename, "rb").read() keycode, bit = algorithm(data) file = open(keycode + ".out", "wb") file.write(chr(bit)) file.close() print "compressed", filename, print len(data), "=>", 1, round(100.0/len(data), 3), "%" for file in glob.glob("*.mp3"): compress(file) Muchas gracias. Although there may be a bug. I compressed my Evanescence albumn, but after decompression it became the complete works of Charles Dickens.. -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) -- http://mail.python.org/mailman/listinfo/python-list
Behaviour of str.split
Hi, I'm curious about the behaviour of the str.split() when applied to empty strings. "".split() returns an empty list, however.. "".split("*") returns a list containing one empty string. I would have expected the second example to have also returned an empty list. What am I missing? TIA, Will McGugan -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: random number between 0 and 20
[EMAIL PROTECTED] wrote: How can I generate a random number between 0 - 20 and store the number in nrrandom? Assuming its inclusive.. >>> from random import randint >>> nrrandom = randint(0,20) Will McGugan -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: What is rstrip() in python?
On Sunday, November 9, 2014 6:12:24 AM UTC-5, satish...@gmail.com wrote: > What is rstrip() in python? > > What does it do in the following piece of code? > > import sqlite3 > conn = sqlite3.connect('dbase1') > curs = conn.cursor() > > file = open('data.txt') > rows = [line.rstrip().split(',') for line in file] rstrip() removes whitespace, newline characters, tab characters, and carrige return characters (\n \t \r respectively) on the tail of a string. Or it can be used with an input parameter to remove all instances of that parameter from the tail of a string. ex: stringy = "i am helpful \t\t\t\t\n\n " stringy = stringy.rstrip() print stringy stdout: "i am helpful" or: stringy = "my favorite number is 80" stringy = stringy.rstrip('0') print stringy stdout: "my favorite number is 8" pretty simple method, helpful for parsing out formatting characters from scraped content from webpages. https://docs.python.org/2/library/stdtypes.html?highlight=rstrip#str.rstrip -- https://mail.python.org/mailman/listinfo/python-list
Re: Python modules
On Sunday, November 9, 2014 11:51:41 PM UTC-5, Steve Hayes wrote: > I have a book on Python that advocates dividing programs into modules, and > importing them when needed. > > I have a question about this. > > I can understand doing that in a compiled language, where different modules > can be imported from all sorts of places when the program is compiled. > > But I understand that Python is an interpreted language, and If I wrote a > program in Python like that, and wanted to run it on another computer, how > would it find all the modules to import at run-time, unless I copied the whole > directory structure over to the other computer? > > > > > -- > Steve Hayes from Tshwane, South Africa > Web: http://www.khanya.org.za/stevesig.htm > Blog: http://khanya.wordpress.com > E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk I have had a lot of trouble with executing relative imports with some of my projects in python. Are there any best practices or methods besides '../../' type hard-coding? In one project, a spider using scrapy, I used this method to import a module from 'the other side' of a file directory. spider_lib_path = os.path.realpath(os.path.dirname(__file__) + '/../../../../../library/python') object_builder_printer = imp.load_source('object_builder_printer', spider_lib_path + '/object_builder_printer.py') object_builder = object_builder_printer.object_builder_printer(settings) the file structure was: spiders/ -current/ --app/ ---spiders/ scrapy/ -Charlotte/ --1.0/ ---pipelines.py (the file that needs to import object_builder_printer.py) --library/ ---python/ object_builder_printer.py I think the issue had something to do with there being duplicitous file names, as in, there are multiple directories named 'spiders'. -- https://mail.python.org/mailman/listinfo/python-list