Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread M Jared Finder
Alex Martelli wrote:
> Stefan Nobis <[EMAIL PROTECTED]> wrote:
> 
>> [EMAIL PROTECTED] (Alex Martelli) writes:
>>
>>> if anonymous functions are available, they're used in even more
>>> cases where naming would help
>> Yes, you're right. But don't stop here. What about expressions? Many
>> people write very complex expression, that are hard to understand. A
>> good language should forbid these abuse and don't allow expressions
>> with more than 2 or maybe 3 operators!
> 
> That would _complicate_ the language (by adding a rule).  I repeat what
> I've already stated repeatedly: a good criterion for deciding which good
> practices a language should enforce and which ones it should just
> facilitate is _language simplicity_.  If the enforcement is done by
> adding rules or constructs it's probably not worth it; if the
> "enforcements" is done by NOT adding extra constructs it's a double win
> (keep the language simpler AND push good practices).

Your reasoning, taken to the extreme, implies that an assembly language, 
by virtue of having the fewest constructs, is the best designed language 
ever.  But we know that not to be the case -- rarely do even embedded 
developers program in assembly language any more.  Why?

Because assembly language is so simple that it's very tedious to write. 
   There's no function call primitive -- you have to manually generate a 
function call pattern yourself.  There's no looping primitive -- you 
have to manually generate a looping pattern yourself.  I feel sorry for 
the person who's debugging an assembly program using manually generated 
code that implements a vtable-based dynamic dispatch.

Any feature that allows me to write less code to do the same thing has a 
huge positive -- the reduction of human generated, and therefore error 
prone, code.  I think the advantages of anonymous functions:
a) explicitly documenting that the function is used in only one place
b) enabling generic iteration and looping routines
c) not having to maintain a unique name for the function
d) making the language more elegant
e) making the language simpler to implement
greatly outweigh the small disadvantage of adding one additional 
construct to the language.

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Petr Prikryl
"Alex Martelli" wrote...
> Joe Marshall  wrote:
>...
> > If you language allows unnamed integers, unnamed strings, unnamed
> > characters, unnamed arrays or aggregates, unnamed floats, unnamed
> > expressions, unnamed statements, unnamed argument lists, etc.  why
> > *require* a name for trivial functions?

Event the trivial function can have a name. Does it make
the trivial function more understandable if I do not give a name?
I understand what lambda means, but it is clearer for me to see
something like (with more meaningful name than shown here):

>>> def fn(x):
... return x + 5

and to use it like...

>>> fn(3)
8

Still, I can anonymize it later, if I really need

>>> a = [fn]

or I can give it another name

   >>> z = fn

In my opinion, the cry for lambda in Python comes
from people used to functional languages, because
they are not used to the procedural style and it
does not fit them at the beginning.
Frankly, functional style seems "more strange" to me
(i.e. the counter example). Still, I do not say it is bad.
But it never came to my mind to say "Please, rewrite
the LISP so that it looked more like Pascal. I do not like
the lambda."

Also, Python is compiled (to bytecode), imperative language,
and the form of definition of the chunks of code is more
natural to the compiler and to the customs
how the procedural program is written and how its parts
are referenced and put together to form bigger chunks
of code.

> I think it's reasonable to make a name a part of functions, classes and
> modules because they may often be involved in tracebacks (in case of
> uncaught errors): to me, it makes sense to let an error-diagnosing
> tracebacks display packages, modules, classes and functions/methods
> involved in the chain of calls leading to the point of error _by name_.

I agree with Alex here. I USUALLY do not need debugger, but sometimes
it is exremely handy to discover what happens (through debugger or few
print commands, its a matter of taste). And Python is very fine here:

>>> dir(fn)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__',
'__getattribute__', '__hash__', '__init__', '__module__', '__name__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
'func_doc', 'func_globals', 'func_name']
>>> fn.__name__
'fn'

and even the anonymized function still knows its original name and type

>>> a[0].__name__
'fn'
>>> type(a[0])


If lambda functions in Python are tweaked internally into normal Python
functions...

>>> z = lambda x: x * 3
>>> dir(z)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__',
'__getattribute__', '__hash__', '__init__', '__module__', '__name__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
'func_doc', 'func_globals', 'func_name']
>>> z.__name__
''
>>> type(z)


... what makes them better, than the named function? If I do not loose
anything by simplification, I want to have it simpler.

pepr


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


Re: Incrementally converting a C app to Python

2006-05-09 Thread G. Monzón
Hi Bjorn,

I think the best approach is highly-dependent to your current C
application design and "way of doing things". For a type of application
you would take the opposite path than for other I thought.

Yes I did that one time, but I re-coded all from scratch... and since
that I usually do in reverse: code in Python, then optimize if needed
in C via pyrex coded extensions and glue.

If you don't know well the current application internals, both
approaches can be harder: to convert step by step to python or
re-implement from scratch. You need to know well what is doing there
that pretty hard to read code for being sure for success and good
starting guidelines.

I thought If your app doesn't have very critical parts, and if you
really know what the application is doing "inside", I would bet for a
complete reimplementation from scratch. More if you say current C code
has a lots of bugs! And all the code you need to be in C, can be easily
done via pyrex, ctypes, etc. Have in mind I don't know your
application!

Swig is harder, is more suited to export whole libraries to between
languages. Anyway, I'm no expert with Swig! :-)

Regards,
Gonzalo Monzón.

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


Re: Deferred Evaluation in Recursive Expressions?

2006-05-09 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> That's a good fix. But I have misgivngs about needing a global name
> registry. I need to support anonymous types and types with local
> (lexical) scope. For example:
> 
> def makeAnonymousRecursiveType(T):
> # anonymous type expression with local scope
> LinkedList = (T, lambda: LinkedList)
> return LinkedList
> 
> local = makeAnonymousRecursiveType(int)

class Names(object):
def __getattribute__(self, name):
return name

types = Names()

class Type(type):
all = {}
def __new__(mcl, name, bases, dict):
assert "_typedef" not in dict
dict["_typedef"] = dict.pop("typedef", ())
cls = type.__new__(mcl, name, bases, dict)
cls.all[name] = cls
return cls
def get_typedef(cls):
def get(item):
result = cls.all.get(item)
if result is None:
result = type(cls).all.get(item, item)
return result
return tuple(get(item) for item in cls._typedef)
def set_typedef(cls, value):
cls._typedef = value
typedef = property(get_typedef, set_typedef)

class TypeDef:
__metaclass__ = Type

class LinkedListA(TypeDef):
typedef = (int, types.LinkedListB)

class LinkedListB(TypeDef):
typedef = (int, types.LinkedListA)

print LinkedListA.typedef
print LinkedListB.typedef
print LinkedListA.typedef

def LocalTypeDef():
class LocalTypeDef(TypeDef):
all = {}
return LocalTypeDef

def makeAnonymousRecursiveType(T):
class LinkedList(LocalTypeDef()):
typedef = (T, types.LinkedList)
return LinkedList

print makeAnonymousRecursiveType(int).typedef
print makeAnonymousRecursiveType(str).typedef

Go with lambda, I'd say...

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread G. Monzón

Carl Banks wrote:
> G. Monzón wrote:
> > Please don't compare PHP with Python... They are very different worlds.
>
> I'm not.  I was simply agreeing that the single executable way the OP
> claimed PHP does it can *sometimes* be preferrable in Python, and
> giving him recommendations thereto.
>
> Carl Banks

Sorry Carl, my reply was for the OP. I pressed the wrong reply
button... doesn't meant you did any comparation!

I said that about comparing, as the OP thought Python coded in Python
approach for a lot of core libraries isn't as efficient as in PHP
'cause they are all coded in C. And that's not true.

Yes, it could be obvious for some people that it "should" run faster
than Python, having all core functions coded in C, yes, but in overall
performance matters, that's not true in any case.

Python has all the primitives C coded as said in this thread. PHP
"primitives" are no more than hash-tables and lots zvals... far away
from the hi-tuned advanced data-types Python exposes. That makes a big
performance improvement over PHP, regards C or Python coded core
functions -let language implementation details apart-. Major loss of
performance in Python and PHP is on translating data values to C side
and all the functions calling done for as little as a value assignment
to a variable. So, sometimes, to code a function in C or let it be
Python, makes no more than a 1us per call difference...
I'd like to see this value compared to PHP. That's why PHP need a C
implementation for all core functions, as if they would be PHP coded,
performance would be even a lot worse.

And I would't say PHP is slow. But It depends on what you need to do.
'Cause PHP can be really slow and ultra-high memory consuming. While
you had this troubles with PHP, is nice to see how Python performs:
consumes a lot less of memory and goes 50 % more fast.

About a single executable file, I thought PHP is being distributed in
windows and linux as an executable plus an dinamic link library, that's
the minimum thing you need to run scripts. So OP is wrong, there is not
a single executable file. You need two files at least + php.ini +
extensions to run almost any PHP script.

And a PHP or Python without extensions or batteries, wouldn't be very
handy... oh well, that depends on the task to do.

Anyway, PHP isn't a bad tool for a *lot* of web-side scripting, but I'd
prefer if I could use Python in many of my work projects. :-) I'd feel
happier !

Regards,
Gonzalo.

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


Re: Is PythonCard dead?

