Re: Code Generator written in python

2010-01-14 Thread Steve Ferg
http://nedbatchelder.com/code/cog/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: heapq._siftdown / decrease-key support?

2010-01-14 Thread Joshua Bronson
Thanks for the responses!

On Thu, Jan 14, 2010 at 12:23 AM, Daniel Stutzbach
 wrote:
> Your guess is correct.  Someday I'd like to rewrite HeapDict in C for speed, 
> but I haven't been able to find the time (and no one has offered to pay me to 
> make the time ;) ).

Daniel, did you realize you can accomplish logarithmic-time priority
change (albeit indirectly) with the built-in heapq module using this
mark-as-invalid trick? Are there other algorithms requiring decrease-
key besides A* and Dijkstra where this technique doesn't help?

On Thu, Jan 14, 2010 at 2:41 AM, Mikael Lind  wrote:
> If I recall correctly, avoiding the linear search did wonders for
> algorithm complexity.

It's still possible to perform the decrease-key operation without
having to do a linear search; heapdict does it in logarithmic time. If
my cursory benchmarks were accurate (which upon reconsideration I'm
not actually sure they are), I think the only explanation for it being
possibly slower is that it's running in pure Python.

I just switched back to using heapq but now with the mark-as-invalid
trick instead of the linear scan, and the performance I'm observing is
very close to heapdict's. Which is curious, because now that both
operations are running in logarithmic time, I'd expect the heapq
implementation to be much faster since it's written in C. Maybe I have
some confounding variables in how I'm running my tests.

By the way, I just realized that the obvious reason the heapq module
doesn't support priority change is that its functions are designed to
operate on external lists rather than providing an encapsulating data
structure like heapdict. With heapdict, logarithmic decrease_key is
possible because it's also storing the positions of the elements in an
underlying dictionary, so instead of a linear scan it does a constant-
time lookup. My guess is that the simplicity of having heapq operate
on external lists is preferable to supporting decrease-key directly,
so it isn't likely to change any time soon, especially since you can
accomplish the same thing with the mark-as-invalid technique.

Raymond, do you think this technique is worth documenting in the heapq
module? It'd be too bad if any future users incorrectly think that it
won't meet their needs the way I did.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple distributed example for learning purposes?

2010-01-14 Thread Tim Golden

On 13/01/2010 20:24, Aahz wrote:

In article,
Tim Golden  wrote:


I'm trying to come up with something which will illustrate the
usefulness of a distributed processing model. Since I may not be using
the term "distributed" exactly, my criteria are:


Distributed spider with firewall that limits network I/O per computer
(the firewall is useful but not essential).


Thanks; I'll add that to the list.

TJG
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting access to the process table from python?

2010-01-14 Thread Simon Brunning
2010/1/13 Roy Smith :
> I need to get information about what processes are running on a box.
> Right now, I'm interested in Solaris and Linux, but eventually
> probably other systems too.  I need to know things like the pid,
> command line, CPU time, when the process started running, and owner.
>
> Has anybody written a module to do this?  I know I can run ps and
> parse the output, or troll /proc directly, but if somebody's already
> written all that, I'd rather not reinvent the wheel.



-- 
Cheers,
Simon B.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: force URLencoding script

2010-01-14 Thread João
On Jan 12, 10:07 pm, r0g  wrote:
> João wrote:
> > On Jan 12, 8:05 pm, r0g  wrote:
> >> João wrote:
> >>> Someone please?
> >> Haven't seen your original post yet mate, usenet can be flaky like that,
> >> might have been a good idea to quote your original post!
>
> >> Roger.
>
> > Thanks Roger.
>
> >> João wrote:
> >>> Someone please?
> >>> Hi.
> >>> I'm trying to figure out how to force URLencoding in my Python 2.4.3
> >>> environment, receiving data as an input argument but I'm really at a loss
> >>> here.
>
> >>> What am I doing wrong?
> > headers =  {  ’User-Agent’  :  user_agent  }
>
> Those quotes need to be either " or ' i.e.
>
> headers =  {  'User-Agent'  :  user_agent  }
>
> If that doesn't sort it then it would be helpful to see a traceback or,
> if it is not crashing, get a description of how it is failing to do what
> you expect.
>
> Cheers,
>
> Roger.

Weird, I had the correct quotes in my script, maybe I've pasted with
some error.
This is my current script,

(and though I got it working with the subprocess.call I don't know how
to use a pure Python version.

for the following data,
authentication = "UID=somestring&"
message = 'PROBLEM severity High: OperatorX Plat1(locationY) global
Succ. : 94.47%'
dest_number = 'XXX'

url_values = urlencode({'M':message})
enc_data = authentication + url_values + dest_number


I'm getting null for
full_url = Request(url, enc_data, headers)

and thus,
response = urlopen(full_url).read()
returns,
TypeError: 

)

#!/usr/bin/env python
import sys
import os
import subprocess
from urllib import urlencode, urlopen
from urllib2 import Request

destination = sys.argv[1]
msg = sys.argv[2]

authentication = "UID=somestring&"
dest_number = "&N=%s" % destination

message = '%s' % msg
url_values = urlencode({'M':message})

enc_data = authentication + url_values + dest_number

url = 'http://10.112.28.221:38080/GwHTTPin/sendtext'

subprocess.call('echo "%s" | /usr/bin/POST -P "%s"' % (enc_data, url),
shell=True)
-- 
http://mail.python.org/mailman/listinfo/python-list


maintain 2 versions of python on my computer

2010-01-14 Thread luis

Hi

I am not an expert in programming and using Python for its simplicity

I have 2 versions of python installed on my computer (windos xp) to
begin the transition from version 2.4 to 2.6 or 3. maintaining the
operability of my old scripts

Is there any way to indicate the version of the python interpreter
must use a script?

thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: heapq._siftdown / decrease-key support?

2010-01-14 Thread Terry Reedy

On 1/14/2010 5:03 AM, Joshua Bronson wrote:

Thanks for the responses!

On Thu, Jan 14, 2010 at 12:23 AM, Daniel Stutzbach
  wrote:

Your guess is correct.  Someday I'd like to rewrite HeapDict in C for speed, 
but I haven't been able to find the time (and no one has offered to pay me to 
make the time ;) ).


Daniel, did you realize you can accomplish logarithmic-time priority
change (albeit indirectly) with the built-in heapq module using this
mark-as-invalid trick? Are there other algorithms requiring decrease-
key besides A* and Dijkstra where this technique doesn't help?

On Thu, Jan 14, 2010 at 2:41 AM, Mikael Lind  wrote:

If I recall correctly, avoiding the linear search did wonders for
algorithm complexity.


It's still possible to perform the decrease-key operation without
having to do a linear search; heapdict does it in logarithmic time. If
my cursory benchmarks were accurate (which upon reconsideration I'm
not actually sure they are), I think the only explanation for it being
possibly slower is that it's running in pure Python.

I just switched back to using heapq but now with the mark-as-invalid
trick instead of the linear scan, and the performance I'm observing is
very close to heapdict's. Which is curious, because now that both
operations are running in logarithmic time, I'd expect the heapq
implementation to be much faster since it's written in C. Maybe I have
some confounding variables in how I'm running my tests.

By the way, I just realized that the obvious reason the heapq module
doesn't support priority change is that its functions are designed to
operate on external lists rather than providing an encapsulating data
structure like heapdict. With heapdict, logarithmic decrease_key is
possible because it's also storing the positions of the elements in an
underlying dictionary, so instead of a linear scan it does a constant-
time lookup.


If the values in the queue are associated with 0 to n-1, as can be used 
for graph node identifiers , the positions can also be kept in an list, 
again with constant time lookup.



 My guess is that the simplicity of having heapq operate

on external lists is preferable to supporting decrease-key directly,
so it isn't likely to change any time soon, especially since you can
accomplish the same thing with the mark-as-invalid technique.

Raymond, do you think this technique is worth documenting in the heapq
module? It'd be too bad if any future users incorrectly think that it
won't meet their needs the way I did.



--
http://mail.python.org/mailman/listinfo/python-list


Re: maintain 2 versions of python on my computer

2010-01-14 Thread Alf P. Steinbach

* luis:

Hi

I am not an expert in programming and using Python for its simplicity

I have 2 versions of python installed on my computer (windos xp) to
begin the transition from version 2.4 to 2.6 or 3. maintaining the
operability of my old scripts

Is there any way to indicate the version of the python interpreter
must use a script?


I think the most direct way is to use different filename extensions, and 
associate them with corresponding interpreters via the 'assoc' and 'ftype' 
Windows commands.


An alternative is to associate '.py' and '.pyw' with two dummy programs (console 
and GUI subsystem programs) that in some way determines the Python version of 
the script and invokes the right interpreter.


Offhand I can think of three ways to let such a dummy program know the Python 
version of a script (filename extensions are not a way because with distinct 
filename extensions you don't need the dummy program):


  * version information in comment in the file.

  * version information in the filename, like e.g. 'myscript.python31.py',
or version information in the general path, e.g. 'python31\myscript.py'.

  * version information in some kind of 'database', which might be a
separate file or simply hardcoded in your dummy startup program.

But I think personally I'd go for filename extensions and using 'assoc' and 
'ftype', because while ugly it's simplest, like '.py24', '.py26', 'py31'.



Cheers & hth.,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code Generator written in python

2010-01-14 Thread trzewiczek

On 01/13/2010 05:09 PM, Arnaud Delobelle wrote:

nyoka  writes:

   

Can someone help me with sample python code for a code generator
 

Sure, here are some example of self-evaluating python objects, i.e. for each v
below,

v == eval(v)

I'm quite proud of the last one.

v = (lambda x:x%('"''""'+x+'"''""'))("""(lambda 
x:x%%('"''""'+x+'"''""'))(%s)""")

v = (lambda x:x%('r\"'+x+'\"'))(r"(lambda x:x%%('r\"'+x+'\"'))(%s)")

v = (lambda x:x%`x`)('(lambda x:x%%`x`)(%s)')

v = (lambda x: x+"("+`x`+")")('(lambda x: x+"("+`x`+")")')

v = "\"%s\" %% ((r\"%s\",)*2)" % ((r"\"%s\" %% ((r\"%s\",)*2)",)*2)

:)

   
If you're proud of the last one, consider moving to Perl. Python is - as 
I heard - about elegance and readability of code...

--
http://mail.python.org/mailman/listinfo/python-list


Re: maintain 2 versions of python on my computer

2010-01-14 Thread Gabriel Genellina

En Thu, 14 Jan 2010 08:21:28 -0300, luis  escribió:


I am not an expert in programming and using Python for its simplicity

I have 2 versions of python installed on my computer (windos xp) to
begin the transition from version 2.4 to 2.6 or 3. maintaining the
operability of my old scripts

Is there any way to indicate the version of the python interpreter
must use a script?


See http://www.effbot.org/zone/exemaker.htm
It uses the #! line to determine which version to load, resembling the  
Unix way.

(I've written a variant of the same idea but isn't ready yet)

Or, you can always invoke your scripts with an explicit interpreter.  
Create a python24.cmd file containing just this line:


@c:\path\to\python.exe %*

(and a similar one for 2.6 and 3.0) and put them somewhere in your path  
(it is convenient to add a single directory to the system PATH for your  
own utilities; I use c:\util; others use c:\bin).


Then you can say:

python26 foo.py

to execute foo.py using Python 2.6

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Steve Holden
Alf P. Steinbach wrote:
> Just as a contribution, since someone hinted that I haven't really
> contributed much to the Python community.
> 
> The [simple_sound] code will probably go into my ch 3 at  http://tinyurl.com/programmingbookP3>, but sans sine wave generation
> since I haven't yet discussed trig functions, and maybe /with/ changes
> suggested by you?
> 
I wouldn't hold back on the sine wave just because it would represent a
"forward reference". That's OK sometimes. Why not just put a comment in
to the effect that "The sine wave is created using a function from the
math module, which we'll be looking at in ..."?

Since the sine is the basis for all other waveforms its omission would
seem more than a little strange to anyone knowledgeable about audio, for
example.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Steve Holden:

Alf P. Steinbach wrote:

Just as a contribution, since someone hinted that I haven't really
contributed much to the Python community.

The [simple_sound] code will probably go into my ch 3 at http://tinyurl.com/programmingbookP3>, but sans sine wave generation
since I haven't yet discussed trig functions, and maybe /with/ changes
suggested by you?


I wouldn't hold back on the sine wave just because it would represent a
"forward reference". That's OK sometimes. Why not just put a comment in
to the effect that "The sine wave is created using a function from the
math module, which we'll be looking at in ..."?

Since the sine is the basis for all other waveforms its omission would
seem more than a little strange to anyone knowledgeable about audio, for
example.


I don't know very much if anything about audio. For example, in the code what I 
called "sawtooth" wave is really "triangle" wave. The sawtooth is simpler, what 
I called "linear" in the code.


And if you wonder, I was just checking the terminology now before starting to 
write it up... Perhaps should have done that before posting code. But once I got 
the idea of posting it I just posted it.


Anyway, as I recall any wave can be decomposed into sine waves, or square waves, 
or almost whatever kind of waves. Think about a square wave of frequency f and 
one of frequency 3f and perhaps third the amplitude (not sure), combined that's 
already a good start on a sine wave. With some ugly staircasing but hey. And as 
a matter of programming practicality, a triangle wave sounds almost like a sine 
wave. It's just a little more edgy or "hairy", a slight buzz.




Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


a problem with writing a generator

2010-01-14 Thread Paweł Banyś
Hello,

