Re: catch argc-argv

2005-06-20 Thread mg
John Machin wrote:

>Duncan Booth wrote:
>  
>
>>John Machin wrote:
>>
>>
>>
>>
So, my question is: does the Python API containe fonctions like 
'get_argc()' and 'get_argv()' ?



>>>If you can't see them in the documentation, they aren't there. If they
>>>aren't there, that's probably for a good reason -- no demand, no use
>>>case. 
>>>
>>>
>>>  
>>>
>>Leaving aside whether or not there is a use-case for this, the reason they 
>>aren't there is that they aren't needed.
>>
>>
>
>"no use-case" == "no need" in my book
>
>  
>
>>As the OP was already told, to 
>>access argv, you simply import the 'sys' module and access sys.argv.
>>
>>
>
>Simple in Python, not in C.
>
>  
>
>>There are apis both to import modules and to get an attribute of an 
>>existing Python object.
>>
>>
>
>I know that; my point was why should you do something tedious like that 
>when you shouldn't be interested in accessing sys.argv from a C 
>extension anyway.
>
>  
>
>> So all you need is something like (untested):
>>
>>PyObject *sys = PyImport_ImportModule("sys");
>>PyObject *argv = PyObject_GetAttrString(sys, "argv");
>>int argc = PyObject_Length(argv);
>>if (argc != -1) {
>>   ... use argc, argv ...
>>}
>>Py_DECREF(argv);
>>Py_DECREF(sys);
>>
>>
I understand all the good arguments explained before, and I am agree 
with them.
Nevertheless, I implement Python bindings from a generic parallel 
framework and a new application based on this framework needs to call a 
kind of initilization class : the constructor arguments are argc and 
argv... Then, the previous solution can be a work around to test some 
behavours of my bindings.
Thanks for your answers ;-) 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extensions on Linux: import without underscore?

2005-06-20 Thread Terry Hancock
On Monday 20 June 2005 06:39 am, Kent Johnson wrote:
> Terry Hancock wrote:
> > Okay, you may want a more elegant way to do this and other people
> > have already responded to that point, but you do at least know you
> > can just give it a new name:
> > 
> > import _bright
> > bright = _bright
> 
> or more idiomatically and without adding _bright to the namespace:
> import _bright as bright

Um, yeah, I knew that.  Really I did. ;-)

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: references/addrresses in imperative languages

2005-06-20 Thread Xah Lee
Dear Andrea Griffini,

Thanks for explaning this tricky underneath stuff.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

Andrea Griffini wrote:
> On Sun, 19 Jun 2005 22:25:13 -0500, Terry Hancock
> <[EMAIL PROTECTED]> wrote:
>
> >> PS is there any difference between
> >> t=t+[li]
> >> t.append(li)
> >
> >No, but
>
> Yes, a big one. In the first you're creating a new list
> and binding the name t to it, in the second you're extending
> a list by adding one more element at the end.
> To see the difference:
>
>   >>> a = [1,2,3]
>   >>> b = a
>   >>> a = a + [4]
>   >>> print a
>   [1, 2, 3, 4]
>   >>> print b
>   [1, 2, 3]
>   >>>
>   >>> a = [1,2,3]
>   >>> b = a
>   >>> a.append(4)
>   >>> print a
>   [1, 2, 3, 4]
>   >>> print b
>   [1, 2, 3, 4]
>   >>>
> 
> Andrea

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

regarding cache clearing header in python cgi

2005-06-20 Thread praba kar
Dear All,
 
In Php the following headers base we can clean
 the cache in the url  "header('Cache-Control:
no-store, no-cache,  must-revalidate'); "
I want to know Php equivalent headers in Python-cgi
If anybody know regarding this kindly mail me.
 
regards,
Prabahar
 




___
Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for 
FREE! http://in.mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overcoming herpetophobia (or what's up w/ Python scopes)?

2005-06-20 Thread Paul Du Bois
kj wrote:
> I am hoping that it may be better this time around.  For one thing,
> like Perl, Python was then (and maybe still is) a "work in progress."
> So I figure that Python scoping may have improved since then.  Even
> if not, I think that Python is mature enough by now that adequate
> alternatives must have been devised for the Perlish features that
> I missed during my first attempt.

I don't know of any tutorials, but given that you're familiar with the
concept of closures and scopes I don't think you really need one to
understand what Python does and doesn't provide.

Python does allow you to refer to variables in lexically enclosing
scopes, and it closes over them properly.  Python (annoyingly) does
_not_ provide a way to write to the closed-over variable.  Assignments
always go into the local scope.  There is a "global" statement that
allows you to "target" the module scope; one can imagine an analagous
statement that allows you to target an intervening scope, but it
doesn't exist.

Some (incorrectly) interpret this to mean that the variable isn't
actually closed-over.  The following code executes without errors,
which shows that the closure really does refer to the outer variable,
and not some constant copy:

def closure_test():
def make_closure():
def closure():
# a += 1  # this will give you an unbound local error at
runtime
return a
return closure
fn = make_closure()

a = 1
assert fn() == a
a = 2
assert fn() == a

closure_test()

The canonical way around this is to add a layer of indirection -- isn't
that always the solution?

def closure_test2():
def make_closure():
def closure():
a[0] += 1
return a[0]
return closure
fn = make_closure()

a = [1]
assert fn() == 2
assert fn() == 3
closure_test2()

p

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


A tool for Python - request for some advice

2005-06-20 Thread TPJ
First I have to admit that my English isn't good enough. I'm still
studying and sometimes I just can't express what I want to express.


A few weeks ago I've written 'Python Builder' - a bash script that
allows anyone to download, compile (with flags given by user) and
install Python and some external modules (e.g. wxPython, PyGTK,
Numeric...). I use Python every day and when new version of Python (or
some external module) is released, I want to check if my projects will
run on this new version (sometimes I want to know if my projects will
run on specific combination of older Python and some older external
modules...). It happens four - five times a year. Frequently not enough
to memorize all commands used to configure, compile and install all of
this software (so I have to read documentation every time I'm doing it)
- but frequently enough to consume considerable amounts of my working
time. So I thought that writing a script to do it all automatically
(download sources, unpack them, configure them, compile them and then
install them; all of this with options given by me - the user) would be
a good idea.

(It's not about using emerge, get-apt or some another tool of this
kind. My need is very special - I want to have Python, it's modules and
sometimes documentation installed in particular place; usually
somewhere in my home directory. My script installs some additional
scripts which I can use to run Python. These additional scripts have
properly set LD_LIBRARY_PATH so they are able to run Python and
external modules that require libraries installed in non-standard
locations.)

I've written this script in bash, because I thought it would be better
to have a script which would run in environment without Python (it all
was about installing Python anyway!). I used bash, dialog, wget... And
now someone suggested, that I shuld use Python. That using Python would
lead to clearer and - probably - smaller code. (I have to admit it - my
code in bash is just messy.)

And now I'm considering this idea. Python is already present on
(almost?) every distribution today, so why worry about it's presence?
Writing in Python would lead to easier i18n (for now it's all in
Polish...) and to easier implementation of future enhancements (due to
language's features and much more clearer coding style in Python). Well
- I've already found it hard to implement new features in pure bash.

But, on the other hand, I'm thinking that writing in bash is more
universal solution. I mean that requirements to run bash scripts are
lower than requirements to run Python scripts. Could this requirements
be decisive for some users (or is it only my imagination)? Sometimes
users just have no access to Python (e.g. LFS, some stages of Gentoo,
some rescue and specialized distros).


And there's also something more. For now "Python Builder" works in text
mode. It was written in bash and I assumed it should be some kind of
"basic" tool - so text mode and bash seemed to be the best choice. But
if I rewrote all code in Python I could make some GUI. It could works
even better - I could easily check if GUI mode is available and run in
proper (GUI or text) mode. But is GUI needed by people who just want it
to do it's job and quit?


Well, what do you think?

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


Re: references/addrresses in imperative languages

2005-06-20 Thread Kaz Kylheku


SM Ryan wrote:
> "Kaz Kylheku" <[EMAIL PROTECTED]> wrote:
> # SM Ryan wrote:
> # > # easy way to see this, is to ask yourself: how come in mathematics
> # > # there's no such thing as "addresses/pointers/references".
> # >
> # > The whole point of Goedelisation was to add to name/value references into
> # > number theory.
> #
> # Is that so? That implies that there is some table where you can
> # associate names (or whatever type of locators: call them pointers,
> # whatever) with arbitrary values. But in fact that's not the case.
>
> Do you really believe the Goedel number of a statement is the statement
> itself? Is everything named Kaz the same as you?

The Goedel number is a representation of the statement in a way that
the name Kaz isn't a representation of me. You cannot identify parts of
the name Kaz with parts of me; there is no isomorphism there at all. I
am not the translated image of the name Kaz, nor vice versa.

A Goedel number isn't anything like a name or pointer. It's an encoding
of the actual typographic ``source code'' of the expression. There is
nothing external to refer to other than the encoding scheme, which
isn't particular to any given Goedel number. The encoding scheme is
shallow, like a record player; it doesn't contribute a significant
amount of context. If I decode a Goedel number, I won't have the
impression that the formula was hidden in the numbering scheme, and the
Goedel number simply triggered it out like a pointer. No, it will be
clear that each piece of the resulting formula is the direct image of
some feature of the Goedel number.

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


Re: references/addrresses in imperative languages

2005-06-20 Thread Kaz Kylheku


SM Ryan wrote:
> "Kaz Kylheku" <[EMAIL PROTECTED]> wrote:
> # SM Ryan wrote:
> # > # easy way to see this, is to ask yourself: how come in mathematics
> # > # there's no such thing as "addresses/pointers/references".
> # >
> # > The whole point of Goedelisation was to add to name/value references into
> # > number theory.
> #
> # Is that so? That implies that there is some table where you can
> # associate names (or whatever type of locators: call them pointers,
> # whatever) with arbitrary values. But in fact that's not the case.
>
> Do you really believe the Goedel number of a statement is the statement
> itself? Is everything named Kaz the same as you?

The Goedel number is a representation of the statement in a way that
the name Kaz isn't a representation of me. You cannot identify parts of
the name Kaz with parts of me; there is no isomorphism there at all. I
am not the translated image of the name Kaz, nor vice versa.

A Goedel number isn't anything like a name or pointer. It's an encoding
of the actual typographic ``source code'' of the expression. There is
nothing external to refer to other than the encoding scheme, which
isn't particular to any given Goedel number. The encoding scheme is
shallow, like a record player; it doesn't contribute a significant
amount of context. If I decode a Goedel number, I won't have the
impression that the formula was hidden in the numbering scheme, and the
Goedel number simply triggered it out like a pointer. No, it will be
clear that each piece of the resulting formula is the direct image of
some feature of the Goedel number.

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


after transfer of data from MS-outlook(mail ids) to application, mail ids are consisting of strange characters

2005-06-20 Thread vamsikrishna_b

Hello all,the following problem i encountered while transferring
data(mail ids) from MS-outlook to one application.Some mail ids after
came into the application looked as strange characters.Eg are [Å@ [Å.
[Å,©Ä@ ©Ä. ©Ä etc.I thought these are the Ascii characters but
i'm not quite sure about this.And also each mail id following a certain
format as you can observe from the above mail ids.Only one string is
repeating in all the 3 parts of the mail id.Is there any procedure to
convert these characters to the plain letters.I hope somebody will help
me in this regard to unfold this mystery.Bye.

Best Regards,
Vamsi

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


Re: references/addrresses in imperative languages

2005-06-20 Thread SM Ryan
"Kaz Kylheku" <[EMAIL PROTECTED]> wrote:
# SM Ryan wrote:
# > # easy way to see this, is to ask yourself: how come in mathematics
# > # there's no such thing as "addresses/pointers/references".
# >
# > The whole point of Goedelisation was to add to name/value references into
# > number theory.
# 
# Is that so? That implies that there is some table where you can
# associate names (or whatever type of locators: call them pointers,
# whatever) with arbitrary values. But in fact that's not the case.

Do you really believe the Goedel number of a statement is the statement
itself? Is everything named Kaz the same as you?

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Sothat would make Bethany part black?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regarding cache clearing header in python cgi

2005-06-20 Thread praba kar
Dear All,

   In Php the following headers base we can clean
the cache in the url
"header('Cache-Control: no-store, no-cache,
must-revalidate'); "
I want to know Php equivalent headers in Python-cgi

If any know regarding this kindly mail me.

regards,
Prabahar



__
How much free photo storage do you get? Store your friends 'n family snaps for 
FREE with Yahoo! Photos http://in.photos.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list



Using code objects?

2005-06-20 Thread Chinook
Using code objects?
===

As an OO exercise I have a factory pattern that returns class objects that 
each have an "action" method.  ClassObj.action() in turn returns a code 
object in my recursive process loop.

I create the code objects as a one time step outside my factory pattern and 
potential class definitions, then reference them in my potential classes 
which seems to work as expected.  

When I create the code objects though, it seems a couple different ways work 
and I'm wondering which is better and why (or is there a more correct 
technique in this situation)?

The two different ways are illustrated below:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)]
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(st):
...   print st
... 
>>> exp1 = 'foo("#expersion 1#")'
>>> exp2 = 'foo("#expersion 2#")'
>>> obj1 = compile(exp1, 'whatever', 'single')
>>> exec obj1
#expersion 1#
>>> obj2 = compile(exp2, 'whatever', 'exec')
>>> exec obj2
#expersion 2#
>>> 

Thank you,
Lee C


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


Re: references/addrresses in imperative languages

2005-06-20 Thread Kaz Kylheku
Lawrence D’Oliveiro wrote:
> In article <[EMAIL PROTECTED]>,
>  "Xah Lee" <[EMAIL PROTECTED]> wrote:
>
> >A[n] easy way to see this, is to ask yourself: how come in mathematics
> >there's no such thing as "addresses/pointers/references".
>
> Yes there are such things in mathematics, though not necessarily under
> that name.
>
> For instance, in graph theory, edges can be considered as "pointers".
> After all, make a change to a node, and that change is visible via all
> edges pointing to that node.

Oh yeah, by the way, note how such destructive changes to a variable
become whole-environment derivations in the discipline of proving the
correctness of imperative programs.

E.g. say you have this assignment:

   x <- x + 1

and you want to deduce what preconditions must exist in order for the
desired outcome   x = 42   to be true after the execution of the
statement. What do you do? You pretend that the program is not
modifying a variable in place, but rather manufacturing a new
environment out of an old one. In the new environment, the variable X
has a value that is one greater than the corresponding variable in the
old environment. To distinguish the two variables, you call the one in
the old environment X' .

You can then transform the assignment by substituting X' for X in the
right hand side and it becomes

  x <= x' + 1

and from that, the precondition  x' = 41  is readily deduced from the
x = 42  postcondition.

Just to be able to sanely reason about the imperative program and its
destructive variable assignment, you had to nicely separate past and
future, rename the variables, and banish the in-place modification from
the model.

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


Re: references/addrresses in imperative languages

2005-06-20 Thread Kaz Kylheku
SM Ryan wrote:
> # easy way to see this, is to ask yourself: how come in mathematics
> # there's no such thing as "addresses/pointers/references".
>
> The whole point of Goedelisation was to add to name/value references into
> number theory.

Is that so? That implies that there is some table where you can
associate names (or whatever type of locators: call them pointers,
whatever) with arbitrary values. But in fact that's not the case.

> Thus Goedel was able to add back pointers contrary to the
> set hierarchy of the theory of types and reintroduce Russel's paradox.

Nope. Goedel didn't add anything, he just revealed what was already
there: that you can have statements of number theory, well-formed
formulas constructed out of existing operators without any backpointer
tricks, which have true interpretations, but are not theorems.

Everything in a Goedel's string can be recursively expanded to yield an
ordinary formula! There is no infinite regress, no unchased embedded
pointer-like things left behind.

Self-reference is achieved using two tricks: Goedel numbering, and
indirect reference. Godel numbering allows a formula to talk about
formulas, by way of embedding their Godel numbers, and translating
formula-manipulations into arithmetic manipulations (of interest are
finite ones that will nicely unfold into finite formulas). In essence
that which used to be ``code'' can be now treated as ``data''', and
operations on code (logical derivations) become arithmetic operations
on data.

Indirect reference is needed because a formula G's Goedel number cannot
be inserted into itself directly. If you start with a formula G which
has some free variable V, and then produce some new formula by
substituting G's Goedel number into it directly for occurences of V,
you no longer have G but that other formula.  You want whatever comes
out to be G, and so the input formula, the one with the free variable,
cannot be G, but perhaps a close relative which either talks about G,
or whose constituent formulas cleverly end up talking about G after the
substitution takes place.

Instead of a direct (Goedel number) reference, you can insert into a
formula some /procedure/ for making that formula's Goedel number out of
another formula's Goedel number and talk about it that way. As an
example, instead of saying ``here is a number'' by inserting its
literal digits, you can say ``the number that results by applying this
formula to this other number''. For instance, instead of writing the
number 4 we can write   successor(3). or   2 + 2.   We explicitly
mention some other number, and say how 4 is constructed out of it.

Douglas Hofstadter exposition of all this is very good. To allow the
formula G to mention its own Goedel number, Douglas Hofstadter uses
another formula which he calls U, the ``uncle''. The trick is that: the
procedure for making G's Goedel number out of U's number is the
arithmetic equivalent of the same procedure that's used to substitute
the Goedel number of U for the free variable in U itself. So as U (the
formula) is treated by substituting its own Godel number for its one
and only free variable, it produces G, and, at the same time, the
arithmetic version of that substitution, fully contained inside the U
formula itself, turns the now substituted copy of U into G also.  U
contains the fully expanded ``source code'' for the arithmetic version
of the free-variable substitution procedure, and it contains a free
variable representing the arithmetic version of the formula on which
that algorithm is to be done. As that free variable within U is
replaced by the Goedel number U, the overall formula becomes G, and the
embedded free-variable-replacement procedure is instantiated concretely
over U's Goedel number, so it becomes a constant, unparameterized
calculation that produces G's Goedel number.

Voila, G contains a procedure that computes the arithmetic object
(Goedel number) that represents G's ``source code'' (the symbolic
formula), out of the embedded number representing U's source code.
Using that giant formula, G can assert things about itself, like ``I am
not a theorem'' (i.e. ``there exists no integer representing the Goedel
numbers of a list of true statements that represent a derivation
deducing myself as the conclusion'').

There are no name references or pointers or anything. All the functions
are primitive recursive, and so can be expanded into finite-length
formulas which contain only numbers and operators and variables---dummy
ones that are bound to existential quantifiers, not to concrete values
some external name/value table.

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


Re: multi threading and win9x

2005-06-20 Thread Tim Peters
[Timothy Smith]
> i want to run my sql statements on a seperate thread to prevent my app
> from stop responding to input (atm is says "not responding" under
> windows until the sql is finished)
> but i'm hesitant because i have to still support win9x and i'm not sure
> how well this will play.

All versions of Windows >= Win95 use threads heavily, have very solid
thread support, and the Win32 API was thread-aware from the start 
Thread _scheduling_ is pretty bizarre <= WinME, but process scheduling
is too.  Don't try to use hundreds of threads <= WinME and you should
be fine.
-- 
http://mail.python.org/mailman/listinfo/python-list


multi threading and win9x

2005-06-20 Thread Timothy Smith
i want to run my sql statements on a seperate thread to prevent my app 
from stop responding to input (atm is says "not responding" under 
windows until the sql is finished)
but i'm hesitant because i have to still support win9x and i'm not sure 
how well this will play.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple Unpacking in raise

2005-06-20 Thread James Stroud
Thank you Steven and Konstantin, that clears things up.

Sometimes I forget how incomplete my Python Essential Reference is.

James

On Monday 20 June 2005 05:40 pm, Steven Bethard wrote:
> Well, it's not a bug, because that's what the documentation says it'll do:
>
> "The second object is used to determine the exception value: If it is an
> instance of the class, the instance becomes the exception value. If the
> second object is a tuple, it is used as the argument list for the class
> constructor; if it is None, an empty argument list is used, and any
> other object is treated as a single argument to the constructor."[1]
>
> In the example above (as well as almost all code), there's no need to
> use the two argument version of raise.  You can simply write:
>
>  raise MyErr(sometup)
>
> If you need the three argument version of raise, I believe you can still
> write it as:
>
>  raise MyErr(sometup), None, tb
>
> Note that Guido has mentioned a few times that in Python 3.0, he wants
> tracebacks to be attributes of the Exception objects so that all raise
> statements are like the one argument version.
>
> STeVe
>
> P.S. If you insist on using the two argument version of raise, you can
> do it like this:
>
> py> class E(Exception):
> ... def __init__(self, atup):
> ... Exception.__init__(self, "Error with %s-%s" % atup)
> ...
> py> raise E, ((1, 2),)
> Traceback (most recent call last):
>File "", line 1, in ?
> E: Error with 1-2
>
> But that seems a lot less elegant than simply using the one argument
> version.
>
> [1] http://docs.python.org/ref/raise.html

-- 
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


getting list of all available modules

2005-06-20 Thread Benjamin Rutt
I note that the help() function of interactive python can determine
all available modules:

[EMAIL PROTECTED] ~]$ python
Python 2.4 (#1, Mar 31 2005, 15:26:02) 
[GCC 3.2.3 (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help()

[...]

help> modules

Please wait a moment while I gather a list of all available modules...

BaseHTTPServer  bisect  linuxaudiodev   shelve
Bastion bsddb (package) locale  shlex
BicycleRepairMan_Idle cPickle logging (package)   shutil
CDROM   cStringIO   macpath signal
CGIHTTPServer   calendarmacurl2path site
Canvas  cgi mailbox smtpd
ConfigParsercgitb   mailcap smtplib

[...]

I want to do the same (get all such modules in a python list); how can
I do so?  Or where is the code for the REPL for help() itself so I can
find out myself?

This is to build a code introspection tool BTW.  Thanks,
-- 
Benjamin Rutt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a list from a file

2005-06-20 Thread Rune Strand
:-/  You're right!

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


Re: Tuple Unpacking in raise

2005-06-20 Thread Konstantin Veretennicov
On 6/21/05, Steven Bethard <[EMAIL PROTECTED]> wrote:
> James Stroud wrote:
> P.S. If you insist on using the two argument version of raise, you can
> do it like this:
> 
> py> class E(Exception):
> ... def __init__(self, atup):
> ... Exception.__init__(self, "Error with %s-%s" % atup)
> 
> But that seems a lot less elegant than simply using the one argument
> version.

Another workaround would be to use __init__(self, *atup), but raising
an explicitly constructed exception is preferable (IMO).

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


Re: Tuple Unpacking in raise

2005-06-20 Thread Konstantin Veretennicov
On 6/21/05, James Stroud <[EMAIL PROTECTED]> wrote:
> Hello All,
> 
> Is this a bug?

No, it works as documented. You should've consulted language reference:
http://docs.python.org/ref/raise.html

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


Re: Tuple Unpacking in raise

2005-06-20 Thread Steven Bethard
James Stroud wrote:
> Hello All,
> 
> Is this a bug? Why is this tuple getting unpacked by raise? Am I missing some 
> subtle logic? Why does print not work the same way as raise? Both are 
> statements. Why does raise need to be so special?
> 
> py> sometup = 1,2
> py> print sometup
> (1, 2)
> py> print 1,2,3, sometup
> 1 2 3 (1, 2)
> py> class MyErr(Exception):
> ...   def __init__(self, atup):
> ... Exception.__init__(self, "Error with %s-%s" % atup)
> ...
> py> raise MyErr, sometup
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: __init__() takes exactly 2 arguments (3 given)
> py> e = MyErr(sometup)
> py> print e
> Error with 1-2

Well, it's not a bug, because that's what the documentation says it'll do:

"The second object is used to determine the exception value: If it is an 
instance of the class, the instance becomes the exception value. If the 
second object is a tuple, it is used as the argument list for the class 
constructor; if it is None, an empty argument list is used, and any 
other object is treated as a single argument to the constructor."[1]

In the example above (as well as almost all code), there's no need to 
use the two argument version of raise.  You can simply write:

 raise MyErr(sometup)

If you need the three argument version of raise, I believe you can still 
write it as:

 raise MyErr(sometup), None, tb

Note that Guido has mentioned a few times that in Python 3.0, he wants 
tracebacks to be attributes of the Exception objects so that all raise 
statements are like the one argument version.

STeVe

P.S. If you insist on using the two argument version of raise, you can 
do it like this:

py> class E(Exception):
... def __init__(self, atup):
... Exception.__init__(self, "Error with %s-%s" % atup)
...
py> raise E, ((1, 2),)
Traceback (most recent call last):
   File "", line 1, in ?
E: Error with 1-2

But that seems a lot less elegant than simply using the one argument 
version.

[1] http://docs.python.org/ref/raise.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a list from a file

2005-06-20 Thread Konstantin Veretennicov
On 6/20/05, David Bear <[EMAIL PROTECTED]> wrote:
> I have a file that contains lists -- python lists. sadly, these
> are not pickled. These are lists that were made using
> a simple print list statement.

Sad, indeed. But what kind of objects they held? Only ints? Ints and
strings? Arbitrary objects?

> 
> Is there an easy way to read this file into a list again?
> I'm thinking I would have to
> 
> read until char = '['
>read until char = " ' "
> 
> Well, reading character by char until I have the list and then
> parse it all myself.

At least you can leave tokenizing to python lib:

>>> import tokenize, token, pprint
>>> token_names = dict([
... (value, name) for (name, value)
... in token.__dict__.iteritems()
... if isinstance(value, int)])
>>> tokens = tokenize.generate_tokens(
... iter(['[1, 2, "ab\'c,d"]']).next)
>>> pprint.pprint([(token_names[t[0]], t[1]) for t in tokens])
[('OP', '['),
 ('NUMBER', '1'),
 ('OP', ','),
 ('NUMBER', '2'),
 ('OP', ','),
 ('STRING', '"ab\'c,d"'),
 ('OP', ']')]

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


Re: sudoku dictionary attack

2005-06-20 Thread r.e.s.
"Oliver Albrecht" <[EMAIL PROTECTED]> wrote ...
> Has some one an sodoku-task-generator?

Sudoku puzzles can be generated (and solved) online at
http://act365.com/sudoku/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want to learn a language - is Python right?

2005-06-20 Thread James Stroud
Python will help you as a novice for these reasons:

1. Help you to learn programming concepts and develop good habits.
2. Powerful Standard Library to help you do more advanced things.
3. Smooth, shallow learning curve, e.g. hello world is:

 print "Hello World"

   So you can do simple things in python with minimal learning.

4. Excellent, friendly, patient, helpful user base.
5. Code is inherently more maintainable than other languages.
6. comp.lang.python

In short, you have come to the right place. I have used many programming 
languages (C, Java, Fortran, Python, Perl, just to name the more famous ones) 
and python takes the cake as a general purpose programming language.

By the way, ignore any posts talking about speed of execution. This is 
generally a non-issue for new programmers. If you want your code to run 
faster, buy a faster computer.

James

On Monday 20 June 2005 07:47 am, Aziz McTang wrote:
> What I'm looking for is more to learn one good, comprehensive
> programming language well than several approximately on an ad hoc
> basis. What I also failed to mention is the desire to develop my
> presently limited computer skills a lot further.

-- 
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


Tuple Unpacking in raise

2005-06-20 Thread James Stroud
Hello All,

Is this a bug? Why is this tuple getting unpacked by raise? Am I missing some 
subtle logic? Why does print not work the same way as raise? Both are 
statements. Why does raise need to be so special?

py> sometup = 1,2
py> print sometup
(1, 2)
py> print 1,2,3, sometup
1 2 3 (1, 2)
py> class MyErr(Exception):
...   def __init__(self, atup):
... Exception.__init__(self, "Error with %s-%s" % atup)
...
py> raise MyErr, sometup
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: __init__() takes exactly 2 arguments (3 given)
py> e = MyErr(sometup)
py> print e
Error with 1-2

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: reading a list from a file

2005-06-20 Thread John Machin
Rune Strand wrote:
> But iif it are many lists in the file and they're organised like this:
> 
> ['a','b','c','d','e']
> ['a','b','c','d','e']
> ['A','B','C','D','E'] ['X','F','R','E','Q']
> 
> I think this'll do it
> 
> data = open('the_file', 'r').read().split(']')
> 
> lists = []
> for el in data:
>   el = el.replace('[', '').strip()
>   el = el.replace("'", "")
>   lists.append(el.split(','))
> 
> # further processing of lists
> 
> but the type problem is still to be resolved ;-)
> 

Try this:

["O'Reilly, Fawlty, and Manuel", '""', ',', '"Hello", said O\'Reilly']

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


Install MySQL-python-0.9.1

2005-06-20 Thread Cathy Hui
I am trying to install MySQL-Python 0.9.1 on my Solaris 8 system.  The
system has Python 2.3.3 and Mysql 4.0.21 installed.

This is where I downloaded the distribution of the Mysql-python
package:

http://www.ravenbrook.com/project/p4dti/import/2001-10-16/MySQL-python-0.9.1/MySQL-python-0.9.1.tar.gz

I have been doing whatever instructed from the README file.

i.e.

change the setup.py according to what OS I'm using:

elif sys.platform == "sunos5": # Solaris 2.8
include_dirs = ['/usr/local/mysql/include/mysql']
library_dirs = ['/usr/local/mysql/lib/mysql']
libraries = [mysqlclient, "z"]
runtime_library_dirs =
['/usr/local/lib:/usr/openwin/lib:/usr/dt/lib']
extra_objects = []

Then run the setup.py script with Python, here is the problem.

I am encountering the following issue when running the setup.py script.
 Do u know why is that?  Thanks!

==

python setup.py build
Traceback (most recent call last):
  File "setup.py", line 123, in ?
extra_objects=extra_objects,
  File "/usr/local/lib/python2.3/distutils/core.py", line 101, in setup
_setup_distribution = dist = klass(attrs)
  File "/usr/local/lib/python2.3/distutils/dist.py", line 130, in
__init__
setattr(self, method_name, getattr(self.metadata, method_name))
AttributeError: DistributionMetadata instance has no attribute
'get___doc__'


python setup.py install
Traceback (most recent call last):
  File "setup.py", line 123, in ?
extra_objects=extra_objects,
  File "/usr/local/lib/python2.3/distutils/core.py", line 101, in setup
_setup_distribution = dist = klass(attrs)
  File "/usr/local/lib/python2.3/distutils/dist.py", line 130, in
__init__
setattr(self, method_name, getattr(self.metadata, method_name))
AttributeError: DistributionMetadata instance has no attribute
'get___doc__'

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


Re: Question about HTMLgen

2005-06-20 Thread Konstantin Veretennicov
On 6/20/05, Sebastian Bassi <[EMAIL PROTECTED]> wrote:
> Hello,
> 
> I am using HTMLgen. It is very nice. But I can't make it to
> generate an arbitrary command.
> For example I want to output this:
> 
>  type="image/svg+xml" name="wmap" wmode="transparent">

Works for me...

>>> d = HTMLgen.BasicDocument()
>>> d.append('')
>>> print d




  
 


 

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


Re: Python and encodings drives me crazy

2005-06-20 Thread John Machin
Oliver Andrich wrote:
> 2005/6/21, Konstantin Veretennicov <[EMAIL PROTECTED]>:
> 
>>It does, as long as headline and caption *can* actually be encoded as
>>macroman. After you decode headline from utf-8 it will be unicode and
>>not all unicode characters can be mapped to macroman:
>>
>>
>u'\u0160'.encode('utf8')
>>
>>'\xc5\xa0'
>>
>u'\u0160'.encode('latin2')
>>
>>'\xa9'
>>
>u'\u0160'.encode('macroman')
>>
>>Traceback (most recent call last):
>>  File "", line 1, in ?
>>  File "D:\python\2.4\lib\encodings\mac_roman.py", line 18, in encode
>>return codecs.charmap_encode(input,errors,encoding_map)
>>UnicodeEncodeError: 'charmap' codec can't encode character u'\u0160' in 
>>position
>> 0: character maps to 
> 
> 
> Yes, this and the coersion problems Diez mentioned were the problems I
> faced. Now I have written a little cleanup method, that removes the
> bad characters from the input

By "bad characters", do you mean characters that are in Unicode but not 
in MacRoman?

By "removes the bad characters", do you mean "deletes", or do you mean 
"substitutes one or more MacRoman characters"?

If all you want to do is torch the bad guys, you don't have to write "a 
little cleanup method".

To leave a tombstone for the bad guys:

 >>> u'abc\u0160def'.encode('macroman', 'replace')
'abc?def'
 >>>

To leave no memorial, only a cognitive gap:

 >>> u'The Good Soldier \u0160vejk'.encode('macroman', 'ignore')
'The Good Soldier vejk'

Do you *really* need to encode it as MacRoman? Can't the Mac app 
understand utf8?

You mentioned cp850 in an earlier post. What would you be feeding 
cp850-encoded data that doesn't understand cp1252, and isn't in a museum?

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


Re: What is different with Python ?

2005-06-20 Thread Mike Meyer
"Claudio Grondi" <[EMAIL PROTECTED]> writes:
> 
> What has it all to do with Python? To be not fully off-topic, I
> suggest here,  that it is much easier to discuss programming
> related matters (especially in case of Python :-) or mathematics
> than any other subjects related to nature, because programming is
> _so easy_ compared to what is going on in the "real world".
> I see the reason for that in the fact, that programming is based
> on ideas and rules developed by humans themselves, so it is
> relatively easy to test and proove if statements are right or not.

As a mathematician, I have to say "ugh". Not all statements are easy
to test and prove. In fact, in any non-trivial mathematical system,
there will be statements that *cannot* be proven to be either true
or false. Some of those statements are interesting. The legends of
mathematics are problems that aren't easy to test and prove: fermant's
last theorem, the four color map theorem, and so on. Check out http://mathworld.wolfram.com/UnsolvedProblems.html > for a longer list.

It's not clear that the ideas/rules were "developed" by humans. I'd
say "discovered". In some cases in the past, mathematicians unhappy
about some rule set out to show that it must be true (or false). In
failing to show that, they invented a new branch of mathematics.

I'd say programming is more like that. But I approach programming from
a mathematicians viewpoint.

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


Re: What is different with Python ?

2005-06-20 Thread Mike Meyer
Andrew Dalke <[EMAIL PROTECTED]> writes:

> Andrea Griffini wrote:
> > Wow... I always get surprises from physics. For example I
> > thought that no one could drop confutability requirement
> > for a theory in an experimental science...
> 
> Some physicists (often mathematical physicists) propose
> alternate worlds because the math is interesting.

Mathematicians, on the other hand, tried to demonstrate that their
alternate worlds couldn't exist - and found the math in their failures
interesting. Hence we get non-euclidean geometries and other
interesting things - that physicists find useful. (To be fair, some
of the alternate mathematical world were first explored by physicists).

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


Re: What is different with Python ?

2005-06-20 Thread Mike Meyer
Andrea Griffini <[EMAIL PROTECTED]> writes:

> On Tue, 14 Jun 2005 16:40:42 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:
> 
> >Um, you didn't do the translation right.
> 
> Whoops.
> 
> So you know assembler, no other possibility as it's such
> a complex language that unless someone already knows it
> (and in the specific architecture) what i wrote is pure
> line noise.
> 
> You studied it after python, I suppose.

Nope. I don't think I've learned any assemblers since I learned Python.
Of course, I'd been writing code for 20 years before I learned Python.

> >> or, even more concrete and like what I learned first
> >>
> >>  lda $300
> >>  clc
> >>  adc $301
> >>  sta $302
> >>
> >> is simpler to understand.
> >
> >No, it isn't - because you have to worry about more details.
> 
> In assembler details are simply more explicit. Unfortunately
> with computers you just cannot avoid details, otherwise your
> programs will suck bad. When I wrote in an high level language
> or even a very high level one the details are understood even
> if I'm not writing down them. After a while a programmer will
> even be able to put them at a subconscius level and e.g. by
> just looking at O(N^2) code that could be easily rewritten as
> O(N) or O(1) a little bell will ring in you brain telling you
> "this is ugly". But you cannot know if something is O(1) or
> O(N) or O(N^2) unless you know some detail. If you don't like
> details then programming is just not the correct field.

I've never argued otherwise.

> Think that "a = b + c" in computes the sum of two real
> numbers and your program will fail (expecting, how fool,
> that adding ten times 0.1 you get 1.0) and you'll spend
> some time wondering why the plane crashed... your code
> was "correct" after all.

Especially if b and c aren't floats. I've always used "real" as a
mathematical term, since they had it first. Computers don't deal with
reals.

> >For instance, whitesmith had a z80 assembler that let you write:
> >
> >  a = b + c
> >
> >and it would generate the proper instructions via direct
> >translation.
> 
> To use that I've to understand what registers will be
> affected and how ugly (i.e. inefficient) the code could
> get. Programmin in assembler using such an high level
> feature without knowing those little details woul be
> just suicidal.

The assembler lets you specify which registers to use. You either name
them in place of variables, or variables that are labels for the
registers.

> >> But saying for example that
> >>
> >>  del v[0]
> >>
> >> just "removes the first element from v" you will end up
> >> with programs that do that in a stupid way, actually you
> >> can easily get unusable programs, and programmers that
> >> go around saying "python is slow" for that reason.
> >
> >That's an implementation detail. It's true in Python, but isn't
> >necessarily true in other languages.
> 
> Yeah. And you must know which is which. Otherwise you'll
> write programs that just do not give the expected result
> (because the user killed them earlier).

Actually, it isn't always true in Python. What if v is a dictionary (in
which case the description is wrong), or a class that maps an SQL table's
row id's to objects holding the data for that row? In either case, the
statement will be O(1).

You do need to know which is which.

> >Yes, good programmers need to know that information - or,
> >as I said before, they need to know that they need to know
> >that information, and where to get it.
> 
> I think that a *decent* programmer must understand if the
> code being written is roughly O(n) or O(n^2). Without
> at least that the possibility of writing useful code,
> excluding may be toy projects, is a flat zero.
> Looking that information later may be just "too" late,
> because the wrong data structure has already been used
> and nothing can be done (except rewriting everything).

I don't think those two statements contradict each other. A decent
programmer will know the O() of the code they write - or where to
find that information. And they'll check it beforehand.

The advantage of using an HLL is that rewriting everything to try
other data structures (after all, the constants that O() notation
ignore matter as well, so that the fastest O() notation may not be
the fastest solution for the problem in hand).

> >That may well be true of the standard C++ library - I don't write
> >it. But it certainly doesn't appear to be true of, for instance,
> >Python internals. I've never seen someone explain why, for instance, 
> >string addition is O(n^2) beyond the very abstract "it creates a new
> >string with each addition". No concrete details at all.
> The problem is that unless you really internalized what
> that means you'll forget about it. Don't ask me why,
> but it happens. Our mind works that way. You just cannot
> live with a jillion of unrelated details you cannot place
> in a scheme. It doesn't work. One would do thousand times
> the effort 

Re: references/addrresses in imperative languages

2005-06-20 Thread Andrea Griffini
On Sun, 19 Jun 2005 22:25:13 -0500, Terry Hancock
<[EMAIL PROTECTED]> wrote:

>> PS is there any difference between
>> t=t+[li]
>> t.append(li)
>
>No, but

Yes, a big one. In the first you're creating a new list
and binding the name t to it, in the second you're extending
a list by adding one more element at the end.
To see the difference:

  >>> a = [1,2,3]
  >>> b = a
  >>> a = a + [4]
  >>> print a
  [1, 2, 3, 4]
  >>> print b
  [1, 2, 3]
  >>>
  >>> a = [1,2,3]
  >>> b = a
  >>> a.append(4)
  >>> print a
  [1, 2, 3, 4]
  >>> print b
  [1, 2, 3, 4]
  >>>

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


Re: Using print with format to stdout generates unwanted space

2005-06-20 Thread Tim Williams (gmail)
On 6/20/05, Michael Hoffman <[EMAIL PROTECTED]> wrote:
> Paul Watson wrote:
> 
> > While printf() does tightly control formatting in C, it does not in
>  > Python.
> 
> There is no printf() in Python. You should not think of print as being a
> Python version of printf.

For quick and simple removal of the extra space,  append a '\b'
backspace character to your output "string"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a list from a file

2005-06-20 Thread Rune Strand
But iif it are many lists in the file and they're organised like this:

['a','b','c','d','e']
['a','b','c','d','e']
['A','B','C','D','E'] ['X','F','R','E','Q']

I think this'll do it

data = open('the_file', 'r').read().split(']')

lists = []
for el in data:
el = el.replace('[', '').strip()
el = el.replace("'", "")
lists.append(el.split(','))

# further processing of lists

but the type problem is still to be resolved ;-)

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


Re: references/addrresses in imperative languages

2005-06-20 Thread Jordan Rastrick
You can add Australia to the list :)

Any volunteers for a fourth continent? Antarctica, perhaps? ;)

- Jordan

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


Re: reading a list from a file

2005-06-20 Thread Jordan Rastrick
If you decide to steer clear of eval, the following comes close to what
you want, and is somewhat Pythonic (I feel):

def back_to_list(str):
   return str.strip("[]").split(", ")

>>> s = "[1, 2, 3, 4, 5, 6]"
>>> back_to_list(s)
['1', '2', '3', '4', '5', '6']

So parsing the list structure is pretty easy. The problem is the list
elements are still in string form.

If they're only integers like in this example, you're fine. If they're
arbitrary objects, on the other hand, well then you may need eval after
all.

Question is, how did they get printed to a file in this form in the
first place?

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


Re: Python and encodings drives me crazy

2005-06-20 Thread Oliver Andrich
2005/6/21, Konstantin Veretennicov <[EMAIL PROTECTED]>:
> It does, as long as headline and caption *can* actually be encoded as
> macroman. After you decode headline from utf-8 it will be unicode and
> not all unicode characters can be mapped to macroman:
> 
> >>> u'\u0160'.encode('utf8')
> '\xc5\xa0'
> >>> u'\u0160'.encode('latin2')
> '\xa9'
> >>> u'\u0160'.encode('macroman')
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "D:\python\2.4\lib\encodings\mac_roman.py", line 18, in encode
> return codecs.charmap_encode(input,errors,encoding_map)
> UnicodeEncodeError: 'charmap' codec can't encode character u'\u0160' in 
> position
>  0: character maps to 

Yes, this and the coersion problems Diez mentioned were the problems I
faced. Now I have written a little cleanup method, that removes the
bad characters from the input and finally I guess I have macroman
encoded files. But we will see, as soon as I try to open them on the
Mac. But now I am more or less satisfied, as only 3 obvious files
aren't converted correctly and the other 1000 files are.

Thanks for your hints, tips and so on. Good Night.

Oliver

-- 
Oliver Andrich <[EMAIL PROTECTED]> --- http://fitheach.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and encodings drives me crazy

2005-06-20 Thread Konstantin Veretennicov
On 6/20/05, Oliver Andrich <[EMAIL PROTECTED]> wrote:
> Does the following code write headline and caption in
> MacRoman encoding to the disk?
> 
> f = codecs.open(outfilename, "w", "macroman")
> f.write(headline)

It does, as long as headline and caption *can* actually be encoded as
macroman. After you decode headline from utf-8 it will be unicode and
not all unicode characters can be mapped to macroman:

>>> u'\u0160'.encode('utf8')
'\xc5\xa0'
>>> u'\u0160'.encode('latin2')
'\xa9'
>>> u'\u0160'.encode('macroman')
Traceback (most recent call last):
  File "", line 1, in ?
  File "D:\python\2.4\lib\encodings\mac_roman.py", line 18, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0160' in position
 0: character maps to 

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


Re: reading a list from a file

2005-06-20 Thread Jordan Rastrick
Be careful, though - make sure you can absolutely trust your source of
data before calling eval on it.

If an unauthorised person could forseeably modify your file, then they
could insert a string containing arbitrary Python code into it in place
of your list, and then running your program would cause that code to be
executed.

So, to put it bluntly, eval is dangerous.

Sure is convenient, though :)

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


Re: Python and encodings drives me crazy

2005-06-20 Thread Diez B. Roggisch
Oliver Andrich wrote:
> Well, I narrowed my problem down to writing a macroman or cp850 file
> using the codecs module. The rest was basically a misunderstanding
> about codecs module and the wrong assumption, that my input data is
> iso-latin-1 encode. It is UTF-8 encoded. So, curently I am at the
> point where I have my data ready for writing
> 
> Does the following code write headline and caption in MacRoman
> encoding to the disk? Or better that, is this the way to do it?
> headline and caption are both unicode strings.
> 
> f = codecs.open(outfilename, "w", "macroman")
> f.write(headline)
> f.write("\n\n")
> f.write(caption)
> f.close()

looks ok - but you should use u"\n\n" in general - if that line for some 
reason chages to "öäü" (german umlauts), you'll get the error you 
already observed. But using u"äöü" the parser pukes at you when the 
specified coding of the file can't decode that bytes to the unicode object.

Most problems occdure when one confuses unicode objects with strings - 
this requires a coercion that will be done using the default encoding 
error you already observed.


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


Re: Using print with format to stdout generates unwanted space

2005-06-20 Thread Michael Hoffman
Paul Watson wrote:

> While printf() does tightly control formatting in C, it does not in
 > Python.

There is no printf() in Python. You should not think of print as being a 
Python version of printf.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: references/addrresses in imperative languages

2005-06-20 Thread Michael Sparks
Jeremy Jones wrote:

> I think the only reason I read your posts is for comedy,

Indeed. 

> Xah Lee wrote:
> ... [ lots of stuff, that if Xah cared about Xah would attempt to write
> better docs, rather than criticise) ... 
...
>>Btw, behavior such as this one, common in imperative languages and info
>>tech industry, is a criminality
>>
> Nice.  If you don't like something, just call it "a criminality".  Let
> me try:  the criminality of Xah Lee's postings caused all occupants of
> at least 4 continents to roll their eyes.  You know - even though I
> think my assertion had some validity, I think even there it's ridiculous
> to make such a forceful assertion without a foundation for it.

Oh, I don't know, the level of swearing on Xah's posts might be criminal in
some countries attached to Usenet - there's a lot of dodgy governments in
the world. (Then again, Xah may just have "net-tourettes" (no offense to
anyone intended) :-)

However 4 continents rolling their eyes? I'm guessing that you're in the
North American continent from your email, I'm in Europe, so that's at least
2 continents...

 >:-)


Michael.

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


Question about HTMLgen

2005-06-20 Thread Sebastian Bassi
Hello,

I am using HTMLgen. It is very nice. But I can't make it to generate
an arbitrary command.
For example I want to output this:



Each time I put "<" it gets escaped from HTML, instead of being inserted inside.

-- 
http://www.spreadfirefox.com/?q=affiliates&id=24672&t=1";>La
web sin popups ni spyware: Usa Firefox en lugar de Internet
Explorer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a list from a file

2005-06-20 Thread Tim Williams

- Original Message - 
From: "David Bear" <[EMAIL PROTECTED]>


> I have a file that contains lists -- python lists. sadly, these are not
> pickled. These are lists that were made using a simple print list
> statement.
> 
> Is there an easy way to read this file into a list again?  I'm thinking I
> would have to 
> 
> 
> I was hoping there was a pythonic way of doing this..
> 

a = '[1,2,3,4,5]'
>>> b = eval(a)
>>> b
[1, 2, 3, 4, 5]
>>> b[2]
3

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


Re: Python and encodings drives me crazy

2005-06-20 Thread Oliver Andrich
Well, I narrowed my problem down to writing a macroman or cp850 file
using the codecs module. The rest was basically a misunderstanding
about codecs module and the wrong assumption, that my input data is
iso-latin-1 encode. It is UTF-8 encoded. So, curently I am at the
point where I have my data ready for writing

Does the following code write headline and caption in MacRoman
encoding to the disk? Or better that, is this the way to do it?
headline and caption are both unicode strings.

f = codecs.open(outfilename, "w", "macroman")
f.write(headline)
f.write("\n\n")
f.write(caption)
f.close()

Best regards,
Oliver

-- 
Oliver Andrich <[EMAIL PROTECTED]> --- http://fitheach.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


reading a list from a file

2005-06-20 Thread David Bear
I have a file that contains lists -- python lists. sadly, these are not
pickled. These are lists that were made using a simple print list
statement.

Is there an easy way to read this file into a list again?  I'm thinking I
would have to 

read until char = '['
   read until char = " ' "

Well, reading character by char until I have the list and then parse it all
myself.

I was hoping there was a pythonic way of doing this..

-- 
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sudoku dictionary attack

2005-06-20 Thread Oliver Albrecht
Has some one an sodoku-task-generator?
Here another solutions-ways:
http://www.python-forum.de/viewtopic.php?t=3378

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


Re: Python and encodings drives me crazy

2005-06-20 Thread Oliver Andrich
> I know this isn't your question, but why write:
> 
>  > data = apply(string.replace, [data, html, char])
> 
> when you could write
> 
>  data = data.replace(html, char)
> 
> ??

Cause I guess, that I am already blind. Thanks.

Oliver

-- 
Oliver Andrich <[EMAIL PROTECTED]> --- http://fitheach.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JEP and JPype in a single process

2005-06-20 Thread Steve Menard
skn wrote:
> Hello,
> 
> I have written a very simple java class file, which invokes a Python script
> using JEP.
> 
> Code snippet:-
> ---
> Jep jep = new Jep(false);
> jep.runScript("C:\\temp\\testscript.py");
> jep.close();
> 
> Now inside this Python script I want to make Java calls using JPype.
> If I use startjvm() inside this Python script, a Runtime Error (exception)
> is thrown.
> Also tried attachThreadToJVM(), but doesn't work, again Runtime Error.
> 
> Any clues as to how I could achieve my goal??
> The interaction shown below should happen in a single process.
> 
> JAVA ==> jep ==> PYTHON ==> jpype ==> JAVA
> 
> Regards,
> skn
> 
> 

You're trying to do something I hope to make possible somewhere down the 
road ...

As of today, I do not think it is possible. JPype does not provide a way 
to initialize the JVM-bridge system except for startJvm .. which seems 
to be prohibited when a JVM is already running.

AttachThreadToJVM will only work once the JVM-bridge system has been 
initialize.

I will look into providing a sister method to startJVM to attach to the 
currently running JVM instead of starting a new one. IF it does not 
require major changes I will release it as 0.5.1. If you'd like you can 
submit an enhancement request on the JPype sourceforge page, so this 
doesn't get lost.



-- 
Steve Menard

Maintainer of http://jpype.sourceforge.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and encodings drives me crazy

2005-06-20 Thread Steven Bethard
Oliver Andrich wrote:
> def remove_html_entities(data):
>   for html, char in html2text:
> data = apply(string.replace, [data, html, char])
>   return data

I know this isn't your question, but why write:

 > data = apply(string.replace, [data, html, char])

when you could write

 data = data.replace(html, char)

??

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


[no subject]

2005-06-20 Thread python-list-bounces+archive=mail-archive . com
#! rnews 902
Newsgroups: comp.lang.python
Path: 
news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp
From: Harry George <[EMAIL PROTECTED]>
Subject: Re: Couple functions I need, assuming they exist?
X-Nntp-Posting-Host: cola2.ca.boeing.com
Content-Type: text/plain; charset=us-ascii
Message-ID: <[EMAIL PROTECTED]>
User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4
Lines: 15
Sender: [EMAIL PROTECTED]
Organization: The Boeing Company
References: <[EMAIL PROTECTED]>
Mime-Version: 1.0
Date: Mon, 20 Jun 2005 20:12:51 GMT
Xref: news.xs4all.nl comp.lang.python:382593

Charles Krug <[EMAIL PROTECTED]> writes:

[snip]
> The target of the problems (my daughter) ...
[snip]

That sounds familiar :-).  See:
http://www.seanet.com/~hgg9140/math/index.html
http://www.seanet.com/~hgg9140/math/k6.html


-- 
[EMAIL PROTECTED]
6-6M21 BCA CompArch Design Engineering
Phone: (425) 294-4718
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and encodings drives me crazy

2005-06-20 Thread Oliver Andrich
Hi everybody,

I have to write a little skript, that reads some nasty xml formated
files. "Nasty xml formated" means, we have a xml like syntax, no dtd,
use html entities without declaration and so on. A task as I like it.
My task looks like that...

1. read the data from the file.
2. get rid of the html entities
3. parse the stuff to extract the content of two tags.
4. create a new string from the extracted content
5. write it to a cp850 or even better macroman encoded file

Well, step 1 is easy and obvious. Step is solved for me by 

= code =

from htmlentitydefs import entitydefs

html2text = []
for k,v in entitydefs.items():
  if v[0] != "&":
html2text.append(["&"+k+";" , v])
  else:
html2text.append(["&"+k+";", ""])

def remove_html_entities(data):
  for html, char in html2text:
data = apply(string.replace, [data, html, char])
  return data

= code =

Step 3 + 4 also work fine so far. But step 5 drives me completely
crazy, cause I get a lot of nice exception from the codecs module.

Hopefully someone can help me with that. 

If my code for processing the file looks like that:

def process_file(file_name):
  data = codecs.open(file_name, "r", "latin1").read()
  data = remove_html_entities(data) 
  dom = parseString(data)
  print data

I get

Traceback (most recent call last):
  File "ag2blvd.py", line 46, in ?
process_file(file_name)
  File "ag2blvd.py", line 33, in process_file
data = remove_html_entities(data)
  File "ag2blvd.py", line 39, in remove_html_entities
data = apply(string.replace, [data, html, char])
  File "/usr/lib/python2.4/string.py", line 519, in replace
return s.replace(old, new, maxsplit)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position
0: ordinal not in range(128)

I am pretty sure that I have iso-latin-1 files, but after running
through my code everything looks pretty broken. If I remove the call
to remove_html_entities I get

Traceback (most recent call last):
  File "ag2blvd.py", line 46, in ?
process_file(file_name)
  File "ag2blvd.py", line 35, in process_file
print data
UnicodeEncodeError: 'ascii' codec can't encode character u'\x96' in
position 2482: ordinal not in range(128)

And this continues, when I try to write to a file in macroman encoding. 

As I am pretty sure, that I am doing something completely wrong and I
also haven't found a trace in the fantastic cookbook, I like to ask
for help here. :)

I am also pretty sure, that I do something wrong as writing a unicode
string with german umlauts to a macroman file opened via the codecs
module works fine.

Hopefully someone can help me. :)

Best regards,
Oliver

-- 
Oliver Andrich <[EMAIL PROTECTED]> --- http://fitheach.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: binary file

2005-06-20 Thread Scott David Daniels
Kent Johnson wrote:
> Nader Emami wrote:
>> Kent Johnson wrote:
>>> Nader Emami wrote:
 I have used the profile module to measure some thing as the next 
 command:
 profile.run('command', 'file')
 ...How can I read (or convert) the binary file to an ascii file?
>>> Use an instance of pstats.Stats to interpret the results:
>>> from pstats import Stats
>>> s = Stats('file')
>>> s.print_stats()
>> I got the same result as the execution of command. But I would like to 
>> write to the an external 'ascii' file!
> Oh, I get it, pstats.Stats doesn't have a way to send the output to a 
> file. That's surprising!
I may be missing something here, but:
 import sys, pstats

 s = pstats.Stats('file')
 sys.stdout, old = open('somefile.txt', 'w'), sys.stdout
 s.print_stats()
 sys.stdout, old = old, sys.stdout
 old.close()
Looks to solve your problem to me.

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


Re: Python choice of database

2005-06-20 Thread Brian
I am really surprised that someone hasn't mentioned Gadfly yet.  It is a 
quick, free, relational database written directly for Python itself.

http://gadfly.sourceforge.net/

Brian
---


Philippe C. Martin wrote:
> Hi,
> 
> I am looking for a stand-alone (not client/server) database solution for
> Python.
> 
> 1) speed is not an issue
> 2) I wish to store less than 5000 records
> 3) each record should not be larger than 16K
> 
> 
> As I start with Python objects, I thought of using shelve, but looking at
> the restrictions (record size + potential collisions) I feel I should study
> my options a bit further before I get started.
> 
> 
> Regards,
> 
> Philippe
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UML to Python/Java code generation

2005-06-20 Thread Magnus Lycka
James wrote:
> The brain may be fine for generating Python from UML but it is MANY
> MANY orders of magnitude harder to generate UML from code with just
> your brain than using a tool (usually zero effort and error free) no
> matter how good you are at Python.

I've really only used Rational Rose, but that tool is
really limited in both directions. Class structure to
class diagrams work both ways (not for Python, but for
Java and C++ at least) but that's just a tiny part of
UML.

I don't expect any tool to do anything meaningful about e.g.
use case diagrams, but what about activity diagrams, sequence
diagrams, collaboration diagrams and state diagrams?

I agree that the brain is poor at such things, but I doubt
that any current tool is much better except for trivial
subsets of UML.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedded Systems Python?

2005-06-20 Thread Diez B. Roggisch
Dennis Clark wrote:
>   I'm a bit of a newb when it comes to Python, is there anyone with experience
> compiling it on Linux platforms that can offer me pointers to try this out
> myself?

Seatch for cross-compiling python patches. I'm working on an XScale255 
platform with python2.2 and soon 2.3 - no trouble there.

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


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
Yes, I agree, but as most of the customer base I target uses the O/S that
cannot be named ;-) , file names could become a problem just as 'ln -s' is
out of the question.

Yet, this might be the best trade-off.

Regards,

Philippe



Oren Tirosh wrote:

> Philippe C. Martin wrote:
>> Hi,
>>
>> I am looking for a stand-alone (not client/server) database solution for
>> Python.
>>
>> 1) speed is not an issue
>> 2) I wish to store less than 5000 records
>> 3) each record should not be larger than 16K
> 
> How about using the filesystem as a database? For the number of records
> you describe it may work surprisingly well. A bonus is that the
> database is easy to manage manually. One tricky point is updating: you
> probably want to create a temporary file and then use os.rename to
> replace a record in one atomic operation.
> 
> For very short keys and record (e.g. email addresses) you can use
> symbolic links instead of files. The advantage is that you have a
> single system call (readlink) to retrieve the contents of a link. No
> need to open, read and close.
> 
> This works only on posix systems, of course. The actual performance
> depends on your filesystem but on linux and BSDs I find that
> performance easily rivals that of berkeleydb and initialization time is
> much faster. This "database" also supports reliable concurrent access
> by multiple threads or processes.
> 
> See http://www.tothink.com/python/linkdb
> 
> Oren

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


Re: references/addrresses in imperative languages

2005-06-20 Thread Kaz Kylheku
Walter Roberson wrote:
> In article <[EMAIL PROTECTED]>,
> Xah Lee <[EMAIL PROTECTED]> wrote:
> >In hindsight analysis, such language behavior forces the programer to
> >fuse mathematical or algorithmic ideas with implementation details. A
> >easy way to see this, is to ask yourself: how come in mathematics
> >there's no such thing as "addresses/pointers/references".
>
> There is. Each variable in predicate calculas is a reference.
> No matter how large the formulae, a change in a variable
> is, in mathematics, immediately propagated to all occurances
> of the variable (potentially changing the references of other
> variables).

Variables don't change in mathematics, at least the run-of-the-mill
everyday mathematics. :)

> If the predicate calculas variables were not equivilent to references,
> then the use of the variable in a formula would have to be a
> non-propogating copy. and a change to the original value whence not
> be reflected in all parts of the formula and would not change
> what the other variables referenced.
>
> Consider for example the proof of Goedel's Incompleteness
> theorem, which involves constructing a formula with a free
> variable, and constructing the numeric encoding of that
> formula, and then substituting the numeric encoding in as
> the value of the free variable, thus ending up with
> a number that is "talking about" iteelf.

All these substitutions ``work'' in a way that is analogous to
functional programming. For example, substituting a variable into a
formula generates a new formula with occurences of that variable
replaced by the given value. You haven't destroyed the old formula.

> The process of
> the proof is *definitely* one of "reference" to a value
> in the earlier stages, with the formula being "evaluated"
> at a later point -- very much like compiling a program
> and then feeding the compiled program as input to itelf.

Actually no. The process specifically avoids the pointer problem by
using an arithmetic coding for the formula, the Goedel numbering. The
formula talks about an encoded version of itself. That's how the
self-reference is smuggled in, via the Goedel numbering.

> You
> cannot do it without a reference, because you need to
> have the entire number available as data at the time
> you start evaluating the mathematical formula.

The final result just /is/ self-referential. It's not constructed bit
by bit like a data structure inside a digital computer that starts out
being non-self-referential and is then backpatched to point to itself.

A mathematical derivation may give you the idea that something is
changing in place, because you always hold the most recent version of
the formula at the forefront of your mind, and can visualize the whole
process as a kind of in-place animation in your head. But really, at
each step you are making something completely new which stands on its
own.

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


Re: Embedded Systems Python?

2005-06-20 Thread Michael Sparks
Dennis Clark wrote:
...
>   Has anyone, or is anyone working with Python in an embedded Linux
> environment?  Mine is NO where near as constrained as a cell phone since
> I've got plenty of memory to work with, I'm just running a Linux 2.4
> kernel on an ARM9 platform.

This really shouldn't be a problem - especially given python can be made
to run on mobile phones (Nokia Series 60). We've found using python on
Series 60 phones to be quite useful, so if you're using a linux box, you're
presumably got more memory/CPU available than there, so I doubt you'll
see major problems.

Regards,


Michael.
--
http://kamaelia.sourceforge.net/

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


Re: What is different with Python ?

2005-06-20 Thread Rocco Moretti
Andrea Griffini wrote:

> Indeed when talking about if learning "C" can hinder
> or help learning "C++" I remember thinking that to
> learn "C++" *superficially* learning "C" first is
> surely pointless or can even hinder.
> But to learn "C++" deeply (with all its quirks) I
> think that learning "C" first helps.

I think you are mistakingly bringing order into the picture, when extent 
is more likely the case. If you want to master C++, I think that most 
would agree you need to understand C. But there are many who would 
disagree that the path to C++ must *start* at C. (In fact, many people 
argue that a lot of bad C++ is due to people programming C in C++.) 
Instead they would argue that you should start by learning C++ 
"superficially", then learn C, and re-evaluate you C++ practices in 
light of the lessons learned from C.

The example I'll pull out is natural languages - I understood the 
grammar & construction of my native tounge *much* better after learning 
a foreign language. From people I've talked to, this is a common 
occurance. But there would be few people who would advocate that one 
should learn a foreign language before learning one's native tounge.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overcoming herpetophobia (or what's up w/ Python scopes)?

2005-06-20 Thread John Ochiltree
On 2005-06-18 05:26:13 +0100, Dennis Lee Bieber <[EMAIL PROTECTED]> said:

> On Sat, 18 Jun 2005 03:02:13 +1000, Steven D'Aprano
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
>> 
>> The language is *always* spelt without the "a", and usually all in
>> lower-case: perl.
>> 
>   Given that, at least one well known, book relates the name to
> Practical Extraction (&) Report Language, whether that was a retrofit or
> not -- I'd be tempted to user PERL for the name... All lowercase most
> likely reflects the standard habits of Linux/Unix command naming.

I'd heard it was pathologically eclectic rubbish lister, but then you 
can't believe everything you hear :-)

John Ochiltree
-- 
667 - The Neighbour of the Beast

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


Re: Python choice of database

2005-06-20 Thread Oren Tirosh
Philippe C. Martin wrote:
> Hi,
>
> I am looking for a stand-alone (not client/server) database solution for
> Python.
>
> 1) speed is not an issue
> 2) I wish to store less than 5000 records
> 3) each record should not be larger than 16K

How about using the filesystem as a database? For the number of records
you describe it may work surprisingly well. A bonus is that the
database is easy to manage manually. One tricky point is updating: you
probably want to create a temporary file and then use os.rename to
replace a record in one atomic operation.

For very short keys and record (e.g. email addresses) you can use
symbolic links instead of files. The advantage is that you have a
single system call (readlink) to retrieve the contents of a link. No
need to open, read and close.

This works only on posix systems, of course. The actual performance
depends on your filesystem but on linux and BSDs I find that
performance easily rivals that of berkeleydb and initialization time is
much faster. This "database" also supports reliable concurrent access
by multiple threads or processes.

See http://www.tothink.com/python/linkdb

Oren

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


RE: Python choice of database

2005-06-20 Thread Hughes, Chad O
One db that is very much worth trying is Firebird.  This is an open
source Interbase 6.0 (Borland product) compatible db.  It is a
SourceForge project.  There are three versions: the super server which
is a client/server db, classic server (the one that I am very familiar
with) which is also a client/server db, and the embedded server which is
a standalone.  In order to access the database you need the open source
module KInterbasdb which is also a SourceForge project.  KInterbasdb is
a Python DB API 2.0 database driver.

Firebird has a lot of documentation.  Moreover it was made based on the
Interbase 6.0, which is was made open source by Borland, so all of
Borland's documentation and tools apply as well.


Firebird can be found at:
http://firebird.sourceforge.net/

KInterbasdb can be found at:
http://kinterbasdb.sourceforge.net/



-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Philippe C. Martin
Sent: Monday, June 20, 2005 8:19 AM
To: python-list@python.org
Subject: Python choice of database


Hi,

I am looking for a stand-alone (not client/server) database solution for
Python.

1) speed is not an issue
2) I wish to store less than 5000 records
3) each record should not be larger than 16K


As I start with Python objects, I thought of using shelve, but looking
at the restrictions (record size + potential collisions) I feel I should
study my options a bit further before I get started.


Regards,

Philippe

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


Re: login website that using PHP

2005-06-20 Thread frost
Thank you all for the help. This problem bothered me for 3 days, Now I
get it! You are right, it is the session cookie, after I use the
cookiejar and the opener, I got it!!! I am really glad I found this
place. Thank you  again!

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


Re: binary file

2005-06-20 Thread Kent Johnson
Nader Emami wrote:
> Kent Johnson wrote:
> 
>> Nader Emami wrote:
>>
>>> L.S.,
>>>
>>> I have used the profile module to measure some thing as the next 
>>> command:
>>>
>>> profile.run('command', 'file')
>>>
>>> But this make a binary file! How can I write the result of 'profile' 
>>> in a ascii file? Others how can I read (or convert) the binary file 
>>> to am ascii file?
>>
>>
>>
>> Use an instance of pstats.Stats to interpret the results:
>>
>> from pstats import Stats
>> s = Stats('file')
>> s.print_stats()
>>
>> etc.
>> http://docs.python.org/lib/profile-stats.html
>>
>> Kent
> 
> I got the same result as the execution of command. But I would like to 
> write to the an external 'ascii' file!

Oh, I get it, pstats.Stats doesn't have a way to send the output to a file. 
That's surprising!

One option would be to write a program that outputs what you want, then 
redirect the output in the shell. Alternatively take a look a the source for 
print_stats() and write your own that outputs to a file.

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


Re: Back to the future - python to C++ advice wanted

2005-06-20 Thread George Sakkis
"Kay Schluehr" wrote:

> I recommend studying C++ idioms carefully.
>
> http://www1.bell-labs.com/user/cope/Patterns/C++Idioms/EuroPLoP98.html

Thanks for the link; very useful indeed.

> If Georges starts on greenfields he may have a look at Qt and it's
> object library which is not only concerned with widgets.
>
> http://doc.trolltech.com/3.3/
>
> BOOST is more high brow and I guess that it compiles slow because it
> uses templates extensively. Template metaprogramming as a compile time
> language was a funny discovery. Here is some prove of it's
> capabilities:
>
> http://osl.iu.edu/~tveldhui/papers/2003/turing.pdf

Many thanks to Kay and Bruno for suggesting Boost; I browsed through
its numerous libraries and they're quite impressive ! They seem
indispensable, especially for python (or other very high level
language) programmers going back to C++. Some libraries that seem to be
very relevant to pythoneers are:

- any: brings dynamic typing in C++
- tuple; 'nuff said
- iterator: out-of-the-box equivalents of
itertools.{imap,ifilter,izip,count}, reversed(), and others not
existing or applicable in python
- tokenizer, string_algo and regex: similar functionality to str.* and
re.*
- bind, mem_fn, function, functional, lambda: first class callables,
currying, higher order (functional) programming
- assign: syntactic sugar through operator overloading for (relatively)
readable container initialization:
map next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
is actually valid and equivalent to
next = dict([(1,2), (2,3), (3,4), (4,5), (5,6)])
- many, many more goodies, with or without respective standard python
equivalent (threads, graphs, math utils, serialization,
metaprogramming, etc).
- and last but not least, Boost.Python. I don't think it's just a
coincidence that among all languages they chose Python to make
interoperable with C++ :-)

Thanks again,
George

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


Re: utf8 and ftplib

2005-06-20 Thread Fredrik Lundh
Richard Lewis wrote:

> On Mon, 20 Jun 2005 14:27:17 +0200, "Fredrik Lundh"
> <[EMAIL PROTECTED]> said:
> >
> > well, you're messing it up all by yourself.  getting rid of all the
> > codecs and
> > unicode2charrefs nonsense will fix this:
> >
> Thanks for being so patient and understanding.
>
> OK, I've taken it all out. The only thinking about encoding I had to do
> in the actual code I'm working on was to use:
> file.write(document.toxml(encoding="utf-8"))
>
> instead of just
> file.write(document.toxml())
>
> because otherwise I got errors on copyright symbol characters.

sounds like a bug in minidom...

> My code now works without generating any errors but Konqueror's KHTML
> and Embedded Advanced Text Viewer and IE5 on the Mac still show
> capital-A-with-a-tilde in all the files that have been
> generated/altered. Whereas my text editor and Mozilla show them
> correctly.
>
> The "unicode2charrefs() nonsense" was an attempt to make it output with
> character references rather than literal characters for all characters
> with codes greater than 128. Is there a way of doing this?

character references refer to code points in the Unicode code
space, so you just convert the bytes you get after converting
to UTF-8. however, if you're only using characters from the ISO
Latin 1 set (which is a strict subset of Unicode), you could en-
code to "iso-8859-1" and run unicode2charrefs on the result.

but someone should really fix minidom so it does the right thing.

(fwiw, if you use my ElementTree kit, you can simply do

tree.write(encoding="us-ascii")

and the toolkit will then use charrefs for any character that's
not plain ascii.  you can get ElementTree from here:

http://effbot.org/zone/element-index.htm

)





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


Re: utf8 and ftplib

2005-06-20 Thread Kent Johnson
Richard Lewis wrote:
> My code now works without generating any errors but Konqueror's KHTML
> and Embedded Advanced Text Viewer and IE5 on the Mac still show
> capital-A-with-a-tilde in all the files that have been
> generated/altered. Whereas my text editor and Mozilla show them
> correctly.

How are you viewing the files? You have to tell the browser that they are 
UTF-8. If you just double-click the file, the browser will use its default 
encoding. If you are server the files from a web server then you should set the 
Content-Type header correctly.

Or you can tell the browser directly (try View / Encoding in IE).

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


Re: Embedded Systems Python?

2005-06-20 Thread phil
I developed for my former employee a thin client whose primary purpose
was AS400 connectivity.  This required a fairly complex interactive
gui configuration which I wrote in Python.
This system could also be configed by a remote manager. Wrote
that also in python using UDP sockets.
The hardware was 64Mb memory and 64Mb compact flash.

OS wa 2.4.20 linux from Debian

I did a lot of cleanup removing unneeded modules but
other than that, standard Python 2.3.4
worked great.

Dennis Clark wrote:

> Hi all,
> 
>   I've looked through the threads about embedded Python that are a year
> and a half old, and I thought that I'd ask this question now to see if
> anything has changed.
> 
>   Has anyone, or is anyone working with Python in an embedded Linux 
> environment?  Mine is NO where near as constrained as a cell phone since
> I've got plenty of memory to work with, I'm just running a Linux 2.4 kernel
> on an ARM9 platform.
> 
>   Are there success stories for Python on embedded Linux systems today?
> The embedded Java JVM's seem to all be propriatary and have quite high
> license fees (don't mention Kaffe, it seems pretty fragile to me.)
> 
>   I'm a bit of a newb when it comes to Python, is there anyone with experience
> compiling it on Linux platforms that can offer me pointers to try this out
> myself?
> 
> thanks,
> DLC
> 



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


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
Correct, that's not a constraint right now.


Paul Rubin wrote:

> "Philippe C. Martin" <[EMAIL PROTECTED]> writes:
>> 1) speed is not an issue
>> 2) I wish to store less than 5000 records
>> 3) each record should not be larger than 16K
> 
> You don't mention whether multiple running programs need to use it
> concurrently.  That's usually done with client/server db's but it can
> be done standalone.

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


Re: Couple functions I need, assuming they exist?

2005-06-20 Thread Charles Krug
On 20 Jun 2005 15:51:07 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Peter Hansen wrote:
> 
>>> The target of the problems (my daughter) would prefer that the thousands
>>> be delimited.  Is there a string function that does this?
>> 
>> You refer to something like putting a comma between groups of three 
>> digits, as in 1,000?  This is locale-specific, and there's a "locale" 
>> module that should have what you need.
> 
 import locale
 locale.setlocale(locale.LC_ALL, '')
> 'English_United Kingdom.1252'
 print locale.format("%d", 100, True)
> 1,000,000

Perfect!

Thanks.

Sometimes "hard part" is figuring out which package already does the
thing I need done.


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


Re: login website that using PHP

2005-06-20 Thread J Correia
"frost" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>
> I am trying to login a website that using PHP and javascript. This is
> what happend if you browse that website using IE, after you login, you
> can go anywhere without enter your name and password again, as long as
> you keep that IE open, but after you close that IE, then later on open
> that website in a new window, you need to login again. I guess some
> session is created as long as your original login window dose not
> close.
>
> How I can handle this in python? I want get some information from that
> website. But the login page is not what I want, how can I simulate
> regular IE browser? I mean after I login, I can get to other pages from
> it, but I find my programe can't go other place except the login page.
>
> Hope you could understand my question. Thank you very much!
>

Check here for some other examples, specifically 'Submitting values
 and clicking buttons in IE'
 http://tinyurl.com/7n7xf


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


Re: login website that using PHP

2005-06-20 Thread Drazen Gemic
On Sun, 19 Jun 2005 19:11:38 -0700, frost wrote:

> Hi,
> 
> I am trying to login a website that using PHP and javascript. This is
> what happend if you browse that website using IE, after you login, you

Browser remembers so called HTTP authorization header field. It sends
authorization information whenever server requiress authorization by
sending corresponding status code and, so called, realm specification.

It is beyond the scope of this group and it is well described in HTTP
standard and corresponding RFC.

DG

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


Re: sudoku dictionary attack

2005-06-20 Thread Jonathan


[EMAIL PROTECTED] wrote:
> Thought I'd offer a method for solving all possible 9x9 sudoku puzzles
> in one go. It'll takes a bit of time to run however (and 9x9 seems to
> be about as big as is reasonably possible before combinatorial
> explosion completely scuppers this type of program)...
>
> Basic idea:-
>
> Start with a grid initialised with:
>
> 123456789
> 234567891
> 345678912
> 456789123
> 567891234
> 678912345
> 789123456
> 891234567
> 912345678
>
> Note that all rows and columns contain all 9 digits (but that the
> sub-tiles aren't correct for a sudoku solution).
>
> Next write a program which permutes all 9 columns, and then for each of
> those permutations permutes the last 8 rows. This will, I believe,
> generate all possible grids with no digit repetitions in any row or
> column. It will generate 14,631,321,600 (9!*8!) possible sudoku
> candidates. Finally, check each candidate to see if any 3x3 subtile has
> a repeated digit in it and discard as soon as a repeat is found (sooner
> the better). Any that come through unscathed get written as a 82 (81 +
> lf) char string to an output file.

I'm having trouble coming up with anything that fits this grid:

..12.
..2x.
.
.
.
.
.
.
.

where x is not 3, by permuting columns, then rows.  You may also have
to permute the numbers.  Although, even then, x=1 is still impossible.

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


Re: Python choice of database

2005-06-20 Thread Paul Rubin
"Philippe C. Martin" <[EMAIL PROTECTED]> writes:
> 1) speed is not an issue
> 2) I wish to store less than 5000 records
> 3) each record should not be larger than 16K

You don't mention whether multiple running programs need to use it
concurrently.  That's usually done with client/server db's but it can
be done standalone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couple functions I need, assuming they exist?

2005-06-20 Thread Paul Watson

"Charles Krug" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> The target of the problems (my daughter) would prefer that the thousands
> be delimited.  Is there a string function that does this?

Be sure to use the locale approach and avoid rolling your own. 


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


Re: Want to learn a language - is Python right?

2005-06-20 Thread Paul Watson
"Aziz McTang" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi Paul,
>
> Thanks for your input.
>
> As usual, hearing some answers helps formulate the question...
>
> What I'm looking for is more to learn one good, comprehensive
> programming language well than several approximately on an ad hoc
> basis. What I also failed to mention is the desire to develop my
> presently limited computer skills a lot further.

You have received some good advice.  There are strong tools to support 
localization, but they are not inexpensive.  They might be lower cost than 
developing your own.  However, your goal to develop your programming skills 
is also a cost to be considered.  Are you interested in developing an open 
source localization tool?

A consideration for web applications is who will be maintaining the code. 
If these are all your own and no one else will ever work on them, then use 
any tool you like.  Coding them in x86 assembly language would increase your 
computer knowledge, but we both know that is not the right tool for this 
task. 


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


sudoku dictionary attack

2005-06-20 Thread sub1ime_uk
Thought I'd offer a method for solving all possible 9x9 sudoku puzzles
in one go. It'll takes a bit of time to run however (and 9x9 seems to
be about as big as is reasonably possible before combinatorial
explosion completely scuppers this type of program)...

Basic idea:-

Start with a grid initialised with:

123456789
234567891
345678912
456789123
567891234
678912345
789123456
891234567
912345678

Note that all rows and columns contain all 9 digits (but that the
sub-tiles aren't correct for a sudoku solution).

Next write a program which permutes all 9 columns, and then for each of
those permutations permutes the last 8 rows. This will, I believe,
generate all possible grids with no digit repetitions in any row or
column. It will generate 14,631,321,600 (9!*8!) possible sudoku
candidates. Finally, check each candidate to see if any 3x3 subtile has
a repeated digit in it and discard as soon as a repeat is found (sooner
the better). Any that come through unscathed get written as a 82 (81 +
lf) char string to an output file.

I've written a short program (in Python; see below) that tries out this
idea. Indications are that my HP nc6000 laptop can check around 30,000
candidates/sec and that c.0.15% of them are valid sudoku solutions.
That means it would take around 6.5 days to generate the between 20-30
million possible sudoku solutions it will find. That would require
around 2GB in uncompressed disk storage. Gzip does a VERY good job of
compressing files containing this type of data -- so I'd expect well
over 80% compression (might even fit on a CD then).

Once you've generated the solution data then comes the fun of searching
it efficiently which I leave as an exercise for the reader :-)

Regards,  sub1ime_uk (at) yahoo (dot) com

==
#!python
#
# sudoku.py - generate all valid sudoku solutions
#
# Usage: sudoku  
#eg: sudoku 9 3
# Whare:-
#N is the grid size (ie 9 for 9x9)
#S is the sub-tile size (3 for 3x3)
#
# (c) 2005 sub1ime_uk (at) yahoo (dot) com
#
import sys
from gzip import GzipFile
from time import time

def permute(s):
  if len(s)==0: return
  if len(s)==1:
yield s
return
  for i in range(len(s)):
for t in permute(s[:i]+s[i+1:]):
  yield s[i:i+1]+t
  return

def populate(sz, ini):
  tile = []
  for i in range(sz):
tile.append([])
for j in range(sz):
  x = chr((i+j)%sz+ord(ini))
  tile[i].append(x)
  return tile

def subtilesok(t, c, r, n, s):
  for x in range(0, n, s):
for y in range(0, n, s):
  d = {}
  for i in range(s):
cn = c[x+i]
for j in range(s):
  rn = r[y+j]
  d[t[cn][rn]] = 1
  if len(d.keys())!=n: return 0
  return 1

def displaytile(t, c, r, lf):
  lfstr=''
  print
  for i in r:
row = []
for j in c:
  row.append(t[j][i])
r=''.join(row)
lfstr += r
print "",r
  print
  lf.write(lfstr+"\n")

def fact(n):
  if n<2: return 1
  return n*fact(n-1)

if __name__ == '__main__':
  st = time()
  logf = GzipFile("c:\\temp\\sudoku.gz", "w")
  N=int(sys.argv[1])
  S=int(sys.argv[2])
  estimate = fact(N)*fact(N-1)
  if N!=S*S:
print "Subtile size", S, "not sqrt of tile size", N
sys.exit(1)
  cols = [x for x in range(N)]
  rows = [x for x in range(1, N)]
  primarytile = populate(N, '1')
  count = 0
  answc = 0
  for colp in permute(cols):
for rowp in permute(rows):
  count += 1
  if subtilesok(primarytile, colp, [0]+rowp, N, S):
answc += 1
ct = time()
et=ct-st
if et>0.0:
  print "Found: %d out of %d (%.2f%%) checked" % (answc, count,
(answc*100./count))
  print "Progress: %.2f%%" % ((count*100./estimate))
  print "Elapsed time: %.2f secs, checked: %d/s, found %d/s." %
(et, (count/et), (answc/et))
  print "Estimate time to go: %.2f hours" %
((estimate-count)*et/(count*3600.))
else:
  print "%d / %d (%5.2f%%)" % (answc, count,
(answc*100./count))
displaytile(primarytile, colp, [0]+rowp, logf)
  print
  print "Checked", count,"tiles. Found", answc,"answers."
  logf.close()
  sys.exit()
===

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


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
Thanks, I'm looking at KirbyBase also but wonder if it can handle bitmaps (I
could always pickle it first I guess).

Regards,

Philippe



John Abel wrote:

> Philippe C. Martin wrote:
> 
>>Thank you all for your answers.
>>
>>A pure Python would have beenmy first choice. yet I now feel I should
>>spend some time looking at PySQLite (I like the fact it's pre-compiled for
>>Windows).
>>
>>Thanks.
>>
>>Philippe
>>
>>
>>
>>Philippe C. Martin wrote:
>>
>>  
>>
>>>Hi,
>>>
>>>I am looking for a stand-alone (not client/server) database solution for
>>>Python.
>>>
>>>1) speed is not an issue
>>>2) I wish to store less than 5000 records
>>>3) each record should not be larger than 16K
>>>
>>>
>>>As I start with Python objects, I thought of using shelve, but looking at
>>>the restrictions (record size + potential collisions) I feel I should
>>>study my options a bit further before I get started.
>>>
>>>
>>>Regards,
>>>
>>>Philippe
>>>
>>>
>>
>>  
>>
> Out of the suggestions SnakeSQL and KirbyBase are pure python.  Gadfly
> is sorta pure, in that it will work without the compiled kjbuckets lib.
> 
> J

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


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
> 1.  5000 files -- my personal favourite.
You got a point

William Park wrote:

> Philippe C. Martin <[EMAIL PROTECTED]> wrote:
>> Hi,
>> 
>> I am looking for a stand-alone (not client/server) database solution
>> for Python.
>> 
>> 1) speed is not an issue
>> 2) I wish to store less than 5000 records
>> 3) each record should not be larger than 16K
>>
>> As I start with Python objects, I thought of using shelve, but looking
>> at the restrictions (record size + potential collisions) I feel I
>> should study my options a bit further before I get started.
> 
> Possible approach might be:
> 1.  5000 files -- my personal favourite.
> 2.  GDBM
> 3.  SQLite
> 

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


Re: Python choice of database

2005-06-20 Thread William Park
Philippe C. Martin <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I am looking for a stand-alone (not client/server) database solution
> for Python.
> 
> 1) speed is not an issue
> 2) I wish to store less than 5000 records
> 3) each record should not be larger than 16K
>
> As I start with Python objects, I thought of using shelve, but looking
> at the restrictions (record size + potential collisions) I feel I
> should study my options a bit further before I get started.

Possible approach might be:
1.  5000 files -- my personal favourite.
2.  GDBM
3.  SQLite

-- 
William Park <[EMAIL PROTECTED]>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
   http://home.eol.ca/~parkw/thinflash.html
BashDiff: Full featured Bash shell
  http://freshmeat.net/projects/bashdiff/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
OK, I'll try that too.

Regards,

Philippe



Erik Max Francis wrote:

> Philippe C. Martin wrote:
> 
>> You mean pickling a dictionnary of 5000/16K objects ?
> 
> Yes.  You said speed was not an issue; pickling only 5000 objects, each
> no more than 16 kB, is easily handled by any remotely modern machine
> (and even plenty which are not very modern).
> 

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


Re: Couple functions I need, assuming they exist?

2005-06-20 Thread George Sakkis
> I assume you mean translating something like '100' to '1,000,000'?
> I don't know of an existing function that does this, but here's a
> relatively simple implementation:
>
> py> import itertools as it
> py> def add_commas(s):
> ... rev_chars = it.chain(s[::-1], it.repeat('', 2))
> ... return ','.join(''.join(three_digits)
> ... for three_digits
> ... in it.izip(*[rev_chars]*3))[::-1]
> ...

Or for an equivalent less cryptic (IMHO) recipe:

def num2str(num):
'''Return a string representation of a number with the thousands
being delimited.

>>> num2str(65837)
'65,837'
>>> num2str(6582942)
'6,582,942'
>>> num2str(23)
'23'
>>> num2str(-1934)
'-1,934'
'''
parts = []
div = abs(num)
while True:
div,mod = divmod(div,1000)
parts.append(mod)
if not div:
if num < 0: parts[-1] *= -1
return ','.join(str(part) for part in reversed(parts))


Regards,
George

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


Re: Python choice of database

2005-06-20 Thread John Abel
Philippe C. Martin wrote:

>Thank you all for your answers.
>
>A pure Python would have beenmy first choice. yet I now feel I should spend
>some time looking at PySQLite (I like the fact it's pre-compiled for
>Windows).
>
>Thanks.
>
>Philippe
>
>
>
>Philippe C. Martin wrote:
>
>  
>
>>Hi,
>>
>>I am looking for a stand-alone (not client/server) database solution for
>>Python.
>>
>>1) speed is not an issue
>>2) I wish to store less than 5000 records
>>3) each record should not be larger than 16K
>>
>>
>>As I start with Python objects, I thought of using shelve, but looking at
>>the restrictions (record size + potential collisions) I feel I should
>>study my options a bit further before I get started.
>>
>>
>>Regards,
>>
>>Philippe
>>
>>
>
>  
>
Out of the suggestions SnakeSQL and KirbyBase are pure python.  Gadfly 
is sorta pure, in that it will work without the compiled kjbuckets lib.

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


Re: Python choice of database

2005-06-20 Thread Erik Max Francis
Philippe C. Martin wrote:

> You mean pickling a dictionnary of 5000/16K objects ?

Yes.  You said speed was not an issue; pickling only 5000 objects, each 
no more than 16 kB, is easily handled by any remotely modern machine 
(and even plenty which are not very modern).

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   I used to walk around / Like nothing could happen to me
   -- TLC
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import via pathname

2005-06-20 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> AhhI see.  I played around with the sys.path function...and it
> looks like python automatically looks in the same directory as my
> script first.  Then is searches to all the other pre-defined paths.  So
> it works for me to just keep my main script in the same directory as
> the two modules I'm using.  

Yup, as long as you're not worried about having too many modules around, 
that should work fine. =)

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


Re: Want to learn a language - is Python right?

2005-06-20 Thread Harlin Seritt
Aziz McTang wrote:

> Hi Paul,
> 
> Thanks for your input.
> 
> As usual, hearing some answers helps formulate the question...
> 
> What I'm looking for is more to learn one good, comprehensive
> programming language well than several approximately on an ad hoc
> basis. What I also failed to mention is the desire to develop my
> presently limited computer skills a lot further.
> 
> So although your answer to 1 suggests I'd be using a steam-roller to
> kill a fly, if I do need to go further (or ask other people to help and
> still understand what's going on: one site I may want to develop later
> involves a number of languages including Japanese as well as audio) I
> won't have to re-learn another program. Is this right?
> 
> As to 2, I have yet to find a canned program that does what I want, and
> so far every programmer I've asked to write it has said "hey that's
> easy" then escaped, never to be heard of again.
> 
> And 3: good! Actually, having learned half a dozen languages, I can
> vouch for it being an excellent way to acquire and consolidate
> vocabulary. Talking to (or, rather, understanding) the natives is
> another kettle of fish!
> 
> Thanks again!
> 
> Any new slants from yourself or others are welcome.
> 
> Aziz

You can use CherryPy for creating a Python-esque web application. Never buy
into the fluff that says Python is not as good as PHP for web apps! PHP is
still too Perl-Like (meaning old and useless)! Python is the choice of a
new generation baby!!! :) JK... 

For your vocab program, Python is actually perfect. This could even go for
apps that require some Unicode and other Internationalization snafus (like
right-to-left characters and Cyrillic typesets). 

If you're looking for one programming language then you should consider the
idea that no one language can do it all (although Python comes close in my
biased opinion). Python is not for memory management, writing device
drivers and the like. 

As far as needing something for web apps, CherryPy is great -- just learn
Python first. PHP is good but it has fallen out of favor with me though
there are a ton of people out there who think it is the greatest thing
since sliced bread.

Take a look at the Python tutorial: http://docs.python.org/tut/tut.html. 

Good luck,

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


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
You mean pickling a dictionnary of 5000/16K objects ?



Erik Max Francis wrote:

> Philippe C. Martin wrote:
> 
>> Well that would be shelve I guess ... with the restrictions I mentioned.
> 
> I was talking about pickle, not shelve.
> 

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


Re: Couple functions I need, assuming they exist?

2005-06-20 Thread Duncan Booth
Peter Hansen wrote:

>> The target of the problems (my daughter) would prefer that the thousands
>> be delimited.  Is there a string function that does this?
> 
> You refer to something like putting a comma between groups of three 
> digits, as in 1,000?  This is locale-specific, and there's a "locale" 
> module that should have what you need.

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'English_United Kingdom.1252'
>>> print locale.format("%d", 100, True)
1,000,000
>>> print locale.format("%.2f", 100, True)
1,000,000.00
>>> locale.setlocale(locale.LC_ALL, 'fr')
'French_France.1252'
>>> print locale.format("%d", 100, True)
1 000 000
>>> print locale.format("%.2f", 100, True)
1 000 000,00

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


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
Thank you all for your answers.

A pure Python would have beenmy first choice. yet I now feel I should spend
some time looking at PySQLite (I like the fact it's pre-compiled for
Windows).

Thanks.

Philippe



Philippe C. Martin wrote:

> Hi,
> 
> I am looking for a stand-alone (not client/server) database solution for
> Python.
> 
> 1) speed is not an issue
> 2) I wish to store less than 5000 records
> 3) each record should not be larger than 16K
> 
> 
> As I start with Python objects, I thought of using shelve, but looking at
> the restrictions (record size + potential collisions) I feel I should
> study my options a bit further before I get started.
> 
> 
> Regards,
> 
> Philippe

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


Re: Python choice of database

2005-06-20 Thread Erik Max Francis
Philippe C. Martin wrote:

> Well that would be shelve I guess ... with the restrictions I mentioned.

I was talking about pickle, not shelve.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   I used to walk around / Like nothing could happen to me
   -- TLC
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python choice of database

2005-06-20 Thread Philippe C. Martin
Well that would be shelve I guess ... with the restrictions I mentioned.

Regards,

Philippe



Erik Max Francis wrote:

> Philippe C. Martin wrote:
> 
>> I am looking for a stand-alone (not client/server) database solution for
>> Python.
>> 
>> 1) speed is not an issue
>> 2) I wish to store less than 5000 records
>> 3) each record should not be larger than 16K
>> 
>> 
>> As I start with Python objects, I thought of using shelve, but looking at
>> the restrictions (record size + potential collisions) I feel I should
>> study my options a bit further before I get started.
> 
> Why not just use native Python data structures and pickle them?
> 

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


Re: Couple functions I need, assuming they exist?

2005-06-20 Thread Steven Bethard
Charles Krug wrote:
> myWords = split(aString, aChar) 
> 
> is depreciated but
> 
> myWords = aString.split(aChgar)
> 
> is not?

Yes, that's basically correct.  What's deprecated are the functions in 
the string module.  So
 string.split(a_str, b_str)
is deprecated in favor of
 a_str.split(b_str)


> The target of the problems (my daughter) would prefer that the thousands
> be delimited.  Is there a string function that does this?

I assume you mean translating something like '100' to '1,000,000'? 
I don't know of an existing function that does this, but here's a 
relatively simple implementation:

py> import itertools as it
py> def add_commas(s):
... rev_chars = it.chain(s[::-1], it.repeat('', 2))
... return ','.join(''.join(three_digits)
... for three_digits
... in it.izip(*[rev_chars]*3))[::-1]
...
py> add_commas('10')
'10'
py> add_commas('100')
'100'
py> add_commas('1000')
'1,000'
py> add_commas('10')
'1,000,000,000'

In case you haven't seen it before, it.izip(*[itr]*N)) iterates over the 
'itr' iterator in chunks of size N, discarding the last chunk if it is 
less than size N.  To avoid losing any digits, I initially pad the 
sequence with two empty strings, guaranteeing that only empty strings 
are discarded.

So basically, the function iterates over the string in reverse order, 3 
characters at a time, and joins these chunks together with commas.

HTH,

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


Re: Python choice of database

2005-06-20 Thread Peter Hansen
John Abel wrote:
> Gadfly
> PySQLite ( requires SQLite library )

I want to clarify this parenthetical comment, for the record.  When I 
first downloaded PySQLite I had already gone and installed SQLite, 
thinking it was a prerequisite in that sense.

In fact, the PySQLite install includes a .pyd which contains a 
statically linked version of the complete SQLite library.  No additional 
installation is required, making it an even simpler solution than I 
thought at first.

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


Re: Using print with format to stdout generates unwanted space

2005-06-20 Thread Paul Watson
Thanks for all replies.

Ok.  I agree.  While printf() does tightly control formatting in C, it does 
not in Python.  Using write() can be used to output with no changes to the 
data.

"Tim Hoffman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi Paul
>
> Based on your description of what you want to do, print is probably  not 
> the correct method of controlling output format. You should use write() 
> method of the file handle to get unadulterated output.
>
> print is working as documented .  From the Python 2.3 documentation, 
> Section 6.6 The Print statement.
>
> "print evaluates each expression in turn and writes the resulting object 
> to standard output (see below). If an object is not a string, it is first 
> converted to a string using the rules for string conversions. The 
> (resulting or original) string is then written. A space is written before 
> each object is (converted and) written, unless the output system believes 
> it is positioned at the beginning of a line. This is the case (1) when no 
> characters have yet been written to standard output, (2) when the last 
> character written to standard output is "\n", or (3) when the last write 
> operation on standard output was not a print statement."
>
> As you can see a space char is written and is correct as per the docs.
>
> Rgds
>
> Tim
>
> Paul Watson wrote:
>> #!/usr/bin/env python
>>
>> #   Using a print statement to stdout results in an
>> #   unwanted space character being generated at the
>> #   end of each print output.  Same results on
>> #   DOS/Windows and AIX.
>> #
>> #   I need precise control over the bytes that are
>> #   produced.  Why is print doing this?
>> #
>> import sys
>>
>> #   If this is a DOS/Windows platform, then put stdout
>> #   into binary mode so that only the UNIX compatible newline
>> #   will be generated.
>> #
>> try:
>> import msvcrt, os
>> msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
>> except:
>> print 'This is not an msvcrt platform.'
>> pass
>>
>> #   Using print with newline suppressed generates a space at the
>> #   end of each print statement.
>> #
>> for i in range(3):
>> print '%d,60,' % (i),
>> for j in range(10):
>> print '%d,' % (j),
>> print ''
>>
>> #   Using a list and doing a join does not result in the space
>> #   character being generated.
>> #
>> for i in range(3):
>> alist = []
>> alist.append('%d,60,' % (i))
>> for j in range(10):
>> alist.append('%d,' % (j))
>> print ''.join(alist)
>>
>> sys.exit(0) 


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


Re: JEP and JPype in a single process

2005-06-20 Thread Konstantin Veretennicov
On 6/20/05, skn <[EMAIL PROTECTED]> wrote:
> Hello,
> 
> I have written a very simple java class file, which invokes a Python script
> using JEP.
. . .
> Now inside this Python script I want to make Java calls using JPype.

I am not familiar with either Jepp or JPype, but I spotted this
snippet on Jepp page (http://jepp.sourceforge.net/):

import jep
FileInputStream = jep.findClass('java.io.FileInputStream')
try:
fin = FileInputStream('adsf')
except jep.FileNotFoundException:
print 'Invalid file'

Are you sure you need to call JPype?

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


Re: Python choice of database

2005-06-20 Thread Peter Hansen
Philippe C. Martin wrote:
> I am looking for a stand-alone (not client/server) database solution for
> Python.
> 
> 1) speed is not an issue
> 2) I wish to store less than 5000 records
> 3) each record should not be larger than 16K
> 
> As I start with Python objects, I thought of using shelve, but looking at
> the restrictions (record size + potential collisions) I feel I should study
> my options a bit further before I get started.

You don't say whether you want *pure* Python solutions, so I'll suggest 
pysqlite which wraps the SQLite embedded database in a pretty much 
totally transparent fashion and is highly effective, fast, compact, 
reliable (so far, in my experience), and clean.

You also don't say whether you want a SQL database, so if you are free 
to try anything, you might look at ZODB or Durus (think of it as a 
lighter-weight ZODB).  I believe Durus is pure Python, but it might have 
some C code for performance (like ZODB).  It's not SQL, and should 
perhaps be thought of (as it describes itself) as an object persistence 
solution, rather than a "database".

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


Re: import via pathname

2005-06-20 Thread passion_to_be_free
AhhI see.  I played around with the sys.path function...and it
looks like python automatically looks in the same directory as my
script first.  Then is searches to all the other pre-defined paths.  So
it works for me to just keep my main script in the same directory as
the two modules I'm using.  

Thx!

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


  1   2   >