error: db type could not be determined

2005-02-26 Thread neutrinman
why does the following error occur?
(B
(Bdef quit_time():
(Bdata_file = shelve.open("data.dat", "c")
(Bdata_file["quit_time"] = datetime.datetime.today()
(Bprint data_file["quit_time"]
(Braw_input("enter")
(B
(B
(BTraceback (most recent call last):
(B  File "D:\a\TEXT\Py\going_over\going_over.py", line 192, in -toplevel-
(Bmain()
(B  File "D:\a\TEXT\Py\going_over\going_over.py", line 190, in main
(Bquit_time()
(B  File "D:\a\TEXT\Py\going_over\going_over.py", line 156, in quit_time
(Bdata_file = shelve.open("data.dat", "c")
(B  File "D:\A\UTILITIES\PYTHON\PYTHON23J\lib\shelve.py", line 231, in
(Bopen
(Breturn DbfilenameShelf(filename, flag, protocol, writeback, binary)
(B  File "D:\A\UTILITIES\PYTHON\PYTHON23J\lib\shelve.py", line 212, in
(B__init__
(BShelf.__init__(self, anydbm.open(filename, flag), protocol,
(Bwriteback, binary)
(B  File "D:\A\UTILITIES\PYTHON\PYTHON23J\lib\anydbm.py", line 80, in
(Bopen
(Braise error, "db type could not be determined"
(Berror: db type could not be determined
(B
(B-- 
(Bhttp://mail.python.org/mailman/listinfo/python-list

Re: Yet another logo design...

2005-02-26 Thread Harlin Seritt
I like the type logo (on the right of the image). The black snake-like
image can be cropped though. :-)

Harlin

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


Re: Watermark on images

2005-02-26 Thread Michele Simionato
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879

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


Error in pywordnet

2005-02-26 Thread Gurpreet Sachdeva
I am using pywordnet and when ever I import the package
from wordnet import *, I get an error:

"Exception exceptions.AttributeError: "DbfilenameShelf instance has no
attribute 'writeback'" in  ignored"

Now the package works fine until I tried to use that in Apache via
CGI. Apache is showing a Server Error and the error_logs states that:

[Fri Feb 25 16:06:08 2005] [error] [client 192.168.1.125] from
wordnet import *, referer: http://garry/cgi-bin/test.py
[Fri Feb 25 16:06:08 2005] [error] [client 192.168.1.125] ImportError:
No module named wordnet, referer: http://garry/cgi-bin/test.py

While googling, I found:
"It is a simple fix that adds the writeback argument to shelve.open calls."

Source:
http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?forum=185&thread=72747&cat=11

Do anyone have any idea about that? Is there any fix or workaround?

Thanks and Regards,
Garry

http://garrythegambler.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fdups: calling for beta testers

2005-02-26 Thread Patrick Useldinger
John Machin wrote:
(1) It's actually .bz2, not .bz (2) Why annoy people with the
not-widely-known bzip2 format just to save a few % of a 12KB file?? (3)
Typing that on Windows command line doesn't produce a useful result (4)
Haven't you heard of distutils?
(1) Typo, thanks for pointing it out
(2)(3) In the Linux world, it is really popular. I suppose you are a 
Windows user, and I haven't given that much thought. The point was not 
to save space, just to use the "standard" format. What would it be for 
Windows - zip?
(4) Never used them, but are very valid point. I will look into it.

(6) You are keeping open handles for all files of a given size -- have
you actually considered the possibility of an exception like this:
IOError: [Errno 24] Too many open files: 'foo509'
(6) Not much I can do about this. In the beginning, all files of equal 
size are potentially identical. I first need to read a chunk of each, 
and if I want to avoid opening & closing files all the time, I need them 
open together.
What would you suggest?

Once upon a time, max 20 open files was considered as generous as 640KB
of memory. Looks like Bill thinks 512 (open files, that is) is about
right these days.
Bill also thinks it is normal that half of service pack 2 lingers twice 
on a harddisk. Not sure whether he's my hero ;-)

(7)
Why sort? What's wrong with just two lines:
! for size, file_list in self.compfiles.iteritems():
! self.comparefiles(size, file_list)
(7) I wanted the output to be sorted by file size, instead of being 
random. It's psychological, but if you're chasing dups, you'd want to 
start with the largest ones first. If you have more that a screen full 
of info, it's the last lines which are the most interesting. And it will 
produce the same info in the same order if you run it twice on the same 
folders.

(8) global
MIN_FILESIZE,MAX_ONEBUFFER,MAX_ALLBUFFERS,BLOCKSIZE,INODES
That doesn't sit very well with the 'everything must be in a class'
religion seemingly espoused by the following:
(8) Agreed. I'll think about that.
(9) Any good reason why the "executables" don't have ".py" extensions
on their names?
(9) Because I am lazy and Linux doesn't care. I suppose Windows does?
All in all, a very poor "out-of-the-box" experience. Bear in mind that
very few Windows users would have even heard of bzip2, let alone have a
bzip2.exe on their machine. They wouldn't even be able to *open* the
box.
As I said, I did not give Windows users much thought. I will improve this.
And what is "chown" -- any relation of Perl's "chomp"?
chown is a Unix command to change the owner or the group of a file. It 
has to do with controlling access to the file. It is not relevant on 
Windows. No relation to Perl's chomp.

Thank you very much for your feedback. Did you actually run it on your 
Windows box?

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


Re: netmask arithmetic?

2005-02-26 Thread Roel Schroeven
Dan Stromberg wrote:
> Before I go and reinvent the wheel, does anyone already have python code
> that can do netmask arithmetic - for example, determining if a list of
> hostnames are on subnets described by a list of networks+netmasks like:
> 
> 128.200.34.0/24
> 128.195.16.128/25
> 
> ...and so on?

http://pynms.sourceforge.net/ipv4.html

-- 
"Codito ergo sum"
Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error: db type could not be determined

2005-02-26 Thread John Machin

[EMAIL PROTECTED] wrote:
> why does the following error occur?

I don't know; I've never used the shelve module. Let's see what as two
utter n00bz we can find out. Let's check out where it clagged:
lib\anydbm.py, line 80, in open ...

Hmm, reading backwards a little, looks like it called whichdb.whichdb
to nut out what sort of database it was, and whichdb reported back that
it was an existing file, of unknown type. Flicking through whichdb.py
confirms this.

Let's see if we can reproduce that:

=== step 1: file doesn't exist ===
C:\junk>c:\python23\python
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import shelve
>>> df = shelve.open('mydata.dat', 'c')
>>> ^Z

C:\junk>dir mydata.dat
[snip]
26/02/2005  08:40p  24,576 mydata.dat

=== looks like file created OK ==

C:\junk>del mydata.dat
C:\junk>copy con mydata.dat
any old codswallop
^Z
1 file(s) copied.

=== OK, now mydata.dat is trash.

C:\junk>c:\python23\python
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import shelve
>>> df = shelve.open('mydata.dat', 'c')
Traceback (most recent call last):
  File "", line 1, in ?
  File "c:\python23\lib\shelve.py", line 231, in open
return DbfilenameShelf(filename, flag, protocol, writeback, binary)
  File "c:\python23\lib\shelve.py", line 212, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol,
writeback, binary)
  File "c:\python23\lib\anydbm.py", line 80, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined
>>>

Uh-huh.

By the way, it's probably not a good idea to use a ".dat" extension;
evidently (read whichdb.py for the gory details) some of the dbms add
an extension to the supplied name. One of them uses ".dat". Could
become a source of confusion.

Take a hint: they say "Google is your friend", but better still is the
source in lib\*.py -- it's quite legible, you don't need an Internet
connection, and there sure ain't no ads in the margin. And don't just
open it in emergencies: pick a module that covers a topic that
interests you and just read it. You'll see good coding style, good ways
of doing things, wise utterances by the timbot, ...

HTH,
John

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


Re: Converting HTML to ASCII

2005-02-26 Thread Paul Rubin
Jorgen Grahn <[EMAIL PROTECTED]> writes:
> You should probably do what some other poster suggested -- download
> lynx or some other text-only browser and make your code execute it
> in -dump mode to get the text-formatted html. You'll get that
> working in an hour or so, and then you can see if you need something
> more complicated.

Lynx is pathetically slow for large files.  It seems to use a
quadratic algorithm for remembering where the links point, or
something.  I wrote a very crude but very fast renderer in C that I
can post if someone wants it, which is what I use for this purpose.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: split a directory string into a list

2005-02-26 Thread Duncan Booth
Josef Meile wrote:

> "This should work ***reasonably*** reliably on Windows and Unix". Are
> there any cases when it does not work?

The most obvious case where it wouldn't work would be for a UNC path name. 
Using the string split method gives two empty strings:

>>> os.path.normpath(r'\\machine\share').split(os.path.sep)
['', '', 'machine', 'share']
>>> 


whereas the splitpath function I proposed gives you:

>>> splitpath(r'\\machine\share')
['', 'machine', 'share']

So to find out the type of path (relative, absolute, unc), you only have to 
consider the first element with my function but you have to look at the 
first two elements if you just naively split the string.

Also a relative windows path with a drive letter doesn't get fully split:

>>> os.path.normpath(r'c:dir\file').split(os.path.sep)
['c:dir', 'file']
>>> splitpath(r'c:dir\file')
['c:', 'dir', 'file']

If you really are worried about speed (and are sure you aren't optimising 
prematurely), then you could combine some special case processing near the 
start of the string with a simple split of the remainder.
-- 
http://mail.python.org/mailman/listinfo/python-list


Polling selections from a listbox (Tkinter)

2005-02-26 Thread Harlin Seritt
I am trying to poll selections from a listbox but can't seem to get it
to work correctly.

class pollstuff:
   def __init__(self, master):
  self.listbox = Listbox(master)
  self.listbox.pack()

  names = ['Bob', 'Neal', 'Mike']
  for n in names:
 self.listbox.insert(END, n)
  self.listbox.select_set(0)

  LabelStr = StringVar()
  self.label = Label(master, textvariable=LabelStr)
  self.label.pack()
  LabelStr.set(names[map(int, self.listbox.curselection())])

root = Tk()
app = pollstuff(root)
root.mainloop()

Obviously when this starts up this is going to show selection #0 inside
the label box. How do I make sure that whatever is arbitrarily selected
ends up in the label box as this gui runs? I tried doing a bind:

self.listbox.bind("", self.changelabel)

This did not work as intended as the changelabel's text option only
showed what the selection index was BEFORE the event took place. Does
anyone know of any special thing I need to do in order to poll the
listbox items?

Thanks,

Harlin

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


Re: Which module is "set " in?

2005-02-26 Thread Raymond Hettinger
[Michael Hartl]
> It's good that you're using Python 2.3, which does have sets available,
> as a previous poster mentioned.  Users of Python 2.2 or earlier can get
> most of the Set functionality using the following class (from Peter
> Norvig's utils.py file):

Py2.3's set module also works under Py2.2.  Get a copy from viewcvs:

  http://tinyurl.com/6lqr3

or


http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/dist/src/Lib/sets.py?content-type=text%2Fplain&rev=1.43.4.2

Of course, if upgrading to Py2.4 is an option, that is the way to go.  If you're
living in a pre 2.2 world without iterators and generators, you're really
missing out.


Raymond Hettinger






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


Re: generic equivalence partition

2005-02-26 Thread Xah Lee
# the following solution is submitted by
# Sean Gugler and David Eppstein independently
# 20050224.

@def parti(aList, equalFunc):
@result = []
@for i in range(len(aList)):
@for s in result:
@if equalFunc( aList[i], aList[s[0]] ):
@s.append(i)
@break
@else:
@result.append( [i] )
@return [[x+1 for x in L] for L in result] # add 1 to all numbers
@
@---

as for my original perl code, i realized it is written to work on a
sorted input. Here it is and the translated Python code.

# perl
sub parti($$) {
my @li = @{$_[0]};
my $sameQ = $_[1];

my @tray=(1);
my @result;

for (my $i=1; $i <= ((scalar @li)-1); $i++) {
  if (&$sameQ($li[$i-1], $li[$i])) {
push @tray, $i+1}
  else {
push @result, [EMAIL PROTECTED]; @tray=($i+1);
  }
}
push @result, [EMAIL PROTECTED];
return [EMAIL PROTECTED];
}


@#python
@def parti(li,sameQ):
@tray=[1];
@result=[];
@
@for i in range(1, len(li) ):
@if sameQ(li[i-1],li[i]):
@tray.append(i+1)
@else:
@result.append(tray)
@tray=[i+1]
@result.append(tray)
@return result
@

http://xahlee.org/perl-python/gen_parti_by_equiv.html

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


function expression with 2 arguments

2005-02-26 Thread Xah Lee
is there a way to write a expression of a function with more than 1
argument?

e.g., i want a expression that's equivalent to

def f(x,y)
  return x+y

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


class factory example needed (long)

2005-02-26 Thread Gary Ruben
I have a class factory problem. You could say that my main problem is
that I don't understand class factories.
My specific problem:
I have a class with several methods I've defined.
To this class I want to add a number of other class methods where the
method names are taken from a list.
For each list member, I want to build a method having the list member
name so that I can override another method of the same name for objects
which are instances of this class. Finally, I want my class factory
which creates the method to call the overridden method.
I'm sure my description is confusing, so I'll try to illustrate it.
import Numeric
# The Numeric module contains a whole lot of methods which operate on
certain number types
class foo:
""" this is a number type class
"""
def __init__(self, value):
self.value = float(value)
def __str__(self):
.
. other methods here
.
import string
ufuncs = string.split("""
sqrt arccos arccosh arcsin arcsinh arctan arctanh cos cosh tan tanh
log10 sin sinh sqrt absolute fabs floor ceil fmod exp log conjugate
""")# these are the methods from Numeric that I want to
override/wrap for my number type
for u in ufuncs:
I need something here which builds methods called sqrt(),
arccos(), etc.
An illustrative example of the class methods I want to build with
some sort of class factory is
def sqrt(self):
val = Numeric.sqrt(self.value)
return foo(Numeric.sqrt(self.value) + 42)
def arccos(self):
val = Numeric.arccos(self.value)
return foo(Numeric.arccos(self.value) + 42)
if __name__ == "__main__":
a = 9
b = foo(7)
print Numeric.sqrt(a)
print Numeric.sqrt(b)
This would print
3
7
Note that the methods I want to create under program control are all
identical in form. In this example they all call the wrapped method with
an argument 42 greater than the value of the number.
Does anyone have an example where they've done something similar or
could help me out with an example?
thanks in anticipation,
Gary
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-02-26 Thread Harlin Seritt
Not exactly sure what you're looking for but you can do the following:

def dosomething(numlist):
   return numlist[0] + numlist[1]

numlist = [ 5, 10]
val = dosomething(numlist)

If so, that would be somewhat pointless. It's always best to keep it
simple. It looks like the function you wrote above is very adequate for
the results you want returned.

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


Making a calendar

2005-02-26 Thread Pete.....
Hi all.

I'm trying to make a calendar for my webpage, python and html is the only 
programming languages that I know, is it possible to make such a calendar 
with pythong code and some html.

The Idea is that when I click the link calendar on my webpage, then the user 
will be linked to the calendar.

The calendar should show one month at the time, and the user should be able 
to browse to the other month.

I will make a script that puts events and such into a db ( I know how to do 
this)

Then I need a script that puts the events from the db into the calendar, if 
every day in the calendar has a value id that part will not be hard.

What I need is a script that generates the calender, in such a way that each 
month will be have a value, and that the user then can click the days to see 
more info about the events.

I was thinking something like the iMPcal calender: 
http://www.heidgerken.org/impcal2/calendar.php

Is there any modules I can use, or does any of you hardcore programmers have 
some advice on how I should proceed with this little project of mine :)

Thanks


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


Problem When Unit Testing with PMock

2005-02-26 Thread steven
Hi,

Anyone was using pmock for unit testing with python?  I met a problem
and hope someone to help me.  For short, the pmock seems can not mock a
iterator object.

For example, the tested object is foo, who need to send message to
another object bar.  So, to test the foo, I need mock a mockBar.  But
the bar is a iterator, the foo use the bar in this way:

 foo.method(self, bar):
 for n in bar:
 do somthing
  ...
my purpose is create a mockBar and pass this mock object to
foo.method(), but this ideal simply does not work. Python will complain
that calling on an uniteraterable object.  I'v already set anything
like mockBar.expects(__iter__()) and mockBar.expects(next()).

Does anyone has some clues?

-
narke

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


Re: possible python/linux/gnome issue!!

2005-02-26 Thread Lee Harr
On 2005-02-26, bruce <[EMAIL PROTECTED]> wrote:
> hi...
>
> i'm running rh8.0 with gnome.. i'm not sure of the version (it's whatever rh
> shipped).
>
> i've recently updated (or tried to update) python to the latest version.
> when i try to run the 'Server Settings/Services' Icon within gnome, nothing
> happens...
>
> i tried to run the 'start services' command from a command line, and got the
> following...
>
> it appears to be a conflict somewhere...
>
> 
> [EMAIL PROTECTED] bin]# redhat-config-services
> /usr/share/redhat-config-services/serviceconf.py:331: SyntaxWarning:
> argument named None
>   def on_mnuRescan_activate(self,None):

I don't think this has ever been legal... so that's strange.


> import gtk
> ImportError: No module named gtk

Which version of python were you using before?
Is it still installed?
Try something like ...

ls -l /usr/bin/python*


> can someone perhaps suggest a solution, or point me to where i might find a
> solution to this issue. could the python changes be causing a problem? would
> upgrading gnome potentially fix the issue? can you upgrade gnome without
> upgrading the rh kernel?
>

You can try pointing /usr/bin/python (which on many systems
is just a link to the actual program) to the old version
of python.

This is really more of a red hat question than a python
question, so I also recommend asking on a red hat list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-02-26 Thread Reinhold Birkenfeld
Xah Lee wrote:
> is there a way to write a expression of a function with more than 1
> argument?
> 
> e.g., i want a expression that's equivalent to
> 
> def f(x,y)
>   return x+y

Looking for lambda?

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


Re: possible python/linux/gnome issue!!

2005-02-26 Thread Jarek Zgoda
Lee Harr napisaƂ(a):
[EMAIL PROTECTED] bin]# redhat-config-services
/usr/share/redhat-config-services/serviceconf.py:331: SyntaxWarning:
argument named None
 def on_mnuRescan_activate(self,None):
I don't think this has ever been legal... so that's strange.
It was, but currently is not 
(http://www.python.org/doc/2.4/whatsnew/node12.html).

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
--
http://mail.python.org/mailman/listinfo/python-list


remove strings from source

2005-02-26 Thread qwweeeit
For a python code I am writing I need to remove all strings
definitions from source and substitute them with a place-holder.

To make clearer:
line 45  sVar="this is the string assigned to sVar"
must be converted in:
line 45 sVar=s1

Such substitution is recorded in a file under:
s0001[line 45]="this is the string assigned to sVar"

For curious guys:
I am trying to implement a cross variable reference tool and the
variability (in lenght) of the string definitions (expecially if
multi-line) can cause display problems.

I need your help in correctly identifying the strings (also embedding
the r'xx..' or u'yy...' as part of the string definition). The problem
is mainly on the multi-line definitions or in cached strings
(embedding chr() definitions or escape sequences).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading and consuming output from processes

2005-02-26 Thread Jack Orenstein
I asked:
I am developing a Python program that submits a command to each node
of a cluster and consumes the stdout and stderr from each. I want all
the processes to run in parallel, so I start a thread for each
node. There could be a lot of output from a node, so I have a thread
reading each stream, for a total of three threads per node. (I could
probably reduce to two threads per node by having the process thread
handle stdout or stderr.)
Simon Wittber said:
> In the past, I have used the select module to manage asynchronous
> IO operations.
>
> I pass the select.select function a list of file-like objects, and it
> returns a list of file-like objects which are ready for reading and
> writing.
Donn Cave said:
As I see another followup has already mentioned, the classic
"pre threads" solution to multiple I/O sources is the select(2)
function, ...
Thanks for your replies. The streams that I need to read contain
pickled data. The select call returns files that have available input,
and I can use read(file_descriptor, max) to read some of the input
data. But then how can I convert the bytes just read into a stream for
unpickling? I somehow need to take the bytes arriving for a given file
descriptor and buffer them until the unpickler has enough data to
return a complete unpickled object.
(It would be nice to do this without copying the bytes from one place
to another, but I don't even see how do solve the problem with
copying.)
Jack
--
http://mail.python.org/mailman/listinfo/python-list


any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Just
While googling for a non-linear equation solver, I found 
Math::Polynomial::Solve in CPAN. It seems a great little module, except 
it's not Python... I'm especially looking for its poly_root() 
functionality (which solves arbitrary polynomials). Does anyone know of 
a Python module/package that implements that?

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


Re: remove strings from source

2005-02-26 Thread Mark McEahern
qwweeeit wrote:
For a python code I am writing I need to remove all strings
definitions from source and substitute them with a place-holder.
To make clearer:
line 45  sVar="this is the string assigned to sVar"
must be converted in:
line 45 sVar=s1
Such substitution is recorded in a file under:
s0001[line 45]="this is the string assigned to sVar"
For curious guys:
I am trying to implement a cross variable reference tool and the
variability (in lenght) of the string definitions (expecially if
multi-line) can cause display problems.
I need your help in correctly identifying the strings (also embedding
the r'xx..' or u'yy...' as part of the string definition). The problem
is mainly on the multi-line definitions or in cached strings
(embedding chr() definitions or escape sequences).
 

Approach this in a test-driven development way.  Create sample input and 
output files.  Write a unit test something like this (below) and run 
it.  You'll either solve the problem yourself or ask more specific 
questions.  ;-)

Cheers,
// m
#!/usr/bin/env python
import unittest
def substitute(data):
   # As a first pass, just return the data itself--obviously, this 
should fail.
   return data

class Test(unittest.TestCase):
   def test(self):
   data = open("input.txt").read()
   expected = open("expected.txt").read()
   actual = substitute(data)
   self.assertEquals(expected, actual)
if __name__ == '__main__':
   unittest.main()
--
http://mail.python.org/mailman/listinfo/python-list


Re: PythonCard and Py2Exe

2005-02-26 Thread PipedreamerGrey
That did it.  Thanks a lot.

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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Nick Coghlan
Just wrote:
While googling for a non-linear equation solver, I found 
Math::Polynomial::Solve in CPAN. It seems a great little module, except 
it's not Python... I'm especially looking for its poly_root() 
functionality (which solves arbitrary polynomials). Does anyone know of 
a Python module/package that implements that?

Just
Does SciPy do what you want? Specifically Scientific.Functions.FindRoot [1] & 
Scientific.Functions.Polynomial [2]

Regards,
Nick.
[1]
http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Scientific_9.html
[2]
http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Scientific_13.html
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting at raw POST data?

2005-02-26 Thread Sarat Venugopal
Erik Johnson wrote:
> I am trying to work with a program that is trying make an HTTP POST
> of text data without any named form parameter. (I don't know - is
> that a normal thing to do?)

Often, people do require abnormal things.

> I need to write a CGI program that
> accepts and processes that data. I'm not seeing how to get at data
> that's not a named form parameter.

As far as CGI is concerned, the POST data resides in stdin. So accessing it
is as simple as reading sys.stdin within the CGI script. Of course, it is up
to you to interpret the data, though you can just read everything as a
string. The POST data could just as well be binary - such as a file upload.

To dump the strings to a file to your webserver, try the following script:

import sys

print 'Content-type: text/plain\r\n\r\n'

dumped = open('test.txt', 'wb')
for line in sys.stdin.readline():
dumped.write(line)

HTH,
Sarat Venugopal
www.huelix.com






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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Just
In article <[EMAIL PROTECTED]>,
 Nick Coghlan <[EMAIL PROTECTED]> wrote:

> Just wrote:
> > While googling for a non-linear equation solver, I found 
> > Math::Polynomial::Solve in CPAN. It seems a great little module, except 
> > it's not Python... I'm especially looking for its poly_root() 
> > functionality (which solves arbitrary polynomials). Does anyone know of 
> > a Python module/package that implements that?
> > 
> > Just
> 
> Does SciPy do what you want? Specifically Scientific.Functions.FindRoot [1] & 
> Scientific.Functions.Polynomial [2]
> 
> Regards,
> Nick.
> 
> [1]
> http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Sci
> entific_9.html
> [2]
> http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Sci
> entific_13.html

(Hm, I had the impression that scipy != Konrad Hinsen's Scientific 
module.)

I had played with [1], but it "only" calculates one root, and I need all 
roots (specifically, for a quintic equation). [2] doesn't seem to be a 
solver?

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


Re: cgi: getting at raw POST data?

2005-02-26 Thread madsurfer2000
Erik Johnson wrote:
> I am trying to work with a program that is trying make an HTTP POST
of text
> data without any named form parameter. (I don't know - is that a
normal
> thing to do?) I need to write a CGI program that accepts and
processes that
> data. I'm not seeing how to get at data that's not a named form
parameter.
>

Got this from a quick search with Google. Haven't tried it, but it
looks like it does what you want.

http://mail.python.org/pipermail/python-list/2002-September/122977.html

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


Re: remove strings from source

2005-02-26 Thread Duncan Booth
qwweeeit wrote:

> I need your help in correctly identifying the strings (also embedding
> the r'xx..' or u'yy...' as part of the string definition). The problem
> is mainly on the multi-line definitions or in cached strings
> (embedding chr() definitions or escape sequences).
> 

Have a look at tokenize.generate_tokens() in the standard library. That 
ought to give you enough information to identify the strings reliably and 
output modified source.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading and consuming output from processes

2005-02-26 Thread Donn Cave
Quoth Jack Orenstein <[EMAIL PROTECTED]>:
[ ... re alternatives to threads ]
| Thanks for your replies. The streams that I need to read contain
| pickled data. The select call returns files that have available input,
| and I can use read(file_descriptor, max) to read some of the input
| data. But then how can I convert the bytes just read into a stream for
| unpickling? I somehow need to take the bytes arriving for a given file
| descriptor and buffer them until the unpickler has enough data to
| return a complete unpickled object.
|
| (It would be nice to do this without copying the bytes from one place
| to another, but I don't even see how do solve the problem with
| copying.)

Note that the file object copies bytes from one place to another,
via C library stdio.  If we could only see the data in those
stdio buffers, it would be possible to use file objects with
select() in more applications.  (Though not with pickle.)  Since
input very commonly needs to be buffered for various reasons, we
end up writing our own buffer code, all because stdio has no
standard function that tells you how much data is in a buffer.

But unpickling consumes an I/O stream, as you observe, so as a
network data protocol by itself, it's unsuitable for use with
select.  I think the only option would be a packet protocol -
a count field followed by the indicated amount of pickle data.
I suppose I would copy the received data into a StringIO object,
and unpickle that when all the data has been received.

Incidentally, I think I read here yesterday, someone held a book
about Python programming up to some ridicule for suggesting that
pickles would be a good way to send data around on the network.
The problem with this was supposed to have something to do with
"overloading".  I have no idea what he was talking about, but you
might be interested in this issue.

Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making a calendar

2005-02-26 Thread Michele Simionato
Looking at the "calendar" module in the standard library may help.
Also, "pydoc calendar" is your friend.

Michele Simionato

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


Re: fdups: calling for beta testers

2005-02-26 Thread Peter Hansen
Patrick Useldinger wrote:
(9) Any good reason why the "executables" don't have ".py" extensions
on their names?
(9) Because I am lazy and Linux doesn't care. I suppose Windows does?
Unfortunately, yes.  Windows has nothing like the "x" permission
bit, so you have to have an actual extension on the filename and
Windows (XP anyway) will check it against the list of extensions
in the PATHEXT environment variable to determine if it should be
treated like an executable.
Otherwise you must type "python" and the full filename.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-02-26 Thread Peter Hansen
Xah Lee wrote:
is there a way to write a expression of a function with more than 1
argument?
e.g., i want a expression that's equivalent to
def f(x,y)
  return x+y
Since assignment is a statement in Python, not an expression,
and since "def f" is an assignment that binds a function
object to the name "f", you can't do exactly what you've
asked for.
On the other hand, this should be about equivalent, though
it's not merely an expression:
f = lambda x, y: x + y
--
http://mail.python.org/mailman/listinfo/python-list


Whither datetime.date ?

2005-02-26 Thread Harald Hanche-Olsen
I'm confused.  I was going to try linkchecker, and it dies with a
traceback ending in

  File "/usr/local/lib/python2.4/calendar.py", line 32, in _localized_month
_months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
AttributeError: 'module' object has no attribute 'date'

Sure enough, there is no datetime.date, but there is a datetime.Date:

Python 2.4 (#2, Feb 19 2005, 20:35:23)
[GCC 3.4.2 [FreeBSD] 20040728] on freebsd5
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dir(datetime)
['Date', 'DateTime', ...]

However, the Library Reference clearly states that datetime.date
should exist.  Granted, it's been a while since I used python in
anger, but isn't this what it says?

  http://www.python.org/doc/2.4/lib/node243.html
  http://www.python.org/doc/2.4/lib/datetime-date.html

Moreover, the datetime.date class is supposed to have a strftime()
method.  datetime.Date does not.

I'm beginning to wonder if the FreeBSD python package is at fault.

Or what is really going on here?

-- 
* Harald Hanche-Olsen http://www.math.ntnu.no/~hanche/>
- Debating gives most of us much more psychological satisfaction
  than thinking does: but it deprives us of whatever chance there is
  of getting closer to the truth.  -- C.P. Snow
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange SyntaxError

2005-02-26 Thread Scott David Daniels
Attila Szabo wrote:
2005, Feb 25 -> Scott David Daniels wrote :
Attila Szabo wrote:
>>...lambda x: 'ABC%s' % str(x) ...
OK, to no real effect, in main you define an unnamed function that
you can never reference.  Pretty silly, but I'll bite.

This code was simplified, the lambda was part of a map, ...
I'm sorry, upon re-reading my reply, I see how it looks like a
snide comment.  I apologize.  I didn't mean to malign you, and
I did indeed appreciate that the code was obviously boiled down.
I just thought:
 def named(x):
 return 'ABC%s' % str(x)
provides a function name to talk about, exhibits the same problem,
and is "simpler".
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Whither datetime.date ?

2005-02-26 Thread Diez B. Roggisch
Harald Hanche-Olsen wrote:
> I'm beginning to wonder if the FreeBSD python package is at fault.

Maybe - at my system, it has no Date or DateTime

Python 2.4.1a0 (#2, Feb  9 2005, 12:50:04)
[GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__file__', '__name__', 'date',
'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>>   


Maybe this is a clash between a custom datetime module and the python one?

What does

python2.4 -v  -c "import datetime"

give you?
-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Whither datetime.date ?

2005-02-26 Thread Tim Peters
[Harald Hanche-Olsen]
> I'm confused.  I was going to try linkchecker, and it dies with a
> traceback ending in
>
>  File "/usr/local/lib/python2.4/calendar.py", line 32, in _localized_month
>_months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
> AttributeError: 'module' object has no attribute 'date'
>
> Sure enough, there is no datetime.date, but there is a datetime.Date:
>
> Python 2.4 (#2, Feb 19 2005, 20:35:23)
> [GCC 3.4.2 [FreeBSD] 20040728] on freebsd5
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import datetime
> >>> dir(datetime)
> ['Date', 'DateTime', ...]
> 
> However, the Library Reference clearly states that datetime.date
> should exist.  Granted, it's been a while since I used python in
> anger, but isn't this what it says?
> 
>  http://www.python.org/doc/2.4/lib/node243.html
>  http://www.python.org/doc/2.4/lib/datetime-date.html
>
> Moreover, the datetime.date class is supposed to have a strftime()
> method.  datetime.Date does not.
>
> I'm beginning to wonder if the FreeBSD python package is at fault.
>
> Or what is really going on here?

As you've deduced, you're certainly not getting Python's builtin
datetime module.  Therefore you must be getting some other datetime
module.  Run Python with the "-v" switch to get output telling you how
imports are resolved.  That will show you where this other datetime
module is coming from.  Remember that Python searches along sys.path
to resolve imports, taking the first thing it finds with the right
name.  You almost certainly have something _called_ datetime earlier
in your PYTHONPATH than where the standard Python libraries appear.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Terry Reedy

"Just" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> Does SciPy do what you want? Specifically Scientific.Functions.FindRoot 
>> [1] &
>> Scientific.Functions.Polynomial [2]
>> http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Sci
>> entific_9.html
>> [2]
>> http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Sci
>> entific_13.html
>
> (Hm, I had the impression that scipy != Konrad Hinsen's Scientific
> module.)

www.scipy.org (first hit on "Python SciPy" google search)

Terry J. Reedy



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


Re: Whither datetime.date ?

2005-02-26 Thread Harald Hanche-Olsen
+ Tim Peters <[EMAIL PROTECTED]>:

| As you've deduced, you're certainly not getting Python's builtin
| datetime module.

Argh.  Yeah, I've had one lying around in my personal python directory
since 2000, had totally forgotten it was there.  This one ...

*** Author: Jeff Kunce <[EMAIL PROTECTED]>
*** Download from: http://starship.skyport.net/crew/jjkunce

Removed it, now all is well.

Thanks for pointing out the blindingly obvious.

-- 
* Harald Hanche-Olsen http://www.math.ntnu.no/~hanche/>
- Debating gives most of us much more psychological satisfaction
  than thinking does: but it deprives us of whatever chance there is
  of getting closer to the truth.  -- C.P. Snow
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem When Unit Testing with PMock

2005-02-26 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Anyone was using pmock for unit testing with python?  I met a problem
> and hope someone to help me.  For short, the pmock seems can not mock a
> iterator object.

Why bother?

def mockit(): raise StopIteration

now pass mockit()

> For example, the tested object is foo, who need to send message to
> another object bar.  So, to test the foo, I need mock a mockBar.  But
> the bar is a iterator, the foo use the bar in this way:
>
> foo.method(self, bar):
> for n in bar:
> do somthing
>  ...

To properly test the method, *also* feed it an iterator that yields a few 
objects of the appropriate type.  Assuming n is to be an int...

def intit(k):
  for i in range(k): yield i

Terry J. Reedy





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


Re: Watermark on images

2005-02-26 Thread Terry Reedy

"Michele Simionato" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879

Googling "Python image watermark" and first hit is !!!
ASPN : Python Cookbook : Watermark with PIL ... Description: Apply a 
watermark to an image using the Python Imaging Library. Supports color, 
tiling, scaling, and opacity reduction. Source: Text Source. ...
  aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 - 27k - Feb 
24, 2005 - Cached - Similar pages


Learn to use it folks.  Get a Google bar.  Faster and easier than posting 
here.

Terry J. Reedy



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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread John M. Gamble
In article <[EMAIL PROTECTED]>,
Just  <[EMAIL PROTECTED]> wrote:
>While googling for a non-linear equation solver, I found 
>Math::Polynomial::Solve in CPAN. It seems a great little module, except 

Thank you.

>it's not Python... 

Sorry about that.

>   I'm especially looking for its poly_root() 
>functionality (which solves arbitrary polynomials). Does anyone know of 
>a Python module/package that implements that?

Are you looking for that particular algorithm, or for any
source that will find the roots of the polynomial?  The
original source for the algorithm used in the module is
from Hiroshi Murakami's Fortran source, and it shouldn't
be too difficult to repeat the translation process to python.

-- 
-john

February 28 1997: Last day libraries could order catalogue cards
from the Library of Congress.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making a calendar

2005-02-26 Thread Ksenia Marasanova
This is close to what you want: 
http://freespace.virgin.net/hamish.sanderson/htmlcalendar.html

You'll also need HTMLTemplate
http://freespace.virgin.net/hamish.sanderson/htmltemplate.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Leo 4.3-a3 Outlining IDE

2005-02-26 Thread Brad Clements
FYI,

After install and you run it for the first time (and if it asks for your
initials), then expect the plug-in manager to throw a bad window name error
in TK.

You must exit, then restart Leo before running the plugin manager after the
initial install.


-- 
Novell DeveloperNet Sysop #5



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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Just
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (John M. Gamble) wrote:

> In article <[EMAIL PROTECTED]>,
> Just  <[EMAIL PROTECTED]> wrote:
> >While googling for a non-linear equation solver, I found 
> >Math::Polynomial::Solve in CPAN. It seems a great little module, except 
> 
> Thank you.
> 
> >it's not Python... 
> 
> Sorry about that.

Heh, how big are the odds you find the author of an arbitrary Perl 
module on c.l.py...

> >   I'm especially looking for its poly_root() 
> >functionality (which solves arbitrary polynomials). Does anyone know of 
> >a Python module/package that implements that?
> 
> Are you looking for that particular algorithm, or for any
> source that will find the roots of the polynomial? 

Any will do. As I wrote in another post, I'm currently only looking for 
a quintic equation solver, which your module does very nicely.

> The
> original source for the algorithm used in the module is
> from Hiroshi Murakami's Fortran source, and it shouldn't
> be too difficult to repeat the translation process to python.

Ah ok, I'll try to locate that (following the instruction in Solve.pm 
didn't work for me :( ).

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


Re: fdups: calling for beta testers

2005-02-26 Thread Serge Orlov
Peter Hansen wrote:
> Patrick Useldinger wrote:
>>> (9) Any good reason why the "executables" don't have ".py"
>>> extensions on their names?
>>
>> (9) Because I am lazy and Linux doesn't care. I suppose Windows does?
>
> Unfortunately, yes.  Windows has nothing like the "x" permission
> bit, so you have to have an actual extension on the filename and
> Windows (XP anyway) will check it against the list of extensions
> in the PATHEXT environment variable to determine if it should be
> treated like an executable.
>
> Otherwise you must type "python" and the full filename.

Or use exemaker, which IMHO is the best way to handle this
problem.

  Serge.


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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread John M. Gamble
In article <[EMAIL PROTECTED]>,
Just  <[EMAIL PROTECTED]> wrote:
>
>Heh, how big are the odds you find the author of an arbitrary Perl 
>module on c.l.py...
>

Hey, that's why it's called lurking.

>
>Any will do. As I wrote in another post, I'm currently only looking for 
>a quintic equation solver, which your module does very nicely.
>
>> The
>> original source for the algorithm used in the module is
>> from Hiroshi Murakami's Fortran source, and it shouldn't
>> be too difficult to repeat the translation process to python.
>
>Ah ok, I'll try to locate that (following the instruction in Solve.pm 
>didn't work for me :( ).
>

Ouch.  I just did a quick search and found that that site has undergone
a few changes, and the code that i reference is missing.  A few other
links in the docs are stale too.  I need to update the documentation.

Anyway, doing a search for 'hqr' and Eispack got me a lot of sites.
In particular, this one is pretty friendly:



Look at the source for balanc.f (does the prep-work) and hqr.f
(does the solving).  Minor annoyance: the real and imaginary
parts of the roots are in separate arrays.  I combined them into
complex types in my perl source, in case you want to make a
comparison.

Of course, all this may be moot if the other suggestions
work out.

-- 
-john

February 28 1997: Last day libraries could order catalogue cards
from the Library of Congress.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fdups: calling for beta testers

2005-02-26 Thread John Machin

Patrick Useldinger wrote:
> John Machin wrote:
>
> > (1) It's actually .bz2, not .bz (2) Why annoy people with the
> > not-widely-known bzip2 format just to save a few % of a 12KB file??
(3)
> > Typing that on Windows command line doesn't produce a useful result
(4)
> > Haven't you heard of distutils?
>
> (1) Typo, thanks for pointing it out
> (2)(3) In the Linux world, it is really popular. I suppose you are a
> Windows user, and I haven't given that much thought. The point was
not
> to save space, just to use the "standard" format. What would it be
for
> Windows - zip?

Yes. Moreover, "WinZip", the most popular archive-handler, doesn't grok
bzip2.

> > (6) You are keeping open handles for all files of a given size --
have
> > you actually considered the possibility of an exception like this:
> > IOError: [Errno 24] Too many open files: 'foo509'
>
> (6) Not much I can do about this. In the beginning, all files of
equal
> size are potentially identical. I first need to read a chunk of each,

> and if I want to avoid opening & closing files all the time, I need
them
> open together.
> What would you suggest?

Test, like I did, to see how many open handles you can get away with. I
was not joking, 20 was the max on MS-DOS at one stage and I vaguely
recall: (a) some low limits on various flavours of *x (b) the "ulimit"
command can be used to vary the per-process limit but (c) there is a
system-wide limit also.

You should consider a fall-back method to be used in this case and in
the case of too many files for your 1Mb (default) buffer pool. BTW 1Mb
seems tiny; desktop PCs come with 512MB standard these days, and Bill
does leave a bit more than 1MB available for applications.

> > And what is "chown" -- any relation of Perl's "chomp"?
>
> chown is a Unix command to change the owner or the group of a file.
It
> has to do with controlling access to the file. It is not relevant on
> Windows. No relation to Perl's chomp.

The question was rhetorical. Your irony detector must be on the fritz.
:-)

> Did you actually run it on your
> Windows box?

Yes, with trepidation, after carefully reading the source. It detected
some highly plausible duplicates, which I haven't verified yet.

Cheers,
John

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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Just
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (John M. Gamble) wrote:

> >> The
> >> original source for the algorithm used in the module is
> >> from Hiroshi Murakami's Fortran source, and it shouldn't
> >> be too difficult to repeat the translation process to python.
> >
> >Ah ok, I'll try to locate that (following the instruction in Solve.pm 
> >didn't work for me :( ).
> >
> 
> Ouch.  I just did a quick search and found that that site has undergone
> a few changes, and the code that i reference is missing.  A few other
> links in the docs are stale too.  I need to update the documentation.
> 
> Anyway, doing a search for 'hqr' and Eispack got me a lot of sites.
> In particular, this one is pretty friendly:
> 
> 
> 
> Look at the source for balanc.f (does the prep-work) and hqr.f
> (does the solving).  Minor annoyance: the real and imaginary
> parts of the roots are in separate arrays.  I combined them into
> complex types in my perl source, in case you want to make a
> comparison.

Thanks! I'll check that out.

> Of course, all this may be moot if the other suggestions
> work out.

SciPy indeed appear to contain a solver, but I'm currently stuck in 
trying to _get_ it for my platform (OSX). I'm definitely not going to 
install a Fortran compiler just to evaluate it (even though my name is 
not "Ilias" ;-). Also, SciPy is _huge_, so maybe a Python translation of 
that Fortran code or your Perl code will turn out to be more attractive 
after all...

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


[solved] Re: error in non-existing code?

2005-02-26 Thread Thomas Newman
Thomas Newman wrote:

>Michael Hoffman wrote:
>
>  
>
>>Thomas Newman wrote:
>>
>>
>>
>>>I wanted to look at the code that gives me the error, but there is no
>>>line 447 in /usr/lib/python2.3/pyclbr.py:
>>>  
>>>
>>Try deleting pyclbr.py[co].
>>
>>
There were recursive imports, meaning file A imported file B and vice
versa.
Solving that issue removed the error.
Still I find it confusing.

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


Re: remove strings from source

2005-02-26 Thread M.E.Farmer
qwweeeit wrote:
> For a python code I am writing I need to remove all strings
> definitions from source and substitute them with a place-holder.
>
> To make clearer:
> line 45  sVar="this is the string assigned to sVar"
> must be converted in:
> line 45 sVar=s1
>
> Such substitution is recorded in a file under:
> s0001[line 45]="this is the string assigned to sVar"
>
> For curious guys:
> I am trying to implement a cross variable reference tool and the
> variability (in lenght) of the string definitions (expecially if
> multi-line) can cause display problems.
>
> I need your help in correctly identifying the strings (also embedding
> the r'xx..' or u'yy...' as part of the string definition). The
problem
> is mainly on the multi-line definitions or in cached strings
> (embedding chr() definitions or escape sequences).

Hello,
I have written a few python parsers before.
Here is my attempt :)
# string_mapper.py
from __future__ import generators# python 2.2
import keyword, os, sys, traceback
import cStringIO, token, tokenize

def StringNamer(num=0):
'''This is a name creating generator'''
while 1:
num += 1
stringname = 's'+str(num).zfill(6)
yield stringname

class ReplaceParser(object):
"""
>>> filein = open('yourfilehere.py').read()
>>> replacer = ReplaceParser(filein, out=sys.stdout)
>>> replacer.format()
>>> replacer.StringMap
"""

def __init__(self, raw, out=sys.stdout):
''' Store the source text.
'''
self.raw =raw.expandtabs().strip()
self.out = out
self.StringName = StringNamer()
self.StringMap = {}

def format(self):
''' Parse and send the source.
'''
self.lines = [0, 0]
pos = 0
self.temp = cStringIO.StringIO()
while 1:
pos = self.raw.find('\n', pos) + 1
if not pos: break
self.lines.append(pos)
self.lines.append(len(self.raw))
self.pos = 0
text = cStringIO.StringIO(self.raw)
try:
tokenize.tokenize(text.readline, self)
except tokenize.TokenError, ex:
traceback.print_exc()

def __call__(self, toktype, toktext, (srow,scol),
   (erow,ecol), line):
''' Token handler.
'''
oldpos = self.pos
newpos = self.lines[srow] + scol
self.pos = newpos + len(toktext)
if toktype in [token.NEWLINE, tokenize.NL]:
self.out.write('\n')
return
if newpos > oldpos:
self.out.write(self.raw[oldpos:newpos])
if toktype in [token.INDENT, token.DEDENT]:
self.pos = newpos
return
if (toktype == token.STRING):
sname = self.StringName.next()
self.StringMap[sname] = toktext
toktext = sname
self.out.write(toktext)
self.out.flush()
return

hth,
M.E.Farmer

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


Re: function expression with 2 arguments

2005-02-26 Thread Xah Lee
lambda x, y: x + y

that's what i was looking for.

... once i have a lambda expr, how to apply it to arguments?

e.g. in Mathematica
Function[#1+#2][a,b]

Python doc is quite confounded in it's way of organization centered
around implementation tied to hardware (as most imperative languages
are hardware-centric), as opposed to algorithm math concepts.

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


Re: function expression with 2 arguments

2005-02-26 Thread Leif K-Brooks
Xah Lee wrote:
lambda x, y: x + y
that's what i was looking for.
... once i have a lambda expr, how to apply it to arguments?
http://python.org/doc/current/ref/calls.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: generic equivalence partition

2005-02-26 Thread Xah Lee
folks:

when using google to post a reply, it sometimes truncates the subject
line. i.e. [perl-python] is lost. This software error is obvious, they
could not have not noticed it.

another thing more egregious is that google _intentionally_ edit with
people's posts. (e.g. they change email address lines without author's
permission, and they also change program codes so it no longer run).
Please spread these google irresponsibility to all related forums on
software responsibility and online forum issues.

Ostensible incorrect behavior like these by google is egregious enough
to generate a law suit and if such company do not take software
correctness seriously, we must punish them.

Please spread this awareness.

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


Using PyOpenGL what should I use for a GUI ?

2005-02-26 Thread Gilles Leblanc
Hi I have started a small project with PyOpenGL. I am wondering what
are the options for a GUI. So far I checked PyUI but it has some
problems with 3d rendering outside the Windows platform.

I know of WxPython but I don't know if I can create a WxPython window,
use gl rendering code in it and then put widgets on top of that...

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


Thread scheduling

2005-02-26 Thread Jack Orenstein
I am using Python 2.2.2 on RH9, and just starting to work with Python
threads.
I started using the threading module and found that 10-20% of the runs
of my test program would hang. I developed smaller and smaller test
cases, finally arriving at the program at the end of this message,
which uses the thread module, not threading. This program seems to
point to problems in Python thread scheduling.
The program is invoked like this:
python threadtest.py THREADS COUNT
THREADS is the number of threads created. Each thread contains a loop
that runs COUNT times, and all threads increment a counter. (The
counter is incremented without locking -- I expect to see a final
count of less than THREADS * COUNT.)
Running with THREADS = 2 and COUNT = 10, most of the time, the
program runs to completion. About 20% of the time however, I see one
thread finish, but the other thread never resumes.
Here is output from a run that completes normally:
[EMAIL PROTECTED] python threadtest.py 2 10
nThreads: 2
nCycles: 10
thread 1: started
thread 1: i = 0, counter = 1
thread 2: started
thread 2: i = 0, counter = 2691
thread 1: i = 1, counter = 13496
thread 2: i = 1, counter = 22526
thread 1: i = 2, counter = 27120
thread 2: i = 2, counter = 40365
thread 1: i = 3, counter = 41264
thread 1: i = 4, counter = 55922
thread 2: i = 3, counter = 58416
thread 2: i = 4, counter = 72647
thread 1: i = 5, counter = 74602
thread 1: i = 6, counter = 88468
thread 2: i = 5, counter = 99319
thread 1: i = 7, counter = 110144
thread 2: i = 6, counter = 110564
thread 2: i = 7, counter = 125306
thread 1: i = 8, counter = 129252
Still waiting, done = 0
thread 2: i = 8, counter = 141375
thread 1: i = 9, counter = 147459
thread 2: i = 9, counter = 155268
thread 1: leaving
thread 2: leaving
Still waiting, done = 2
All threads have finished, counter = 168322
Here is output from a run that hangs. I killed the process using
ctrl-c.
[EMAIL PROTECTED] python threadtest.py 2 10
nThreads: 2
nCycles: 10
thread 1: started
thread 1: i = 0, counter = 1
thread 2: started
thread 2: i = 0, counter = 990
thread 1: i = 1, counter = 11812
thread 2: i = 1, counter = 13580
thread 1: i = 2, counter = 19127
thread 2: i = 2, counter = 25395
thread 1: i = 3, counter = 31457
thread 1: i = 4, counter = 44033
thread 2: i = 3, counter = 48563
thread 1: i = 5, counter = 55131
thread 1: i = 6, counter = 65291
thread 1: i = 7, counter = 78145
thread 2: i = 4, counter = 82715
thread 1: i = 8, counter = 92073
thread 2: i = 5, counter = 101784
thread 1: i = 9, counter = 104294
thread 2: i = 6, counter = 112866
Still waiting, done = 0
thread 1: leaving
Still waiting, done = 1
Still waiting, done = 1
Still waiting, done = 1
Still waiting, done = 1
Still waiting, done = 1
Still waiting, done = 1
Still waiting, done = 1
Still waiting, done = 1
Traceback (most recent call last):
  File "threadtest.py", line 26, in ?
time.sleep(1)
KeyboardInterrupt
[EMAIL PROTECTED] osh]$
In this case, thread 1 finishes but thread 2 never runs again. Is
this a known problem? Any ideas for workarounds? Are threads widely
used in Python?
Jack Orenstein

# threadtest.py
import sys
import thread
import time
nThreads = int(sys.argv[1])
nCycles = int(sys.argv[2])
print 'nThreads: %d' % nThreads
print 'nCycles: %d' % nCycles
counter = 0
done = 0
def run(id):
global done
print 'thread %d: started' % id
global counter
for i in range(nCycles):
counter += 1
if i % 1 == 0:
print 'thread %d: i = %d, counter = %d' % (id, i, counter)
print 'thread %d: leaving' % id
done += 1
for i in range(nThreads):
thread.start_new_thread(run, (i + 1,))
while done < nThreads:
time.sleep(1)
print 'Still waiting, done = %d' % done
print 'All threads have finished, counter = %d' % counter
--
http://mail.python.org/mailman/listinfo/python-list


Re: fdups: calling for beta testers

2005-02-26 Thread Patrick Useldinger
John Machin wrote:
Yes. Moreover, "WinZip", the most popular archive-handler, doesn't grok
bzip2.
I've added a zip file. It was made in Linux with the zip command-line 
tool, the man pages say it's compatible with the Windows zip tools. I 
have also added .py extentions to the 2 programs. I did however not use 
distutils, because I'm not sure it is really adapted to module-less scripts.

You should consider a fall-back method to be used in this case and in
the case of too many files for your 1Mb (default) buffer pool. BTW 1Mb
seems tiny; desktop PCs come with 512MB standard these days, and Bill
does leave a bit more than 1MB available for applications.
I've added it to the TODO list.
The question was rhetorical. Your irony detector must be on the fritz.
:-)
I always find it hard to detect irony by mail with people I do not know. ..
Did you actually run it on your
Windows box?

Yes, with trepidation, after carefully reading the source. It detected
some highly plausible duplicates, which I haven't verified yet.
I would have been reluctant too. But I've tested it intensively, and 
there's strictly no statement that actually alters the file system.

Thanks for your feedback!
-pu
--
http://mail.python.org/mailman/listinfo/python-list


Re: Thread scheduling

2005-02-26 Thread M.E.Farmer
This may help.
http://linuxgazette.net/107/pai.html
Also be sure to google.
search strategy:
Python threading
Python threads
Python thread tutorial
threading.py example
Python threading example
Python thread safety
hth,
M.E.Farmer

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


Re: fdups: calling for beta testers

2005-02-26 Thread Patrick Useldinger
Serge Orlov wrote:
Or use exemaker, which IMHO is the best way to handle this
problem.
Looks good, but I do not use Windows.
-pu
--
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-02-26 Thread Douglas Alan
I wrote:

> Okay, here's the definitive version (or so say I).  Some good doobie
> please make sure it makes its way into the standard library:

Oops, I just realized that my previously definitive version did not
handle multi-character newlines.  So here is a new definition
version.  Oog, now my brain hurts:

def fileLineIter(inputFile, newline='\n', leaveNewline=False, readSize=8192):
   """Like the normal file iter but you can set what string indicates newline.

   The newline string can be arbitrarily long; it need not be restricted to a
   single character. You can also set the read size and control whether or not
   the newline string is left on the end of the iterated lines.  Setting
   newline to '\0' is particularly good for use with an input file created with
   something like "os.popen('find -print0')".
   """
   isNewlineMultiChar = len(newline) > 1
   outputLineEnd = ("", newline)[leaveNewline]

   # 'partialLine' is a list of strings to be concatinated later:
   partialLine = []

   # Because read() might unfortunately split across our newline string, we
   # have to regularly check to see if the newline string appears in what we
   # previously thought was only a partial line.  We do so with this generator:
   def linesInPartialLine():
  if isNewlineMultiChar:
 linesInPartialLine = "".join(partialLine).split(newline)
 if linesInPartialLine > 1:
partialLine[:] = [linesInPartialLine.pop()]
for line in linesInPartialLine:
   yield line + outputLineEnd

   while True:
  charsJustRead = inputFile.read(readSize)
  if not charsJustRead: break
  lines = charsJustRead.split(newline)
  if len(lines) > 1:
 for line in linesInPartialLine(): yield line
 partialLine.append(lines[0])
 lines[0] = "".join(partialLine)
 partialLine[:] = [lines.pop()]
  else:
 partialLine.append(lines.pop())
 for line in linesInPartialLine(): yield line
  for line in lines: yield line + outputLineEnd
   for line in linesInPartialLine(): yield line
   if partialLine and partialLine[-1] != '':
  yield "".join(partialLine)


|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remove strings from source

2005-02-26 Thread qwweeeit
Thank you for your suggestion, but it is too complicated for me...
I decided to proceed in steps:
1. Take away all commented lines
2. Rebuild the multi-lines as single lines

I have already written the code and now I can face the problem of
mouving string definitions into a data base file...
Hopefully I will then build cross reference tables of the variables.
My project is also to implement the code for building functions' tree
.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remove strings from source

2005-02-26 Thread M.E.Farmer
qwweeeit wrote:
> Thank you for your suggestion, but it is too complicated for me...
> I decided to proceed in steps:
> 1. Take away all commented lines
> 2. Rebuild the multi-lines as single lines
ummm,
Ok all i can say is did you try this?
if not save it as a module then import it into the interperter and try
it.
This is a dead simple module to do *exactly* what you asked for :)
Like i said I have done this before so I will restate *I HAVE FAILED AT
THIS BEFORE, MANY TIMES*. Now I have a solution.
It handles stdio by default but can write to a filelike object if you
give it one.
Handles continued lines already, no need to futz around with some
solution.
Here is an example:
Py> filein = """
... class Stripper:
... '''python comment and whitespace stripper
... '''
... def __init__(self, raw):
... ''' Store the source text & set some flags.
... '''
... self.raw = raw
...
... def format(self, out=sys.stdout, comments=0,
...  spaces=1, untabify=1,eol='unix'):
... '''Parse and send the colored source.'''
... # Store line offsets in self.lines
... self.lines = [0, 0]
... pos = 0
... # Strips the first blank line if 1
... self.lasttoken = 1
... self.temp = StringIO.StringIO()
... self.spaces = spaces
... self.comments = comments
...
... if untabify:
...self.raw = self.raw.expandtabs()
... self.raw = self.raw.rstrip()+' '
... self.out = out
... """
Py> replacer = ReplaceParser(filein, out=sys.stdout)
Py> replacer.format()
class Stripper:
s01
def __init__(self, raw):
s02
self.raw = raw

def format(self, out=sys.stdout, comments=0,
 spaces=1, untabify=1,eol=s03):
s04
# Store line offsets in self.lines
self.lines = [0, 0]
pos = 0
# Strips the first blank line if 1
self.lasttoken = 1
self.temp = StringIO.StringIO()
self.spaces = spaces
self.comments = comments

if untabify:
   self.raw = self.raw.expandtabs()
self.raw = self.raw.rstrip()+s05
self.out = out
Py> replacer.StringMap
{'s04': "'''Parse and send the colored source.'''",
 's05': "' '",
 's01': "'''python comment and whitespace stripper :)\n'''",
 's02': "''' Store the source text & set some flags.\n'''",
 's03': "'unix'"}

You can also strip out comments with a few line.
It can easily get single comments or doubles.
add this in your __call__ function:
[snip]
self.pos = newpos
return
# kills comments
if (toktype == tokenize.COMMENT):
return
if (toktype == token.STRING):
sname = self.StringName.next()
[snip]

If you insist on writing something go ahead.
Let me know what your solution is, I am curious.
M.E.Farmer

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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Raymond L. Buvel
Just wrote:

SciPy indeed appear to contain a solver, but I'm currently stuck in 
trying to _get_ it for my platform (OSX). I'm definitely not going to 
install a Fortran compiler just to evaluate it (even though my name is 
not "Ilias" ;-). Also, SciPy is _huge_, so maybe a Python translation of 
that Fortran code or your Perl code will turn out to be more attractive 
after all...

Just
The GNU Scientific Library has a nice root finder for polynomials with 
real coefficients.  I have wrapped this with Pyrex to work with my 
ratfun module see:

http://calcrpnpy.sourceforge.net/ratfun.html
If this will suit your needs, I can send you an alpha release of the 
package with the root finder.  It is not pure Python.  I requires Pyrex 
and a C compiler to install.  My guess is that it will work on OSX as 
well as it does on Linux.  This functionality will be included in the 
next release of the ratfun package but I still have to unit test a 
number of components and update the documentation.  Consequently, an 
official release will not happen soon.

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


Re: generic equivalence partition

2005-02-26 Thread Xah Lee
People,

... sorry for the latching on on this broadside issue, but it is
impotant ...

here's are some germane points from another online discussion:

the bug-reporting issue has came up so many times by so many people i
thought i'd make a comment of my view.

when a software is ostensibly incorrect, and if it is likely in
connection to egregious irresponsibility as most software companies are
thru their irresponsible licensing, the thing one should not do is to
fawn up to their ass as in filing a bug report, and that is also the
least effective in correcting the software.

the common attitude of bug-reporting is one reason that contributed to
the tremendous egregious irresponsible fuckups in computer software
industry that each of us have to endure daily all the time. (e.g.
software A clashed, software B can't do this, C can't do that, D i
don't know how to use, E download location currently broken, F i need
to join discussion group to find a work-around, G is all pretty and
dysfunctional... )

when a software is ostensibly incorrect and when the company is
irresponsible with their licensing, the most effective and moral
attitude is to do legal harm to the legal entity. This one an do by
filing a law suit or spreading the fact. Filing a law suit is
appropriate in severe and serious cases, and provided you have such
devotion to the cause. For most cases, we should just spread the fact.
When a company see facts flying about their incompetence or
irresponsibility, they will immediately mend the problem source, or
cease to exist.

Another harm sprang from the fucking bug-reporting attitude rampant
among IT morons is the multiplication of pop-ups that bug users for
bug-reporting, complete with their privacy intrusion legalese.

http://xahlee.org/UnixResource_dir/writ/responsible_license.html

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html


Xah Lee wrote:
> folks:
>
> when using google to post a reply, it sometimes truncates the subject
> line. i.e. [perl-python] is lost. This software error is obvious,
they
> could not have not noticed it.
>
> another thing more egregious is that google _intentionally_ edit with
> people's posts. (e.g. they change email address lines without
author's
> permission, and they also change program codes so it no longer run).
> Please spread these google irresponsibility to all related forums on
> software responsibility and online forum issues.
>
> Ostensible incorrect behavior like these by google is egregious
enough
> to generate a law suit and if such company do not take software
> correctness seriously, we must punish them.
>
> Please spread this awareness.
> 
>  Xah
>  [EMAIL PROTECTED]
>  http://xahlee.org/PageTwo_dir/more.html

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


Re: Thread scheduling

2005-02-26 Thread Peter Hansen
Jack Orenstein wrote:
I am using Python 2.2.2 on RH9, and just starting to work with Python
threads.
Is this also the first time you've worked with threads in general,
or do you have much experience with them in other situations?
This program seems to point to problems in Python thread scheduling.
While from time to time bugs in Python are found, it's generally
more productive to suspect one's own code.  In any case, you
wouldn't have posted it here if you didn't suspect your own
code at least a bit, so kudos to you for that. :-)
done = 0
def run(id):
global done
print 'thread %d: started' % id
global counter
for i in range(nCycles):
counter += 1
if i % 1 == 0:
print 'thread %d: i = %d, counter = %d' % (id, i, counter)
print 'thread %d: leaving' % id
done += 1
for i in range(nThreads):
thread.start_new_thread(run, (i + 1,))
while done < nThreads:
time.sleep(1)
print 'Still waiting, done = %d' % done
print 'All threads have finished, counter = %d' % counter
Without having tried to run your code, and without having studied
it for long, I am going to point out something that is at the
very least an inherent defect in your code, though you might
not have used Python (or threads?) for long enough to realize
why.  Note that I don't know if this is the cause of your
particular problem, just that it _is_ a bug.
You've got two shared global variables, "done" and "counter".
Each of these is modified in a manner that is not thread-safe.
I don't know if "counter" is causing trouble, but it seems
likely that "done" is.
Basically, the statement "done += 1" is equivalent to the
statement "done = done + 1" which, in Python or most other
languages is not thread-safe.  The "done + 1" part is
evaluated separately from the assignment, so it's possible
that two threads will be executing the "done + 1" part
at the same time and that the following assignment of
one thread will be overwritten immediately by the assignment
in the next thread, but with a value that is now one less
than what you really wanted.
Look at the bytecode produced by the statement "done += 1":
>>> import dis
>>> def f():
...   global done
...   done += 1
...
>>> dis.dis(f)
  3   0 LOAD_GLOBAL  0 (done)
  3 LOAD_CONST   1 (1)
  6 INPLACE_ADD
  7 STORE_GLOBAL 0 (done)
(ignore the last two lines: they just "return None")
 10 LOAD_CONST   0 (None)
 13 RETURN_VALUE
Note here the "store_global" that is separate from the add
operation itself.  If thread A gets loses the CPU (so to speak)
just before that operation, and thread B executes the entire
suite of operations, then later on when thread A executes
that operation it will effectively result in only a single
addition operation being performed, not two of them.
If you really want to increment globals from the thread, you
should look into locks.  Using the "threading" module (as is
generally recommended, instead of using "thread"), you would
use threading.Lock().  There are other thread synchronization
primitives in the threading module as well, some of which
might be more suitable for your purposes.  Note also the
oft-repeated (in this forum) recommendation that if you simply
use nothing but the Queue module for inter-thread communication,
you will be very unlikely to stumble over such issues.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: generic equivalence partition

2005-02-26 Thread Erik Max Francis
Xah Lee wrote:
... sorry for the latching on on this broadside issue, but it is
impotant ...
You made a typo in that last word there.  Obviously you meant to write 
an _e_ instead of an _a_.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  All bad poetry springs from genuine feeling.
  -- Oscar Wilde
--
http://mail.python.org/mailman/listinfo/python-list


Xlib in Python? I need XDrawString()

2005-02-26 Thread Artificial Life
All I really want is to write a few strings to the background of my X
display. XDrawString() is what I need. The Xlib for Python shows it's out
dated. Is there any alternative? 

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


Re: Thread scheduling

2005-02-26 Thread Jack Orenstein
Peter Hansen wrote:
> Jack Orenstein wrote:
>
>> I am using Python 2.2.2 on RH9, and just starting to work with Python
>> threads.
>
>
> Is this also the first time you've worked with threads in general,
> or do you have much experience with them in other situations?
Yes, I've used threading in Java.
> You've got two shared global variables, "done" and "counter".
> Each of these is modified in a manner that is not thread-safe.
> I don't know if "counter" is causing trouble, but it seems
> likely that "done" is.
I understand that. As I said in my posting, "The counter is
incremented without locking -- I expect to see a final count of less
than THREADS * COUNT." This is a test case, and I threw out more and
more code, including synchronization around counter and done, until it
got as simple as possible and still showed the problem.
> Basically, the statement "done += 1" is equivalent to the
> statement "done = done + 1" which, in Python or most other
> languages is not thread-safe.  The "done + 1" part is
> evaluated separately from the assignment, so it's possible
> that two threads will be executing the "done + 1" part
> at the same time and that the following assignment of
> one thread will be overwritten immediately by the assignment
> in the next thread, but with a value that is now one less
> than what you really wanted.
Understood. I was counting on this being unlikely for my test
case. I realize this isn't something to rely on in real software.
> If you really want to increment globals from the thread, you
> should look into locks.  Using the "threading" module (as is
> generally recommended, instead of using "thread"), you would
> use threading.Lock().
As my note said, I did start with the threading module. And variables
updated by different threads were protected by threading.Condition
variables. As I analyzed my test cases, and threading.py, I started
suspecting thread scheduling.  I then wrote the test case in my email,
which does not rely on the threading module at all. The point of the
test is not to maintain counter -- it's to show that sometimes even
after one thread completes, the other thread never is scheduled
again. This seems wrong. Try running the code, and let me see if you
see this behavior.
If you'd like, replace this:
counter += 1
by this:
time.sleep(0.01 * id)
You should see the same problem. So that removes counter from the
picture. And the two increments of done (one by each thread) are still
almost certainly not going to coincide and cause a problem. Also, if
you look at the output from the code on a hang, you will see that
'thread X: leaving' only prints once. This has nothing to do with what
happens with the done variable.
Jack
--
http://mail.python.org/mailman/listinfo/python-list


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Just
In article <[EMAIL PROTECTED]>,
 "Raymond L. Buvel" <[EMAIL PROTECTED]> wrote:

> Just wrote:
> 
> > 
> > SciPy indeed appear to contain a solver, but I'm currently stuck in 
> > trying to _get_ it for my platform (OSX). I'm definitely not going to 
> > install a Fortran compiler just to evaluate it (even though my name is 
> > not "Ilias" ;-). Also, SciPy is _huge_, so maybe a Python translation of 
> > that Fortran code or your Perl code will turn out to be more attractive 
> > after all...
> > 
> > Just
> 
> The GNU Scientific Library has a nice root finder for polynomials with 
> real coefficients.  I have wrapped this with Pyrex to work with my 
> ratfun module see:
> 
> http://calcrpnpy.sourceforge.net/ratfun.html
> 
> If this will suit your needs, I can send you an alpha release of the 
> package with the root finder.  It is not pure Python.  I requires Pyrex 
> and a C compiler to install.  My guess is that it will work on OSX as 
> well as it does on Linux.  This functionality will be included in the 
> next release of the ratfun package but I still have to unit test a 
> number of components and update the documentation.  Consequently, an 
> official release will not happen soon.

Thank you, I'll check this out. I had come across GSL, but not Python 
bindings. (GPL is probably a problem for my project, but it's very good 
to know anyway.)

On the other hand, I just finished translating the relevant portions of 
Math::Polynomial::Solve to Python, so I'm probably all set, at least for 
now. Thanks everyone for the responses, especially to John Gamble!

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


Re: weird strings question

2005-02-26 Thread Lucas Raab
Robert Kern wrote:
Lucas Raab wrote:
Is it possible to assign a string a numerical value?? For example, in 
the string "test" can I assign a number to each letter as in "t" = 45, 
"e" =  89, "s" = 54, and so on and so forth??

Use a dictionary with the strings as keys.
string2num = {}
string2num['t'] = 45
string2num['e'] = 89
etc.
Thanks. That's what I was looking for, but was just unsure exactly how 
to proceed.
--
http://mail.python.org/mailman/listinfo/python-list



[perl-python] generate all possible pairings

2005-02-26 Thread Xah Lee
20050226 exercise: generate all possible pairings

given a list that is a set partitioned into subsets, generate a list
of all possible pairings of elements in any two subset.

Example:

 genpair( [[9,1],[5],[2,8,7]] );

returns:

 [[5,8],[9,5],[1,5],[9,2],[9,7],[1,8],[1,7],[5,2],[1,2],[9,8],[5,7]]

(we do not assume the given set has order, so the result is not
ordered.)

Perl code and Python code will be posted in 2 days.

This is brought to you by the perl-python community. To subscribe, see
http://xahlee.org/perl-python/python.html

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


Re: Converting HTML to ASCII

2005-02-26 Thread Mike Meyer
Michael Spencer <[EMAIL PROTECTED]> writes:

> Mike Meyer wrote:
>
>> It also fails on tags with a ">" in a string in the tag. That's
>> well-formed but ill-used HTML.
>>  True enough...however, it doesn't fail too horribly:
>   >>> striptags("""the text""")
>   "'>the text"
>   >>>

Depends on your example:



and so on. Then again, early browsers actually did the same kind of
parsing as you do, so this type of thing is discouraged.

> and I think that case could be rectified rather easily, by stripping
> any content up to '>' in the result without breaking anything else.

Yes, but then what happens with:

 >text

?

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xlib in Python? I need XDrawString()

2005-02-26 Thread jepler
python-xlib may not see any development, but I used it recently with python 2.2
or 2.3, and don't remember any particular problems doing so.

you may want to give it a try, instead of dismissing it out of hand.

Jeff


pgpEbkioBp45P.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Xlib in Python? I need XDrawString()

2005-02-26 Thread Mike Meyer
Artificial Life <[EMAIL PROTECTED]> writes:

> All I really want is to write a few strings to the background of my X
> display. XDrawString() is what I need. The Xlib for Python shows it's out
> dated. Is there any alternative? 

If you're referring to http://sourceforge.net/projects/python-xlib >, what makes you think
it's outdated? Development on a package sometimes stops when it
reaches a state that the authors are happy with - which is what's
happened here. It works just fine. If not, the authors can be reached
about bug fixes, etc.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] generate all possible pairings

2005-02-26 Thread Mike Meyer
"Xah Lee" <[EMAIL PROTECTED]> writes:

> This is brought to you by the perl-python community. To subscribe, see
> http://xahlee.org/perl-python/python.html

assert len(perl-python community) == 1

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting HTML to ASCII

2005-02-26 Thread Jorgen Grahn
On 26 Feb 2005 02:36:31 -0800, Paul Rubin <> wrote:
> Jorgen Grahn <[EMAIL PROTECTED]> writes:
>> You should probably do what some other poster suggested -- download
>> lynx or some other text-only browser and make your code execute it
>> in -dump mode to get the text-formatted html. You'll get that
>> working in an hour or so, and then you can see if you need something
>> more complicated.
> 
> Lynx is pathetically slow for large files.  It seems to use a
> quadratic algorithm for remembering where the links point, or
> something.  I wrote a very crude but very fast renderer in C that I
> can post if someone wants it, which is what I use for this purpose.

That may be so, but it's fast enough for all the people who use it as a
general html->plaintext tool, so it's probably good enough for the OP.

w3m and links are other options. They provide better formatting than lynx,
and at least w3m has the -dump option.

I wouldn't mind if there was a reusable library for rendering HTML to text,
from various languages. I'd also like to see one (CSS-aware) for rendering
to troff or Postscript.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] generate all possible pairings

2005-02-26 Thread Chris Mattern
Mike Meyer wrote:

> "Xah Lee" <[EMAIL PROTECTED]> writes:
> 
>> This is brought to you by the perl-python community. To subscribe, see
>> http://xahlee.org/perl-python/python.html
> 
> assert len(perl-python community) == 1
> 
>http://mail.python.org/mailman/listinfo/python-list


string methods (warning, newbie)

2005-02-26 Thread anthonyberet
Is there a string mething to return only the alpha characters of a string?
eg 'The Beatles - help - 03 - Ticket to ride', would be 
'TheBeatlesTickettoride'

If not then how best to approach this?
I have some complicated plan to cut the string into individual 
characters and then concatenate a new string with the ones that return 
true with the .isalpha string method.

Is there an easier way?
--
http://mail.python.org/mailman/listinfo/python-list


Re: fdups: calling for beta testers

2005-02-26 Thread John Machin
On Sat, 26 Feb 2005 23:53:10 +0100, Patrick Useldinger
<[EMAIL PROTECTED]> wrote:

> I've tested it intensively

"Famous Last Words" :-)

>Thanks for your feedback!

Here's some more:

(1) Manic s/w producing lots of files all the same size: the Borland
C[++] compiler produces a debug symbol file (.tds) that's always
384KB; I have 144 of these on my HD, rarely more than 1 in the same
directory.

Here's a snippet from a duplicate detection run:

DUP|393216|2|\devel\delimited\build\lib.win32-1.5\delimited.tds|\devel\delimited\build\lib.win32-2.1\delimited.tds
DUP|393216|2|\devel\delimited\build\lib.win32-2.3\delimited.tds|\devel\delimited\build\lib.win32-2.4\delimited.tds

(2) There appears to be a flaw in your logic such that it will find
duplicates only if they are in the *SAME* directory and only when
there are no other directories with two or more files of the same
size. The above duplicates were detected only when I made the
following changes to your script:


--- fdups   Sat Feb 26 06:41:36 2005
+++ fdups_jm.py Sun Feb 27 12:18:04 2005
@@ -29,13 +29,14 @@
 self.count = self.totalsize = self.inodecount =
self.slinkcount = 0
 self.gain  = self.bytescompared = self.bytesread  =
self.inodecount = 0
 for toplevel in args:
-os.path.walk(toplevel, self.buildList, None)
+os.path.walk(toplevel, self.updateDict, None)
 if self.count > 0:
 self.compare()

-def buildList(self,arg,dirpath,namelist):
-""" build a dictionnary of files to be analysed, indexed by
length """
-files = {}
+def updateDict(self,arg,dirpath,namelist):
+""" update a dictionary of files to be analysed, indexed by
length """
+# files = {}
+files = self.compfiles
 for filepath in namelist:
 fullpath = os.path.join(dirpath,filepath)
 if os.path.isfile(fullpath):
@@ -51,20 +52,23 @@
 if  size >= MIN_FILESIZE:
 self.count += 1
 self.totalsize += size
+# is above totalling in the wrong place?
 if size not in files:
 files[size]=[fullpath]
 else:
 files[size].append(fullpath)
-for size in files:
-if len(files[size]) != 1:
-self.compfiles[size]=files[size]
+# for size in files:
+# if len(files[size]) != 1:
+# self.compfiles[size]=files[size]

 def compare(self):
 """ compare all files of the same size  - outer loop """
 sizes=self.compfiles.keys()
 sizes.sort()
 for size in sizes:
-self.comparefiles(size,self.compfiles[size])
+list_of_filenames = self.compfiles[size]
+if len(list_of_filenames) > 1:
+   self.comparefiles(size, list_of_filenames)

 def comparefiles(self,size,filelist):
 """ compare all files of the same size  - inner loop """


(3) Your fdups-check gadget doesn't work on Windows; the commands
module works only on Unix but is supplied with Python on all
platforms. The results might just confuse a newbie:

(1, "'{' is not recognized as an internal or external
command,\noperable program or batch file.")

Why not use the Python filecmp module?

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


Re: string methods (warning, newbie)

2005-02-26 Thread anthonyberet
anthonyberet wrote:
Is there a string mething [method] to return only the alpha characters of a string?
eg 'The Beatles - help - 03 - Ticket to ride', would be 
'TheBeatlesTickettoride' 

erm, no it wouldn't, it would be 'TheBeatleshelpTickettoride', but you 
get me, I am sure.

If not then how best to approach this?
I have some complicated plan to cut the string into individual 
characters and then concatenate a new string with the ones that return 
true with the .isalpha string method.

Is there an easier way?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dealing with config files what's the options

2005-02-26 Thread Jorgen Grahn
On Fri, 25 Feb 2005 21:54:16 -0500, Tom Willis <[EMAIL PROTECTED]> wrote:
> On Fri, 25 Feb 2005 15:02:04 -0700, Dave Brueck
> <[EMAIL PROTECTED]> wrote:
>> Jorgen Grahn wrote:
...
>> > How about writing them in Python?
...
> I actually thought of this, and I was kind of on the fence due to the
> intended audience.
>
> I don't think it's too much to ask that they are comfy with the
> concept of variables. I mean, if it was a shell script they'd be at
> the top of the file anyway.
> 
> Then again I'm some what hesitant to help them make the connection
> that I'm giving them the ability to indirectly edit the code. Kind of
> like opening pandoras box. Once the figure out they can open any file
> (*.py) with notepad, there will be utter anarchy and I'll get the call
> at 4am that somethings wrong with the production data.

There's two issues there.

One is about hiding knowledge from the users.  I'm against that; this isn't
the middle ages. If they shoot themselves in the foot, that is /their/
problem, not yours. You support /your/ code, not whatever they hack together.
And with 99.999% certainty, they won't touch it.

The other is about the config file messing up the environment for your main
program. Seems hard to do by mistake -- you'd have to write endless loops or
import modules and modify them, or someting. I seem to recall that you can
evaluate a piece of code in a separate environment/sandbox -- maybe that's
the way to go?

(Personally, I try to avoid designs which need config files. If I /did/ need
one I'd steal the design from some well-known Unix program, because that's
my primary target, and I'd prefer not to lock myself into Python -- I might
want to rewrite the thing in C, or Perl, or ...)

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thread scheduling

2005-02-26 Thread Peter Hansen
Jack Orenstein wrote:
Peter Hansen wrote:
 > You've got two shared global variables, "done" and "counter".
 > Each of these is modified in a manner that is not thread-safe.
 > I don't know if "counter" is causing trouble, but it seems
 > likely that "done" is.
I understand that. 

 > Basically, the statement "done += 1" is equivalent to the
 > statement "done = done + 1" which, in Python or most other
 > languages is not thread-safe.  

Understood. I was counting on this being unlikely for my test
case. I realize this isn't something to rely on in real software.
Hmm... okay.  I may have been distracted by the fact that your
termination condition is based on "done" incrementing properly,
and that it was possible this wouldn't happen because of the race
condition.  So, if I understand you now, you're saying that the
reason "done" doesn't increment is actually because one of the
threads is never finishing properly, for some reason not related
to the code itself. (?)
The point of the
test is not to maintain counter -- it's to show that sometimes even
after one thread completes, the other thread never is scheduled
again. This seems wrong. Try running the code, and let me see if you
see this behavior.
On my machines (one Py2.4 on WinXP, one Py2.3.4 on RH9.0) I don't
see this behaviour.  Across about fifty runs each.
And the two increments of done (one by each thread) are still
almost certainly not going to coincide and cause a problem. Also, if
you look at the output from the code on a hang, you will see that
'thread X: leaving' only prints once. This has nothing to do with what
happens with the done variable.
Okay, I believe you.  As I said, I hadn't taken the time to read
through everything at first, jumping on an "obvious" bug related
to the "done" variable not meeting your termination conditions.
I can see that something else is likely to be causing this.
One thing you might try is experimenting with sys.setcheckinterval(),
just to see what effect it might have, if any.
It's also possible there were some threading bugs in Py2.2 under
Linux.  Maybe you could repeat the test with a more recent
version and see if you get different behaviour.  (Not that that
proves anything conclusively, but at least it might be a good
solution for your immediate problem.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: string methods (warning, newbie)

2005-02-26 Thread Peter Hansen
anthonyberet wrote:
Is there a string mething to return only the alpha characters of a string?
eg 'The Beatles - help - 03 - Ticket to ride', would be 
'TheBeatlesTickettoride'

If not then how best to approach this?
I have some complicated plan to cut the string into individual 
characters and then concatenate a new string with the ones that return 
true with the .isalpha string method.

Is there an easier way?
Look into the string module's "translate" function.  It will
do this for you fairly easily.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting HTML to ASCII

2005-02-26 Thread Grant Edwards
On 2005-02-26, Paul Rubin  wrote:
> Jorgen Grahn <[EMAIL PROTECTED]> writes:
>> You should probably do what some other poster suggested -- download
>> lynx or some other text-only browser and make your code execute it
>> in -dump mode to get the text-formatted html. You'll get that
>> working in an hour or so, and then you can see if you need something
>> more complicated.
>
> Lynx is pathetically slow for large files.

First, make it work.  Then make it work right.  Then worry
about how fast it is.  

"Premature optimization..."

> It seems to use a quadratic algorithm for remembering where
> the links point, or something.  I wrote a very crude but very
> fast renderer in C that I can post if someone wants it, which
> is what I use for this purpose.

If lynx really is too slow, try w3m or links.  Both do a better
job of rendering anyway.

-- 
Grant Edwards   grante Yow!  I know how to do
  at   SPECIAL EFFECTS!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: string methods (warning, newbie)

2005-02-26 Thread Jimmy Retzlaff
Anthonyberet wrote:
> Is there a string mething to return only the alpha characters of a
string?
> eg 'The Beatles - help - 03 - Ticket to ride', would be
> 'TheBeatlesTickettoride'
> 
> If not then how best to approach this?
> I have some complicated plan to cut the string into individual
> characters and then concatenate a new string with the ones that return
> true with the .isalpha string method.
> 
> Is there an easier way?

The approach you are considering may be easier than you think:

>>> filter(str.isalpha, 'The Beatles - help - 03 - Ticket to ride')
'TheBeatleshelpTickettoride'

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


Re: string methods (warning, newbie)

2005-02-26 Thread Terry Reedy

"anthonyberet" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Is there a string mething to return only the alpha characters of a 
> string?
> eg 'The Beatles - help - 03 - Ticket to ride', would be 
> 'TheBeatlesTickettoride'

I believe you can do this with string.translate (string module, not str())

tjr



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


Re: Thread scheduling

2005-02-26 Thread Jack Orenstein
On my machines (one Py2.4 on WinXP, one Py2.3.4 on RH9.0) I don't
see this behaviour.  Across about fifty runs each.
Thanks for trying this.
One thing you might try is experimenting with sys.setcheckinterval(),
just to see what effect it might have, if any.
That does seem to have an impact. At 0, the problem was completely
reproducible. At 100, I couldn't get it to occur.
It's also possible there were some threading bugs in Py2.2 under
Linux.  Maybe you could repeat the test with a more recent
version and see if you get different behaviour.  (Not that that
proves anything conclusively, but at least it might be a good
solution for your immediate problem.)
2.3 (on the same machine) does seem better, even with setcheckinterval(0).
Thanks for your suggestions.
Can anyone with knowledge of Python internals comment on these results?
(Look earlier in the thread for details. But basically, a very simple
program with the thread module, running two threads, shows that on
occasion, one thread finishes and the other never runs again. python2.3
seems better, as does python2.2 with  sys.setcheckinterval(100).)
Jack
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making a calendar

2005-02-26 Thread Brian Sutherland
On Sat, Feb 26, 2005 at 01:57:20PM +0100, Pete. wrote:
> I'm trying to make a calendar for my webpage, python and html is the only 
> programming languages that I know, is it possible to make such a calendar 
> with pythong code and some html.
> 
> The Idea is that when I click the link calendar on my webpage, then the user 
> will be linked to the calendar.
> 
> The calendar should show one month at the time, and the user should be able 
> to browse to the other month.
> 
> I will make a script that puts events and such into a db ( I know how to do 
> this)
> 
> Then I need a script that puts the events from the db into the calendar, if 
> every day in the calendar has a value id that part will not be hard.

All this and more (perhaps overkill):

http://www.schooltool.org/schoolbell

-- 
Brian Sutherland

It's 10 minutes, 5 if you walk fast.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thread scheduling

2005-02-26 Thread Peter Hansen
Jack Orenstein wrote:
One thing you might try is experimenting with sys.setcheckinterval(),
just to see what effect it might have, if any.
That does seem to have an impact. At 0, the problem was completely
reproducible. At 100, I couldn't get it to occur.
If you try other values in between, can you directly affect
the frequency of the failure?  That would appear to suggest
a race condition.
It's also possible there were some threading bugs in Py2.2 under
Linux.  Maybe you could repeat the test with a more recent
version and see if you get different behaviour.  (Not that that
proves anything conclusively, but at least it might be a good
solution for your immediate problem.)
2.3 (on the same machine) does seem better, even with setcheckinterval(0).
The default check interval was changed from 10 in version 2.2
and earlier to 100 in version 2.3.  (See 
http://www.python.org/2.3/highlights.html for details.)

On the other hand, with version 2.3.4 under RH9, I tried values
of 10 and 1 with no failures at any time.  This might still
be an issue with your own particular system, so having others
try it out might be helpful...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Nick Coghlan
Just wrote:
(Hm, I had the impression that scipy != Konrad Hinsen's Scientific 
module.)
You're probably right :)
I had played with [1], but it "only" calculates one root, and I need all 
roots (specifically, for a quintic equation). [2] doesn't seem to be a 
solver?
Actually, I was curious whether the 'zeros' method in [2] did the right 
thing.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-02-26 Thread Nick Coghlan
Xah Lee wrote:
Python doc is quite confounded in it's way of organization centered
around implementation tied to hardware (as most imperative languages
are hardware-centric), as opposed to algorithm math concepts.
Actually, Python's docs are centred around the fact that they expect people to 
start out by at least skimming the freaking tutorial. . .

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: string methods (warning, newbie)

2005-02-26 Thread Nick Coghlan
Jimmy Retzlaff wrote:
The approach you are considering may be easier than you think:

filter(str.isalpha, 'The Beatles - help - 03 - Ticket to ride')
'TheBeatleshelpTickettoride'
Hmm, I think this is a case where filter is significantly clearer than the 
equivalent list comprehension:

Py> "".join([c for c in 'The Beatles - help - 03 - Ticket to ride' if c.isalpha(
)])
'TheBeatleshelpTickettoride'
Py>
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Is it possible to pass a parameter by reference?

2005-02-26 Thread Anthony Liu
I defined two functions, f1 and f2.  

f1 modifies the value of a variable called apple.

I want to pass the modified value of apple to f2.

How can I do this?  I got stuck.




__ 
Do you Yahoo!? 
Yahoo! Mail - You care about security. So do we. 
http://promotions.yahoo.com/new_mail
-- 
http://mail.python.org/mailman/listinfo/python-list


PyUnit and multiple test scripts

2005-02-26 Thread Calvin Spealman
I'm trying to find the best way to use PyUnit and organize my test scripts.
What I really want is to separate all my tests into 'test' directories
within each module of my project. I want all the files there to define a
'suite' callable and to then all all those suites from all those test
directories into one big suite and run it all. I'm having trouble with
this.

My first barrier was just loading the modules. As I had to be able to find
them automatically (would be tedious to maintain a manual list of them) I
needed to then load the modules from the paths to the files after I found
them. This wasn't working, I just couldn't get it to load. I couldn't
understand the imp module correctly.

1) Is there a very simple way to just take a file path and name, that I
could use to open the source file, and load it as a module object, no
strings attached?

2) Is there already a framework around that will do what I need?

I've tried py.test, but I really do not like the way it displays results.

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


Re: Is it possible to pass a parameter by reference?

2005-02-26 Thread M.E.Farmer
Anthony Liu wrote:
> I defined two functions, f1 and f2.
>
> f1 modifies the value of a variable called apple.
>
> I want to pass the modified value of apple to f2.
>
> How can I do this?  I got stuck.


Py>def f1(apple):
...apple += 1
...f2(apple)

py>def f2(apple):
...print 'you have %s apples' % apple

py>f1(4)
'you have 5 apples'
Read the docs this is pretty basic, it will save you time.
If in doubt try it out.
Use the interpreter, it is your friend.
hth,
M.E.Farmer

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


Re: Problem When Unit Testing with PMock

2005-02-26 Thread steven
> def mockit(): raise StopIteration
> now pass mockit()

but it behaviors differenctly when pass in a mockit()  and pass in an
iterator with empty.  so i think the code emulates nothing.

> def intit(k):
>  for i in range(k): yield i

Now you mean define my own iteration without the help of pmock.   but
there are still so many other methods in the iterator for pass in,  i
have to mock them one by one totally manually, its boring and thats the
reason why i want pmock.

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


parse lines to name value pairs

2005-02-26 Thread sunriselee
Hi all,

I want to parse some string lines into name value pairs, where the value
will be a list. Here are some sample lines:

line1 = """path {{data/tom} C:/user/john}"""
line2 = """books{{book music red} {book {math 1}
blue} {book {tom's book} green}}"""

For line1, the name is "path", the name-value should be the following
forms:

["path", ["data/tom", "C:/user/john"]]

For line 2, the name is "books", and the value should be a list in either
one of the following forms (either one is ok):

["books", [["book","music","red"],["book","math 1","blue"],["book", "tom's
book", "green"]]]

or

["books", ["book","music","red","book","math 1","blue","book", "tom's
book", "green"]]

Any ideas?

Many thanks!

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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-02-26 Thread Carl Banks
Just wrote:
> While googling for a non-linear equation solver, I found
> Math::Polynomial::Solve in CPAN. It seems a great little module,
except
> it's not Python... I'm especially looking for its poly_root()
> functionality (which solves arbitrary polynomials). Does anyone know
of
> a Python module/package that implements that?

If you don't have a great need for speed, you can accomplish this
easily with the linear algebra module of Numeric/numarray.   Suppose
your quintic polynomial's in the form

   a + b*x + c*x**2 + d*x**3 + e*x**4 + x**5

The roots of it are equal to the eigenvalues of the companion matrix:

  0   1   0   0   0
  0   0   1   0   0
  0   0   0   1   0
  0   0   0   0   1
 -a  -b  -c  -d  -e

It should be pretty easy to set up a Numeric matrix and call
LinearAlgebra.eigenvalues.  For example, here is a simple quintic
solver:

. from Numeric import *
. from LinearAlgebra import *
.
. def quinticroots(p):
. cm = zeros((5,5),Float32)
. cm[0,1] = cm[1,2] = cm[2,3] = cm[3,4] = 1.0
. cm[4,0] = -p[0]
. cm[4,1] = -p[1]
. cm[4,2] = -p[2]
. cm[4,3] = -p[3]
. cm[4,4] = -p[4]
. return eigenvalues(cm)


now-you-can-find-all-five-Lagrange-points-ly yr's,

-- 
CARL BANKS

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


simple input that can understand special keys?

2005-02-26 Thread Gabriel B.
i'm writting an application that will use Tinker in a newer future.
Now it's console only. I simply ommit some data on the display,
print() some other and go on. The problem is that i can't test the
actions tiggered by special keys, like Page Up/Down or the F1...12

Right now i'm using raw_input() since even the Tk version will have
only one input place, and for debuging i'm literally writting pageup,
pagedow and the F's. But i want to put it in test while i write the
GUI.

is there any hope for me? I wanted to stay only with the console for
now. And it's windows by the way :)

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


  1   2   >