Please forgive me if I repeat the subject anyhow. I am trying to write a
simple program in Python which scans a config file in search for
"include" lines. If those lines are found, the files included there are
followed and scanned and if any further "include" lines are found, the
whole procedure repeats itself. The program ends when the whole tree
structure of those "includes" is generated.

I seem to have some blackout in my mind because I cannot understand how
to use a generator functionality to complete the task. If anybody has
already done such thing I would be very grateful for any guidance.

Regards,

Paweł
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem with writing a generator

2010-01-14 Thread Alf P. Steinbach

* Paweł Banyś:

Hello,

Please forgive me if I repeat the subject anyhow. I am trying to write a
simple program in Python which scans a config file in search for
"include" lines. If those lines are found, the files included there are
followed and scanned and if any further "include" lines are found, the
whole procedure repeats itself. The program ends when the whole tree
structure of those "includes" is generated.

I seem to have some blackout in my mind because I cannot understand how
to use a generator functionality to complete the task. If anybody has
already done such thing I would be very grateful for any guidance.


Assuming that include directives are like

  #include "blahblah"

and further that config files do not contain stuff that's not valid as C 
preprocessor tokens, may I suggest to check whether your C or C++ compiler 
offers an option to show the include file hierarchy.


For example, with gcc or g++ use option '-H' (it has other options for 
generating makefiles!), or with Microsoft's Visual C++, '-showIncludes'. You'll 
also have to ask the compiler to only preprocess.


Disclaimer: I haven't used *nix, if that's your environment, since mid 1990's...



Cheers & hth.,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: a problem with writing a generator

2010-01-14 Thread Paweł Banyś
> Assuming that include directives are like
> 
>   #include "blahblah"

Yes, I have already tried the methods related to source code processing
using Python generators but unfortunately I am dealing with BIND and its
named.conf files.

Regards,

Paweł
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem with writing a generator

2010-01-14 Thread Steven D'Aprano
On Thu, 14 Jan 2010 15:11:29 +0100, Paweł Banyś wrote:

> Hello,
> 
> Please forgive me if I repeat the subject anyhow. I am trying to write a
> simple program in Python which scans a config file in search for
> "include" lines. If those lines are found, the files included there are
> followed and scanned and if any further "include" lines are found, the
> whole procedure repeats itself. The program ends when the whole tree
> structure of those "includes" is generated.
> 
> I seem to have some blackout in my mind because I cannot understand how
> to use a generator functionality to complete the task. 

Do you have to use a generator? Just write the code in whatever way feels 
most comfortable to you. Generators aren't compulsory.

Anyway, here's an untested recursive generator solution that ignores 
everything but include lines, and yields the names of the files indented 
according to the depth of the structure.