2006-05-09 Thread Luis M. González
18 months? Wow!.. time flies...
Anyway, PythonCard is a fine product, and it's very good just the way
it is.
It would be great if a new release comes up though...

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread Ravi Teja
Addendum:
Python has zip imports (similar to Java's jar files). You can put all
your *.py files in a zip file and access them from it if this means so
much to you.

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


Re: SciPy - I need an example of use of linalg.lstsq()

2006-05-09 Thread Robert Kern
I. Myself wrote:
> And it has to run on Windows, so it can't use xplt.

Huh?

A. xplt runs on Windows, too.
B. xplt has nothing to do with linalg.lstsq().
C. xplt has been removed from scipy.

> I would prefer that it use the simplest multi-dimensional model, z = k + 
> a*x1 + b*x2 + c*x3 + d*x4

In [1]: import numpy as np

In [2]: np.linalg.lstsq?
Type:   function
Base Class: 
String Form:
Namespace:  Interactive
File:
/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/numpy-0.9.7.2476-py2.4-macosx-10.4-ppc.egg/numpy/linalg/linalg.py
Definition: np.linalg.lstsq(a, b, rcond=1e-10)
Docstring:
returns x,resids,rank,s
where x minimizes 2-norm(|b - Ax|)
  resids is the sum square residuals
  rank is the rank of A
  s is the rank of the singular values of A in descending order

If b is a matrix then x is also a matrix with corresponding columns.
If the rank of A is less than the number of columns of A or greater than
the number of rows, then residuals will be returned as an empty array
otherwise resids = sum((b-dot(A,x)**2).
Singular values less than s[0]*rcond are treated as zero.


In [3]: z = np.rand(10)

In [4]: x1 = np.rand(10)

In [5]: x2 = np.rand(10)

In [6]: x3 = np.rand(10)

In [7]: x4 = np.rand(10)

In [8]: A = np.column_stack([x1, x2, x3, x4, np.ones(10, float)])

In [9]: A
Out[9]:
array([[ 0.07257264,  0.36544251,  0.68467294,  0.3381,  1.],
   [ 0.09520828,  0.27102091,  0.04673061,  0.12905473,  1.],
   [ 0.839834  ,  0.46010114,  0.3949568 ,  0.38983012,  1.],
   [ 0.49776387,  0.70666191,  0.85005579,  0.47738743,  1.],
   [ 0.25457977,  0.93335912,  0.88441593,  0.05255062,  1.],
   [ 0.85982216,  0.97920853,  0.27991214,  0.94230651,  1.],
   [ 0.03224487,  0.1275237 ,  0.66943552,  0.320765  ,  1.],
   [ 0.86807363,  0.63800103,  0.67153924,  0.69125023,  1.],
   [ 0.26571213,  0.68845408,  0.06478114,  0.03657494,  1.],
   [ 0.46615143,  0.99464106,  0.9303421 ,  0.61363703,  1.]])

In [10]: np.linalg.lstsq(A, z)
Out[10]:
(array([-0.32421087, -0.23330787,  0.13369118, -0.28334431,  0.84010014]),
 array([ 0.22958042]),
 5,
 array([ 4.59505886,  1.1181838 ,  0.85704672,  0.70211311,  0.4420187 ]))


If you have more scipy questions, you will probably want to ask on the
scipy-user list:

  http://www.scipy.org/Mailing_Lists

-- 
Robert Kern

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

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread Ravi Teja
PHP and Python are different languages. They do things differently. You
are just familiar more with one than the other. Give it some time.

The many file approach is the modular design of Python. Having the
standard library separate from the main Python DLL is an advantage, not
a disadvantage. For example, it allows me to pick just the libraries I
want to distribute when I make a single file executables. It allows me
to distribute just the parts of the standard library I want when I
embed Python in another application. Not to mention being able to debug
right into the source.

Most languages take the Python approach. Have you looked at your C
compiler and counted the include and library files? Have you seen Perl
or Ruby to check how their library is distributed? I can think of only
a few languages that take the PHP approach... early BASIC interpreters,
Shells, DSLs and some lesser known interpreters and compilers... none
of which are exactly reputed to be flexible.

How is manually copying files and editing configuration files easier
than clicking through standard distutils installers or typing "setup
install" or better ... using eggs through EasyInstall? BTW, you can
manually copy Python libraries too in most cases to install and PEAR
does offer a package manager for PHP.

Installation has never been a problem for me with Python, if not the
easiest. In fact, among the languages I regularly use, Python is the
only one that includes installer support right in the standard library
(distutils) and I find it surprising that you managed to find it
wanting all because there are more files :-).

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


SciPy - I need an example of use of linalg.lstsq()

2006-05-09 Thread I. Myself
And it has to run on Windows, so it can't use xplt.

I would prefer that it use the simplest multi-dimensional model, z = k + 
a*x1 + b*x2 + c*x3 + d*x4

Anyone have such a thing?

Thanks,

Mitchell Timin

-- 
I'm proud of http://ANNEvolve.sourceforge.net.  If you want to write software,
or articles, or do testing or research for ANNEvolve, let me know.

Humans may know that my email address is: (but remove the 3 digit number)
zenguy at shaw666 dot ca


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


Re: Deferred Evaluation in Recursive Expressions?

2006-05-09 Thread birchb
If we -are- limited to lambdas, I see two options. Either embed lambdas
for each circular link, or have the whole expression in one lambda. ie

LinkedList3 = (int, lambda: LinkedList3, lambda: TypeNameX)

vs

LinkedList2 = lambda: (int, LinkedList2, TypeNameX)

The second option looks neater. Maybe both are OK?

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


optparse and counting arguments (not options)

2006-05-09 Thread Steven Bethard
I feel like I must be reinventing the wheel here, so I figured I'd post 
to see what other people have been doing for this.  In general, I love 
the optparse interface, but it doesn't do any checks on the arguments. 
I've coded something along the following lines a number of times:

 class OptionArgParser(optparse.OptionParser):
 def __init__(self, *args, **kwargs):
 self.min_args = kwargs.pop('min_args', None)
 self.max_args = kwargs.pop('max_args', None)
 self.arg_values = kwargs.pop('arg_values', None)
 optparse.OptionParser.__init__(self, *args, **kwargs)

 def parse_args(self, args=None):
 options, args = optparse.OptionParser.parse_args(self, args)
 if self.min_args is not None and len(args) < self.min_args:
 self.error('too few arguments')
 if self.max_args is not None and len(args) > self.max_args:
 self.error('too many arguments')
 if self.arg_values is not None:
 for arg, values in zip(args, self.arg_values):
 if values is not None and arg not in values:
 message = 'argument %r is not one of: %s'
 self.error(message % (arg, ', '.join(values)))
 return options, args

This basically lets me skip some simple checks by creating instances of 
OptionArgParser instead of optparse.OptionParser, and supplying my new 
options:

 parser = OptionArgParser(
 min_args=1, arg_values=[commands],
 usage='%%prog [options] (%s) ...' % '|'.join(commands),
 description='invoke one of the commands')

Is this problem already solved in some module that I've missed?

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread Carl Banks
G. Monzón wrote:
> Please don't compare PHP with Python... They are very different worlds.

I'm not.  I was simply agreeing that the single executable way the OP
claimed PHP does it can *sometimes* be preferrable in Python, and
giving him recommendations thereto.  

Carl Banks

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


Re: Deferred Evaluation in Recursive Expressions?

2006-05-09 Thread birchb
That's a good fix. But I have misgivngs about needing a global name
registry. I need to support anonymous types and types with local
(lexical) scope. For example:

def makeAnonymousRecursiveType(T):
# anonymous type expression with local scope
LinkedList = (T, lambda: LinkedList)
return LinkedList

local = makeAnonymousRecursiveType(int)

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


Reading Soap struct type

2006-05-09 Thread Thomas Thomas
Hi All,

I am receiving a hash below from my Soap Interface

: {'Field12value': ':C
F3Value', 'Field8': 'Price Text:price_text', 'Field9': 'Text with
File:file_text
', 'Field11value': ':CF2Value', 'Field7': 'Product Code:product_code',
'Field7va
lue': ':product_values', 'Field2': 'Job Reference:job_reference', 'Field3':
'Job
 Description:job_description', 'Field6': 'Campaign Name:campaign_name',
'Field10
value': ':CF1Value', 'Field6value': ':campaign_values', 'Field5':
'Keywords:keyw
ords', 'Field10': 'CF1Title:custom_field1', 'Field11':
'CF2Title:custom_field2',
 'Field12': 'CF3Title:custom_field3', 'Field13': 'CF4Title:custom_field4',
'Fiel
d14': 'Name:meta_filename', 'Field4': 'Display Name:display_name',
'Field13value
': ':CF4Value'}

How can i iterarte through it bcz when do try do something like
myHash.values()
I am getting the error
AttributeError: structType instance has no attribute 'values'

any help

Thomas

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


Re: __all__ does not work?

2006-05-09 Thread AndyL
[EMAIL PROTECTED] wrote:
> Andy> This a mm.py module:
> Andy> _all__=('getsize1',)
> 
> Andy> size=85
> 
> Andy> def getsize1():
> Andy>  return size
> 
> Andy> def getsize2():
> Andy>  return 2*size
> 
> 
> Andy> I do not know why but getsize2 is not kept priviate?
> 
> That's not what __all__ is used for.  Try this:
> 
> from mm import *
> 
> The only name added to your namespace will be getsize1.
> 
> Skip

Okay, got it. Thx.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problemi con POST

2006-05-09 Thread Alex Martelli
Heavy <[EMAIL PROTECTED]> wrote:

> Ciao a tutti,
> sto creando una applicazione in python, che deve fungere anche da
> server web...
> non ho assolutamente problemi a prendere i parametri di una 'GET', mi
> limito a fare il parsing della URL, ma come faccio a prendere i
> parametri di una 'POST'? io cerco di leggere dal socket di lettura
> 'rfile' ma poi resto bloccato all'infinito perché evidemente resta in
> attesa di qualcosaltro... c'è già qualche metodo che mi può
> aiutare?? oppure sapete darmi qualche dritta? grazie...

Riprova a it.comp.lang.python

Try again at it.comp.lang.python


Ciao,

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread G. Monzón
Please don't compare PHP with Python... They are very different worlds.

Maybe not all the Python's core functions are implemented in C, but
Python is really a lot more efficient than PHP in every case you want
to compare.

If you "look inside", there's nothing to compare... they are extremely
different worlds... they are like hell and heaven, from the awesome
brilliant C Python implementation, to the ugly C PHP hack... (after all
it is my personal opinion, I've worked with PHP for more than 4 years,
for websites and console scripting).

Python is more efficient than PHP in every aspect...  I don't know why
got (and still is) so popular, IMHO Python should have taken its place
as the best "web scripting language".

OTOH, my php install have lots more than a single executable file.
Perhaps you don't use any php extension? don't think so... do you use
pear? and pecl? you need lots of files too, and until you don't know
what do they are and what you need or not, you will be in the same
issue as you're with Python. I think you will get it early, as you
find everything is more straightforward than you thought.

Gonzalo Monzón.

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


Matplotlib in Python vs. Matlab, which one has much better graphical pressentation?

2006-05-09 Thread N/A
Hi all,

Can I have your opinions on Matlab vs. Matplotlib in Python in terms of 
2D and 3D graphical presentation please.

Matplotlib in Python vs. Matlab, which one has much better graphical 
pressentation?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Alex Martelli
Joe Marshall <[EMAIL PROTECTED]> wrote:

> Pisin Bootvong wrote:
> > Is this a Slippery Slope fallacious argument?
> > (http://c2.com/cgi/wiki?SlipperySlope)
> >
> > "if python required you to name every function then soon it will
> > require you to name every number, every string, every immediate result,
> > etc. And we know that is bad. Therefore requiring you to name your
> > function is bad So Python is bad"
> 
> No, it is a question about consistency.  Why are functions singled out?

They're not: packages, modules and classes also have names; as I pointed
out, the common factor among these four types is that instance of these
types are liable to occur in tracebacks &c, where a (good) name is
particularly useful as a summary reminder of what the thing is.


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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Alex Martelli
Paul Rubin  wrote:

> [EMAIL PROTECTED] (Alex Martelli) writes:
> > I think it's reasonable to make a name a part of functions, classes and
> > modules because they may often be involved in tracebacks (in case of
> > uncaught errors): to me, it makes sense to let an error-diagnosing
> > tracebacks display packages, modules, classes and functions/methods
> > involved in the chain of calls leading to the point of error _by name_.
> 
> But it would be even nicer if the traceback could point back to the
> exact location in the source code where the function definition
> occurred, and that wouldn't need any name for the function.

I believe a name is a useful "summary" or "conceptual handle" for a
thing, saving us from having to describe/analyze/recognize it in more
detail each and every time.  "Need" may be too strong a word, but I
maintain there's _usefulness_ (and reasonableness, and good common
sense) in the naming.


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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Alex Martelli
Joe Marshall <[EMAIL PROTECTED]> wrote:
   ...
> The problem is that a `name' is a mapping from a symbolic identifier to
> an object and that this mapping must either be global (with the
> attendant name collision issues) or within a context (with the
> attendant question of `in which context').

Why is that a problem?  Even for so-called "global" names, Python
supports a structured, hierarchical namespace, so there can never be any
collision betwen the "globals" of distinct modules (including modules
which happen to have the same name but live in distinct packages or
subpackages) -- I did mention that names could usefully be displayed in
some strcutured form such as apackage.somemodule.thefunction but perhaps
I was too tangential about it;-).


> Matthias Felleisen once suggested that *every* internal function should
> be named.  I just said `continuations'.  He immediately amended his
> statement with `except those'.

If I used continuations (I assume you mean in the call/cc sense rather
than some in which I'm not familiar?) I might feel the same way, or not,
but I don't (alas), so I can't really argue the point either way for
lack of real-world experience.

But if we can agree to name every function except continuations I'll be
content: Python doesn't support continuations, so it's consistent for it
to require every function to be named (since in its case "every
function" and "every function except continuations" coincide;-).


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


Re: Memory leak in Python

2006-05-09 Thread Karthik Gurusamy

[EMAIL PROTECTED] wrote:
> The amount of data I read in is actually small.
>
> If you see my algorithm above it deals with 2000 nodes and each node
> has ot of attributes.
>
> When I close the program my computer becomes stable and performs as
> usual. I check the performance in Performance monitor and using "top"
> and the total memory is being used and on top of that around half a gig
> swap memory is also being used.
>
> Please give some helpful pointers to overcome such memory errors.
>
> I revisited my code to find nothing so obvious which would let this
> leak happen. How to kill cross references in the program. I am kinda
> newbie and not completely aware of the finetuning such programming
> process.
>

I suspect you are trying to store each node's attributes in every other
node.
Basically you have a O(N^2) algorithm (in space and probably more in
time).
For N=2000, N^2 is pretty big and you see memory issues.

Try not to store O(N^2) information and see if you can just scale
memory requirements linearly in N. That is, see if you can store
attributes of a node at only one place per node.

I'm just guessing your implementation; but from what you say
(peer-to-peer), I feel there is a O(N^2) requirements. Also try
experimenting with small N (100 nodes say).

Thanks,
Karthik

> Thanks
>
>
> bruno at modulix wrote:
> > [EMAIL PROTECTED] wrote:
> > > I have a python code which is running on a huge data set. After
> > > starting the program the computer becomes unstable and gets very
> > > diffucult to even open konsole to kill that process. What I am assuming
> > > is that I am running out of memory.
> > >
> > > What should I do to make sure that my code runs fine without becoming
> > > unstable. How should I address the memory leak problem if any ? I have
> > > a gig of RAM.
> > >
> > > Every help is appreciated.
> >
> > Just a hint : if you're trying to load your whole "huge data set" in
> > memory, you're in for trouble whatever the language - for an example,
> > doing a 'buf = openedFile.read()' on a 100 gig file may not be a good
> > idea...
> >
> >
> >
> > --
> > bruno desthuilliers
> > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> > p in '[EMAIL PROTECTED]'.split('@')])"

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


Is PythonCard dead?

2006-05-09 Thread Steve
There haven't been any updates since version 0.8.1 in October 2004,
almost 18 months.  And the new book on wxPython doesn't say anything
about PythonCard, which I find rather surprising.

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


Re: interactive shell -- reload definitions?

2006-05-09 Thread James Stroud
Metalone wrote:
> I have a question about the interactive Python shell.  Is it possible
> to reload a file and get the new definitions.
> 
> For example, if I do
> import xyz
> 
> Then I find a bug in some function in xyz.
> So, I edit xyz.py
> 
> I would like to reload the definitions in xyz.py without leaving my
> current shell session.
> Is this possible?
> 
> 
> Also, is there any way to save definitions created in the interactive
> shell to a file?
> Sometimes I write a simple function in the shell, and this wish I had
> that function in an external file.
> 
> Thanks.
> 

Quoting my python interpreter:

"""
Help on built-in function reload:

reload(...)
 reload(module) -> module

 Reload the module.  The module must have been successfully imported 
before.
"""

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Paul Rubin
rydis (Martin Rydstr|m) @CD.Chalmers.SE writes:
> [Emacs] is written in Lisp, which is the only computer language that is
> beautiful.  -- Neal Stephenson, _In the Beginning was the Command Line_

I don't remember seeing these lyrics in the thread yet, but obviously
it's a requirement:

http://www.songworm.com/lyrics/songworm-parody/EternalFlame.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory leak in Python

2006-05-09 Thread diffuser78
The amount of data I read in is actually small.

If you see my algorithm above it deals with 2000 nodes and each node
has ot of attributes.

When I close the program my computer becomes stable and performs as
usual. I check the performance in Performance monitor and using "top"
and the total memory is being used and on top of that around half a gig
swap memory is also being used.

Please give some helpful pointers to overcome such memory errors.

I revisited my code to find nothing so obvious which would let this
leak happen. How to kill cross references in the program. I am kinda
newbie and not completely aware of the finetuning such programming
process.

Thanks


bruno at modulix wrote:
> [EMAIL PROTECTED] wrote:
> > I have a python code which is running on a huge data set. After
> > starting the program the computer becomes unstable and gets very
> > diffucult to even open konsole to kill that process. What I am assuming
> > is that I am running out of memory.
> >
> > What should I do to make sure that my code runs fine without becoming
> > unstable. How should I address the memory leak problem if any ? I have
> > a gig of RAM.
> >
> > Every help is appreciated.
>
> Just a hint : if you're trying to load your whole "huge data set" in
> memory, you're in for trouble whatever the language - for an example,
> doing a 'buf = openedFile.read()' on a 100 gig file may not be a good
> idea...
>
>
>
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"

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


Re: List of lists of lists of lists...

2006-05-09 Thread Robert Kern
James Stroud wrote:

> Numarray does this sort of thing, but you have to familiarize yourself 
> with its indexing conventions:
> 
> py> import numarray
> py> numarray.ones((3,2))
> array([[1, 1],
> [1, 1],
> [1, 1]])
> py> numarray.ones((1,2,3))
> array([[[1, 1, 1],
>  [1, 1, 1]]])

numpy is the successor to numarray, so if you are just starting with arrays,
please get started with numpy. It should also be noted that numpy can create
arrays of objects as well as arrays of numbers.

In [1]: from numpy import *

In [2]: empty((1,2,3), dtype=object)
Out[2]:
array([[[None, None, None],
[None, None, None]]], dtype=object)

http://numeric.scipy.org

-- 
Robert Kern

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

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


Re: __all__ does not work?

2006-05-09 Thread skip

Andy> This a mm.py module:
Andy> _all__=('getsize1',)

Andy> size=85

Andy> def getsize1():
Andy>  return size

Andy> def getsize2():
Andy>  return 2*size


Andy> I do not know why but getsize2 is not kept priviate?

That's not what __all__ is used for.  Try this:

from mm import *

The only name added to your namespace will be getsize1.

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


Re: multiline strings and proper indentation/alignment

2006-05-09 Thread John Salerno
Gary Herron wrote:
> Gary John Salerno wrote:
> 
>> How do you make a single string span multiple lines, but also allow 
>> yourself to indent the second (third, etc.) lines so that it lines up 
>> where you want it, without causing the newlines and tabs or spaces to be 
>> added to the string as well?
>>
>> Example (pretend this is all on one line):
>>
>> self.DTD = '> 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd";>\n\n'
>>
>> I want it to read:
>>
>> self.DTD = '''>"http://www.w3.org/TR/html4/strict.dtd";>\n\n'''
>>
>> Or anything like that, but I don't want the extra newline or tabs to be 
>> a part of the string when it's printed.
>>
>> Thanks.
>>  
>>
> The textwrap module has a function to do just the thing you want.  
> 
> *dedent*( text)
> 
> Remove any whitespace that can be uniformly removed from the left of
> every line in text.
> 
> This is typically used to make triple-quoted strings
> line up with the left edge of screen/whatever, while still
> presenting it in the source code in indented form.
> 
> Gary Herron
> 
> 

But does this do anything to the newline character that gets added to 
the end of the first line?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of lists of lists of lists...

2006-05-09 Thread James Stroud
Ángel Gutiérrez Rodríguez wrote:
> I would like to have a list of lists N times deep, and my solution is (in
> pseudocode):
> 
> def deep(x):
>   a=[x]
>   return a
> 
> mylist=[]
> for N: mylist=deep(mylist)
> 
> Is there a more elegant way to do it?
> 
> The maine idea is: from a list having the numbre of steps along N
> dimensions, generate a list with an item at each possible point.
> 
> Example 1: N=2  list=[2,3]  result=[[1,2],[1,2],[1,2]]
> Example 2: N=3  list=[3,1,2]  result=[[[1,2,3]],[[1,2,3]]]

Numarray does this sort of thing, but you have to familiarize yourself 
with its indexing conventions:

py> import numarray
py> numarray.ones((3,2))
array([[1, 1],
[1, 1],
[1, 1]])
py> numarray.ones((1,2,3))
array([[[1, 1, 1],
 [1, 1, 1]]])

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: hyperthreading locks up sleeping threads

2006-05-09 Thread Lialie KingMax

I haven't try the files yet. But have got a similar problem before. The
situation is nearly the same.
Always at random time , it reported that the memory read or write
violently.But I use Windows 2000(Python 2.3, wxPython 2.4). Windows
issue says 2000 doesn't support HP, so I simply turn it off. It didn't
appear.

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

Re: Enumerating Regular Expressions

2006-05-09 Thread Karthik Gurusamy
[EMAIL PROTECTED] wrote:
> James Stroud wrote:
> > You see the difficulty don't you? How will the computer know in advance
> > that the regex matches only a finite set of possible strings?
>
> Well sure it might be a little difficult to figure _that_ out, although
> probably not all that hard if you converted to an FSA or something.  I
> imagine detecting looping would be as simple as applying the right
> graph algorithm.

That's right. For finite regular language, you don't allow cycles. That
means the graph must be a DAG (directed acyclic graph. If not directed
it must be a tree, simple to check as node-count is edge-count plus
one).

Once you have a DAG, the problem becomes enumerating all paths from
root node to any final node. This is a pretty straighforward problem in
graph theory. I think you can simply find all from root-node to any
other node and discard any of the path ending in a non-final state
node.

Karthik

>
> But that's not the point, you don't strictly need to know in advance
> whether the regex represents a finite or infinite language.  I just
> want to enumerate it, if it's going to take longer than the life of the
> universe and a stack size to match to do it, then so be it.  It's
> surely up to the user to be careful about how they form their
> expressions.  One way to get around it would be to disallow the *
> operator in enumerations.
> 
> Cheers,
> -Blair

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


Re: installing numpy

2006-05-09 Thread Robert Kern
Raymond L. Buvel wrote:

> Since you are a new Linux user, you should definitely follow Robert's
> advice about building as an ordinary user separately from the install.
> I sometimes take a shortcut and just do the install as user root.
> However, I then wind up cleaning out the build directory as user root
> (not a very safe thing to do).

For small, pure Python packages, that may be fine. numpy's build is complicated
enough that you really, *really* want to build as a regular user.

-- 
Robert Kern

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

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


Re: installing numpy

2006-05-09 Thread Raymond L. Buvel
Robert Kern wrote:
> Gary Wessle wrote:
> 
>>"Raymond L. Buvel" <[EMAIL PROTECTED]> writes:
> 
> 
>>>When installing from source on a Debian system, you want the installed
>>>package to wind up in /usr/local/lib/python2.x/site-packages (where x
>>>represents the version of Python you are running the installer from).
>>>This allows you to keep it separate from the apt managed directories and
>>>allows for easy removal/upgrade.  So the command you want to execute
>>
>>>from root is
>>
>>>python setup.py install --prefix=/usr/local
>>
>>sorry if this is boring since I am not a seasoned Linux user.
>>
>>setup.py isn't located at the root, do you mean, execute the command above
>>from root, as to do this
>>:~$ cd /
>>:/$ python setup.py install --prefix=/usr/local
>>or 
>>:/$ python home/fred/numpy-0.9.6/setup.py install --pref...
>>or AS root
>>:/# python setup.py install --prefix=/usr/local
>>or 
>>:/# python home/fred/numpy-0.9.6/setup.py install --pref...
> 
> 
> I think he meant "as the root user". You will probably want to build numpy as 
> a
> regular user and then only install as the root user. You will probably want to
> use sudo(1) to gain root privileges. You can read the sudo man-page for more
> information on how to do that.
> 
> ~$ cd numpy-0.9.6
> ~/numpy-0.9.6$ python setup.py build
> ~/numpy-0.9.6$ sudo python setup.py install --prefix=/usr/local
> 
> However, instead of setting --prefix every time you execute setup.py for every
> Python package, it will be easier for you to create the file 
> ~/.pydistutils.cfg
> with the contents
> 
> [install]
> prefix=/usr/local
> 
> See http://docs.python.org/inst/config-syntax.html for more information.
> 
> Then, you can just do
> 
> ~$ cd numpy-0.9.6
> ~/numpy-0.9.6$ python setup.py build
> ~/numpy-0.9.6$ sudo python setup.py install
> 
> 
>>>By the way, to get NymPy to use the high-performance libraries, you must
>>>install these libraries and the associated -dev packages before running
>>>the Python install.
>>
>>I wish to know the debian names for those packages, my first guess
>>would be refblas3 under testing since blas is not available for
>>debian/testing, there is also
>>refblas3-dev  Basic Linear Algebra Subroutines 3, static library 
>>which I don't have installed.
>>
>>would refblas3 be all what NymPy need to the high-performance?
> 
> 
> No. refblas3 provides the reference (unoptimized) implementation of the BLAS. 
> In
> Ubuntu (a Debian-based distribution) the package that you would want is
> atlas3-base-dev. It should have a similar name in your version of Debian
> (possibly atlas-dev or atlas3-dev or some other variant).
> 
> If you need more help, you will probably get more focused help on the
> numpy-discussion mailing list.
> 
>   http://lists.sourceforge.net/lists/listinfo/numpy-discussion
> 

Since you are a new Linux user, you should definitely follow Robert's
advice about building as an ordinary user separately from the install.
I sometimes take a shortcut and just do the install as user root.
However, I then wind up cleaning out the build directory as user root
(not a very safe thing to do).

The Debian/testing package you want to install is indeed
atlas3-base-dev.  This package contains the header files needed to build
against the optimized blas library.  Note that the dependancies listed
in this package will cause the library package to be installed as well.

There are packages that are optimized for the extended instruction sets
available on some processors.  If you want to try and install one of
these instead of atlas3-base, just search the package list for anything
with atlas3 in the name.  Then carefully read the package descriptions
to find one that is optimized for your hardware.  Make sure you install
the -dev package or you will wind up using the unoptimized default in NumPy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do "some action" once a minute

2006-05-09 Thread James Stroud
Petr Jakes wrote:
> I would like to do "some action" once a minute. My code (below) works,
> I just wonder if there is some more pythonic approach or some "trick"
> how to do it differently.
> 
> minutes=time.localtime()[4]
> while 1:
> min, sec = time.localtime()[4:6]
> if  sec==0 and minutes!=min: # first occur of sec==0 only!! polling
> 10x a second
> minutes=min
> print "Eureca"
> time.sleep(0.1)
> 
> Regards
> 
> Petr Jakes
> 

This may be what you want:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464959

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


__all__ does not work?

2006-05-09 Thread AndyL
This a mm.py module:

_all__=('getsize1',)

size=85

def getsize1():
 return size

def getsize2():
 return 2*size


I do not know why but getsize2 is not kept priviate?

$ python
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.

 >> import mm
 >> mm.getsize2()

170




Any ideas?

A.

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


BayPIGgies: May 11, 7:30pm (Google)

2006-05-09 Thread Aahz
The next meeting of BayPIGgies will be Thurs, May 11 at 7:30pm at Google.

Note: Dennis Reinhardt is coordinating Google badges.  Please send e-mail
to [EMAIL PROTECTED] by 4pm Weds 5/10 to get an advance badge.


Dennis Reinhardt will present a short tutorial of using ctypes with the
Windows API, followed by Stephen McInerney discussing the results of the
BayPIGgies member survey.


BayPIGgies meetings alternate between IronPort (San Bruno, California)
and Google (Mountain View, California).  For more information and
directions, see http://baypiggies.net/


Before the meeting, we sometimes meet at 6pm for dinner.  Discussion of
dinner plans is handled on the BayPIGgies mailing list.  

Advance notice:  We can use a speaker for June.  Please e-mail
[EMAIL PROTECTED] if you want to suggest an agenda (or volunteer to
give a presentation).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Game Challenge results (and new hosting) UP!

2006-05-09 Thread Richard Jones
After some problems with hosting which were solved thanks to the PSF the
PyWeek site is back.

   http://www.pyweek.org/

Go see the results of the challenge, in particular the outstanding Nelly's
Rooftop Garden and Trip on the Funny Boat.

PyWeek challenges entrants to develop a complete game in Python in a week.
Inspired by similar programming challenges and National Novel Writing
Month, the event capitalises on the extraordinary work people can produce
under the combined influence of a very short deadline and a community of
like-minded people. This year there were approximately 100 entries, of
which about 35 were completed. The next PyWeek will be in about 6 months.

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


Performance of Blocks in Python

2006-05-09 Thread Dilip

I read a couple of interesting blog posts about the performance of
blocks in languages like Ruby, Python here[1] and here[2].  The posts
start out questioning Ruby but towards the middle and the end it does
draw analogies between python's design decision to introduce 'with'
statement as a language extension rather than a closure.

[1] http://pluralsight.com/blogs/dbox/archive/2006/05/09/23068.aspx
[2] http://pluralsight.com/blogs/dbox/archive/2006/05/08/23001.aspx

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


Re: Dictionaries -- ahh the fun.. (newbie help)

2006-05-09 Thread Bruno Desthuilliers
rh0dium a écrit :
> Hi all,
> 
> Can someone help me out.  I am trying to determing for each run whether
> or not the test should pass or fail but I can't seem to access the
> results ..
>  
(snip)
> cells={}
> 
> cells["NOR3X1"]= {
> 'run'   : [ 'lvs', 'drc' ],
> 'results'   : [{ 'lvs' : 'pass' },
>{ 'drc' : 'fail' }]
>  }
> 
> cells["OR3X1"] = {
> 'run'   : [ 'lvs' ],
> 'results'   : [{ 'lvs' : 'pass' }]
>  }
> 
> cells["AND3X1"] = {
> 'run'   : [ 'drc' ],
> 'results'   : [{ 'drc' : 'fail' }]
>  }
> 
> 
> def main():
> 
> for cell in cells:
> print cell
> for run in cells[cell]['run']:
> print cell, run, "should",
> cells[cell]['results'].index(run)
> 
> 
> I would expect the following
> 
> OR3X1
> OR3X1 lvs should pass
> NOR3X1
> NOR3X1 lvs should pass
> NOR3X1 drc should fail
> AND3X1
> AND3X1 drc should fail
> 

Congratulations, almost a perfect post - you just forgot to tell the 
actual result !-)

 >>> ## working on region in file /usr/tmp/python-99973O0...
 >>> main()
OR3X1
OR3X1 lvs should
Traceback (most recent call last):
   File "", line 1, in ?
   File "/usr/tmp/python-99973O0", line 24, in main
ValueError: list.index(x): x not in list

May I suggest that you type "help(list.index)" in your python shell ?

 > Alternatively can someone suggest a better structure ( and a lesson as
 > to the reasoning ) that would be great too!!

What seems flawed is the cell['results'] : you use a list of dicts, each 
one having a single entry - which is somewhat useless. Since you want to 
use the values of cell['run'] to lookup the expected results, using a 
single dict for results makes things a bit more usable:

cells={}
cells["NOR3X1"]= {
 'run'   : [ 'lvs', 'drc' ],
 'results'   : {'lvs' : 'pass',
'drc' : 'fail' }
  }
cells["OR3X1"] = {
 'run'   : [ 'lvs' ],
 'results'   : { 'lvs' : 'pass' }
  }
cells["AND3X1"] = {
 'run'   : [ 'drc' ],
 'results'   : { 'drc' : 'fail' }
  }

def main():
 for cellname, cellcontent in cells.items():
 print cellname
 for run in cellcontent['run']:
 print cellname, run, "should", cellcontent['results'][run]


This runs and produces the expected output. Now let's simplify. The 
values of cell['run'] are uselessly duplicated as keys in 
cell['results'] - and duplication is Bad(tm). So let's get rid of this:

cells={}
cells["NOR3X1"]= {
 'results'   : {'lvs' : 'pass',
'drc' : 'fail' }
  }
cells["OR3X1"] = {
 'results'   : { 'lvs' : 'pass' }
  }
cells["AND3X1"] = {
 'results'   : { 'drc' : 'fail' }
  }


Now we only have a single entry ('results') for each cell. This is a 
useless indirection level, so let's get rid of this too:

cells={
   "NOR3X1": {
 'lvs' : 'pass',
 'drc' : 'fail',
 },

   "OR3X1" : {
 'lvs' : 'pass',
 },

   "AND3X1" : {
 'drc' : 'fail',
 },
}

Looks simpler, isn't it ?-)

def main():
 for cellname, cellcontent in cells.items():
 print cellname
 for run, result in cellcontent.items():
 print cellname, run, "should", result

If you want to get the equivalent of cells[XXX]['runs'], just use 
cells[XXX].keys().

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


Re: Dictionaries -- ahh the fun.. (newbie help)

2006-05-09 Thread Scott David Daniels
rh0dium wrote:
> Hi all,
> 
> Can someone help me out.  I am trying to determing for each run whether
> or not the test should pass or fail but I can't seem to access the
> results ..
> 
> Alternatively can someone suggest a better structure ( and a lesson as
> to the reasoning ) that would be great too!!

Here's a little less convoluted version:

 cells = dict(NOR3X1=dict(lvs='pass', drc='fail'),
  OR3X=dict(lvs='pass'),
  AND3X1=dict(drc='fail'))

 for cell in cells:
 print cell
 for run, expect in cells[cell].items():
 print cell, run, "should", expect

Or even:

 for cell, expectations in cells.items():
 print cell
 for run, expect in expectations.items():
 print cell, run, "should", expect

You might prefer .iteritems rather than .items if the lists get huge.

* I use the dict(name=val [, name=val)*) form if the keys are symbols.
* Don't get any more indirect than you need to.
* A list of single-entry dictionaries is almost never a good idea;
   if you mean a list of pairs, use that.  if you mean a dictionary
   with a number of keys, use that.

-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyExcelerator: How does one close a file?

2006-05-09 Thread John Machin
On 10/05/2006 7:57 AM, [EMAIL PROTECTED] wrote:
> I use PyExcelerator to write data into Excel files, and repeatedly call
> the function writeData with different filenames fn from my main
> routine. Unfortunately, only one file - the last one - is created. The
> problem seems to lie with the fact that I do not close the existing
> file before calling the function again,

If you needed to close a file that was opened in another module, that 
would be a very peculiar API design. You don't need to.

> and the existing file is
> therefore just saved with a new name.

Your function creates a new instance of the Workbook class, as it 
should. The instance is abandoned when your function exits. One would 
not expect any carry-over between instances.

  Is there a way to close a
> PyExcelerator Excel file so that each call to the function results in a
> new file? There is no close() method as far as I can tell.
> 
> def writeData(fn, Data):
> """Write the data into an Excel file named fn using PyExcelerator
> Data is a list of real numbers"""
> w=PyExcelerator.Workbook()

Last time I looked, the name was pyExcelerator -- that's a lower-case 
"p" at the front. How come you didn't get an exception here (or on 
earlier import)? Have you posted the actual code you executed???

> ws = w.add_sheet("Sheet1")
> for i in range(len(Data)):
> ws.write(i, 0, Data[i])
> w.save(fn)
> 

pyExcelerator is open-source; you should read it. According to my 
reading of the version 0.6.3 source (which version are you using?), the 
Workbook.save method calls the CompoundDoc.save method, which opens a 
physical file with the supplied name, writes to it, and closes it. 
AFAICT, there is no hint of anything that could cause the symptoms you 
describe.

I did a quick test using the following code and your function (with 
appropriate module name) on version 0.6.3. It worked as expected (Python 
2.4.3 on Windows XP). Which Python version are you using? What OS?

for k in range(3):
 writeData("zzz%d.xls" % k, range(k, k+10))

Perhaps the problem is closer to home; try inserting
print repr(fn)
before each call to your function, and
os.system("ls -l " + fn) # or "dir " + fn, or whatever it takes
after each call.

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


Re: Dictionaries -- ahh the fun.. (newbie help)

2006-05-09 Thread BJörn Lindqvist
> Can someone help me out.  I am trying to determing for each run whether
> or not the test should pass or fail but I can't seem to access the
> results ..
>
> Alternatively can someone suggest a better structure ( and a lesson as
> to the reasoning ) that would be great too!!

Flat is better than nested. Pretend you write one billion cells in
your cells dict. To save disk space and memory (and make code
readable!) you wan't to make your structure as optimal as possible.

[snip]
> cells["NOR3X1"]= {
> 'run'   : [ 'lvs', 'drc' ],
> 'results'   : [{ 'lvs' : 'pass' },
>{ 'drc' : 'fail' }]
>  }
[snip]
> def main():
>
> for cell in cells:
> print cell
> for run in cells[cell]['run']:
> print cell, run, "should",
> cells[cell]['results'].index(run)

That is good code and AFAICT it should work as you have described.
Just replace cells[cell]['results'].index(run) with
cells[cell]['results'][run]

However, notice how you have defined each cell:

> cells["NOR3X1"]= {
> 'run'   : [ 'lvs', 'drc' ],
> 'results'   : [{ 'lvs' : 'pass' },
>{ 'drc' : 'fail' }]
>  }

Here you have repetition, you are writing the string lvs and drc
twice. Imagine you have hundreds of these in each cell, wouldn't it be
annoying to have to type so much redundant data. So you optimize the
structure:

cells["NOR3X1"] = {'run' : [('lvs', 'pass'), ('drc', 'fail')]}

Your code for printing the results become:

for cell, d in cells.items():
print cell
for testname, testresult in d['run']:
print cell, testname,  'should', testresult

for cell, d in cells.items() runs through all the key-value pairs in
the dict. cell becomes "NOR3X1" (the key) and d becomes {'run' :
[('lvs', 'pass'), ('drc', 'fail')]} (the value) for one loop for
example. for testname, testresult in d['run'] runs through all items
in the list d['run'] and "unpacks" them. testname becomes 'lvs' and
testresult 'pass' for one loop for example.

The next step in this refactoring is realizing that all items in the
cell dict are a dict with just one element. I.e: {'run' : ('drc',
'fail')} for the 'AND3X1' item. So you can optimize your structure
another step:

cells["NOR3X1"] = [('lvs', 'pass'), ('drc', 'fail')]

Here, we have just removed the subdict. Dicts with just one item are
rarely useful so we replace the dict with its sole item. This I think
is the optimal structure for your example, because it contains no
needless repetition. The following is your original example using the
reworked cells structure.

P = 'pass'
F = 'fail'
cells['NOR3X1'] = [('lvs', P), ('drc', F)]
cells['OR3X1'] = [('lvs', P')]
cells['AND3X1] = [('drc', F)]

for cellname, celltests in cells.items():
print cellname
for testname, restresult in celltests:
print cellname, testname, 'should', testresult

As you can see I have replaced the 'pass' and 'fail' strings with the
variables P and F. Sometimes that is a useful technique because it
reduces repetitive typing. You are also less likely misspell things
like 'flai' instead of 'fail'. One golden rule of programming is that
you should never write the same thing twice. Ofcourse that is very
hard to achieve in practice, but the stronger you get the less often
you do it. If you can spot that you have written something twice or
more times in your code, then you have also spotted what is wrong with
your code.

--
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries -- ahh the fun.. (newbie help)

2006-05-09 Thread James Stroud
rh0dium wrote:
> Hi all,
> 
> Can someone help me out.  I am trying to determing for each run whether
> or not the test should pass or fail but I can't seem to access the
> results ..
> 
> Alternatively can someone suggest a better structure ( and a lesson as
> to the reasoning ) that would be great too!!
> 
> cells={}
> 
> cells["NOR3X1"]= {
> 'run'   : [ 'lvs', 'drc' ],
> 'results'   : [{ 'lvs' : 'pass' },
>{ 'drc' : 'fail' }]
>  }
> 
> cells["OR3X1"] = {
> 'run'   : [ 'lvs' ],
> 'results'   : [{ 'lvs' : 'pass' }]
>  }
> 
> cells["AND3X1"] = {
> 'run'   : [ 'drc' ],
> 'results'   : [{ 'drc' : 'fail' }]
>  }
> 
> 
> def main():
> 
> for cell in cells:
> print cell
> for run in cells[cell]['run']:
> print cell, run, "should",
> cells[cell]['results'].index(run)
> 
> 
> I would expect the following
> 
> OR3X1
> OR3X1 lvs should pass
> NOR3X1
> NOR3X1 lvs should pass
> NOR3X1 drc should fail
> AND3X1
> AND3X1 drc should fail
> 

This might be better



cells["NOR3X1"]= {
 'run'   : [ 'lvs', 'drc' ],
 'results'   : { 'lvs' : 'pass', 'drc' : 'fail' }
  }
# etc.
   print cell, run, "should", cells[cell]['results'][run]

James


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: hyperthreading locks up sleeping threads

2006-05-09 Thread Delaney, Timothy (Tim)
[EMAIL PROTECTED] wrote:

> Thanks for trying and reporting the results.  Both of you and Tim and
> Dave have run the .py program now (all on hyper-threaded CPUs) and
> none of you were able to reproduce the problem.
> 
> So that indicates that there is something special about our PC.  We
> are planing to re-install Windows XP (and nothing else) and try again.

Hmm - you say you've got multiple identical machines that it hangs on -
were they all built by putting the same disc image on them? Or from a
customised XP install? If so, that might indicate that there's something
specific to the XP install. Otherwise it may well be specific to the
hardware ... :(

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


Re: logging module: add client_addr to all log records

2006-05-09 Thread Vinay Sajip
[EMAIL PROTECTED] wrote:

> Hi!
>
> I'm writing a server and I want to use the logging module for logging
> stuff. I want to log all transactions in detail, and if everything goes
> haywire I want to know which client did it. Therefore I want to affix
> the client address to every single log item.
>
> I would like to do the following:
> Formatter("[%(client_addr)s]: %(message)s")
> ...
> logger.critical("Offal Barrage Detected: Running Away", client_addr =
> 'french.knights.org')
>
> I've written something that accomplishes this (example below), but I
> have this nagging feeling that this could have been done in a better
> way. Any ideas?
>
> When test.py executes it prints this:
> [WARNING|2006-05-08 23:44:57,421|internal]: Unable to Pronounce 'ni!'
> [WARNING|2006-05-08 23:44:57,421|french.knights.nu]: Incoming Bovine
> Detected
>
> I'm grateful for any advice.
>
> Cheers!
> /Joel Hedlund
>

See a very similar example which uses the new 'extra' keyword argument:

http://docs.python.org/dev/lib/module-logging.html

The example is for a similar use case to yours - showing the IP address
of a client in a logging message.

Best regards,

Vinay Sajip

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


Re: problemi con POST

2006-05-09 Thread Bruno Desthuilliers
Michael Hobbs a écrit :
> Bruno Desthuilliers wrote:
> 
>> Heavy a écrit :
>>  
>>
>>> Ciao a tutti,
>>> sto creando una applicazione in python, che deve fungere anche da
>>> server web...
>>> non ho assolutamente problemi a prendere i parametri di una 'GET', mi
>>> limito a fare il parsing della URL, ma come faccio a prendere i
>>> parametri di una 'POST'? io cerco di leggere dal socket di lettura
>>> 'rfile' ma poi resto bloccato all'infinito perché evidemente resta in
>>> attesa di qualcosaltro... c'è già qualche metodo che mi può
>>> aiutare?? oppure sapete darmi qualche dritta? grazie...
>>>
>>> 
>>
>> Désolé, mais je n'ai rien compris (enfin, si : que tu avais des 
>> problèmes pour parser une requête HTTP POST et que tu te retrouvais 
>> avec une lecture bloquante sur un socket, mais ce n'est pas avec ça 
>> qu'on va pouvoir t'aider). Tu pourrais nous reposter ça en english ?-)
>>   
> 
> Aay Enchfray eplyray otay anay Italianay estionquay? Ellway, Iay ancay 
> itewray inay aay oreignfay anguagelay ootay!

didnee !-)

WTB, rof eht elpoep ereh taht t'nod kaeps hcnerf, I saw tsuj gniyrt ot 
nialpxe eht PO taht gnitsoper ni hsilgnE thgim eb a doog aedi.

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


Re: python rounding problem.

2006-05-09 Thread Dan Bishop
Grant Edwards wrote:
> On 2006-05-09, Dan Bishop <[EMAIL PROTECTED]> wrote:
> > Grant Edwards wrote:
> > ...
> >> Did they actually have 60 unique number symbols and use
> >> place-weighting in a manner similar to the arabic/indian system
> >> we use?
> >
> > The Bablyonians did use a place-value system, but they only had two
> > basic numerals: a Y-like symbol for 1 and a <-like symbol for ten.
> > These were combined to make base-60 digits.  For example, 59 was
> > represented by
> >
> >  <   YYY
> > < <  YYY
> >< <   YYY
> >
> > Zero (used as a placeholder, but not as a number in itself) was
> > represented by a space.
>
> And they also (acording to the web pages I found) used base-60
> floating point notation, but without an actual symbol to
> represent the sexagesimal point.  Which seems really ambiguous --
> even to somebody who does know how to use a slide rule.

Yes, it was.  ("Our spy's message says that Cyrus the Great has '6 '
troops.  Does that mean 360 or 21,600?")

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


Dictionaries -- ahh the fun.. (newbie help)

2006-05-09 Thread rh0dium
Hi all,

Can someone help me out.  I am trying to determing for each run whether
or not the test should pass or fail but I can't seem to access the
results ..

Alternatively can someone suggest a better structure ( and a lesson as
to the reasoning ) that would be great too!!

cells={}

cells["NOR3X1"]= {
'run'   : [ 'lvs', 'drc' ],
'results'   : [{ 'lvs' : 'pass' },
   { 'drc' : 'fail' }]
 }

cells["OR3X1"] = {
'run'   : [ 'lvs' ],
'results'   : [{ 'lvs' : 'pass' }]
 }

cells["AND3X1"] = {
'run'   : [ 'drc' ],
'results'   : [{ 'drc' : 'fail' }]
 }


def main():

for cell in cells:
print cell
for run in cells[cell]['run']:
print cell, run, "should",
cells[cell]['results'].index(run)


I would expect the following

OR3X1
OR3X1 lvs should pass
NOR3X1
NOR3X1 lvs should pass
NOR3X1 drc should fail
AND3X1
AND3X1 drc should fail

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


Re: What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY?

2006-05-09 Thread glomde
Thanks,

but the thing is that I want to have the syntactical sugar.
And I think that you could use elementtree or xist or any
other python tree structure module at the bottom. It could
be quite generic.

And with the syntactical sugar I find it a lot more readable.
A little bit like yaml, but you have the power of python aswell.

For example with syntactical sugar:

  # build a tree structure
  root = ET.Element("html")
  *!*root:
 *!*head("head"):
 *!*title("title):
  *=*text = "Page Title"
 *!*body("body"):
  *=*bgcolor = "#ff"
  *=*text = "Hello, World!"

This would then be this with element tree package.


  # build a tree structure
  root = ET.Element("html")
  head = ET.SubElement(root, "head")
  title = ET.SubElement(head, "title")
  title.text = "Page Title"
  body = ET.SubElement(root, "body")
  body.set("bgcolor", "#ff")
  body.text = "Hello, World!"

I find it a lot more readable with the syntactical sugar.
So I would really like to add this syntax.

/T

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


interactive shell -- reload definitions?

2006-05-09 Thread Metalone
I have a question about the interactive Python shell.  Is it possible
to reload a file and get the new definitions.

For example, if I do
import xyz

Then I find a bug in some function in xyz.
So, I edit xyz.py

I would like to reload the definitions in xyz.py without leaving my
current shell session.
Is this possible?


Also, is there any way to save definitions created in the interactive
shell to a file?
Sometimes I write a simple function in the shell, and this wish I had
that function in an external file.

Thanks.

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


PyExcelerator: How does one close a file?

2006-05-09 Thread tkpmep
I use PyExcelerator to write data into Excel files, and repeatedly call
the function writeData with different filenames fn from my main
routine. Unfortunately, only one file - the last one - is created. The
problem seems to lie with the fact that I do not close the existing
file before calling the function again, and the existing file is
therefore just saved with a new name. Is there a way to close a
PyExcelerator Excel file so that each call to the function results in a
new file? There is no close() method as far as I can tell.

def writeData(fn, Data):
"""Write the data into an Excel file named fn using PyExcelerator
Data is a list of real numbers"""
w=PyExcelerator.Workbook()
ws = w.add_sheet("Sheet1")
for i in range(len(Data)):
ws.write(i, 0, Data[i])
w.save(fn)

Thanks in advance

Thomas Philips

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread Carl Banks
Jack wrote:
> Then again, I do like the Python language. It would be great if
> Python (or a variation of Python) can be made the PHP way, one
> executable file, and you get everything.

True, sometimes it can be a real convenience to have this.  There are
solutions that implement your solution to some degree.  For instance,
for Windows there's Moveable Python (it costs a scant 5 pounds):

http://www.voidspace.org.uk/python/movpy/

I don't believe it's a single file, but it is "installationless".
Py2exe and PyInstaller can let you distribute programs as single-file
executables.  PyInstaller works on Unix too, IIRC.

If you're good at tweaking stuff and have some knowledge of Python
internals; it's possible to make a minimal distro just by copying files
out of a regular installation by hand (and maybe zipping some them up).
 This can be a security and bug risk, so be careful.


Carl Banks

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


Incrementally converting a C app to Python

2006-05-09 Thread BJörn Lindqvist
Hello. At work I'm the sole maintainer and developer of a medium sized
~50k line C application. The lion share of this app was written before
my time so it is pretty hard to read and also contain lots of bugs.
I'm contemplating converting the project to Python because I think
that, in the long run, maintenance will become much easier. And also
because is so much more fun than C.

The app is to big to be rewritten from scratch so I'm thinking of a
way to rewrite it "incrementally." Something like one module, or file,
at a time. Using tools like SWIG, Pyrex or embedding Python in C it
seems like this would be possible. My question is what tools should I
apply and what strategy should I use? Would it be best to use a
top-down approach and rewrite the main files first and work my way
down wrapping the remaining C files using SWIG? Or should I convert
the isolated code files to Python and then embedd it in the C code?
Maybe Pyrex help me with this task? Any insight on this matter is
greatly appreciated. Surely someone has done the exact same thing as
me before.
--
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Martin Rydstr|m
[EMAIL PROTECTED] (Alex Martelli) writes:
> Didn't want to trigger some flamewar;-), but, yes, if that was my only
> choice, I'd much rather use small, simple Scheme than huge, complicated,
> rich, powerful Common Lisp.  ((But in this case I'm biased by early
> experiences, since when I learned and used Lisp-ish languages there WAS
> no Common Lisp, while Scheme was already there, although not quite the
> same language level as today, I'm sure;-)).

If that was in the early to mid eighties, which I seem to recall you
mentioning, the Lisp dialects mostly in use were huger, more
complicated, richer and more powerful than Common Lisp in many, if not
most, respects, as far as I can tell.  Common Lisp is a (later)
augmented least common denominator of those Lisps. The really big
thing that's newer and greater in CL is CLOS and the condition system.

',mr

-- 
[Emacs] is written in Lisp, which is the only computer language that is
beautiful.  -- Neal Stephenson, _In the Beginning was the Command Line_
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problemi con POST

2006-05-09 Thread Michael Hobbs
Bruno Desthuilliers wrote:
> Heavy a écrit :
>   
>> Ciao a tutti,
>> sto creando una applicazione in python, che deve fungere anche da
>> server web...
>> non ho assolutamente problemi a prendere i parametri di una 'GET', mi
>> limito a fare il parsing della URL, ma come faccio a prendere i
>> parametri di una 'POST'? io cerco di leggere dal socket di lettura
>> 'rfile' ma poi resto bloccato all'infinito perché evidemente resta in
>> attesa di qualcosaltro... c'è già qualche metodo che mi può
>> aiutare?? oppure sapete darmi qualche dritta? grazie...
>>
>> 
> Désolé, mais je n'ai rien compris (enfin, si : que tu avais des 
> problèmes pour parser une requête HTTP POST et que tu te retrouvais avec 
> une lecture bloquante sur un socket, mais ce n'est pas avec ça qu'on va 
> pouvoir t'aider). Tu pourrais nous reposter ça en english ?-)
>   
Aay Enchfray eplyray otay anay Italianay estionquay? Ellway, Iay ancay 
itewray inay aay oreignfay anguagelay ootay!

- Ikemay

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


Re: Deferred Evaluation in Recursive Expressions?

2006-05-09 Thread Lonnie Princehouse
The first 'typedef' line will have a NameError when it tries to
evaluate LinkedListB

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


Re: problemi con POST

2006-05-09 Thread Bruno Desthuilliers
Heavy a écrit :
> Ciao a tutti,
> sto creando una applicazione in python, che deve fungere anche da
> server web...
> non ho assolutamente problemi a prendere i parametri di una 'GET', mi
> limito a fare il parsing della URL, ma come faccio a prendere i
> parametri di una 'POST'? io cerco di leggere dal socket di lettura
> 'rfile' ma poi resto bloccato all'infinito perché evidemente resta in
> attesa di qualcosaltro... c'è già qualche metodo che mi può
> aiutare?? oppure sapete darmi qualche dritta? grazie...
> 
Désolé, mais je n'ai rien compris (enfin, si : que tu avais des 
problèmes pour parser une requête HTTP POST et que tu te retrouvais avec 
une lecture bloquante sur un socket, mais ce n'est pas avec ça qu'on va 
pouvoir t'aider). Tu pourrais nous reposter ça en english ?-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread Diez B. Roggisch
> With Python, things are really messy. I have to run the installer
> to install dozens of directories and hundreds of files, and I don't
> really know if  all of them are necessary. Plus, lots of libraries
> are in .py, which is of course not as efficient/clean as having all
> of the core functions built-in in the C/C++ core, like in PHP.
> 
> Then again, I do like the Python language. It would be great if
> Python (or a variation of Python) can be made the PHP way, one
> executable file, and you get everything. 

You have a somewhat distorted view of things. I've been cursing PHP 
quite a few times exactly for that monolitic nature. If you need e.g. 
oracle support, you have to recompile the whole lot, not just a module 
as it has no no C-module concept - so you can't add functionality 
besides using PHP-includes. So much for efficiency.

Diez

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


Re: installing numpy

2006-05-09 Thread Robert Kern
Gary Wessle wrote:
> "Raymond L. Buvel" <[EMAIL PROTECTED]> writes:

>>When installing from source on a Debian system, you want the installed
>>package to wind up in /usr/local/lib/python2.x/site-packages (where x
>>represents the version of Python you are running the installer from).
>>This allows you to keep it separate from the apt managed directories and
>>allows for easy removal/upgrade.  So the command you want to execute
>>from root is
>>
>>python setup.py install --prefix=/usr/local
> 
> sorry if this is boring since I am not a seasoned Linux user.
> 
> setup.py isn't located at the root, do you mean, execute the command above
> from root, as to do this
> :~$ cd /
> :/$ python setup.py install --prefix=/usr/local
> or 
> :/$ python home/fred/numpy-0.9.6/setup.py install --pref...
> or AS root
> :/# python setup.py install --prefix=/usr/local
> or 
> :/# python home/fred/numpy-0.9.6/setup.py install --pref...

I think he meant "as the root user". You will probably want to build numpy as a
regular user and then only install as the root user. You will probably want to
use sudo(1) to gain root privileges. You can read the sudo man-page for more
information on how to do that.

~$ cd numpy-0.9.6
~/numpy-0.9.6$ python setup.py build
~/numpy-0.9.6$ sudo python setup.py install --prefix=/usr/local

However, instead of setting --prefix every time you execute setup.py for every
Python package, it will be easier for you to create the file ~/.pydistutils.cfg
with the contents

[install]
prefix=/usr/local

See http://docs.python.org/inst/config-syntax.html for more information.

Then, you can just do

~$ cd numpy-0.9.6
~/numpy-0.9.6$ python setup.py build
~/numpy-0.9.6$ sudo python setup.py install

>>By the way, to get NymPy to use the high-performance libraries, you must
>>install these libraries and the associated -dev packages before running
>>the Python install.
> 
> I wish to know the debian names for those packages, my first guess
> would be refblas3 under testing since blas is not available for
> debian/testing, there is also
> refblas3-dev  Basic Linear Algebra Subroutines 3, static library 
> which I don't have installed.
> 
> would refblas3 be all what NymPy need to the high-performance?

No. refblas3 provides the reference (unoptimized) implementation of the BLAS. In
Ubuntu (a Debian-based distribution) the package that you would want is
atlas3-base-dev. It should have a similar name in your version of Debian
(possibly atlas-dev or atlas3-dev or some other variant).

If you need more help, you will probably get more focused help on the
numpy-discussion mailing list.

  http://lists.sourceforge.net/lists/listinfo/numpy-discussion

-- 
Robert Kern

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

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


Re: elementtidy, \0 chars and parsing from a string

2006-05-09 Thread Simon Percivall
Well, it seems you can do:

parser = elementtidy.TidyHTMLTreeBuilder.TidyHTMLTreeBuilder()
parser.feed(your_str)
tree = elementtree.ElementTree.ElementTree(element=parser.close())

Look at the parse() method in the ElementTree class.

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


problemi con POST

2006-05-09 Thread Heavy
Ciao a tutti,
sto creando una applicazione in python, che deve fungere anche da
server web...
non ho assolutamente problemi a prendere i parametri di una 'GET', mi
limito a fare il parsing della URL, ma come faccio a prendere i
parametri di una 'POST'? io cerco di leggere dal socket di lettura
'rfile' ma poi resto bloccato all'infinito perché evidemente resta in
attesa di qualcosaltro... c'è già qualche metodo che mi può
aiutare?? oppure sapete darmi qualche dritta? grazie...

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


Re: ascii to latin1

2006-05-09 Thread richie
[Luis]
> The script converted the ÇÃ from the first line, but not the º from
> the second one.

That's because º, 0xba, MASCULINE ORDINAL INDICATOR is classed as a
letter and not a diacritic:

  http://www.fileformat.info/info/unicode/char/00ba/index.htm

You can't encode it in ascii because it's not an ascii character, and
the script doesn't remove it because it only removes diacritics.

I don't know what the best thing to do with it would be - could you use
latin-1 as your base encoding and leave it in there?  I don't speak any
language that uses it, but I'd guess that anyone searching for eg. 5º
(forgive me if I have the gender wrong 8-) would actually type 5º -
are there any Italian/Spanish/Portuguese speakers here who can confirm
or deny that?

In the general case, you have to decide what happens to characters that
aren't diacritics and don't live in your base encoding - what happens
when a Chinese user searches for a Chinese character?  Probably you
should just encode(base_encoding, 'ignore').

-- 
Richie Hindle
[EMAIL PROTECTED]

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


elementtidy, \0 chars and parsing from a string

2006-05-09 Thread Steven Bethard
So I see that elementtidy doesn't like strings with \0 characters in them:

 >>> import urllib
 >>> from elementtidy import TidyHTMLTreeBuilder
 >>> url = 'http://news.bbc.co.uk/1/hi/world/europe/492215.stm'
 >>> url_file = urllib.urlopen(url)
 >>> tree = TidyHTMLTreeBuilder.parse(url_file)
Traceback (most recent call last):
   ...
   File "...elementtidy\TidyHTMLTreeBuilder.py", line 90, in close
 stdout, stderr = _elementtidy.fixup(*args)
TypeError: fixup() argument 1 must be string without null bytes, not str

The obvious solution would be to str.replace('\0', '') on the file's 
text, but I'm not sure how to ask elementtidy to parse from a string 
instead of a file-like object.  Do I need to wrap it in a StringIO, or 
is there a better way?

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


Re: Shadow Detection?

2006-05-09 Thread Gary Herron
Michael Yanowitz wrote:

>Hello:
>
>  Many times, people are warning things like
>"Don't use 'str' as a variable name as it will shadow the
>built in str function." 
>   Is there some way to determine if a string is already
>defined in some higher scope?
>Maybe something like
>
>
>if isdefined ('str'):
>   print 'str is already defined, please choose another name'
>
>
>
>  If not, would it be easy to write this?
>
>Thanks in advance:
>
>  
>

Just try to access the name and see what happens, catching the resulting 
error if you wish

try:
   xyzzy
except NameError:
  print 'xyzzy is not currently bound'


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


Re: installing numpy

2006-05-09 Thread Gary Wessle
"Raymond L. Buvel" <[EMAIL PROTECTED]> writes:

> Gary Wessle wrote:
> > Hi
> > 
> > I am trying to install NumPy in my debian/testing linux
> > 2.6.15-1-686. 
> > 
> 
> 
> When installing from source on a Debian system, you want the installed
> package to wind up in /usr/local/lib/python2.x/site-packages (where x
> represents the version of Python you are running the installer from).
> This allows you to keep it separate from the apt managed directories and
> allows for easy removal/upgrade.  So the command you want to execute
> from root is
> 
> python setup.py install --prefix=/usr/local


sorry if this is boring since I am not a seasoned Linux user.

setup.py isn't located at the root, do you mean, execute the command above
from root, as to do this
:~$ cd /
:/$ python setup.py install --prefix=/usr/local
or 
:/$ python home/fred/numpy-0.9.6/setup.py install --pref...
or AS root
:/# python setup.py install --prefix=/usr/local
or 
:/# python home/fred/numpy-0.9.6/setup.py install --pref...

 
> 
> By the way, to get NymPy to use the high-performance libraries, you must
> install these libraries and the associated -dev packages before running
> the Python install.

I wish to know the debian names for those packages, my first guess
would be refblas3 under testing since blas is not available for
debian/testing, there is also
refblas3-dev  Basic Linear Algebra Subroutines 3, static library 
which I don't have installed.

would refblas3 be all what NymPy need to the high-performance?

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


Re: Is Welfare Part of Capitalism?

2006-05-09 Thread Rune Strand
Welfare is not a built-in, but in some distributions it's available as
a module. Just type import Welfare. However, be aware of the
Welfare.division() queerness. It won't be fixed until the Python 3000
is a fact. There is also some issues with the garbage collection. Under
certain circumstances the dreaded Dutch disease may occur.

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


Re: ascii to latin1

2006-05-09 Thread Peter Otten
Luis P. Mendes wrote:

> The script converted the ÇÃ from the first line, but not the º from the
> second one.  Still in *, I also don't get a list as [115448,DAÇÃO] but a
> [u'115448,DAÇÃO'] element, which doesn't suit my needs.
> 
> Would you mind telling me what should I change?

Sometimes you are faster if you put the gloves off. Just write the
translation table with the desired substitute for every non-ascii character
in the latin1 charset by hand and be done.

Cyril Kyree


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


Re: Shadow Detection?

2006-05-09 Thread [EMAIL PROTECTED]

Carl J. Van Arsdall wrote:
> Michael Yanowitz wrote:
> > Hello:
> >
> >   Many times, people are warning things like
> > "Don't use 'str' as a variable name as it will shadow the
> > built in str function."
> >Is there some way to determine if a string is already
> > defined in some higher scope?
> > Maybe something like
> > 
> >
> > if isdefined ('str'):
> >print 'str is already defined, please choose another name'
> >
> >
> You might check out globals() which returns a dictionary of everything:
>
> Python 2.2 (#1, Mar 26 2002, 15:46:04)
> [GCC 2.95.3 20010315 (SuSE)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> globals()
> {'__builtins__': , '__name__':
> '__main__', '__doc__': None}
>  >>> blah = None
>  >>> globals()
> {'__builtins__': , '__name__':
> '__main__', '__doc__': None, 'blah': None}
>
> #Taking this a step further, this is a dictionary so you can use the
> has_key method or try to access the dict and catch an exception should
> the key not exist
>
>  >>> if globals().has_key('blah'):
> ...   print "I have blah"
> ...
> I have blah
>
>
> -carl
>
>
> --
>
> Carl J. Van Arsdall
> [EMAIL PROTECTED]
> Build and Release
> MontaVista Software

There's also the dir() function:

>>> dir()
['__builtins__', '__doc__', '__name__']


>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError',
'ImportError', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError',
'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError',
'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
'TabError', 'True', 'TypeError', 'UnboundLocalError',
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning',
'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__',
'__import__', '__name__', 'abs', 'apply', 'basestring', 'bool',
'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']


>>> dir(__name__)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__',
'__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count',
'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind',
'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']


>>> dir(__doc__)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__']

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


Re: Shadow Detection?

2006-05-09 Thread Carl J. Van Arsdall
Michael Yanowitz wrote:
> Hello:
>
>   Many times, people are warning things like
> "Don't use 'str' as a variable name as it will shadow the
> built in str function." 
>Is there some way to determine if a string is already
> defined in some higher scope?
> Maybe something like
> 
>
> if isdefined ('str'):
>print 'str is already defined, please choose another name'
>
>   
You might check out globals() which returns a dictionary of everything:

Python 2.2 (#1, Mar 26 2002, 15:46:04)
[GCC 2.95.3 20010315 (SuSE)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> globals()
{'__builtins__': , '__name__': 
'__main__', '__doc__': None}
 >>> blah = None
 >>> globals()
{'__builtins__': , '__name__': 
'__main__', '__doc__': None, 'blah': None}

#Taking this a step further, this is a dictionary so you can use the 
has_key method or try to access the dict and catch an exception should 
the key not exist

 >>> if globals().has_key('blah'):
...   print "I have blah"
...
I have blah


-carl


-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread Rene Pijlman
Jack:
>I have to run the installer to install dozens of directories and 
>hundreds of files, 

That's not unusual and not considered a problem by most people.

>and I don't really know if all of them are necessary.

Don't let that bother you. Life's too short.

>Plus, lots of libraries are in .py, which is of course not as 
>efficient/clean as having all of the core functions built-in in 
>the C/C++ core, like in PHP.

Performance-critical parts _are_ implemented in C/C++. But not everything
falls into this category. Yes, there's probably room for more performance
improvements. Just like there is with PHP. Did you know, for example, that
PHP doesn't store and re-use compiled versions of the scripts by default?
With PHP you need to fiddle with eAccelerator, Zend and the like. The
Python interpreter does this automatically.

There are advantages to having library code in Python too, such as being
able to seemlessly debug it in a Python debugger. Also, Python API's tend
to be a lot cleaner than PHP's. This probably reflects the language
they're implemented in.

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Upgrading Class Instances Automatically on Reload

2006-05-09 Thread malv
Indeed, as I indicated the old recipe/160164 by Michael Hudson works
flawlessly for me.

I am referring here to the latest edition: cookbook #2 which features
an upgraded version.
You find the examples in:
http://examples.oreilly.com/pythoncook2/cb2_examples.zip

The files are named cb2_6_21_*.py, but the book has the recipe in
chapter
20.15. 

malv

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


Re: Enumerating Regular Expressions

2006-05-09 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Hi all,
> 
> Does anybody know of a module that allows you to enumerate all the
> strings a particular regular expression describes?

Make a generator that yields *all* strings in your chosen alphabet (see 
the monthly threads about permutations and combinations for hints). 
Filter with the regex. Halting is left as an exercise for the reader. 
(Halting when the length reaches a predetermined limit would be one way 
to do it.)

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


Shadow Detection?

2006-05-09 Thread Michael Yanowitz
Hello:

  Many times, people are warning things like
"Don't use 'str' as a variable name as it will shadow the
built in str function." 
   Is there some way to determine if a string is already
defined in some higher scope?
Maybe something like


if isdefined ('str'):
   print 'str is already defined, please choose another name'



  If not, would it be easy to write this?

Thanks in advance:

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


Re: Econometrics in Panel data?

2006-05-09 Thread Cameron Laird
In article <[EMAIL PROTECTED]>, I counseled:
>In article <[EMAIL PROTECTED]>,
>DeepBlue  <[EMAIL PROTECTED]> wrote:
>>so are you saying that Python is not an appropriate language for doing 
>>econometrics stuff?
>>
>>
>>Dennis Lee Bieber wrote:
>>> On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <[EMAIL PROTECTED]> declaimed 
>>> the
>>> following in comp.lang.python:
>>> 
 Hi all,

 I am new to Python. Just wondering can Python able to do econometric 
 regression in either Time-series or pooled (panel) data? As well as test 
 for hetero, autocorrelation, or endogeneity?
.
.
.
>There is not, however, a readily-accessible library targeted
>for this sort of work.  If I had the opportunity to work in
>econometrics now, I'd think seriously about R, Lisp, and
>Mathematica, and see what's available among the functional
>languages, along with Python.

Smalltalk, too; I'd throw it in the mix.  Much serious econometrics
has been done with Fortran, but I have no enthusiasm for pursuing
that direction, mostly because I think too much of the computing
world is going in a different one.

But I'm not you, DeepBlue, or, more specifically, it's unlikely that
our circumstances are at all similar.  Is your project at a hobbyist
level?  How does hardware constrain you?  How big is your team ...?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Upgrading Class Instances Automatically on Reload

2006-05-09 Thread Rene Pijlman
malv:
>At the statement b = Bar(), the following error occurs:
>The debugged program raised the exception unhandled AttributeError
>"type object 'Bar' has no attribute '__instance_refs__'"

I haven't studied it at all, but the code on
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 seems to
run fine with Python 2.4.2 in WingIDE on Windows XP. There's no exception
and it prints:
1
2
3

Are you perhaps using an older dead tree version of the Cookbook?

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Paul Rubin
[EMAIL PROTECTED] (Alex Martelli) writes:
> I think it's reasonable to make a name a part of functions, classes and
> modules because they may often be involved in tracebacks (in case of
> uncaught errors): to me, it makes sense to let an error-diagnosing
> tracebacks display packages, modules, classes and functions/methods
> involved in the chain of calls leading to the point of error _by name_.

But it would be even nicer if the traceback could point back to the
exact location in the source code where the function definition
occurred, and that wouldn't need any name for the function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Welfare Part of Capitalism?

2006-05-09 Thread Tim Daneliuk
[EMAIL PROTECTED] wrote:
> This article is dedicated to:
> 



But I am still confused:  Is this a statement or an expression?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to recast integer to a string

2006-05-09 Thread Christoph Haas
On Tue, May 09, 2006 at 12:34:05PM -0700, James wrote:
> 
> Christoph Haas wrote:
> > On Tue, May 09, 2006 at 12:17:34PM -0700, James wrote:
> > > How to recast an integer to a string?
> > >
> > > something like
> > > n = 5
> > > str = str + char(n)
> >
> > str(n)
> >
> > Kindly
> >  Christoph
> 
> In python2,4, I 've got
> TypeError: 'str' object is not callable 

What I meant was:

string_from_number = str(n)

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


Re: Calling python functions from C

2006-05-09 Thread Ronny Mandal
On 9 May 2006 10:05:48 -0700, [EMAIL PROTECTED] wrote:

>I am a newbie to Python. I want to call python functions from C. I
>looked for examples but I couldn't get any simple one. Lets say my
>python code is :
>def add(a,b)
> return (a+b)
>
>I want to call add from C. Could anybody please help me? Thanks in
>advance.
This is also known as "callback".

Check out 
http://www.google.com/search?client=opera&rls=en&q=python+c+callback&sourceid=opera&ie=utf-8&oe=utf-8
or
http://www.python.org/doc/current/ext/ext.html

-RM
>
>R.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to recast integer to a string

2006-05-09 Thread Fredrik Lundh
James wrote:

> > > How to recast an integer to a string?
> > >
> > > something like
> > > n = 5
> > > str = str + char(n)
> >
> > str(n)
> >
> > Kindly
> >  Christoph
>
> In python2,4, I 've got
> TypeError: 'str' object is not callable

if you want to use a builtin function, you cannot use the same name
for your own variables.





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


Re: multiline strings and proper indentation/alignment

2006-05-09 Thread Gary Herron
Gary John Salerno wrote:

>How do you make a single string span multiple lines, but also allow 
>yourself to indent the second (third, etc.) lines so that it lines up 
>where you want it, without causing the newlines and tabs or spaces to be 
>added to the string as well?
>
>Example (pretend this is all on one line):
>
>self.DTD = '4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd";>\n\n'
>
>I want it to read:
>
>self.DTD = '''"http://www.w3.org/TR/html4/strict.dtd";>\n\n'''
>
>Or anything like that, but I don't want the extra newline or tabs to be 
>a part of the string when it's printed.
>
>Thanks.
>  
>
The textwrap module has a function to do just the thing you want.  

*dedent*(   text)

Remove any whitespace that can be uniformly removed from the left of
every line in text.

This is typically used to make triple-quoted strings
line up with the left edge of screen/whatever, while still
presenting it in the source code in indented form.

Gary Herron


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


Re: python rounding problem.

2006-05-09 Thread Grant Edwards
On 2006-05-09, Dan Bishop <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
> ...
>> Did they actually have 60 unique number symbols and use
>> place-weighting in a manner similar to the arabic/indian system
>> we use?
>
> The Bablyonians did use a place-value system, but they only had two
> basic numerals: a Y-like symbol for 1 and a <-like symbol for ten.
> These were combined to make base-60 digits.  For example, 59 was
> represented by
>
>  <   YYY
> < <  YYY
>< <   YYY
>
> Zero (used as a placeholder, but not as a number in itself) was
> represented by a space.

And they also (acording to the web pages I found) used base-60
floating point notation, but without an actual symbol to
represent the sexagesimal point.  Which seems really ambiguous --
even to somebody who does know how to use a slide rule.

-- 
Grant Edwards   grante Yow!  I'm totally
  at   DESPONDENT over the LIBYAN
   visi.comsituation and the price
   of CHICKEN...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Econometrics in Panel data?

2006-05-09 Thread Robert Kern
DeepBlue wrote:
> so are you saying that Python is not an appropriate language for doing 
> econometrics stuff?

Alan Isaac certainly thinks it is appropriate and lists many Python resources
for econometrics:

  http://www.american.edu/econ/pytrix/pytrix.htm

You may also want to look at QuantLib, which has a Python interface via SWIG.

  http://www.quantlib.org

-- 
Robert Kern

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

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


Re: How to recast integer to a string

2006-05-09 Thread Larry Bates
James wrote:
> How to recast an integer to a string?
> 
> something like
> n = 5
> str = str + char(n)
> 
> 
> J.L
> 
Two items:

1) Never use 'str' as a variable name as it will
shadow the built in str function.  If you do, this
WILL jump up and bite you.

2) Either s=str(n) or s="%i" % n will return string
containing '5' (without the quotes of course).

Note: chr(n) would return character whose ASCII decimal
value is 5 (ASCII ENQ).

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


Re: Can Python installation be as clean as PHP?

2006-05-09 Thread malv
If this bothers you, why don't you stick to a linux distro with Python
installed.
Very few don't.

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


Re: python rounding problem.

2006-05-09 Thread Dan Bishop
Grant Edwards wrote:
...
> Did they actually have 60 unique number symbols and use
> place-weighting in a manner similar to the arabic/indian system
> we use?

The Bablyonians did use a place-value system, but they only had two
basic numerals: a Y-like symbol for 1 and a <-like symbol for ten.
These were combined to make base-60 digits.  For example, 59 was
represented by

  <   YYY
 < <  YYY
< <   YYY

Zero (used as a placeholder, but not as a number in itself) was
represented by a space.

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


Re: Progress bar in web-based ftp?

2006-05-09 Thread Larry Bates
CatDude wrote:
> I've got an application that prompts the user to select a file from his
> local computer, checks the user's selection, then sends the file via 
>  enctype="multipart/form-data">
> 
> In the python code that receives the files I've got a section that does
> the following:
> 
> if not os.path.isfile(filePath):
> file(filePath, 'wb').write(str(form[name].value))
> else:
> print "File already exists - deleting"
> os.unlink(filePath)
> file(filePath, 'wb').write(str(form[name].value))
> 
> after error checking, etc.
> 
> My question is whether anyone has ideas as to how I could implement a
> progress bar. When I send a large file this way it can take a long time,
> and I'd like to be able to reassure the user that something really is
> happening.
> 
> 
Turns out that this is more difficult than you might think.  The problem
is you must have the client communicate with the server in some way and
have the server know what the progress is at any point.  HTML POST
action=upload doesn't give you anything to work with to provide such
information to the client's browser (if it does I'm not aware of it
anyway).  It also would take something like JavaScript and XMLRPC on
the client to make the round trip to get updated progress information.

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


Re: How to recast integer to a string

2006-05-09 Thread Grant Edwards
On 2006-05-09, James <[EMAIL PROTECTED]> wrote:
> How to recast an integer to a string?

> something like
> n = 5
> str = str + char(n)

str = str + chr(5)

-- 
Grant Edwards   grante Yow!  I want EARS! I
  at   want two ROUND BLACK
   visi.comEARS to make me feel warm
   'n secure!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python rounding problem.

2006-05-09 Thread Grant Edwards
On 2006-05-09, Thomas Bartkus <[EMAIL PROTECTED]> wrote:

>>> Even base 60 makes more sense if you like it when a lot of
>>> divisions come out nice and even.
>>
>> Did they actually have 60 unique number symbols and use
>> place-weighting in a manner similar to the arabic/indian
>> system we use?
>
> I don't know.

I googled around a while last night, and they ahd sort of a
hybrid notation.  The Sumerians started withindividual "tic
marks" up to 9, and symbols for 10, 60, 600, 3600 and so on.
That evolved into the Babylonian base-60 position-weighted
system (without a zero symbol) that used only the 1 symbol and
the 10 symbol.

http://it.stlawu.edu/%7Edmelvill/mesomath/sumerian.html
http://www.ancientscripts.com/sumerian.html
http://www-gap.dcs.st-and.ac.uk/~history/HistTopics/Babylonian_numerals.html

> I do know that we have 360 degrees in a circle

And 60 seconds in a minute, 60 minutes in a hour (for both time
and angles), and 60 minutes in a degree.

-- 
Grant Edwards   grante Yow!  PARDON me, am I
  at   speaking ENGLISH?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Upgrading Class Instances Automatically on Reload

2006-05-09 Thread malv
Rene,

No,  I couldn't get it to work. Sorry, I should have included that
information.

At the statement b = Bar(), the following error occurs:
The debugged program raised the exception unhandled AttributeError
"type object 'Bar' has no attribute '__instance_refs__'"

malv

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


Re: How to recast integer to a string

2006-05-09 Thread James

Christoph Haas wrote:
> On Tue, May 09, 2006 at 12:17:34PM -0700, James wrote:
> > How to recast an integer to a string?
> >
> > something like
> > n = 5
> > str = str + char(n)
>
> str(n)
>
> Kindly
>  Christoph

In python2,4, I 've got
TypeError: 'str' object is not callable 

J.L

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


Can Python installation be as clean as PHP?

2006-05-09 Thread Jack
I like Python but I don't really like Python's installation.
With PHP, I only need one file (on Linux) and maybe two files
on Windows then I can run my PHP script. This means no installation
is required in most cases. I just copy the file and I get PHP.
Extending PHP is fairly easy, too, just by copying a few DLLs
and modifying the php.ini a bit.

With Python, things are really messy. I have to run the installer
to install dozens of directories and hundreds of files, and I don't
really know if  all of them are necessary. Plus, lots of libraries
are in .py, which is of course not as efficient/clean as having all
of the core functions built-in in the C/C++ core, like in PHP.

Then again, I do like the Python language. It would be great if
Python (or a variation of Python) can be made the PHP way, one
executable file, and you get everything. 


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


Re: installing numpy

2006-05-09 Thread Robert Kern
Christoph Haas wrote:

> Yes, you are right. "python-numeric" refers to NumPy but contains the
> "Numeric" version of it (24-2). It's pretty misleading.

It's an unfortunate consequence of letting software packages acquire nicknames.
C.f.:

  http://www.scipy.net/pipermail/scipy-user/2006-May/007847.html

-- 
Robert Kern

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

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


Re: multiline strings and proper indentation/alignment

2006-05-09 Thread John Salerno
Scott David Daniels wrote:
> John Salerno wrote:
>> How do you make a single string span multiple lines, but also allow 
>> yourself to indent the second ... without causing the newlines and 
>> tabs or spaces to be added to the string as well?
>  >
>> self.DTD = '''>"http://www.w3.org/TR/html4/strict.dtd";>\n\n'''
>>
>> ..., but I don't want the extra newline or tabs to be a part of the 
>> string when it's printed.
> 
> The easiest way:
> 
> self.DTD = (' '"http://www.w3.org/TR/html4/strict.dtd";>\n\n')
> 
> Adjacent strings are combined at compile-time, and parens around allows
> you to do a multi-line expression.
> 
> --Scott David Daniels
> [EMAIL PROTECTED]

Thanks guys. Looks like both of your suggestions are pretty much the 
same thing, which is putting strings next to one another. Something 
about it looks wrong, but I guess it works!)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing numpy

2006-05-09 Thread Robert Kern
Christoph Haas wrote:

> P.S.: Your mail client seems break the references. Your reply doesn't show
>   up as a proper followup to my posting.

This probably has nothing to do with his mail/news client but rather the
mail-news gateway that links python-list and comp.lang.python .

-- 
Robert Kern

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

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


Re: Python editor recommendation.

2006-05-09 Thread Jack
PyScripter, a nativen Windows application, free.

>
> Can any one please recommend me an editor for coding Python. Thank u.
> I have Komodo (www.activestate.com) in my mind. Is the editor any good?
>
> regards. 


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


Re: regular expressions, substituting and adding in one step?

2006-05-09 Thread John Salerno
Kent Johnson wrote:

> Do it all in one match / substitution using \1 to insert the value of 
> the paragraph group at the new location:
> 
> In [19]: test = "self.source += '' + paragraph + '\n\n'"
> 
> In [20]: re.sub(r"'' \+ (.*?) \+ '\n\n'", r"'%s\n\n' % 
> \1", test)
> Out[20]: "self.source += '%s\n\n' % paragraph"

Interesting. Thanks! I was just doing some more reading of the re 
module, so now I understand sub() better. I'll give this a try too. Call 
me crazy, but I'm interested in regular expressions right now. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to recast integer to a string

2006-05-09 Thread Christoph Haas
On Tue, May 09, 2006 at 12:17:34PM -0700, James wrote:
> How to recast an integer to a string?
> 
> something like
> n = 5
> str = str + char(n)

str(n)

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


  1   2   3   >