def includes(filename, depth=0):
yield "%s%s" % ("  "*depth, filename)
f = open(filename, 'r')
for line in f:
if line.startswith('include '):
inc, fname = line.split(None, 1)
for line in includes(fname, depth=depth-1):
yield line
f.close()




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Steve Holden
Alf P. Steinbach wrote:
> * Steve Holden:
>> Alf P. Steinbach wrote:
>>> Just as a contribution, since someone hinted that I haven't really
>>> contributed much to the Python community.
>>>
>>> The [simple_sound] code will probably go into my ch 3 at >> http://tinyurl.com/programmingbookP3>, but sans sine wave generation
>>> since I haven't yet discussed trig functions, and maybe /with/ changes
>>> suggested by you?
>>>
>> I wouldn't hold back on the sine wave just because it would represent a
>> "forward reference". That's OK sometimes. Why not just put a comment in
>> to the effect that "The sine wave is created using a function from the
>> math module, which we'll be looking at in ..."?
>>
>> Since the sine is the basis for all other waveforms its omission would
>> seem more than a little strange to anyone knowledgeable about audio, for
>> example.
> 
> I don't know very much if anything about audio. For example, in the code
> what I called "sawtooth" wave is really "triangle" wave. The sawtooth is
> simpler, what I called "linear" in the code.
> 
> And if you wonder, I was just checking the terminology now before
> starting to write it up... Perhaps should have done that before posting
> code. But once I got the idea of posting it I just posted it.
> 
> Anyway, as I recall any wave can be decomposed into sine waves, or
> square waves, or almost whatever kind of waves. Think about a square
> wave of frequency f and one of frequency 3f and perhaps third the
> amplitude (not sure), combined that's already a good start on a sine
> wave. With some ugly staircasing but hey. And as a matter of programming
> practicality, a triangle wave sounds almost like a sine wave. It's just
> a little more edgy or "hairy", a slight buzz.
> 
It's not clear to me that you can approximate any waveform with a
suitable combination of square waves, though I admit the idea has
intuitive appeal. But I know beyond a shadow of a doubt from my
education that any periodic function with a fundamental frequency f can
be approximated to whatever desired accuracy by the sum of sine and
cosine waves of frequencies Nf (N = 0, 1, 2, 3, ...) of appropriate
amplitudes (the frequency 0 component allows you to insert a "DC shift"
for waveforms that aren't symmetrical about zero). I seem to remember
the Fourier's theorem was the fundamental proof.

There is a very pretty discussion of all this, if you are mathematically
inclined, in

  http://press.princeton.edu/books/maor/chapter_15.pdf

with a specific example for the sawtooth waveform.

I would definitely recommend renaming the waveforms you *do* use to
conform with accepted terminology. This will reduce reader confusion.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem with writing a generator

2010-01-14 Thread Tim Chase

Paweł Banyś wrote:

Assuming that include directives are like

  #include "blahblah"


Yes, I have already tried the methods related to source code processing
using Python generators but unfortunately I am dealing with BIND and its
named.conf files.


(dealing with BIND named.conf files doesn't sound like homework, 
so I'll bite, though this might make a pretty good CS homework 
problem in the right context)


Sounds like a recursive generator could do the trick.  I'd also 
keep track of "files already recursed" to make sure you don't 
have infinite loops.  Something like this (untested):


  import re
  import os
  class ImportException(Exception): pass
  class RecursionException(Exception): pass
  include_re = re.compile(r'^\s*#include\s+"([^"]+"')
  def importer(fname, paths=None,seen=None):
if not paths: paths = [os.curdir]
if seen is None: seen = set()
f = file(fname)
for i, line in enumerate(f):
  m = include_re.match(line)
  if m: # this line is an "#include"
recurse_fname = m.group(1)
if recurse_fname in seen:
  raise RecursionException(
"[%s:%i] Recursion detected on [%s]" %
(fname, i, recurse_fname)
)
for pth in paths:
  full_path = os.path.join(pth, recurse_fname)
  if os.isfile(full_path):
seen.add(recurse_fname) # push
for line in importer(full_path, paths, seen):
  yield line
seen.remove(recurse_fname) # pop
break
else:
  raise ImportException("[%s:%i] could not find [%s]" %
(fname, i, recurse_fname))
  else: # not an include
yield line
f.close()

There might be some bugs lurking in there, and there might be 
some robustness aspects to consider (like using "with" for the 
file to make sure it gets closed, or wrapping it in a try/finally 
if you're using an older version of Python), and you might also 
consider allowing a certain depth of recursion (I'd use a dict of 
fname->recursion-depth to keep tabs on how deep I'd gotten, and 
raise an exception if I go too deep), but otherwise, that should 
give you a pretty straight-forward and easy-to-tweak starting point.


Hope this helps,

-tim


--
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Steve Holden:

Alf P. Steinbach wrote:

* Steve Holden:

Alf P. Steinbach wrote:

Just as a contribution, since someone hinted that I haven't really
contributed much to the Python community.

The [simple_sound] code will probably go into my ch 3 at http://tinyurl.com/programmingbookP3>, but sans sine wave generation
since I haven't yet discussed trig functions, and maybe /with/ changes
suggested by you?


I wouldn't hold back on the sine wave just because it would represent a
"forward reference". That's OK sometimes. Why not just put a comment in
to the effect that "The sine wave is created using a function from the
math module, which we'll be looking at in ..."?

Since the sine is the basis for all other waveforms its omission would
seem more than a little strange to anyone knowledgeable about audio, for
example.

I don't know very much if anything about audio. For example, in the code
what I called "sawtooth" wave is really "triangle" wave. The sawtooth is
simpler, what I called "linear" in the code.

And if you wonder, I was just checking the terminology now before
starting to write it up... Perhaps should have done that before posting
code. But once I got the idea of posting it I just posted it.

Anyway, as I recall any wave can be decomposed into sine waves, or
square waves, or almost whatever kind of waves. Think about a square
wave of frequency f and one of frequency 3f and perhaps third the
amplitude (not sure), combined that's already a good start on a sine
wave. With some ugly staircasing but hey. And as a matter of programming
practicality, a triangle wave sounds almost like a sine wave. It's just
a little more edgy or "hairy", a slight buzz.


It's not clear to me that you can approximate any waveform with a
suitable combination of square waves,


Oh. It's simple to prove. At least conceptually! :-)

Consider first that you need an infinite number of sine waves to create a 
perfect square wave.


The opposite also holds: infinite number of square waves to create a perfect 
sine wave (in a way sines and squares are opposites, the most incompatible).


With the goal of just a rough approximation you can go about it like this:

  1. Divide a full cycle of the sine wave into n intervals. With
 sine wave frequency f this corresponds to n*f sample rate for digital
 representation.

  2. Each interval will be approximated by a rectangular bar extending
 up to or down to the sine wave. As it happens this (the bar's height) is
 the sample value in a digital representation.

  3. In the first half of the cycle, for each bar create that bar as
 a square wave of frequency f, amplitude half the bar's height, and phase
 starting at the bar's left, plus same square wave with negative sign
 (inverted amplitude) and phase starting at the bar's right. And voilà,
 not only this bar generated  but also the corresponding other-way bar in
 second half of cycle.

  4. Sum all the square waves from step 3.

  5. Let n go to infinity for utter perfectness! :-)

And likewise for any other waveform.

After all, it's the basis of digital representation of sound!



though I admit the idea has
intuitive appeal. But I know beyond a shadow of a doubt from my
education that any periodic function with a fundamental frequency f can
be approximated to whatever desired accuracy by the sum of sine and
cosine waves of frequencies Nf (N = 0, 1, 2, 3, ...) of appropriate
amplitudes (the frequency 0 component allows you to insert a "DC shift"
for waveforms that aren't symmetrical about zero). I seem to remember
the Fourier's theorem was the fundamental proof.


Yes, the good Fourier had a thing for roundish curves. He saw them everywhere 
and in anything. Eventually he found an infinite number of them in, to others, 
invisible /sound/.




There is a very pretty discussion of all this, if you are mathematically
inclined, in

  http://press.princeton.edu/books/maor/chapter_15.pdf

with a specific example for the sawtooth waveform.

I would definitely recommend renaming the waveforms you *do* use to
conform with accepted terminology. This will reduce reader confusion.


Yes, thanks.


Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: a problem with writing a generator

2010-01-14 Thread Wolodja Wentland
On Thu, Jan 14, 2010 at 15:11 +0100, Paweł Banyś wrote:

> I seem to have some blackout in my mind because I cannot understand how
> to use a generator functionality to complete the task. If anybody has
> already done such thing I would be very grateful for any guidance.

I guess the following slides will help you a lot:

http://www.dabeaz.com/generators/

If you have further questions just ask and have fun playing with
generators in Python ...

-- 
  .''`. Wolodja Wentland 
 : :'  :
 `. `'` 4096R/CAF14EFC 
   `-   081C B7CD FF04 2BA9 94EA  36B2 8B7F 7D30 CAF1 4EFC


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem with writing a generator

2010-01-14 Thread Dave Angel

PaweB Bany[ wrote:

Hello,

Please forgive me if I repeat the subject anyhow. I am trying to write a
simple program in Python which scans a config file in search for
"include" lines. If those lines are found, the files included there are
followed and scanned and if any further "include" lines are found, the
whole procedure repeats itself. The program ends when the whole tree
structure of those "includes" is generated.

I seem to have some blackout in my mind because I cannot understand how
to use a generator functionality to complete the task. If anybody has
already done such thing I would be very grateful for any guidance.

Regards,

Paweł

  
If you really want a tree structure, then I don't see why you expect a 
generator to be necessary, or helpful. A generator is frequently a good 
way tor reduce a tree to linear form, so if you were trying to make a 
single set of includes, I'd write a generator. Otherwise, you just need 
a recursive function.


Do you understand recursion? Have you any experience with it in other 
programming languages?


In this case, you write a single function that takes a filename as an 
argument, and returns a list of the includes contained within it. Then, 
inside that function, right after finding such an include, you call the 
same function, passing it the include name, and append the return value 
to your own list.


All the details of building the tree just work, if you get it right.

If you get stuck implementing this outline, then post whatever code you 
have so far, and give the reason why you're stuck. Also, at that point, 
define exactly what you expect the "tree" to look like. There are at 
least a few reasonable choices, and there's no point in heading the 
wrong way.


DaveA

--
http://mail.python.org/mailman/listinfo/python-list


Writing a string.ishex function

2010-01-14 Thread chandra
Folks,

I am new to Python and could not find a function along the lines of
string.ishex in Python. There is however, a string.hexdigits constant
in the string module. I thought I would enhance the existing modlue
but am unsure how I should go about it. Specifically, I have attempted
this much:
---cut---
#! /usr/bin/python
# -*- coding: utf-8 -*-

import string

def ishex(string):
ishex = False
for i in string:
if i in string.hexdigits:
ishex = True
else:
ishex = False
break
return ishex
---cut---

Can someone help me get further along please?

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Those two controversial 2nd & 3rd paragraphs of my ch 1

2010-01-14 Thread Lie Ryan
On 01/14/10 11:08, Alf P. Steinbach wrote:
> * Daniel Fetchinson:
>>
>> Nobody is deliberately trying to keep people from porting! I think you
>> misunderstand what is being said, these two statements are very
>> different: (1) single code base working on both python versions (2)
>> creating a second code from a code so that the second code works with
>> python 3 and the first one with python 2. Statement (2) is about
>> porting, statement (1) is about something else.
>>
>> Having said all that I actually seriously doubt (probably in agreement
>> with you) that Alf is able to write good and helpful material on the
>> relationship between python 2 and 3, porting, migrating, etc, based on
>> his emails :)
> 
> You're mostly absolutely right. :-)
> 
> I think it's OK to write things like "It's possible to travel to the
> moon" and "It's very difficult to travel to the moon", because those are
> just general observations  --  even though an astronaut may disagree
> with the latter stm.
> 
> But in order to write about the design of rockets, planning, economics,
> the physics of it, life support, etc., all the nitty gritty details
> about traveling to the moon so as to enable someone to do it, one needs
> to have done it.
> 
> And so far I haven't done that 2.x/3.x compatible code thing except for
> some very trivial stuff. It so happened that what I wrote in Oct 2009 or
> whenever it was, about "/", was verified just now by stumbling upon the
> "/" bug in [wave.py]. But that apparent detail was again just a general
> observation based on common sense and experience with similar
> differences in other languages, much like "you can expect problems if
> you have a big hole where your rocket's nose tip should be". To write
> about actual porting, version-compatible code, etc., so that it's useful
> to the reader would or will require far more. I'm probably not going to
> do that.
> 
> There are however some comments about 2.x/3.x differences, e.g. about
> "range" and "/", and I'm just now progressing into territory where I'll
> mention "long".
> 
> And I think that those comments constitute good and helpful material on
> the relationship between 2.x and 3.x?

The GNU Build System have succeeded in producing a program that can
write shell scripts (./configure) that works across any shell
implementation and any shell version on any OS (even on Windows with
Cygwin) generally without the need for manual tweaking.

It is common knowledge that a carefully written python scripts is easily
portable between different OS-es, and since there is only one "shell" to
support[1], why do you think this scenario is harder than what GNU Build
System developers were facing? They have shown that it is "possible" to
write a complex *and* portable shell script; why do you think it is
"impossible" to write a complex and portable python script?

Though keeping everything in one code base may often be difficult and
only of little practical benefit, it is not impossible. Modern version
control systems makes creating a fork not-so-difficult[2]; and
maintaining two or more codebase is much cheaper nowadays than they used
to be.


[1] we're ignoring other python implementations since they haven't
targeted 3.0; but anyway due to the much better defined standard,
alternative implementations doesn't pose much difference except for
occasional lack of the newest feature on many cases
[2] though not, by any definition, "easy"; but at least it's often
easier to fork than to keep things in one code base. Another, better,
alternative is to write a program that transform a human readable code
to portable code; which is what 2to3 is about.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem with writing a generator

2010-01-14 Thread Lie Ryan
On 01/15/10 01:49, Steven D'Aprano wrote:
> On Thu, 14 Jan 2010 15:11:29 +0100, Paweł Banyś wrote:
> 
>> Hello,
>>
>> Please forgive me if I repeat the subject anyhow. I am trying to write a
>> simple program in Python which scans a config file in search for
>> "include" lines. If those lines are found, the files included there are
>> followed and scanned and if any further "include" lines are found, the
>> whole procedure repeats itself. The program ends when the whole tree
>> structure of those "includes" is generated.
>>
>> I seem to have some blackout in my mind because I cannot understand how
>> to use a generator functionality to complete the task. 
> 
> Do you have to use a generator? Just write the code in whatever way feels 
> most comfortable to you. Generators aren't compulsory.
> 
> Anyway, here's an untested recursive generator solution that ignores 
> everything but include lines, and yields the names of the files indented 
> according to the depth of the structure.
> 
> def includes(filename, depth=0):
> yield "%s%s" % ("  "*depth, filename)
> f = open(filename, 'r')
> for line in f:
> if line.startswith('include '):
> inc, fname = line.split(None, 1)
> for line in includes(fname, depth=depth-1):
> yield line
> f.close()

that would always produce an empty file, no?

# another completely untested code; bugs may still be around
def includes(filename, depth=0):
yield "%s%s" % ("  "*depth, filename)
f = open(filename, 'r')
for line in f:
if line.startswith('include '):
inc, fname = line.split(None, 1)
for line in includes(fname, depth=depth+1):
yield line
else:
yield line
f.close()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Peter Otten
Alf P. Steinbach wrote:

> Just as a contribution, since someone hinted that I haven't really
> contributed much to the Python community.
> 
> The [simple_sound] code will probably go into my ch 3 at  http://tinyurl.com/programmingbookP3>, but sans sine wave generation since
> I haven't yet discussed trig functions, and maybe /with/ changes suggested
> by you?

> def _append_as_big_endian_int16_to( a, i ):
>  if i < 0:
>  i = i + 65536
>  assert( 0 <= i < 65536 )
>  a.append( i // 256 )
>  a.append( i % 256 )

>  data = array.array( "B" )   # B -> unsigned bytes.

Do you know that array.array() supports 16 bit signed integers? There's even 
a byteswap() method to deal with endianess.

> Utility class that may be used to capture output (an instance of this or
> any other file like class can be passed as "filename" to
> simple_sound.Writer):
> 
> 
> class BytesCollector:

Are you reinventing io.BytesIO() here?

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Steve Holden
Alf P. Steinbach wrote:
> * Steve Holden:
[...]
> With the goal of just a rough approximation you can go about it like this:
> 
>   1. Divide a full cycle of the sine wave into n intervals. With
>  sine wave frequency f this corresponds to n*f sample rate for digital
>  representation.
> 
>   2. Each interval will be approximated by a rectangular bar extending
>  up to or down to the sine wave. As it happens this (the bar's
> height) is
>  the sample value in a digital representation.
> 
>   3. In the first half of the cycle, for each bar create that bar as
>  a square wave of frequency f, amplitude half the bar's height, and
> phase
>  starting at the bar's left, plus same square wave with negative sign
>  (inverted amplitude) and phase starting at the bar's right. And voilà,
>  not only this bar generated  but also the corresponding other-way
> bar in
>  second half of cycle.
> 
>   4. Sum all the square waves from step 3.
> 
>   5. Let n go to infinity for utter perfectness! :-)
> 
> And likewise for any other waveform.
> 
> After all, it's the basis of digital representation of sound!
> 
> 
I'm sorry, but this is merely hand-waving. It looks appealing, but
there's no rigor there.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Mel
Alf P. Steinbach wrote:
> * Steve Holden:

>> It's not clear to me that you can approximate any waveform with a
>> suitable combination of square waves,
> 
> Oh. It's simple to prove. At least conceptually! :-)
> 
> Consider first that you need an infinite number of sine waves to create a
> perfect square wave.
> 
> The opposite also holds: infinite number of square waves to create a
> perfect sine wave (in a way sines and squares are opposites, the most
> incompatible).

No, it doesn't.  The infinite set of sine waves that make a square wave 
leave out the sine waves of frequency 2f, 4f, 6f, 8f, ... (2*n*f) ... .  
Once you've left them out, you can never get them back.  So sawtooth waves, 
for example, can't generally be built out of sets of square waves.

You can inject even harmonics up to a given limit by adding "rectangular 
waves" with given duty cycles, but the "given" part makes the math grubby.

Fourier transforms are cute to play with.  If you don't care about run-time 
there's:


#!/usr/bin/env python
# -*- coding: ASCII -*-
'''
$Id$'''
import math

def dft (sample):
'''Discrete Fourier Transform'''
n = len (sample)
n21 = n / 2 + 1
twopi = math.pi * 2.0
sin = math.sin
cos = math.cos
rex = [0]*n21
imx = [0]*n21
for k in xrange (n):
for i in xrange (n21):
a = twopi * k * i / n
rex[i] += sin(a) * sample[k]
imx[i] -= cos(a) * sample[k]
return rex, imx

#~ wave = [1]*32 + [-1]*32  # rectangular duty-cycle 1/2
#~ wave = [3]*16 + [-1]*48  # rectangular duty-cycle 1/4
wave = [7]*8 + [-1]*56  # rectangular duty-cycle 1/8
#~ wave = [15]*4 + [-1]*60  # rectangular duty-cycle 1/16
#~ wave = [31]*2 + [-1]*62  # rectangular duty-cycle 1/32
rex, imx = dft (wave)
print rex
print
print imx



The real coefficients show how the 8th, 16th, 24th, 32nd harmonics -- where 
the coefficients are near zero -- have dropped out of the waveform.



Mel.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Those two controversial 2nd & 3rd paragraphs of my ch 1

2010-01-14 Thread Alf P. Steinbach

* Lie Ryan -> Alf P. Steinbach:

why do you think it is "impossible" to write a complex and portable
python script?


I don't. You're not quoting me.



Though keeping everything in one code base may often be difficult and
only of little practical benefit, it is not impossible. Modern version
control systems makes creating a fork not-so-difficult[2]; and
maintaining two or more codebase is much cheaper nowadays than they used
to be.


Huh.



[1] we're ignoring other python implementations since they haven't
targeted 3.0; but anyway due to the much better defined standard,
alternative implementations doesn't pose much difference except for
occasional lack of the newest feature on many cases
[2] though not, by any definition, "easy"; but at least it's often
easier to fork than to keep things in one code base. Another, better,
alternative is to write a program that transform a human readable code
to portable code; which is what 2to3 is about.


The upshot for 2.x/3.x compatible code base is to write in 2.x and convert 
automatically to 3.x, that is, to write the source code in *one* language.


That's because it's very hard to write code that works directly in both 
languages (or language versions, if you prefer).


The paragraph in the book is about why one, in practice, has to choose one 
version for one's source code, and why one shouldn't automatically think that 
what's learned about that version necessarily applies to the other version.



Cheers & hth.,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Mel:

Alf P. Steinbach wrote:

* Steve Holden:



It's not clear to me that you can approximate any waveform with a
suitable combination of square waves,

Oh. It's simple to prove. At least conceptually! :-)

Consider first that you need an infinite number of sine waves to create a
perfect square wave.

The opposite also holds: infinite number of square waves to create a
perfect sine wave (in a way sines and squares are opposites, the most
incompatible).


No, it doesn't.  The infinite set of sine waves that make a square wave 
leave out the sine waves of frequency 2f, 4f, 6f, 8f, ... (2*n*f) ... .  
Once you've left them out, you can never get them back.  So sawtooth waves, 
for example, can't generally be built out of sets of square waves.


The way to build a sine wave out of square waves is not a Fourier transform.

See the post you replied to for a simple procedure to build the sine wave.


Cheers & hth.,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Iain King
On Jan 14, 3:52 pm, chandra  wrote:
> Folks,
>
> I am new to Python and could not find a function along the lines of
> string.ishex in Python. There is however, a string.hexdigits constant
> in the string module. I thought I would enhance the existing modlue
> but am unsure how I should go about it. Specifically, I have attempted
> this much:
> ---cut---
> #! /usr/bin/python
> # -*- coding: utf-8 -*-
>
> import string
>
> def ishex(string):
>     ishex = False
>     for i in string:
>         if i in string.hexdigits:
>             ishex = True
>         else:
>             ishex = False
>             break
>     return ishex
> ---cut---
>
> Can someone help me get further along please?
>
> Thanks.

better would be:
def ishex(s):
for c in s:
if c not in string.hexdigits:
return False
return True

Iain
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Steve Holden:

Alf P. Steinbach wrote:

* Steve Holden:

[...]

With the goal of just a rough approximation you can go about it like this:

  1. Divide a full cycle of the sine wave into n intervals. With
 sine wave frequency f this corresponds to n*f sample rate for digital
 representation.

  2. Each interval will be approximated by a rectangular bar extending
 up to or down to the sine wave. As it happens this (the bar's
height) is
 the sample value in a digital representation.

  3. In the first half of the cycle, for each bar create that bar as
 a square wave of frequency f, amplitude half the bar's height, and
phase
 starting at the bar's left, plus same square wave with negative sign
 (inverted amplitude) and phase starting at the bar's right. And voilà,
 not only this bar generated  but also the corresponding other-way
bar in
 second half of cycle.

  4. Sum all the square waves from step 3.

  5. Let n go to infinity for utter perfectness! :-)

And likewise for any other waveform.

After all, it's the basis of digital representation of sound!



I'm sorry, but this is merely hand-waving. It looks appealing, but
there's no rigor there.


Bullshit.


Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread D'Arcy J.M. Cain
On Thu, 14 Jan 2010 07:52:58 -0800 (PST)
chandra  wrote:
> Folks,
> 
> I am new to Python and could not find a function along the lines of

Welcome.

> string.ishex in Python. There is however, a string.hexdigits constant
> in the string module. I thought I would enhance the existing modlue
> but am unsure how I should go about it. Specifically, I have attempted
> this much:

You should always test code before posting and post the exact code that
you tested.

> ---cut---
> #! /usr/bin/python
> # -*- coding: utf-8 -*-
> 
> import string
> 
> def ishex(string):

Bad idea to name your variable after a module.  This function fails
because of that.

> ishex = False
> for i in strdef ishex(sing:
> if i in string.hexdigits:
> ishex = True
> else:
> ishex = False
> break
> return ishex

After renaming the variable this works but you can simplify it.


> ---cut---

Just return False once you find a non-hex digit.

def ishex(s):
  for c in s:
if not c in string.hexdigits: return False

  return True

And here are your unit tests.  Every line should print "True".

print ishex('123') is True
print ishex('abc') is True
print ishex('xyz') is False
print ishex('0123456789abcdefABCDEF') is True
print ishex('0123456789abcdefABCDEFG') is False

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Peter Otten:

Alf P. Steinbach wrote:


Just as a contribution, since someone hinted that I haven't really
contributed much to the Python community.

The [simple_sound] code will probably go into my ch 3 at http://tinyurl.com/programmingbookP3>, but sans sine wave generation since
I haven't yet discussed trig functions, and maybe /with/ changes suggested
by you?



def _append_as_big_endian_int16_to( a, i ):
 if i < 0:
 i = i + 65536
 assert( 0 <= i < 65536 )
 a.append( i // 256 )
 a.append( i % 256 )



 data = array.array( "B" )   # B -> unsigned bytes.


Do you know that array.array() supports 16 bit signed integers?


Yes. I used bytes since that seemed to be what [wave] required. But I tested now 
and at least [aifc] handles 16-bit integers fine.


Hm, nice example down the drain...


There's even 
a byteswap() method to deal with endianess.



Utility class that may be used to capture output (an instance of this or
any other file like class can be passed as "filename" to
simple_sound.Writer):


class BytesCollector:


Are you reinventing io.BytesIO() here?


Probably. :-) Checking... Yes, I was; thanks!


Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread chandra
On Jan 15, 12:22 am, "D'Arcy J.M. Cain"  wrote:

> Just return False once you find a non-hex digit.
>
> def ishex(s):
>   for c in s:
>     if not c in string.hexdigits: return False
>
>   return True
>
> And here are your unit tests.  Every line should print "True".
>
> print ishex('123') is True
> print ishex('abc') is True
> print ishex('xyz') is False
> print ishex('0123456789abcdefABCDEF') is True
> print ishex('0123456789abcdefABCDEFG') is False
>

Thanks to Iain and to you.

One further question: even though it is a single function, is there
any way to convert it into a module? Can existing modules be enhanced
with functions such as these? If not, how may I make my own module,
called, say mystring? At present, I am saving the file as ishex.py and
calling it after declaring

from ishex import ishex

Is there a more elegant way to integrate this function and make it
available to other python scripts using the import mechanism?

Thanks.

Chandra
-- 
http://mail.python.org/mailman/listinfo/python-list


SMTPException: No suitable authentication method found (Server: Microsoft ESMTP MAIL Service)

2010-01-14 Thread Thomas Guettler
Hi,

I try to login, but I get this exception:

  File "/home/foo/django/core/mail.py", line 137, in open
self.connection.login(self.username, self.password)
  File "/home/foo/smtplib.py", line 587, in login
raise SMTPException("No suitable authentication method found.")


Trace from tcpdump+wireshark

220 remote.example.com Microsoft ESMTP MAIL Service ready at Thu, 14 Jan 2010 
17:20:38 +0100
client: ehlo foo.example.com
250-remote.example.com Hello [127]
250-SIZE 10485760
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-AUTH
250-8BITMIME
250-BINARYMIME
250 CHUNKING

The same happens if I use TLS.

Any hints?

  Thomas

-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Grant Edwards
On 2010-01-14, Alf P. Steinbach  wrote:

>> It's not clear to me that you can approximate any waveform
>> with a suitable combination of square waves,
>
> Oh. It's simple to prove. At least conceptually! :-)

[...]

> With the goal of just a rough approximation you can go about
> it like this:
>
>1. Divide a full cycle of the sine wave into n intervals.
>   With sine wave frequency f this corresponds to n*f
>   sample rate for digital representation.
>
>2. Each interval will be approximated by a rectangular bar
>   extending up to or down to the sine wave. As it happens
>   this (the bar's height) is the sample value in a digital
>   representation.
>
>3. In the first half of the cycle, for each bar create that
>   bar as a square wave of frequency f, amplitude half the
>   bar's height, and phase starting at the bar's left, plus
>   same square wave with negative sign (inverted amplitude)
>   and phase starting at the bar's right. And voil?, not
>   only this bar generated but also the corresponding
>   other-way bar in second half of cycle.
>
>4. Sum all the square waves from step 3.
>
>5. Let n go to infinity for utter perfectness! :-)
>
> And likewise for any other waveform.
>
> After all, it's the basis of digital representation of sound!

Huh?  I've only studied basic DSP, but I've never heard/seen
that as the basis of digital represention of sound.  I've also
never seen that representation used anywhere.  Can you provide
any references?

-- 
Grant Edwards   grante Yow! CHUBBY CHECKER just
  at   had a CHICKEN SANDWICH in
   visi.comdowntown DULUTH!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Generator written in python

2010-01-14 Thread Arnaud Delobelle
trzewiczek  writes:

> On 01/13/2010 05:09 PM, Arnaud Delobelle wrote:
[...]
>> Sure, here are some example of self-evaluating python objects,
>> i.e. for each v below,
>>
>> v == eval(v)
>>
>> I'm quite proud of the last one.
[...]
>> v = "\"%s\" %% ((r\"%s\",)*2)" % ((r"\"%s\" %% ((r\"%s\",)*2)",)*2)
>>
>> :)
>>
>>
> If you're proud of the last one, consider moving to Perl. Python is -
> as I heard - about elegance and readability of code...

No thanks.  It's far too easy to write unreadable code in Perl and I
like a challenge :)

Seriously - this is a self-evaluating string, not code for landing a
$1bn rocket on Mars.  Do you expect it to be readable?  I don't.
However, I definitely find a certain elegance to it.

-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Grant Edwards:

On 2010-01-14, Alf P. Steinbach  wrote:


It's not clear to me that you can approximate any waveform
with a suitable combination of square waves,

Oh. It's simple to prove. At least conceptually! :-)


[...]


With the goal of just a rough approximation you can go about
it like this:

   1. Divide a full cycle of the sine wave into n intervals.
  With sine wave frequency f this corresponds to n*f
  sample rate for digital representation.

   2. Each interval will be approximated by a rectangular bar
  extending up to or down to the sine wave. As it happens
  this (the bar's height) is the sample value in a digital
  representation.

   3. In the first half of the cycle, for each bar create that
  bar as a square wave of frequency f, amplitude half the
  bar's height, and phase starting at the bar's left, plus
  same square wave with negative sign (inverted amplitude)
  and phase starting at the bar's right. And voil?, not
  only this bar generated but also the corresponding
  other-way bar in second half of cycle.

   4. Sum all the square waves from step 3.

   5. Let n go to infinity for utter perfectness! :-)

And likewise for any other waveform.

After all, it's the basis of digital representation of sound!


Huh?  I've only studied basic DSP, but I've never heard/seen
that as the basis of digital represention of sound.


Oh, you have... The end result above (for finite n) is a sequence of sample 
values of a sine wave. Ordinary digital representation of sound is exactly the 
same, a sequence of sample values.




I've also never seen that representation used anywhere.


Yes, you have. A sequence of sample values is the representation used in any 
direct wave file. Like [.wav]  and, I believe, [.aiff].




 Can you provide any references?


I don't have any references for the above procedure, it's sort of trivial. 
Probably could find some references with an hour of googling. But no point.



Cheers & hth.,

- Alf


PS: To extend the above to a non-symmetric waveform, just first decompose that 
waveform into sine waves (Fourier transform), then add up the square wave 
representations of each sine wave. :-)

--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Chris Rebert
On Thu, Jan 14, 2010 at 8:14 AM, Iain King  wrote:
> On Jan 14, 3:52 pm, chandra  wrote:
>> Folks,
>>
>> I am new to Python and could not find a function along the lines of
>> string.ishex in Python. There is however, a string.hexdigits constant
>> in the string module. I thought I would enhance the existing modlue
>> but am unsure how I should go about it. Specifically, I have attempted
>> this much:
>> ---cut---
>> #! /usr/bin/python
>> # -*- coding: utf-8 -*-
>>
>> import string
>>
>> def ishex(string):
>>     ishex = False
>>     for i in string:
>>         if i in string.hexdigits:
>>             ishex = True
>>         else:
>>             ishex = False
>>             break
>>     return ishex
>> ---cut---
>>
>> Can someone help me get further along please?
>>
>> Thanks.
>
> better would be:
> def ishex(s):
>    for c in s:
>        if c not in string.hexdigits:
>            return False
>    return True

Even more succinctly:

def ishex(s):
return all(c in string.hexdigits for c in s)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Steve Holden
Grant Edwards wrote:
> On 2010-01-14, Alf P. Steinbach  wrote:
[bogus hand-waving]
>> After all, it's the basis of digital representation of sound!
> 
> Huh?  I've only studied basic DSP, but I've never heard/seen
> that as the basis of digital represention of sound.  I've also
> never seen that representation used anywhere.  Can you provide
> any references?
> 
Of course he can't. And it isn't the basis of analog quantization. And I
suspect Alf has never hear of Shannon's theorem.

But don't listen to me, apparently I'm full of it.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Steve Holden
chandra wrote:
> On Jan 15, 12:22 am, "D'Arcy J.M. Cain"  wrote:
> 
>> Just return False once you find a non-hex digit.
>>
>> def ishex(s):
>>   for c in s:
>> if not c in string.hexdigits: return False
>>
>>   return True
>>
>> And here are your unit tests.  Every line should print "True".
>>
>> print ishex('123') is True
>> print ishex('abc') is True
>> print ishex('xyz') is False
>> print ishex('0123456789abcdefABCDEF') is True
>> print ishex('0123456789abcdefABCDEFG') is False
>>
> 
> Thanks to Iain and to you.
> 
> One further question: even though it is a single function, is there
> any way to convert it into a module? Can existing modules be enhanced
> with functions such as these? If not, how may I make my own module,
> called, say mystring? At present, I am saving the file as ishex.py and
> calling it after declaring
> 
> from ishex import ishex
> 
> Is there a more elegant way to integrate this function and make it
> available to other python scripts using the import mechanism?
> 
Nope, that's about as elegant as it gets.

You can, of course, include it in a generic utility module and import
several things from that module - you aren't limited to defining a
single object in a module.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Ignore leading '>>>' and ellipsis?

2010-01-14 Thread Reckoner

Hi,

I am studying some examples in a tutorial where there are a lot of
leading >>> characters and ellipsis in the text. This makes it hard to
cut and paste into the IPython interpreter since it doesn't like these
strings.

Is there another interpreter I could use that will appropriately
ignore and interpret these leading terms?

For example, I cannot paste the following directly into the
interpreter:

>>> d = dict(x.__array_interface__)
>>> d['shape'] = (3, 2, 5)
>>> d['strides'] = (20, 20, 4)

>>> class Arr:
... __array_interface__ = d
... base = x
-- 
http://mail.python.org/mailman/listinfo/python-list


Drawing a surface with matplotlib

2010-01-14 Thread Monnin
Hello,
I have a newbie question about using matplotlib
I would like to draw the surface defined by the lists X, Y and the
matrix Z.
I get to a nice graphical output with the following code.
My problem is that the labels on the axes indicate values
corresponding to the indices in Tables X and Y.
I would like to see these values between xmin and xmax, ymin and ymax.
If I uncomment the lines set_xlim and set_ylim, the axes are properly
represented, but the picture is squashed into a corner.
How have the values on the axes and correct the image full screen?
Thank you in advance.

#! /usr/bin/env python

from pylab import *

x=[0,1,2,3]
y=[12, 32,81]
z=[2,3,1,4,2,5,6,8,10,4,11,3]
Z=zeros((len(x),len(y)))
count=0
for i in range(0,len(x)):
for j in range(0,len(y)):
Z[i,j]=z[count]
count=count+1

ax = subplot(111)

im = imshow(Z,  interpolation='bilinear')
xmin=x[0]
xmax=x[len(x)-1]
ymin=y[0]
ymax=y[len(y)-1]

#ax.set_xlim(xmin,xmax)
#ax.set_ylim(ymin,ymax)
#axes().set_aspect('auto',adjustable='box')

colorbar()

show()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Steve Holden:

Grant Edwards wrote:

On 2010-01-14, Alf P. Steinbach  wrote:

[bogus hand-waving]

After all, it's the basis of digital representation of sound!

Huh?  I've only studied basic DSP, but I've never heard/seen
that as the basis of digital represention of sound.  I've also
never seen that representation used anywhere.


Just for the record: Grant has seen that representation numerous times, he just 
didn't recognize it.




 Can you provide any references?



Of course he can't.  And it isn't the basis of analog quantization.


Of course it isn't the basis of quantization: it *is* quantization, directly.

Which is the basis of digital representation.



And I suspect Alf has never hear of Shannon's theorem.


It's about 30 years since I did that stuff.



But don't listen to me, apparently I'm full of it.


You're spouting innuendo and personal attacks, repeatedly, so that seems to be 
the case, yes. :-)



Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ignore leading '>>>' and ellipsis?

2010-01-14 Thread Javier Collado
Hello,

I think that's exactly what the cpaste magic function does. Type
'cpaste?' in your IPython session for more information.

Best regards,
Javier

2010/1/14 Reckoner :
>
> Hi,
>
> I am studying some examples in a tutorial where there are a lot of
> leading >>> characters and ellipsis in the text. This makes it hard to
> cut and paste into the IPython interpreter since it doesn't like these
> strings.
>
> Is there another interpreter I could use that will appropriately
> ignore and interpret these leading terms?
>
> For example, I cannot paste the following directly into the
> interpreter:
>
 d = dict(x.__array_interface__)
 d['shape'] = (3, 2, 5)
 d['strides'] = (20, 20, 4)
>
 class Arr:
> ...     __array_interface__ = d
> ...     base = x
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread D'Arcy J.M. Cain
On Thu, 14 Jan 2010 09:07:47 -0800
Chris Rebert  wrote:
> Even more succinctly:
> 
> def ishex(s):
> return all(c in string.hexdigits for c in s)

I'll see your two-liner and raise you.  :-)

ishex = lambda s: all(c in string.hexdigits for c in s)


-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: force URLencoding script

2010-01-14 Thread r0g
João wrote:
> On Jan 12, 10:07 pm, r0g  wrote:
>> João wrote:
> 
> for the following data,
> authentication = "UID=somestring&"
> message = 'PROBLEM severity High: OperatorX Plat1(locationY) global
> Succ. : 94.47%'
> dest_number = 'XXX'
> 
> url_values = urlencode({'M':message})
> enc_data = authentication + url_values + dest_number
> 
> 
> I'm getting null for
> full_url = Request(url, enc_data, headers)
> 
> and thus,
> response = urlopen(full_url).read()
> returns,
> TypeError: 
> 
> )


Are you sure it's returning a null and not just some other unexpected
type?

I think your problem may be that you are passing a urllib2 class to
urllib(1)'s urlopen. Try using urllib2's urlopen instead e.g.

import urllib2
request_object = urllib2.Request('http://www.example.com')
response = urllib2.urlopen(request_object)
the_page = response.read()

Roger.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: maintain 2 versions of python on my computer

2010-01-14 Thread r0g
luis wrote:
> Hi
> 
> I am not an expert in programming and using Python for its simplicity
> 
> I have 2 versions of python installed on my computer (windos xp) to
> begin the transition from version 2.4 to 2.6 or 3. maintaining the
> operability of my old scripts
> 
> Is there any way to indicate the version of the python interpreter
> must use a script?
> 
> thanks


On unix you would start the file with a "hashbang" e.g.

#!/usr/bin/python3

Fraid I don't know if that works on XP though.

Roger.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Christian Heimes
Iain King wrote:
> better would be:
> def ishex(s):
> for c in s:
> if c not in string.hexdigits:
> return False
> return True

Even more elegant and probably a faster solutions:

---
from string import hexdigits
hexdigits = frozenset(hexdigits)

def ishex(s):
return set(s).issubset(hexdigits)
---

If you are also interested in the integer value of a hex string:

---
def gethex(s):
try:
return int(s, 16)
except ValueError:
return None
---

Check for "gethex(s) is not None" to see if s is a hex string.

Christian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference Between Two datetimes

2010-01-14 Thread Steve Ferg

> I'd like to start with two dates as strings, as
> "1961/06/16 04:35:25" and "1973/01/18 03:45:50"
> How do I get the strings into a shape that will accommodate a difference?

Pyfdate  http://www.ferg.org/pyfdate/index.html
has a numsplit function that should do the trick:
http://www.ferg.org/pyfdate/tutorial.html#contents_item_14

It splits a string into its numeric parts and return a list containing
the numeric parts converted to ints.

>>> from pyfdate import *
>>> numsplit("2007_10_09")
[2007, 10, 9]
>>> numsplit("2007-10-09T23:45:59")
[2007, 10, 9, 23, 45, 59]
>>> numsplit("2007/10/09 23.45.59")
[2007, 10, 9, 23, 45, 59]




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Steve Holden
Alf P. Steinbach wrote:
> * Steve Holden:
>> Grant Edwards wrote:
>>> On 2010-01-14, Alf P. Steinbach  wrote:
>> [bogus hand-waving]
 After all, it's the basis of digital representation of sound!
>>> Huh?  I've only studied basic DSP, but I've never heard/seen
>>> that as the basis of digital represention of sound.  I've also
>>> never seen that representation used anywhere.
> 
> Just for the record: Grant has seen that representation numerous times,
> he just didn't recognize it.
> 
> 
>>  Can you provide any references?
>>>
>> Of course he can't.  And it isn't the basis of analog quantization.
> 
> Of course it isn't the basis of quantization: it *is* quantization,
> directly.
> 
Nope, quantization is taking the *instantaneous value* of a waveform and
using that as the representation for one sample period. That is nowhere
near the same as summing periodic square waves.

> Which is the basis of digital representation.
> 
Well at least we agree that quantization is the basis of digital
representations. But I've never seen any summed square wave presentation
of it.

> 
>> And I suspect Alf has never hear of Shannon's theorem.
> 
> It's about 30 years since I did that stuff.
> 
Well me too, but information theory is, after all, the theoretical
underpinning for the way I make my living, so I felt obliged to study it
fairly thoroughly.
> 
>> But don't listen to me, apparently I'm full of it.
> 
> You're spouting innuendo and personal attacks, repeatedly, so that seems
> to be the case, yes. :-)
> 
Nothing personal about it. I'm just asking you to corroborate statements
you have made which, in my ignorance, I consider to be bogus hand-waving.

Nothing about you there. Just the information you are promoting. I don't
normally deal in innuendo and personal attacks. Though I do occasionally
get irritated by what I perceive to be hogwash. People who know me will
tell you, if I am wrong I will happily admit it.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple distributed example for learning purposes?

2010-01-14 Thread Mike Driscoll
On Dec 26 2009, 2:06 pm, Tim Golden  wrote:
> I'm trying to work up a programming course using Python,
> aimed at secondary school students [*] here in London. One
> of my aims is to have a series of compact but functional
> examples, each demonstrating a particular field in which
> Python (and programming) can be useful.
>
> I'm trying to come up with something which will illustrate
> the usefulness of a distributed processing model. Since I
> may not be using the term "distributed" exactly, my
> criteria are:
>
> * It should be clear that the application produces results
> sooner when run via multiple cooperating computers
> than when run on one.
>
> * The problem being solved should be broadly comprehensible by
> the students. This rules out some abstruse mathematical
> calculation which would benefit from multiple processors but
> which will fail to engage their interest.
>
> * I don't mind using / installing some library as a black box
> so long as the other criteria are met. This is at least partly
> because I want the code to be compact and I'm quite happy to
> point to a library call and say "this does the hard work".
>
> I'm not asking anyone to write code: what I'm after is some sort
> of problem space which will meet my criteria. Part of the issue
> is that computers are just so fast these days that almost anything
> I can come up with can be managed so quickly on one laptop that
> the overhead of distribution (or of the IO) will dwarf the benefits
> of distributing.
>
> The kind of things I've considered briefly include: speech recognition;
> image analysis; large scale indexing (effectively: building a search
> engine). At present I'm looking at that last one, not least because I
> have little knowledge of the other domains so there's a overhead for
> me in setting the example up.
>
> Any suggestions, either from your own experience of something similar,
> or from sheer inspiration, will be gratefully received.
>
> Thanks
>
> TJG
>
> [*] roughly, ages 14-18

I think distributed transcoding of hi-def videos would be cool, but I
haven't found much with Google. Still, you might find this useful for
your project:

http://pypi.python.org/pypi/AsynCluster/0.3

For reasons I don't understand, the home page listed in that link is
blocked here.

---
Mike Driscoll

Blog:   http://blog.pythonlibrary.org

PyCon 2010 Atlanta Feb 19-21  http://us.pycon.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Arnaud Delobelle
"D'Arcy J.M. Cain"  writes:

> On Thu, 14 Jan 2010 09:07:47 -0800
> Chris Rebert  wrote:
>> Even more succinctly:
>> 
>> def ishex(s):
>> return all(c in string.hexdigits for c in s)
>
> I'll see your two-liner and raise you.  :-)
>
> ishex = lambda s: all(c in string.hexdigits for c in s)

I'see your one-liner and raise you by four characters :o)

ishex1 = lambda s: all(c in string.hexdigits for c in s) # Yours
ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Mine

Notice that ishex2 is more accurate than ishex1.  E.g.

>>> ishex1(['abc', '123'])
True
>>> ishex2(['abc', '123'])
False

-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


unittest help needed!

2010-01-14 Thread Oltmans
Hi Python gurus,

I'm quite new to Python and have a problem. Following code resides in
a file named test.py
---
import unittest


class result(unittest.TestResult):
pass



class tee(unittest.TestCase):
def test_first(self):
print 'first test'
print '-'
def test_second(self):
print 'second test'
print '-'
def test_final(self):
print 'final method'
print '-'

r = result()
suite = unittest.defaultTestLoader.loadTestsFromName('test.tee')

suite.run(r)

---

Following is the output when I run it
---
final method
-
first test
-
second test
-
final method
-
first test
-
second test
-

---

Looks like it's running every test twice, I cannot figure out why?
Shouldn't output be more like

---
final method
-
first test
-
second test
-
---

Please help me solve the problem. Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread MRAB

D'Arcy J.M. Cain wrote:

On Thu, 14 Jan 2010 07:52:58 -0800 (PST)
chandra  wrote:

Folks,

I am new to Python and could not find a function along the lines of


Welcome.


string.ishex in Python. There is however, a string.hexdigits constant
in the string module. I thought I would enhance the existing modlue
but am unsure how I should go about it. Specifically, I have attempted
this much:


You should always test code before posting and post the exact code that
you tested.


---cut---
#! /usr/bin/python
# -*- coding: utf-8 -*-

import string

def ishex(string):


Bad idea to name your variable after a module.  This function fails
because of that.


ishex = False
for i in strdef ishex(sing:
if i in string.hexdigits:
ishex = True
else:
ishex = False
break
return ishex


After renaming the variable this works but you can simplify it.



---cut---


Just return False once you find a non-hex digit.

def ishex(s):
  for c in s:
if not c in string.hexdigits: return False

  return True

And here are your unit tests.  Every line should print "True".

print ishex('123') is True
print ishex('abc') is True
print ishex('xyz') is False
print ishex('0123456789abcdefABCDEF') is True
print ishex('0123456789abcdefABCDEFG') is False


Don't use 'is', use '=='.

BTW, ishex('') should return False.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Phlip

MRAB wrote:


BTW, ishex('') should return False.


So should int('')!
--
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Alf P. Steinbach

* Steve Holden:

Alf P. Steinbach wrote:

* Steve Holden:

Grant Edwards wrote:

On 2010-01-14, Alf P. Steinbach  wrote:

[bogus hand-waving]

After all, it's the basis of digital representation of sound!

Huh?  I've only studied basic DSP, but I've never heard/seen
that as the basis of digital represention of sound.  I've also
never seen that representation used anywhere.

Just for the record: Grant has seen that representation numerous times,
he just didn't recognize it.



 Can you provide any references?
Of course he can't.  And it isn't the basis of analog quantization.

Of course it isn't the basis of quantization: it *is* quantization,
directly.


Nope, quantization is taking the *instantaneous value* of a waveform and
using that as the representation for one sample period. That is nowhere
near the same as summing periodic square waves.


There are two three things wrong with that paragraph. First, quantization can 
not physically be instantaneous. So it's pretty much moot to try to restrict it 
to that.


Second, for the mathematical exercise you can let the measurement be an 
instantaneous value, that is, the value at a single point.


Third, the result of quantization is a sequence of values, each value present 
for an interval of time, and the same is obtained by summing square waves.


I'm beginning to believe that you maybe didn't grok that simple procedure.

It's very very very trivial, so maybe you were looking for something more 
intricate  --  they used to say, in the old days, "hold on, this proof goes by 
so fast you may not notice it!"




Which is the basis of digital representation.


Well at least we agree that quantization is the basis of digital
representations. But I've never seen any summed square wave presentation
of it.


Well, I'm glad to be able to teach something.

Here's the MAIN IDEA in the earlier procedure: a square wave plus same wave 
offset (phase) and negated, produces a set of more rectangular waveforms, which 
I called "bars"  --  in between the bars the two square waves cancel each other:


 _
| |
| |
  __| |__   __
 | |
 | |
 |_|

The bars alternate in positive and negative direction. They can be made as 
narrow as you wish, and when they are as narrow as each sample interval then 
each bar can represent the sample value residing in that interval. Even a sample 
corresponding to a point measurement (if such were physically possible).


And samples are all that's required for representing the sine. And happily the 
alternation of upgoing and downgoing bars is matched by an identical alternation 
of the sine wave. :-) Otherwise it would be a tad difficult to do this.


But then, representing sines is all that's required for representing any wave 
form, since any wave form can be decomposed into sines.




And I suspect Alf has never hear of Shannon's theorem.

It's about 30 years since I did that stuff.


Well me too, but information theory is, after all, the theoretical
underpinning for the way I make my living, so I felt obliged to study it
fairly thoroughly.

But don't listen to me, apparently I'm full of it.

You're spouting innuendo and personal attacks, repeatedly, so that seems
to be the case, yes. :-)


Nothing personal about it. I'm just asking you to corroborate statements
you have made which, in my ignorance, I consider to be bogus hand-waving.


OK.

May I then suggest going through the procedure I presented and *draw* the square 
waves.


I dunno, but maybe that can help.



Nothing about you there. Just the information you are promoting. I don't
normally deal in innuendo and personal attacks. Though I do occasionally
get irritated by what I perceive to be hogwash. People who know me will
tell you, if I am wrong I will happily admit it.


There's a difference between an algorithm that you can implement, and hogwash.


Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest help needed!

2010-01-14 Thread exarkun

On 06:33 pm, [email protected] wrote:

Hi Python gurus,

I'm quite new to Python and have a problem. Following code resides in
a file named test.py
---
import unittest


class result(unittest.TestResult):
   pass



class tee(unittest.TestCase):
   def test_first(self):
   print 'first test'
   print '-'
   def test_second(self):
   print 'second test'
   print '-'
   def test_final(self):
   print 'final method'
   print '-'

r = result()
suite = unittest.defaultTestLoader.loadTestsFromName('test.tee')

suite.run(r)

---

Following is the output when I run it
---
final method
-
first test
-
second test
-
final method
-
first test
-
second test
-

---

Looks like it's running every test twice, I cannot figure out why?


When you run test.py, it gets to the loadTestsFromName line.  There, it
imports the module named "test" in order to load tests from it.  To 
import

that module, it runs test.py again.  By the time it finishes running the
contents of test.py there, it has run all of your tests once, since part
of test.py is "suite.run(r)".  Having finished that, the import of the 
"test"
module is complete and the "loadTestsFromName" call completes.  Then, 
the

"suite.run(r)" line runs again, and all your tests run again.

You want to protect the suite stuff in test.py like this:

   if __name__ == '__main__':
   ...

Or you want to get rid of it entirely and use `python -m unittest 
test.py`

(with a sufficiently recent version of Python), or another runner, like
Twisted Trial or one of the many others available.

Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread MRAB

Arnaud Delobelle wrote:

"D'Arcy J.M. Cain"  writes:


On Thu, 14 Jan 2010 09:07:47 -0800
Chris Rebert  wrote:

Even more succinctly:

def ishex(s):
return all(c in string.hexdigits for c in s)

I'll see your two-liner and raise you.  :-)

ishex = lambda s: all(c in string.hexdigits for c in s)


I'see your one-liner and raise you by four characters :o)

ishex1 = lambda s: all(c in string.hexdigits for c in s) # Yours
ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Mine


I raise you one character:

ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
ishex3 = lambda s: not set(s)-set(string.hexdigits)  # Mine

I could actually go three better:

ishex3=lambda s:not set(s)-set(string.hexdigits)

:-)


Notice that ishex2 is more accurate than ishex1.  E.g.


ishex1(['abc', '123'])

True

ishex2(['abc', '123'])

False



--
http://mail.python.org/mailman/listinfo/python-list


Re: thanks casevh and Lee

2010-01-14 Thread Dave WB3DWE
Thanks Lee & casevh.
I'm going to remove all python 3 versions, update
to Ubuntu 9.10 and then do a clean installation of
python 3.1.1 via Synaptic.   Dave WB3DWE
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread MRAB

Phlip wrote:

MRAB wrote:


BTW, ishex('') should return False.


So should int('')!


Why?
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest help needed!

2010-01-14 Thread Oltmans


On Jan 14, 11:46 pm, [email protected] wrote:
> When you run test.py, it gets to the loadTestsFromName line.  There, it
> imports the module named "test" in order to load tests from it.  To
> import
> that module, it runs test.py again.  By the time it finishes running the
> contents of test.py there, it has run all of your tests once, since part
> of test.py is "suite.run(r)".  Having finished that, the import of the
> "test"

Many thanks, really appreciate your insight. Very helpful. I need a
program design advice. I just want to know what's the gurus way of
doing it? I've a unittest.TestCase derived class that have around 50
test methods. Design is almost similar to following
---
import unittest

class result(unittest.TestResult):
pass

class tee(unittest.TestCase):
def test_first(self):
print 'first test'
process(123)
def test_second(self):
print 'second test'
process(564)
def test_third(self):
print 'final method'
process(127863)



if __name__=="__main__":
r = result()
suite = unittest.defaultTestLoader.loadTestsFromName('test.tee')
suite.run(r)
---

As you can see, every test method is almost same. Only difference is
that every test method is calling process() with a different value.
Also, I've around 50 test methods coded that way. I just want to know:
is there a way I can make things smaller/smarter/pythonic given the
current design? If you think any information is missing please let me
know. I will really really appreciate any insights. Many thanks in
advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interactive terminal in Ubuntu Linux : libreadline5-dev works only in Python 2.6 not 3.1

2010-01-14 Thread Dave WB3DWE
>The python 3 version in the 9.10 repo is 3.1.1
>
>Actually, if I/O is important, I'd recommend a full install of 9.10 so that
>you can get the ext4 file system. I have found it offers some very
>impressive speedups with the disk -- especially for deleting files.

Thanks casevh and Lee.
I intend to remove all versions python 3, update Ubuntu to 9.10
and then do a clean installation of python 3.1.1 via Synaptic.
Dave  WB3DWE
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Paul Rubin
[email protected] (Aahz) writes:
> Incidentally, my company has had a fair amount of difficulty finding
> Python programmers -- anyone in the SF area looking for a job near
> Mountain View?

I'm surprised there aren't a ton of Python programmers there, given
that's where Brand G is and so forth.  Anyway, when posting that type of
message, it would probably be helpful to describe what your company
does, what you're looking for, and (if possible) supply a url.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Duncan Booth
MRAB  wrote:

> I raise you one character:
> 
> ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
> ishex3 = lambda s: not set(s)-set(string.hexdigits)  # Mine
> 
> I could actually go three better:
> 
> ishex3=lambda s:not set(s)-set(string.hexdigits)

But none of those pass your own "ishex('') should return False" test.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Tkinter Programming by John Grayson

2010-01-14 Thread Mark Roseman
 Peter  wrote:
> Besides, the book is mainly about using Python with Tkinter - and
> Tkinter hasn't changed that much since 2000, so I believe it is just
> as relevant today as it was back then. 

I'd say that Tkinter has substantially changed - with the introduction 
of the 'ttk' themed widgets.  I cover these in my tutorial at 
http://www.tkdocs.com

Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Jean-Michel Pichavant

Phlip wrote:

MRAB wrote:


BTW, ishex('') should return False.


So should int('')!

Did you mean isint('') ?

JM
--
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Robert Kern

On 2010-01-14 13:14 PM, Paul Rubin wrote:

[email protected] (Aahz) writes:

Incidentally, my company has had a fair amount of difficulty finding
Python programmers -- anyone in the SF area looking for a job near
Mountain View?


I'm surprised there aren't a ton of Python programmers there, given
that's where Brand G is and so forth.


They probably absorb more (good) Python programmers than they spit back out.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Jean-Michel Pichavant

Paul Rubin wrote:

[email protected] (Aahz) writes:
  

Incidentally, my company has had a fair amount of difficulty finding
Python programmers -- anyone in the SF area looking for a job near
Mountain View?



I'm surprised there aren't a ton of Python programmers there, given
that's where Brand G is and so forth.  Anyway, when posting that type of
message, it would probably be helpful to describe what your company
does, what you're looking for, and (if possible) supply a url.
  
We're all python fanatics around here, no need to know more than the job 
is about to write Python code !
The real question is "is there enough space for my 3x4 meters poster of 
Guido ?" :o)


JM
--
http://mail.python.org/mailman/listinfo/python-list


Invalid Syntax Error

2010-01-14 Thread Ray Holt
Why am I getting an invalid systax on the first except in the following
code. It was copid from the python tutorial for beginners. Thanks, Ray
import sys
try:
#open file stream
file = open(file_name, "w"
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an eror reading file"
sys.exit
file_text = file.read()
file.close
print file_text

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread MRAB

Duncan Booth wrote:

MRAB  wrote:


I raise you one character:

ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
ishex3 = lambda s: not set(s)-set(string.hexdigits)  # Mine

I could actually go three better:

ishex3=lambda s:not set(s)-set(string.hexdigits)


But none of those pass your own "ishex('') should return False" test.


Neither do the others!
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest help needed!

2010-01-14 Thread Phlip

Oltmans wrote:


def test_first(self):
print 'first test'
process(123)


All test cases use the pattern "Assemble Activate Assert".

You are assembling a 123, and activating process(), but where is your assert? If 
it is inside process() (if process is a test-side method), then that should be 
called assert_process().



As you can see, every test method is almost same. Only difference is
that every test method is calling process() with a different value.
Also, I've around 50 test methods coded that way.


We wonder if your pattern is truly exploiting the full power of testing. If you 
have ~15 different features, you should have ~50 tests (for a spread of low, 
middle, and high input values, to stress the targeted production code).


But this implies your 15 different features should have as many different 
interfaces - not the same interface over and over again. That suggests coupled 
features.


Anyway, the short-term answer is to temporarily abandon "AAA", and roll up your 
input values into a little table:


   for x in [123, 327, 328, ... ]:
  process(x)

(Also, you don't need the print - tests should run silent and unattended, unless 
they fail.)


This refactor is the standard answer to the question "I have an unrolled loop". 
You roll it back up into a table iteration.


However, you lose the test case features, such as restartability and test 
isolation, that AAA give you.


Long term, you should use a literate test runner, such as (>cough<) my Morelia 
project:


   http://c2.com/cgi/wiki?MoreliaViridis

Down at the bottom, that shows how to create a table of inputs and outputs, and 
Morelia does the unrolling for you.


--
  Phlip
  http://zeekland.zeroplayer.com/Uncle_Wiggilys_Travels/1
--
http://mail.python.org/mailman/listinfo/python-list


Re: Invalid Syntax Error

2010-01-14 Thread MRAB

Ray Holt wrote:
Why am I getting an invalid systax on the first except in the following 
code. It was copid from the python tutorial for beginners. Thanks, Ray

import sys
try:
#open file stream
file = open(file_name, "w"

[snip]

Missing ")".

--
http://mail.python.org/mailman/listinfo/python-list


Re: Invalid Syntax Error

2010-01-14 Thread Benjamin Kaplan
How about you just isolate the first few lines

On Thu, Jan 14, 2010 at 2:43 PM, Ray Holt  wrote:
> try:
>     #open file stream
>     file = open(file_name, "w"
> except IOError:
>     print "There was an error writing to", file_name
>     sys.exit()

Notice anything now? Something missing perhaps.

You forgot to close the parenthesis for the open. Python moves on to
the next line to look for where you close the call, and sees an except
which is illegal inside of a function call.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread D'Arcy J.M. Cain
On 14 Jan 2010 19:19:53 GMT
Duncan Booth  wrote:
> > ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
> > ishex3 = lambda s: not set(s)-set(string.hexdigits)  # Mine
> > 
> > I could actually go three better:
> > 
> > ishex3=lambda s:not set(s)-set(string.hexdigits)
> 
> But none of those pass your own "ishex('') should return False" test.

Good point.  Obviously a unit test was missing.

Of course, all this is good clean fun but I wonder how useful an ishex
method really is.  Personally I would tend to do this instead.

try: x = isinstance(s, int) and s or int(s, 0)
except ValueError: [handle invalid input]

IOW return the value whether it is a decimal string (e.g. "12"), a hex
string (e.g. "0xaf") or even if it is already an integer.  Of course,
you still have to test for '' and None.

Naturally this all depends heavily on the actual requirements.  Perhaps
that's why there is no ishex method in the first place.  Such a method
could wind up with more options than ls(1)

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread D'Arcy J.M. Cain
On Thu, 14 Jan 2010 18:36:12 +
MRAB  wrote:
> > print ishex('123') is True
> > print ishex('abc') is True
> > print ishex('xyz') is False
> > print ishex('0123456789abcdefABCDEF') is True
> > print ishex('0123456789abcdefABCDEFG') is False
> > 
> Don't use 'is', use '=='.

Why?  There is only one True and one False in Python.  Is it a style
issue for you?  If so then say "shouldn't" not "don't."

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Aahz
In article ,
Robert Kern   wrote:
>On 2010-01-14 13:14 PM, Paul Rubin wrote:
>> [email protected] (Aahz) writes:
>>>
>>> Incidentally, my company has had a fair amount of difficulty finding
>>> Python programmers -- anyone in the SF area looking for a job near
>>> Mountain View?
>>
>> I'm surprised there aren't a ton of Python programmers there, given
>> that's where Brand G is and so forth.
>
>They probably absorb more (good) Python programmers than they spit back out.

Bingo -- I call it "The Giant Google Sucking Sound"
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Aahz
In article <[email protected]>,
Paul Rubin   wrote:
>[email protected] (Aahz) writes:
>>
>> Incidentally, my company has had a fair amount of difficulty finding
>> Python programmers -- anyone in the SF area looking for a job near
>> Mountain View?
>
>I'm surprised there aren't a ton of Python programmers there, given
>that's where Brand G is and so forth.  Anyway, when posting that type of
>message, it would probably be helpful to describe what your company
>does, what you're looking for, and (if possible) supply a url.

http://www.egnyte.com/

Basically, at this point we're just looking for competent Python
developers who have a reasonably broad experience, preferably with some
web development background.  There's a non-current ad on the Python Job
Board that I need to update.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread exarkun

On 08:15 pm, [email protected] wrote:

On 14 Jan 2010 19:19:53 GMT
Duncan Booth  wrote:

> ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
> ishex3 = lambda s: not set(s)-set(string.hexdigits)  # Mine
>
> I could actually go three better:
>
> ishex3=lambda s:not set(s)-set(string.hexdigits)

But none of those pass your own "ishex('') should return False" test.


Good point.  Obviously a unit test was missing.

Of course, all this is good clean fun but I wonder how useful an ishex
method really is.  Personally I would tend to do this instead.

try: x = isinstance(s, int) and s or int(s, 0)
except ValueError: [handle invalid input]

IOW return the value whether it is a decimal string (e.g. "12"), a hex
string (e.g. "0xaf") or even if it is already an integer.  Of course,
you still have to test for '' and None.


Still missing some unit tests.  This one fails for 0.  Spend a few more 
lines and save yourself some bugs. :)


Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Arnaud Delobelle
MRAB  writes:

> Arnaud Delobelle wrote:
>> "D'Arcy J.M. Cain"  writes:
>>
>>> On Thu, 14 Jan 2010 09:07:47 -0800
>>> Chris Rebert  wrote:
 Even more succinctly:

 def ishex(s):
 return all(c in string.hexdigits for c in s)
>>> I'll see your two-liner and raise you.  :-)
>>>
>>> ishex = lambda s: all(c in string.hexdigits for c in s)
>>
>> I'see your one-liner and raise you by four characters :o)
>>
>> ishex1 = lambda s: all(c in string.hexdigits for c in s) # Yours
>> ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Mine
>>
> I raise you one character:
>
> ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
> ishex3 = lambda s: not set(s)-set(string.hexdigits)  # Mine

Aha! The Operator Precedence trick! I fold.

> I could actually go three better:
>
> ishex3=lambda s:not set(s)-set(string.hexdigits)

In this case, I'll go five better:

h=lambda s:not set(s)-set(string.hexdigits)

;-)

-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Tkinter Programming by John Grayson

2010-01-14 Thread Peter
On Jan 15, 6:24 am, Mark Roseman  wrote:
>  Peter  wrote:
> > Besides, the book is mainly about using Python with Tkinter - and
> > Tkinter hasn't changed that much since 2000, so I believe it is just
> > as relevant today as it was back then.
>
> I'd say that Tkinter has substantially changed - with the introduction
> of the 'ttk' themed widgets.  I cover these in my tutorial 
> athttp://www.tkdocs.com
>
> Mark

But is the ttk themed widgets a "change" to Tkinter or an "addition/
improvement"? i.e. does the themed widgets invalidate any of the
Tkinter stuff in Grayson's book? That certainly isn't my impression of
the themed widgets, I was of the impression that the themed widgets
just added some convenient widgets (such as Scale, Spinbox etc) which
a user could find in other GUI frameworks, for example, Pmw
supplemented the basic Tkinter widget set and offered some (essential
IMO) widgets that were missing in Tkinter - such as the Notebook
widget.

But I'll bow to your greater knowledge on the point on whether ttk
themed widgets are a 'change' to Tkinter.

Lets face it, if somebody wants to get up to speed on Python and GUI
development then the book is still very, very relevant and necessary
(IMO). The documentation for the themed widgets still leaves a lot to
be desired from the perspective of somebody who wants to start using
Python to create GUI applications. As Lord Eldritch reminded me in his
post, the book even has a section on Pmw - which is what I use mainly
for my GUI applications - because Tkinter was missing some vital
widgets that are now available in the ttk themed set.

Personally I will start to incorporate some of the ttk themed widgets
into my applications - but Pmw will remain the 'basis' for my GUI's as
the entire framework (IMO) supports a class oriented approach that
allows easy creation of extensible and reconfigurable (at run time)
GUI interfaces.

Ultimately Grayson does a good job of providing information and
reference to toolkit(s) that allow a beginner to quickly get up to
speed on producing a GUI using Python. It is purely up to the user
afterwards as to whether they stick with Tkinter/Pmw (and now the ttk
themed set) or venture into wxPython or Jython (as two examples of GUI
'systems' that provide 'better' facilities to a Python programmer).

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQT 4.6.2 question about radiobuttons

2010-01-14 Thread News123
Hi,

As you wll notice: I don't have a lot of GUI and only very litte
PyQT-experience.


I have a UI created with qt designer.

The UI contains a few named radio buttons in a button group.
( for example radioButton_one to radioButton_four )


I am unable locate a signal, that is fired whenever one of the
radiobuttons in a group have been changed.


however what I am able to is to connect the same slot to all
of the clicked events of a buttongroup


buttons = [
win.radioButton_one,
win.radioButton_two,
win.radioButton_three,
win.radioButton_four
]

for button in buttons:
button.cloicked.connect( self._mymethod )


My questions are:

1.) Is there a signal in the buttongroup, that would fire?

2.) if not. What is the easiest way to get a list of all radiobuttons
belonging to a buttongroup


Thanks in advance for your any suggestions good pointers




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQT 4.6.2 question about radiobuttons

2010-01-14 Thread Phil Thompson
On Thu, 14 Jan 2010 22:09:20 +0100, News123  wrote:
> Hi,
> 
> As you wll notice: I don't have a lot of GUI and only very litte
> PyQT-experience.
> 
> 
> I have a UI created with qt designer.
> 
> The UI contains a few named radio buttons in a button group.
> ( for example radioButton_one to radioButton_four )
> 
> 
> I am unable locate a signal, that is fired whenever one of the
> radiobuttons in a group have been changed.
> 
> 
> however what I am able to is to connect the same slot to all
> of the clicked events of a buttongroup
> 
> 
> buttons = [
> win.radioButton_one,
> win.radioButton_two,
> win.radioButton_three,
> win.radioButton_four
> ]
> 
> for button in buttons:
> button.cloicked.connect( self._mymethod )
> 
> 
> My questions are:
> 
> 1.) Is there a signal in the buttongroup, that would fire?

QButtonGroup.buttonClicked()

> 2.) if not. What is the easiest way to get a list of all radiobuttons
> belonging to a buttongroup

QButtonGroup.buttons()

> Thanks in advance for your any suggestions good pointers

http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qbuttongroup.html

Phil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2010-01-14 Thread Aahz
In article <[email protected]>,
Steven D'Aprano   wrote:
>On Sat, 02 Jan 2010 09:40:44 -0800, Aahz wrote:
>>
>> OTOH, if you want to do something different depending on whether the
>> file exists, you need to use both approaches:
>> 
>> if os.path.exists(fname):
>> try:
>> f = open(fname, 'rb')
>> data = f.read()
>> f.close()
>> return data
>> except IOError:
>> logger.error("Can't read: %s", fname) return ''
>> else:
>> try:
>> f = open(fname, 'wb')
>> f.write(data)
>> f.close()
>> except IOError:
>> logger.error("Can't write: %s", fname)
>> return None
>
>Unfortunately, this is still vulnerable to the same sort of race 
>condition I spoke about.

True; nevertheless, my point remains that if you want to do something
different depending on whether the file exists, you must use both LBYL
and EAFP.

>Even more unfortunately, I don't know that there is any fool-proof way of 
>avoiding such race conditions in general. Particularly the problem of 
>"open this file for writing only if it doesn't already exist".

IIUC, you can lock files that don't exist.

>> (This is a somewhat stupid example strictly for illustration.  A better
>> and more-elaborate example would be something like trying to copy a file
>> to fname and rename an existing file to '.bak' if it exists.  The tricky
>> part would be trying to rename the '.bak' to fname if the copy fails.
>> And yes, that's exactly what some code I wrote a few days ago does.)
>
>Sounds interesting and useful. Would you care to share it with us, or to 
>publish it as a recipe?

Unfortunately, it's a bit too tightly tied to some other stuff in the
code, plus I'll need to get permission from my bosses.  We'll see.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Executable standalone *.pyc after inserting "#!/usr/bin/python" or other options

2010-01-14 Thread epsilon
All:

I've been playing with "Lua" and found something really cool that I'm
unable to do in "Python". With "Lua", a script can be compiled to byte
code using "luac" and by adding "#!/usr/bin/lua" at the top of the
binary, the byte code becomes a single file executable. After I found
this trick, I ran back to "Python" to give it a try.  Well...  it
didn't work. Is this possible?  There are tools which insert "python"
and related modules inside the byte code, but this is not the
requirement for this situation. The required solution is to insert "#!/
usr/bin/python" (or some string) at the top of a *.pyc byte code file
and run it as standalone executable.  I'm excited about the
possibility and interested in hearing your thoughts.

Thank you,
Christopher Smiga
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread Terry Reedy

On 1/14/2010 12:44 PM, D'Arcy J.M. Cain wrote:

On Thu, 14 Jan 2010 09:07:47 -0800
Chris Rebert  wrote:

Even more succinctly:

def ishex(s):
 return all(c in string.hexdigits for c in s)


I'll see your two-liner and raise you.  :-)

ishex = lambda s: all(c in string.hexdigits for c in s)


This is inferior because the resulting function object has generic name 
attribute '' instead of the specific name 'ishax'.


Please do not push such inferior code on new programmers.

Terry Jan Reedy


--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Tkinter Programming by John Grayson

2010-01-14 Thread Kevin Walzer

On 1/14/10 3:39 PM, Peter wrote:

On Jan 15, 6:24 am, Mark Roseman  wrote:

  Peter  wrote:

Besides, the book is mainly about using Python with Tkinter - and
Tkinter hasn't changed that much since 2000, so I believe it is just
as relevant today as it was back then.


I'd say that Tkinter has substantially changed - with the introduction
of the 'ttk' themed widgets.  I cover these in my tutorial 
athttp://www.tkdocs.com

Mark


But is the ttk themed widgets a "change" to Tkinter or an "addition/
improvement"? i.e. does the themed widgets invalidate any of the
Tkinter stuff in Grayson's book? That certainly isn't my impression of
the themed widgets, I was of the impression that the themed widgets
just added some convenient widgets (such as Scale, Spinbox etc) which
a user could find in other GUI frameworks, for example, Pmw
supplemented the basic Tkinter widget set and offered some (essential
IMO) widgets that were missing in Tkinter - such as the Notebook
widget.


It's both a change and an improvement. The themed widgets can be used in 
conjunction with the traditional widgets, but in many cases it's 
possible (and desirable) to update your entire application to use the 
themed widgets.



Lets face it, if somebody wants to get up to speed on Python and GUI
development then the book is still very, very relevant and necessary
(IMO). The documentation for the themed widgets still leaves a lot to
be desired from the perspective of somebody who wants to start using
Python to create GUI applications. As Lord Eldritch reminded me in his
post, the book even has a section on Pmw - which is what I use mainly
for my GUI applications - because Tkinter was missing some vital
widgets that are now available in the ttk themed set.

Personally I will start to incorporate some of the ttk themed widgets
into my applications - but Pmw will remain the 'basis' for my GUI's as
the entire framework (IMO) supports a class oriented approach that
allows easy creation of extensible and reconfigurable (at run time)
GUI interfaces.


PMW is certainly a helpful addition to the Tkinter developer's toolbox, 
but it also has limitations. It suffers from some of the same 
limitations as Tk itself, i.e. it is rather dated in appearance, and 
even it lacks some modern UI features such as a good multicolumn 
listbox, treeview, etc. In addition to the ttk themed widgets, other, 
more configurable pure Tk-based megawidget packages exist, such as 
BWidgets and Tablelist, and there are Python wrappers for these at the 
Tkinter wiki (http://tkinter.unpythonic.net/wiki/).




Ultimately Grayson does a good job of providing information and
reference to toolkit(s) that allow a beginner to quickly get up to
speed on producing a GUI using Python. It is purely up to the user
afterwards as to whether they stick with Tkinter/Pmw (and now the ttk
themed set) or venture into wxPython or Jython (as two examples of GUI
'systems' that provide 'better' facilities to a Python programmer).


Another book I've found very helpful for learning Tkinter is Programming 
Python by Mark Lutz--a lot of coverage there of GUI development.


--Kevin

--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Novocastrian_Nomad
Why is it so many, so called high tech companies, insist on the 19th
century practice of demanding an employee's physical presence in a
specific geographic location.

This is the 21st century with climate change, carbon footprints,
broadband internet, telecommuting, tele-presence, telephones, fax
machines, mobile phones, electronic funds transfer, express shipping
companies and a host of other gadgets and applications, that make
geographic location almost irrelevant.

I know whereof I speak, I have been fortunate enough to work remotely
(across the country) for the last ten years, for two different
employers.

(possibly OT rant over)
-- 
http://mail.python.org/mailman/listinfo/python-list


SAGE help & support?

2010-01-14 Thread Lou Pecora
Does anyone know of any SAGE support or help newsgroups or email lists?

I know this is not a SAGE group and there is at least one support group 
for SAGE (http://groups.google.com/group/sage-support/), but I have gone 
there and asked similar questions twice and gotten zero replies (it's 
been about a month now).  Any suggestions appreciated.

If you interested more info:  I've installed SAGE from a full successful 
source build on my Mac Book Pro (OS X 10.4.11). SAGE runs in Terminal 
and I can import the usual suspects (numpy, matplotlib) into SAGE, but 
when I try to import pylab I get this message:

ImportError: No module named _tkagg

from inside the tkagg.py module in the site-packages in SAGE folder.  I 
cannot figure out what's going on here.  I use pylab a lot, so I really 
need it.  I've tried to track down the problem, but that's a huge 
framework and I get lost.  I have no idea where to go with this. 

Thanks for any pointers.

-- 
-- Lou Pecora
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple-to-use sound file writer

2010-01-14 Thread Lie Ryan
On 01/15/10 05:42, Alf P. Steinbach wrote:
> I'm beginning to believe that you maybe didn't grok that simple procedure.
> 
> It's very very very trivial, so maybe you were looking for something
> more intricate  --  they used to say, in the old days, "hold on, this
> proof goes by so fast you may not notice it!"

Since you said it's trivial, then...

>> Nothing about you there. Just the information you are promoting. I don't
>> normally deal in innuendo and personal attacks. Though I do occasionally
>> get irritated by what I perceive to be hogwash. People who know me will
>> tell you, if I am wrong I will happily admit it.
> 
> There's a difference between an algorithm that you can implement, and
> hogwash.

please prove your claim by writing that algorithm in code and post it in
this list. The program must accept a .wav file (or sound format of your
choice) and process it according to your algorithm and the output
another .wav file (or sound format of your choice) that sounds roughly
similar to the input file.

PS: I have near-zero experience with sound processing
PPS: I will be equally delighted seeing either Steve admitting his wrong
or you admit your hogwash
PPPS: An alternative way to convince us is to provide a paper/article
that describes this algorithm.
S: Though I will be quite sad if you choose to reject the challenge
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ignore leading '>>>' and ellipsis?

2010-01-14 Thread Rhodri James

On Thu, 14 Jan 2010 17:13:54 -, Reckoner  wrote:


I am studying some examples in a tutorial where there are a lot of
leading >>> characters and ellipsis in the text. This makes it hard to
cut and paste into the IPython interpreter since it doesn't like these
strings.

Is there another interpreter I could use that will appropriately
ignore and interpret these leading terms?

For example, I cannot paste the following directly into the
interpreter:


d = dict(x.__array_interface__)
d['shape'] = (3, 2, 5)
d['strides'] = (20, 20, 4)



class Arr:

... __array_interface__ = d
... base = x


Well don't do that then.

Snippy as that sounds, it's an entirely serious comment.  You will learn  
more by doing it yourself than if you side-step your brain with cut and  
paste.


--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a string.ishex function

2010-01-14 Thread MRAB

Arnaud Delobelle wrote:

MRAB  writes:


Arnaud Delobelle wrote:

"D'Arcy J.M. Cain"  writes:


On Thu, 14 Jan 2010 09:07:47 -0800
Chris Rebert  wrote:

Even more succinctly:

def ishex(s):
return all(c in string.hexdigits for c in s)

I'll see your two-liner and raise you.  :-)

ishex = lambda s: all(c in string.hexdigits for c in s)

I'see your one-liner and raise you by four characters :o)

ishex1 = lambda s: all(c in string.hexdigits for c in s) # Yours
ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Mine


I raise you one character:

ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
ishex3 = lambda s: not set(s)-set(string.hexdigits)  # Mine


Aha! The Operator Precedence trick! I fold.


I could actually go three better:

ishex3=lambda s:not set(s)-set(string.hexdigits)


In this case, I'll go five better:

h=lambda s:not set(s)-set(string.hexdigits)

;-)


Touché!
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] Python 2.5.5 Release Candidate 1.

2010-01-14 Thread Martin v. Löwis
On behalf of the Python development team and the Python community, I'm
happy to announce the release candidate 1 of Python 2.5.5.

This is a source-only release that only includes security fixes. The
last full bug-fix release of Python 2.5 was Python 2.5.4. Users are
encouraged to upgrade to the latest release of Python 2.6 (which is
2.6.4 at this point).

This releases fixes issues with the logging and tarfile modules, and
with thread-local variables. See the detailed release notes at the
website (also available as Misc/NEWS in the source distribution) for
details of bugs fixed.

For more information on Python 2.5.5, including download links for
various platforms, release notes, and known issues, please see:

http://www.python.org/2.5.5

Highlights of the previous major Python releases are available from
the Python 2.5 page, at

http://www.python.org/2.5/highlights.html

Enjoy this release,
Martin

Martin v. Loewis
[email protected]
Python Release Manager
(on behalf of the entire python-dev team)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple distributed example for learning purposes?

2010-01-14 Thread CM
On Dec 26 2009, 3:46 pm, Shawn Milochik  wrote:
> The special features of the Shrek DVD showed how the rendering took so much 
> processing power that everyone's workstation was used overnight as a 
> rendering farm. Some kind of video rendering would make a great example. 
> However, it might be a lot of overhead for you to set up, unless you can find 
> someone with expertise in the area. The nice thing about this is that it 
> would be relevant to the audience. Also, if you describe what goes into 
> processing a single frame in enough depth that they appreciate it, they'll 
> really "get" the power of distributed processing.
>
> Something else incredibly time-expensive but much easier to set up would be 
> matching of names and addresses. I worked at a company where this was, at its 
> very core, the primary function of the business model. Considering the 
> different ways of entering simple data, many comparisons must be made. This 
> takes a lot of time, and even then the match rates aren't necessarily going 
> to be very high.
>
> Here are some problems with matching:
>
> Bill versus William
> '52 10th Street' | '52 tenth street'
> 'E. Smith street' | 'E smith street' | 'east smith street'
> 'Bill Smith' | 'Smith, Bill'
> 'William Smith Jr' | 'William Smith Junior'
> 'Dr. W. Smith' | 'William Smith'
> 'Michael Norman Smith' | 'Michael N. Smith' | 'Michael Smith' | 'Smith, 
> Michael' | 'Smith, Michael N.' | 'Smith, Michael Norman'
>
> The list goes on and on, ad nauseum. Not to mention geocoding, married and 
> maiden names, and scoring partial name matches with distance proximity 
> matches.

I'm not sure I understand the task.  Based on another comment in this
thread, the idea seems to be that the company that does this matching
work is handed a big data set, and then these sorts of matching
comparisons are made on it--but what is the goal?

I can understand with address matches, in that 'east smith street'
should be recognized as the official postal address 'E. Smith Street',
so that the company can send correspondence to the correct address.
Is that the idea?

But what about the names?  If it says 'Michael Norman Smith' as the
name, or 'Michael N. Smith' or 'Smith, Michael', can't one then just
use that on the correspondence?  Why do you need to match 'Michael
Norman Smith' to 'Michael N. Smith' to discover they are the same
person?  Is it that those two variations appear in the same data set
and you want to make sure you don't mail twice to the same person?

I completely accept that this is a real problem, I just don't yet
understand the goal all that well.  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executable standalone *.pyc after inserting "#!/usr/bin/python" or other options

2010-01-14 Thread Martin v. Loewis
> I've been playing with "Lua" and found something really cool that I'm
> unable to do in "Python". With "Lua", a script can be compiled to byte
> code using "luac" and by adding "#!/usr/bin/lua" at the top of the
> binary, the byte code becomes a single file executable. After I found
> this trick, I ran back to "Python" to give it a try.  Well...  it
> didn't work. Is this possible?

In Python, a different approach will work, depending on the operating
system.

E.g. on Linux, you can use binfmt_misc to make executables out of pyc
code. Run

import imp,sys,string
magic = string.join(["\\x%.2x" % ord(c) for c in imp.get_magic()],"")
reg = ':pyc:M::%s::%s:' % (magic, sys.executable)
open("/proc/sys/fs/binfmt_misc/register","wb").write(reg)

once on your Linux system (or, rather, at boot time), and all pyc
files become executable (if the x bit is set).

In Debian, installing the binfmt-support package will do that for
you.

Do "ls /proc/sys/fs/binfmt_misc/" to see what binary types are
already supported on your system.

HTH,
Martin

P.S. The approach you present for Lua indeed does not work for
Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: maintain 2 versions of python on my computer

2010-01-14 Thread Lie Ryan
On 01/14/10 22:21, luis wrote:
> 
> Hi
> 
> I am not an expert in programming and using Python for its simplicity
> 
> I have 2 versions of python installed on my computer (windos xp) to
> begin the transition from version 2.4 to 2.6 or 3. maintaining the
> operability of my old scripts
> 
> Is there any way to indicate the version of the python interpreter
> must use a script?
> 
> thanks

On my Windows machine, I make a copy python.exe and rename it as
python25.exe, python26.exe, python3.exe, etc in their respective
directories. Then after setting up the PATH environment variable, you
can simply call python25, python3, etc from any directory in the command
prompt.

Tips: On Vista and above, you can Shift-Right-Click to show "Open
Command Window Here" in the context menu. On XP, you can install the
PowerToys
http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Aahz
In article <6a12ed15-e7f9-43ab-9b90-984525808...@o28g2000yqh.googlegroups.com>,
Novocastrian_Nomad   wrote:
>
>Why is it so many, so called high tech companies, insist on the 19th
>century practice of demanding an employee's physical presence in a
>specific geographic location.

Because it works better?  My current job is mostly done at the office,
and I think it leads to better morale in many ways.  I'm not sure about
productivity, though.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Author of a Python Success Story Needs a Job!

2010-01-14 Thread Paul Boddie
On 28 Des 2009, 08:32, Andrew Jonathan Fine
 wrote:
>
>   As a hobby to keep me sane, I am attempting to retrain
> part time at home as a jeweler and silversmith, and I sometimes used
> Python for generating and manipulating code for CNC machines.

It occurs to me that in some domains, this combination of Python and
the design and production of physical artifacts could be fairly
attractive, even though it may or may not be what you want to focus on
in pursuing a software career. For example, I follow the goings-on in
the various open hardware communities, and there isn't really a
shortage of boards, controllers, components or chipsets which can be
put to use, but taking these things and producing a well-designed case
in order to deliver a readily usable piece of equipment is something
which seems beyond most of the interested parties: people who know one
thing well can be completely oblivious of the ways of another thing.

Sometimes, it seems to pay to be knowledgeable in two different kinds
of endeavour whose practitioners rarely interact, and perhaps there
might be opportunities for you in this regard. Nevertheless, I
obviously wish you success in your employment search.

Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple distributed example for learning purposes?

2010-01-14 Thread Ethan Furman

CM wrote:

On Dec 26 2009, 3:46 pm, Shawn Milochik  wrote:

The special features of the Shrek DVD showed how the rendering took so much processing 
power that everyone's workstation was used overnight as a rendering farm. Some kind of 
video rendering would make a great example. However, it might be a lot of overhead for 
you to set up, unless you can find someone with expertise in the area. The nice thing 
about this is that it would be relevant to the audience. Also, if you describe what goes 
into processing a single frame in enough depth that they appreciate it, they'll really 
"get" the power of distributed processing.

Something else incredibly time-expensive but much easier to set up would be 
matching of names and addresses. I worked at a company where this was, at its 
very core, the primary function of the business model. Considering the 
different ways of entering simple data, many comparisons must be made. This 
takes a lot of time, and even then the match rates aren't necessarily going to 
be very high.

Here are some problems with matching:

Bill versus William
'52 10th Street' | '52 tenth street'
'E. Smith street' | 'E smith street' | 'east smith street'
'Bill Smith' | 'Smith, Bill'
'William Smith Jr' | 'William Smith Junior'
'Dr. W. Smith' | 'William Smith'
'Michael Norman Smith' | 'Michael N. Smith' | 'Michael Smith' | 'Smith, 
Michael' | 'Smith, Michael N.' | 'Smith, Michael Norman'

The list goes on and on, ad nauseum. Not to mention geocoding, married and 
maiden names, and scoring partial name matches with distance proximity matches.


I'm not sure I understand the task.  Based on another comment in this
thread, the idea seems to be that the company that does this matching
work is handed a big data set, and then these sorts of matching
comparisons are made on it--but what is the goal?

I can understand with address matches, in that 'east smith street'
should be recognized as the official postal address 'E. Smith Street',
so that the company can send correspondence to the correct address.
Is that the idea?


Yes, and...


But what about the names?  If it says 'Michael Norman Smith' as the
name, or 'Michael N. Smith' or 'Smith, Michael', can't one then just
use that on the correspondence?  Why do you need to match 'Michael
Norman Smith' to 'Michael N. Smith' to discover they are the same
person?  Is it that those two variations appear in the same data set
and you want to make sure you don't mail twice to the same person?


yes.  We have one customer who gives us *everything* they have -- about 
20,000 records, and after the duplicate purge process they mail to about 
3,000.  In other cases we'll be combining different data sets from the 
same customer, and again we don't want duplicate mailings.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2010-01-14 Thread [email protected]
On Jan 2, 9:35 pm, Dave Angel  wrote:
> Steven D'Aprano wrote:
> > On Sat, 02 Jan 2010 09:40:44 -0800, Aahz wrote:
>
> >> OTOH, if you want to do something different depending on whether the
> >> file exists, you need to use both approaches:
>
> >> if os.path.exists(fname):
> >>     try:
> >>         f = open(fname, 'rb')
> >>         data = f.read()
> >>         f.close()
> >>         return data
> >>     except IOError:
> >>         logger.error("Can't read: %s", fname) return ''
> >> else:
> >>     try:
> >>         f = open(fname, 'wb')
> >>         f.write(data)
> >>         f.close()
> >>     except IOError:
> >>         logger.error("Can't write: %s", fname)
> >>     return None
>
> > Unfortunately, this is still vulnerable to the same sort of race
> > condition I spoke about.
>
> > Even more unfortunately, I don't know that there is any fool-proof way of
> > avoiding such race conditions in general. Particularly the problem of
> > "open this file for writing only if it doesn't already exist".
>
> > 
>
> In Windows, there is  a way to do it.  It's just not exposed to the
> Python built-in function open().  You use the CreateFile() function,
> with /dwCreationDisposition/  of CREATE_NEW.
>
> It's atomic, and fails politely if the file already exists.
>
> No idea if Unix has a similar functionality.

It does.   In Unix, you'd pass O_CREAT|O_EXCL to the open(2) system
call (O_CREAT means create a new file, O_EXCL means exclusive mode:
fail if the file exists already).

The python os.open interface looks suspiciously like the Unix system
call as far as invocation goes, but it wraps the Windows functionality
properly for the relevant flags.  The following should basically work
on both OSes (though you'd want to specify a Windows filename, and
also set os.O_BINARY or os.O_TEXT as needed on Windows):

import os

def exclusive_open(fname):
rv = os.open(fname, os.O_RDWR|os.O_CREAT|os.O_EXCL)
return os.fdopen(rv)

first = exclusive_open("/tmp/test")
print "SUCCESS: ", first
second = exclusive_open("/tmp/test")
print "SUCCESS: ", second




Run that and you should get:
SUCCESS ', mode 'r' at 0xb7f72c38>
Traceback (most recent call last):
  File "testopen.py", line 9, in 
second = exclusive_open("/tmp/test")
  File "testopen.py", line 4, in exclusive_open
rv = os.open(fname, os.O_RDWR|os.O_CREAT|os.O_EXCL)
OSError: [Errno 17] File exists: '/tmp/test'
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >