Re: When is min(a, b) != min(b, a)?

2008-01-25 Thread Pete Forman
Mark Dickinson <[EMAIL PROTECTED]> writes:

 > Any change to Python that made == and != checks involving NaNs raise
 > an exception would have to consider the consequences for set, dict,
 > list membership testing.
>
>
 > and if Python had separate operators for these two purposes it
 > wouldn't be Python any more.

There are separate Python operators, "==" and "is".

The C99 standard, which Python defers to for its implementation, says
in 6.2.6.1.4: Two values (other than NaNs) with the same object
representation compare equal, but values that compare equal may have
different object representations.

In 7.12.13, the fmax and fmin functions treat NaNs as missing
arguments.  Most other operations return NaN if an argument is NaN, or
for a domain error.

7.12.14 specifies comparison macros that are quiet versions of the
relational operators.

BTW floating-point exceptions in C and IEEE are not the same as
exceptions in higher level languages.  The behavior of signalling NaNs
are not defined in C.  Only quiet NaNs are returned from operations.
An invalid floating-point exception may well just set a status flag.
That may be tested after a set of calculations.  With pipelining the
exact cause of the exception will be unknown.
-- 
Pete Forman-./\.-  Disclaimer: This post is originated
WesternGeco  -./\.-   by myself and does not represent
[EMAIL PROTECTED]-./\.-   the opinion of Schlumberger or
http://petef.port5.com   -./\.-   WesternGeco.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-25 Thread Antoon Pardon
On 2008-01-24, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Thu, 24 Jan 2008 13:34:56 +, Antoon Pardon wrote:
>
>> On 2008-01-21, Steven D'Aprano <[EMAIL PROTECTED]>
>> wrote:
>>> On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote:
>>>
>>> According to the IEEE-754 standard the usual trichotomy of "x is less
>>> than y, x is equal to y, or x is greater than y" has to be extended to
>>> include "x and y are unordered". Comparisons with NaNs are unordered,
>>> and so expressions like "x < nan" should signal an exception.
>> 
>> That doesn't follow. The problem is not that x < nan returns False
>> because that is correct since x isn't smaller than nan.
>
> Comparisons between things which are not comparable risk being terribly 
> misleading, and depend very much on how you define "less than" and 
> "greater than". If you insist that everything must have a boolean yes/no 
> answer ("Does the colour red have a better chance of becoming President 
> than a kick to the head?") then False is not an entirely unreasonable 
> result to return.
>
> But if you consider that having "x is not smaller than y" be equivalent 
> to "x is greater than or equal to y" is more important than forcing a 
> boolean answer in the first place, then you need something to signal 
> Undefined, and an exception is the right solution unless you have multi-
> valued logic system (True, False, Maybe, Undefined, ...)

Why should we consider that? The world is full of partial orders. In
python we have sets and a partial order is perfectly mathematically
sound. 

> SANE (Standard Apple Numerics Environment) explicitly states that it 
> signals an exception when doing ordered comparisons against NaNs because 
> to return False would be misleading. Apple went on to use the same rule 
> in their PowerPC Numerics. That's straight out of the Zen: Practicality 
> Beats Purity.

What is misleading and what is not depends on the context. One could
argue that if comparisons against NaN should signal an exception that
the exception comes late and should already have been signaled at the
moment the NaN was produced because producing a NaN is already
misleading. It gives the impression you have a (meaningfull) result
until you later try to do something with it that is illegal for a
NaN but for legal for a float.

If you allow NaN's as a result then you have extended the floats to
a mathematical set that is now only partially ordered. I see nothing
wrong in having the comparion operators give the result that belongs
to such a partial order.

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


Ideas for Python Programming

2008-01-25 Thread mistersexy
I have been programming in python for some time but I have become
short of ideas. A software exhibition is coming up, and I plan to show
python's worth 'cos it is quite underrated in this part of the world.
Could anyone suggest any really good program ideas and information on
how to implement them? I heartily welcome any good ideas.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and binary compatibility

2008-01-25 Thread Christian Heimes
Ambush Commander wrote:
> The primary problem involves binary extensions to the Python
> interpreter itself, which Mercurial uses. The only C compiler I have
> on my machine is Visual Studio 2005 Express, but Python's binary
> distribution was compiled with VS 2003, so the installer refuses to
> compile the package. I understand that Python 3 uses VS 2008, but
> that's no good for me as it will probably break all of the scripts.

Python 2.6 and 3.0 will use VS 2008. It's not recommended to compile
Python extension with a different compiler but you can compile the
extension with 2003. It will work as long as the extensions don't
exchange file handlers or other handlers. Google for "Mixing CRTs" will
reveal more details.

> So, I'm trying to figure out what I should do. Mercurial's binary
> distribution was built using MingW, and I do have Cygwin lying around
> but I'd like to go for the "native" solution for the most speed. If I
> use MingW, I might as well use their pre-packaged binary. I could
> recompile Python with MSVC 2005, but I expect that will be its own can
> of worms. ActiveState is closed source and appears to have the wrong
> MSVC dependencies. All my troubles could apparently be fixed if I
> could acquire a copy of VS 2003, but Microsoft has made it incredibly
> difficult to find the download for it (I don't think it exists).

You can use MinGW32 to compile the extension, too. Or use the free
toolchain as described at
http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit

Christian

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


Re: Test driven development

2008-01-25 Thread Roel Schroeven
alex23 schreef:
> On Jan 25, 5:44 am, Roel Schroeven <[EMAIL PROTECTED]>
> wrote:
>> I guess I just need to try somewhat harder to use TDD in my daily
>> coding. Apart from books, are there other resources that can help
>> beginners with TDD? Mailing lists, forums, newsgroups possibly?
> 
> There's the Testing-in-Python mailing list. It's pretty low traffic
> but generally relevant:
> 
> http://lists.idyll.org/listinfo/testing-in-python

Thank you, I'll have a look at it.


-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
   -- Isaac Asimov

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


Re: global/local variables

2008-01-25 Thread Helmut Jarausch
Tim Rau wrote:

> I'm sorry: I forgot to say what my problem was. Python seems to think
> that nextID is a local, and complains that it can't find it. THis is
> not the full text of the function, just the level that is causing
> errors. the lack of : on the if is a transcription error.
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 248, in 
> thing.step()
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 112, in step
> allThings[len(allThings)-1].id = nextID
> UnboundLocalError: local variable 'nextID' referenced before
> assignment

But in the next line in the same function you say
   nextID+= 1

Since there is an assignment to nextID in the same function without
a global statement, you tell Python, that nextID is a local variable.

Note:  Assignment (anywhere in a function) is a local definition unless
there is a global statement in this function

> I want to know why it says 'local variable' it never had a problem
> when just allThings was in there.
> 
> as for the objection to global variable: If I didn't make them global,
> I'd make them part of a singleton class called gameVars that would get
> passed everywhere. It's unlikely that they'll get mixed in with
> anyhting else, as they fulfill a unique function. Also, I think it's
> more convenient, and I am, after all, my own employer when it comes to
> programming.


-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python ADO Date Time database fields

2008-01-25 Thread John Machin
On Jan 25, 10:55 am, goldtech <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Given an MS-Access table with a date type field with a value of:
> 12:00:00 AM - just"12:00:00 AM", there's nothing else in the field.
>
> I want to print exactly what's in the field, ie. "12:00:00 AM". What I
> get printed is:   12/30/0/ 00:00:00
>
> I try:
[snip]
> print oRS.Fields(dt).Value  # print here

try this:

val = oRS.Fields(dt).Value
print type(val)
print float(val)

If the last one gives you 0.0, then you have got exactly what's in the
database -- stored as a fraction of a day. Six AM would give you 0.25.

Converting that to 24 hour clock is easy:
>>> val = 0.12345
>>> seconds = int(round(val * 60 * 60 * 24))
>>> minutes, second = divmod(seconds, 60)
>>> hour, minute = divmod(minutes, 60)
>>> '%02d:%02d:%02d' % (hour, minute, second)
'02:57:46'
>>> 46/60.)+57)/60.)+2)/24. # checking
0.12344907407407407

If you don't get 0.0, let us know what you did get.

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


Re: piping into a python script

2008-01-25 Thread Nick Craig-Wood
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>  On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote:
> 
> > Given these two examples:
> > 1. 
> > ./fui.py *.py
> > 2.
> > ls *.py | ./fui.py
> > 
> > How can I capture a list of the arguments?
> > I need to get all the strings (file or dir names) passed via the normal
> > command line and any that may come from a pipe.
> > 
> > There is a third case:
> > 3.
> > ls *.jpg | ./fui.py *.png
> > Where I would be gathering strings from two places.
> > 
> > I am trying to write a command-line friendly tool that can be used in
> > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally.
> > 
> > I have tried:
> > 1. pipedIn = sys.stdin.readlines()
> > Works fine for example 2, but example 1 goes into a 'wait for input' mode
> > and that's no good. Is there a way to tell when no input is coming from a
> > pipe at all?
> 
>  Usually Linux tools that can get the data from command line or files treat
>  a single - as file name special with the meaning of: read from stdin.
> 
>  So the interface if `fui.py` would be:
> 
>  1. ./fui.py *.a
>  2. ls *.a | ./fui.py -
>  3. ls *.a | ./fui.py *.b -

Did anyone mention the (standard library) fileinput module?  (I missed
the start of this thread.)

http://docs.python.org/lib/module-fileinput.html

11.2 fileinput -- Iterate over lines from multiple input streams

This module implements a helper class and functions to quickly write a
loop over standard input or a list of files.

The typical use is:

import fileinput
for line in fileinput.input():
process(line)

This iterates over the lines of all files listed in sys.argv[1:],
defaulting to sys.stdin if the list is empty. If a filename is '-', it
is also replaced by sys.stdin. To specify an alternative list of
filenames, pass it as the first argument to input(). A single file
name is also allowed.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-25 Thread Marc 'BlackJack' Rintsch
On Fri, 25 Jan 2008 07:57:38 +, Pete Forman wrote:

> Mark Dickinson <[EMAIL PROTECTED]> writes:
> 
>  > Any change to Python that made == and != checks involving NaNs raise
>  > an exception would have to consider the consequences for set, dict,
>  > list membership testing.
>  > […]
>  > and if Python had separate operators for these two purposes it
>  > wouldn't be Python any more.
> 
> There are separate Python operators, "==" and "is".

So what?  ``==`` is used for both ``==`` and set/dict/list membership
testing and "nested comparison" of those structures.  There is no ``is``
involved.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Which is more pythonic?

2008-01-25 Thread Paul Hankin
[EMAIL PROTECTED] wrote:
> I have a goal function that returns the fitness of a given solution. I
> need to wrap that function with a class or a function to keep track of
> the best solution I encounter. Which of the following would best serve
> my purpose and be the most pythonic?

You could write a function that generates your trial solutions and use
max.

Eg: instead of using your Goal class:

def f(score_function):
goal = Goal(score_function)
while there's more solutions:
  ... produce trial solution
  goal(trial_solution)
return goal.best

Write a solution generator...
def all_solutions():
while there's more solutions:
... produce trial solution
yield trial_solution

...and find the best using
best = max(all_solutions(), key = score_function)

This uses a builtin rather than either of the snippets in the original
post, and it's also a much cleaner approach.

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


time.gmtime

2008-01-25 Thread asit
we know that time.gmtime(secs) takes a parameter secs. what does this
secs suggest ??What is it's significance ??
-- 
http://mail.python.org/mailman/listinfo/python-list


The dimensions of a tuple

2008-01-25 Thread bg_ie
Hi,

I wish to pass an argument to a function which will inset rows in a
db. I wish to have the follow possibilities -

("one","two")
(("one","two"),("three","four"))

The first possibility would mean that one row is added with "one and
"two" being its column values. The second possibility means that two
rows are added.

So to do this I need to establish the dimension of the duple. Is it a
one dimentional or two dimentional. How do I do this?

Thanks,

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


Re: global/local variables

2008-01-25 Thread Steven D'Aprano
On Thu, 24 Jan 2008 23:04:42 -0800, Tim Rau wrote:

> UnboundLocalError: local variable 'nextID' referenced before assignment

When you assign to a name in Python, the compiler treats it as a local 
variable. So when you have a line like this:

nextID += 1  # equivalent to nextID = nextID + 1

you are getting the value of the _local_ nextID before you have assigned 
a value to it.

> I want to know why it says 'local variable' it never had a problem when
> just allThings was in there.

Because you don't assign to allThings, and therefore it is treated as 
global.


> as for the objection to global variable: If I didn't make them global,
> I'd make them part of a singleton class called gameVars that would get
> passed everywhere. 

*shrug* Or you could consider a different program structure completely. 

> It's unlikely that they'll get mixed in with anyhting
> else, as they fulfill a unique function. Also, I think it's more
> convenient, and I am, after all, my own employer when it comes to
> programming.

Hey, it's your time and effort. If you want to, you can download the 
Python "goto" module, and use goto and comefrom in your code.

No, that's unfair. Globals aren't as harmful as goto. I'm not saying that 
globals are verboten or that they have no place in 21st century 
programming at all. Since I know nothing about your program, I can't 
judge whether globals are the right way to go or not. But I am saying 
that as a general rule, reliance on global variables often leads to 
fragile code with hard-to-diagnose bugs. Your mileage may vary.



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


any library for SOAP 1.1 or SOAP 1.2?

2008-01-25 Thread Amogh Hooshdar
Hi,

I wish to know which python library is popular for SOAP related
programming, especially for sending SOAP requests and parsing SOAP
responses.

I can't find any such library in the Python standard library but I
could find ZSI and soap.py libraries. However, ZSI does not support
SOAP 1.2.

Does anyone know about a library that supports SOAP 1.2 also?
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with gethostbyaddr with intranet addresses on MAC

2008-01-25 Thread shailesh
Hi,

I am facing  a peculiar problem. socket.gethostbyaddr is not working
fine on my MAC for ip addresses on the LAN. The LAN happens to consist
of linux and windows machines and this is the only one MAC on the
LAN.

Please see the example below. I am getting error: socket.herror: (1,
'Unknown host')



apples-computer:~ apple$ ping 192.168.4.123
PING 192.168.4.123 (192.168.4.123): 56 data bytes
64 bytes from 192.168.4.123: icmp_seq=0 ttl=64 time=0.328 ms
64 bytes from 192.168.4.123: icmp_seq=1 ttl=64 time=0.236 ms
64 bytes from 192.168.4.123: icmp_seq=2 ttl=64 time=0.255 ms
^C
--- 192.168.4.123 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.236/0.273/0.328/0.040 ms
apples-computer:~ apple$ python2.4
Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from socket import *
>>> x = gethostbyname('google.com')
>>> x
'64.233.167.99'
>>> gethostbyaddr(x)
('py-in-f99.google.com', [], ['64.233.167.99'])
>>> e = '192.168.4.123'
>>> gethostbyaddr(e)
Traceback (most recent call last):
  File "", line 1, in ?
socket.herror: (1, 'Unknown host')
>>>


With regards,
- Shailesh

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


Fw: Undeliverable Message

2008-01-25 Thread Matthew_WARREN
Hallo pyPeople,

I wrote a little snippet of code that takes a list representing some
'digits', and according to a list of symbols, increments the digits through
the symbol list.

so for example,

digits=["a","a","a"]
symbols=["a","b","c"]


increment(digits,symbols) repeatedly would return digits as

aab
aac
aba
abb
abc
aca


etc..

Heres the code

def increment(digits,symbols):
overflow=True
digitpos=-1
while overflow and -digitpos<=len(digits):
digitsymbolindex=symbols.index(digits[digitpos])
if digitsymbolindex==len(symbols)-1:
overflow=True
digits[digitpos]=symbols[0]
digitpos=digitpos-1
else:
digits[digitpos]=symbols[digitsymbolindex+1]
overflow=False
return digits



Now, this works. All good. It's nice and simple.  I'm just wondering how
anyone else might approach it?


Matt.


This message and any attachments (the "message") is
intended solely for the addressees and is confidential.
If you receive this message in error, please delete it and
immediately notify the sender. Any use not in accord with
its purpose, any dissemination or disclosure, either whole
or partial, is prohibited except formal approval. The internet
can not guarantee the integrity of this message.
BNP PARIBAS (and its subsidiaries) shall (will) not
therefore be liable for the message if modified.
Do not print this message unless it is necessary,
consider the environment.

-

Ce message et toutes les pieces jointes (ci-apres le
"message") sont etablis a l'intention exclusive de ses
destinataires et sont confidentiels. Si vous recevez ce
message par erreur, merci de le detruire et d'en avertir
immediatement l'expediteur. Toute utilisation de ce
message non conforme a sa destination, toute diffusion
ou toute publication, totale ou partielle, est interdite, sauf
autorisation expresse. L'internet ne permettant pas
d'assurer l'integrite de ce message, BNP PARIBAS (et ses
filiales) decline(nt) toute responsabilite au titre de ce
message, dans l'hypothese ou il aurait ete modifie.
N'imprimez ce message que si necessaire,
pensez a l'environnement.


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


Re: time.gmtime

2008-01-25 Thread Paul Boddie
On 25 Jan, 11:43, asit <[EMAIL PROTECTED]> wrote:
> we know that time.gmtime(secs) takes a parameter secs. what does this
> secs suggest ??What is it's significance ??

>From the documentation [1] with some editing:

"""
gmtime([secs])

Convert a time expressed in seconds since the epoch to a time
structure employing UTC. If secs is not provided or None, the current
time as returned by time.time() is used.

The epoch is the point where the time starts. On January 1st of that
year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the
epoch is 1970. To find out what the epoch is, look at gmtime(0).
"""

So, the significance of the secs parameter is that it indicates a
specific point in time. Generally, you'll get this from functions like
time.time or from "UNIX timestamps" stored in things like files and
databases where people have wanted to indicate a point in time without
having to mention things like dates, times and timezones.

Paul

P.S. The datetime module is preferable to the time module, really. The
latter can drive you quite mad when things like timezones start to be
taken into account.

[1] http://docs.python.org/lib/module-time.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-25 Thread Steven D'Aprano
On Fri, 25 Jan 2008 07:57:13 +, Antoon Pardon wrote:

>> But if you consider that having "x is not smaller than y" be equivalent
>> to "x is greater than or equal to y" is more important than forcing a
>> boolean answer in the first place, then you need something to signal
>> Undefined, and an exception is the right solution unless you have
>> multi- valued logic system (True, False, Maybe, Undefined, ...)
> 
> Why should we consider that? 

It's a value judgement. Ask the Apple and IBM engineers and 
mathematicians.

Personally, I think it is more useful to be able to assume that if x is 
not less than y, it must be greater or equal to instead ("completeness"), 
than it is to have a guarantee that x < y will never raise an exception.

Having said that, I think the opposite holds for sorting and calculating 
the min() and max() of floats. Sorting should push the NaNs to one end of 
the list (I don't care which) while min() and max() should ignore NaNs 
and only raise an exception if all the arguments are NaNs.



> The world is full of partial orders. In
> python we have sets and a partial order is perfectly mathematically
> sound.

Sure, we could define floats to have any sort of order we want. We could 
define them to be ordered by their English spelling so that "five million 
point three" would be less than "zero point one". But is it useful?

Putting aside sorting and max/min, what is the use-case for having 
comparisons with NaN succeed? What benefit will it give you?



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


Re: The dimensions of a tuple

2008-01-25 Thread John Machin
On Jan 25, 9:26 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> I wish to pass an argument to a function which will inset rows in a
> db. I wish to have the follow possibilities -
>
> ("one","two")
> (("one","two"),("three","four"))
>
> The first possibility would mean that one row is added with "one and
> "two" being its column values. The second possibility means that two
> rows are added.
>
> So to do this I need to establish the dimension of the duple. Is it a
> one dimentional or two dimentional. How do I do this?

isinstance(arg[0], tuple)

... but I wouldn't do it that way. I'd use a list of tuples, not a
tuple of tuples, to allow for ease of building the sequence with
list.append, and two functions:

insert_one(("one", "two"))
insert_many([("one", "two")])
insert_many([("one", "two"), ("three", "four")])

Which of those 2 functions calls the other depends on which you'd use
more often.

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


Re: global/local variables

2008-01-25 Thread Tim Rau
On Jan 25, 5:31 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Thu, 24 Jan 2008 23:04:42 -0800, Tim Rau wrote:
> > UnboundLocalError: local variable 'nextID' referenced before assignment
>
> When you assign to a name in Python, the compiler treats it as a local
> variable. So when you have a line like this:
>
> nextID += 1  # equivalent to nextID = nextID + 1
>
> you are getting the value of the _local_ nextID before you have assigned
> a value to it.
>
> > I want to know why it says 'local variable' it never had a problem when
> > just allThings was in there.
>
> Because you don't assign to allThings, and therefore it is treated as
> global.
>

Hmm so I can't assign to globals in a  local environment? How do I
make it see that I'm assigning to a global?

> > as for the objection to global variable: If I didn't make them global,
> > I'd make them part of a singleton class called gameVars that would get
> > passed everywhere.
>
> *shrug* Or you could consider a different program structure completely.
>
> > It's unlikely that they'll get mixed in with anyhting
> > else, as they fulfill a unique function. Also, I think it's more
> > convenient, and I am, after all, my own employer when it comes to
> > programming.
>
> Hey, it's your time and effort. If you want to, you can download the
> Python "goto" module, and use goto and comefrom in your code.
>
> No, that's unfair. Globals aren't as harmful as goto. I'm not saying that
> globals are verboten or that they have no place in 21st century
> programming at all. Since I know nothing about your program, I can't
> judge whether globals are the right way to go or not. But I am saying
> that as a general rule, reliance on global variables often leads to
> fragile code with hard-to-diagnose bugs. Your mileage may vary.
>
> --
> Steven

Ha! Gotos I understand the evil of. Human beings don't think that way.
Humans are not put together in terms of gotos. Human language does not
normally contain gotos. Global, however, seem useful to me. It seems
like there are a few things which EVERYONE should know. When you find
something often used from a variety of different places, everyone
should know about it. It saves time from developing lengthy argument
passing chains to follow the passing chains of your program. It keeps
the number of arguments low, and easily remembered. This may be more
important in python, because python has no type, and where you would
have had a type error for forgetting which arg goes where, you have
some random thing.

Also, My programming style tends towards a mongrel of functional and
object oriented programming. I tend to use lone functions when they
have no internal state, and objects when they have internal state, but
it's not ironclad. It's just what makes sense to me at the time. I'm
not defending myself, I'm just setting out my point of view. I'd like
to see what you think of it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global/local variables

2008-01-25 Thread Steven D'Aprano
On Fri, 25 Jan 2008 03:28:05 -0800, Tim Rau wrote:

>> Because you don't assign to allThings, and therefore it is treated as
>> global.
>>
>>
> Hmm so I can't assign to globals in a  local environment? How do I
> make it see that I'm assigning to a global?

I thought somebody had already mentioned this... possibly even me... 

You can declare a name as global by using the global statement:

def foo():
global x
x += 1


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


Re: time.gmtime

2008-01-25 Thread Harald Karner
asit wrote:
> we know that time.gmtime(secs) takes a parameter secs. what does this
> secs suggest ??What is it's significance ??

 >>> import time
 >>> help (time.gmtime)
Help on built-in function gmtime in module time:

gmtime(...)
 gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)

 Convert seconds since the Epoch to a time tuple expressing UTC 
(a.k.a. GMT).  When 'seconds' is not passed in, convert the current time 
instead.

 >>> time.gmtime (0)
(1970, 1, 1, 0, 0, 0, 3, 1, 0)
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Minimum Requirements for Python

2008-01-25 Thread justinrob
Can someone tell me the minimum requitements for Python as I can't
find it anwhere on the site. I have 3 PC's which are only 256mb RAM,
wanted to know if this was sufficenent.

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


Re: global/local variables

2008-01-25 Thread Tim Rau
On Jan 25, 5:31 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Thu, 24 Jan 2008 23:04:42 -0800, Tim Rau wrote:
> > UnboundLocalError: local variable 'nextID' referenced before assignment
>
> When you assign to a name in Python, the compiler treats it as a local
> variable. So when you have a line like this:
>
> nextID += 1  # equivalent to nextID = nextID + 1
>
> you are getting the value of the _local_ nextID before you have assigned
> a value to it.
>
> > I want to know why it says 'local variable' it never had a problem when
> > just allThings was in there.
>
> Because you don't assign to allThings, and therefore it is treated as
> global.
>
> > as for the objection to global variable: If I didn't make them global,
> > I'd make them part of a singleton class called gameVars that would get
> > passed everywhere.
>
> *shrug* Or you could consider a different program structure completely.
>

Oh, wait nevermind, I now understand what global nextID is for

**ENLIGHTENMENT**

  \  /\   |
:o---  X  |
  /  \/   |

[snip]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with gethostbyaddr with intranet addresses on MAC

2008-01-25 Thread Vladimir Rusinov
On 1/25/08, shailesh <[EMAIL PROTECTED]> wrote:
>
> apples-computer:~ apple$ ping 192.168.4.123
> PING 192.168.4.123 (192.168.4.123): 56 data bytes
> 64 bytes from 192.168.4.123: icmp_seq=0 ttl=64 time=0.328 ms
> 64 bytes from 192.168.4.123: icmp_seq=1 ttl=64 time=0.236 ms
> 64 bytes from 192.168.4.123: icmp_seq=2 ttl=64 time= 0.255 ms
> ^C
> --- 192.168.4.123 ping statistics ---
> 3 packets transmitted, 3 packets received, 0% packet loss
> round-trip min/avg/max/stddev = 0.236/0.273/0.328/0.040 ms
> apples-computer:~ apple$ python2.4
> Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from socket import *
> >>> x = gethostbyname('google.com')
> >>> x
> '64.233.167.99'
> >>> gethostbyaddr(x)
> ('py-in-f99.google.com', [], ['64.233.167.99'])
> >>> e = '192.168.4.123'
> >>> gethostbyaddr(e)
> Traceback (most recent call last):
>   File "", line 1, in ?
> socket.herror: (1, 'Unknown host')
> >>>
>

I'm sure your dns server have no reverse records for ' 192.168.4.123'.
So, it can't resolve it (123.4.168.192.in-addr.arpa).

-- 
Vladimir Rusinov
GreenMice Solutions: IT-решения на базе Linux
http://greenmice.info/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: sudoku solver in Python ...

2008-01-25 Thread Boris Borcic

 >> http://norvig.com/sudoku.html
(...)
 > Below is the "winner" of my hacking for an as fast as
> possible 110% pure python (no imports at all!) comprehensive sudoku 
> solver under 50 LOCs, back in 2006. Performance is comparable to the 
> solver you advertize - numbers are slightly better, but platform 
> differences could easily absorb that -

More precise comparisons, after noting that on Norvig's pages there were 
contradictory performance numbers (obviously some 0 inserted or deleted). 
Running on my machine on the "top95" list of hard problems given on Norvig's 
page, my code takes about 7.5 ms/problem while Norvig's takes 42 ms/problem.

So that's a 82% reduction of running time.

Psyco.full() reduces the running time of my code to just about 4 ms/problem 
while it grows Norvig's to 47 ms/problem.

BB

> eg (not counting module 
> initialization and not using psyco) it takes 9.3 ms average on the "AI 
> escargot" problem linked to in Norvig's page, 5.6 ms/problem on some 
> standard "top1465" list of hard problems, and 3.4 ms/problem on the 
> first 1000 on some other "top5" list of relatively hard problems. 
> This on my 2GHz Intel Centrino '05 laptop. Psyco reduces times by about 
> 50%. Dropping performance requirements by half allows reducing LOC count 
> in proportion.
> 
> OTOH, the code although short is nearly unreadable, sorry; should 
> probably feature/comment it on some web page, like the two already 
> proposed in the thread. Will do if/for reviewer. Interface is calling 
> sudoku99(problem) with 'problem' a standard 81 character string with '0' 
> or '.' placeholder for unknowns. Returns same with values filled in.
> 
> Beware that although in practice it solved all well-formed 
> human-solvable problems I could find, it is not guaranteed to deal 
> properly (or even terminate?) for underdetermined problems or determined 
> problems that would require exploring choicepoints with more than 2 
> possibilities (if such exist).
> 
> Cheers, Boris
> 
> 
> 
> w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81]
>for n in range(729)]
> q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s))
> q2w = map(set,zip(*9*[q2w]))
> w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in 
> enumerate(w2q)]
> empty = set(range(729)).copy
> 
> def sudoku99(problem) :
> givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0' ws=search(givens,[9]*len(q2w),empty())
> return ''.join(str(w%9+1) for w in sorted(ws))
> 
> def search(w0s,q2nw,free) :
> while 1 :
> while w0s:
> w0 = w0s.pop()
> for q in w2q[w0] : q2nw[q]=100
> wz = w2q2w[w0]&free
> free-=wz
> for w in wz :
> for q in w2q[w] :
> n = q2nw[q] = q2nw[q]-1
> if n<2 :
> ww,=q2w[q]&free
> w0s.add(ww)
> if len(free)==81 : return free
> thres = int((len(free)+52.85)/27.5)
> ix,vmax = -1,0
> try :
> while 1 :
> ix=q2nw.index(2,ix+1)
> for w0 in (q2w[ix]&free)-w0s :
> v = len(w2q2w[w0]&free)
> if v > vmax :
> ixmax = ix
> if v >=thres : break
> vmax = v
> w0s.add(w0)
> else : continue
> break
> except : pass
> w0,w1 = q2w[ixmax]&free
> try :
> w0s.clear()
> w0s.add(w0)
> return search(w0s,q2nw[:],free.copy())
> except ValueError :
> w0s.clear()
> w0s.add(w1)
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Windows AVIFile problems

2008-01-25 Thread c d saunter
Hi All,

I'm trying to access individual video frames of an AVI file from within 
Python 2.4 or 2.5 under Windows XP.

I have found this example code here for that does exactly what I want,
using the windows avifile.dll but I am unable to find the AVIFile.h 
header...

http://mail.python.org/pipermail/image-sig/2002-February/001748.html

An alternative is to call into avifile.dll dynamically using ctypes, 
however under both Python 2.4 and 2.5 the following error happens:

>>> from ctypes import *
>>> windll.AVIFile

Traceback (most recent call last):
  File "", line 1, in 
windll.AVIFile
  File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__
dll = self._dlltype(name)
  File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 193] %1 is not a valid Win32 application

or

WinDLL('c:/windows/system/AVIFILE.DLL') # same for .../system32/AVI...
Traceback (most recent call last):
  File "", line 1, in 
windll.AVIFile
  File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__
dll = self._dlltype(name)
  File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 193] %1 is not a valid Win32 application

This suggests that the dll is corrupt?  However if I download
and run the exe's from this example of a VB program calling
the DLL, they work:
http://www.shrinkwrapvb.com/avihelp/avihelp.htm

I'm open to suggestions about the specific problems above 
or other ways of getting at the frames.  I've tried pymedia
but it also has issues.

Regards
Chris Saunter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minimum Requirements for Python

2008-01-25 Thread Christian Heimes
[EMAIL PROTECTED] wrote:
> Can someone tell me the minimum requitements for Python as I can't
> find it anwhere on the site. I have 3 PC's which are only 256mb RAM,
> wanted to know if this was sufficenent.

Python runs even on mobile phones with far less memory. However the
memory consumption depends on the application.

Christian

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


Re: The dimensions of a tuple

2008-01-25 Thread bg_ie
On 25 Jan, 12:03, John Machin <[EMAIL PROTECTED]> wrote:
> On Jan 25, 9:26 pm, [EMAIL PROTECTED] wrote:
>
> > Hi,
>
> > I wish to pass an argument to a function which will inset rows in a
> > db. I wish to have the follow possibilities -
>
> > ("one","two")
> > (("one","two"),("three","four"))
>
> > The first possibility would mean that one row is added with "one and
> > "two" being its column values. The second possibility means that two
> > rows are added.
>
> > So to do this I need to establish the dimension of the duple. Is it a
> > one dimentional or two dimentional. How do I do this?
>
> isinstance(arg[0], tuple)
>
> ... but I wouldn't do it that way. I'd use a list of tuples, not a
> tuple of tuples, to allow for ease of building the sequence with
> list.append, and two functions:
>
> insert_one(("one", "two"))
> insert_many([("one", "two")])
> insert_many([("one", "two"), ("three", "four")])
>
> Which of those 2 functions calls the other depends on which you'd use
> more often.
>
> HTH,
> John

Thanks for the tip regarding the list of tuples!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inode number in windows XP

2008-01-25 Thread Steven D'Aprano
On Fri, 25 Jan 2008 04:28:43 -0800, asit wrote:

> why this program shows ambiguous behavior ??


You should read this page, it will help you solve your problem:

http://catb.org/~esr/faqs/smart-questions.html



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


inode number in windows XP

2008-01-25 Thread asit
why this program shows ambiguous behavior ??

import os
import stat
import time
#import types

file_name=raw_input("Enter file name : ")
print file_name, "information"
st=os.stat(file_name)
print "mode", "=>", oct(stat.S_IMODE(st[stat.ST_MODE]))

print "type","=>",
if stat.S_ISDIR(st[stat.ST_MODE]):
print "DIReCTORY"
elif stat.S_ISREG(st[stat.ST_MODE]):
print "REGULAR"
elif stat.S_ISLINK(st[stat.ST_MODE]):
print "LINK"

print "file size", "=>",st[stat.ST_SIZE]
print "inode number", "=>",st[stat.ST_INO]
print "device inode resides on", "=>",st[stat.ST_DEV]
print "number of links to this inode", "=>",st[stat.ST_NLINK]
print "last accessed", "=>", time.ctime(st[stat.ST_ATIME])
print "last modified", "=>", time.ctime(st[stat.ST_MTIME])
print "inode changed", "=>", time.ctime(st[stat.ST_CTIME])



i ran this program in Winows XP SP2 in python 2.5.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: piping into a python script

2008-01-25 Thread Donn Ingle
Nick Craig-Wood wrote:

> This iterates over the lines of all files listed in sys.argv[1:],
> defaulting to sys.stdin if the list is empty. If a filename is '-', it
> is also replaced by sys.stdin. To specify an alternative list of
> filenames, pass it as the first argument to input(). A single file
> name is also allowed.
Yeah it has been discussed. It seems the one problem with it is that it
opens each file. I only want the filenames.

Anyway, this has more-or-less been solved now.

Thanks,
\d

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


Re: inode number in windows XP

2008-01-25 Thread Gabriel Genellina
On 25 ene, 10:28, asit <[EMAIL PROTECTED]> wrote:

> why this program shows ambiguous behavior ??
>
> st=os.stat(file_name)
> print "file size", "=>",st[stat.ST_SIZE]
> print "inode number", "=>",st[stat.ST_INO]
> print "device inode resides on", "=>",st[stat.ST_DEV]
> print "number of links to this inode", "=>",st[stat.ST_NLINK]
>
> i ran this program in Winows XP SP2 in python 2.5.

Using my recently repaired crystal ball, I see that you don't get what
you expect for some of those fields. All files sharing the same inode,
by example.
The usual file systems used by Windows aren't built around the inode
concept, they're different, so there is no "inode number" to report,
among other things. From http://docs.python.org/lib/os-file-dir.html
"On Windows, some items are filled with dummy values". Don't rely on
anything but st_mode, st_size, and st_[cma]time, and perhaps a few
more for fstat.

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


Re: Operator overloading

2008-01-25 Thread Hexamorph
[EMAIL PROTECTED] wrote:
> 
> Diez B. Roggisch wrote:
>> No, there is no way. You would change general interpreter behavior if
>> you could set arbitrary operators for predefined types.
>>
>> Start grumping...
> 
> Thank you, Diez.
> 
> If I ever design a language, please remind me that complete, easy,
> well-documented access to the working of the internals (and the
> ability to change same) would be very, uh, what's the right word?
> Pythonic?


You mean you want the ability to change for example the + operator 
for ints to something like calculating the cosine instead of doing 
addition?

That will break the whole system in general as other parts of the 
language (or modules, libraries and programs) rely on a certain 
inner behaviour.

There are some languages in which you can do this (Lisp/Scheme for 
example) but messing with the internals is almost never done for 
good reasons.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator overloading

2008-01-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> 
> Diez B. Roggisch wrote:
>> No, there is no way. You would change general interpreter behavior if
>> you could set arbitrary operators for predefined types.
>>
>> Start grumping...
> 
> Thank you, Diez.
> 
> If I ever design a language, please remind me that complete, easy,
> well-documented access to the working of the internals (and the
> ability to change same) would be very, uh, what's the right word?
> Pythonic?

As you say - it's a question of design & thus taste. Python has chosen 
to _not_ allow to change (all) inner workings of itself in favor of not 
introducing subtle bugs that arise from somebody (accidentially or not) 
altering behavior of builtins that might effect code he'd never intended 
to touch.

But you _can_ create subclasses of these builtins and adapt their 
behavior. I for once like it that way. If you don't - to bad for you. It 
won't change, so either you live with it, or start working on your 
lex/yacc skillz and create your own language. Or switch to Ruby, which 
allow for what you desire (AFAIK, not entirely sure though)

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread rndblnch
On Jan 25, 8:43 pm, [EMAIL PROTECTED] wrote:
> This means NO X-windows, NO GTK/Gnome, NO
> computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output).
>
> I would like to write some really light weighted GU interface. My
> concept is to have just few user screens (about 10) controlled via 4
> or 5 HW buttons connected to the GPIO pins they are available on the
> motherboard (the HW design and the SW concept of reading this buttons
> is already solved).

what you are looking for is curse :)
http://docs.python.org/lib/module-curses.html
http://www.ibm.com/developerworks/linux/library/l-python6.html

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


looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread petr . jakes . tpc
Hi,
I am working with the Python 2.5 running on the command line version
of Linux Ubuntu 7.04. This means NO X-windows, NO GTK/Gnome, NO
computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output).

I would like to write some really light weighted GU interface. My
concept is to have just few user screens (about 10) controlled via 4
or 5 HW buttons connected to the GPIO pins they are available on the
motherboard (the HW design and the SW concept of reading this buttons
is already solved).

After some googling, I have found below mentioned can be usable, but
first, I would like to ask here for your opinions/experiences/advices.

Best regards

Petr Jakes

http://www.libsdl.org/
http://pyfltk.sourceforge.net/
http://www.pygame.org/news.html
http://pyui.sourceforge.net/
http://pyglet.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator overloading

2008-01-25 Thread Hexamorph
[EMAIL PROTECTED] wrote:
> 
> Hexamorph wrote:
>> You mean you want the ability to change for example the + operator
>> for ints to something like calculating the cosine instead of doing
>> addition?
> 
> Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so
> why shouldn't I define +45 to return cosine of 45, (presuming I needed
> lots of cosines). I'd even let you define your own operators. Lots of
> programmers really liked '++' and '--', for examples.

Well, OK, the cosine example was badly chosen (it would still be 
very wired in terms of common syntax and semantics), but I think you 
got my point. Changing internal behaviour mostly causes more trouble 
as it's worth.

In the end, you probably can access the parser to do this.

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


Re: find minimum associated values

2008-01-25 Thread John Machin
On Jan 26, 7:58 am, [EMAIL PROTECTED] wrote:
> I find the first and third solutions simpler to read, and the first
> solution requires less memory, it probably works quite well with
> Psyco, and it's easy to translate to other languages (that is
> important for programs you want to use for a lot of time or in
> different situations), so I'd use the first solution.
>

The first solution, once one changes "d = dict()" to "d = {}", is
quite free of any impediments to ease of reading, uses the minimum
necessary memory to build the required dict [and it's quite obvious by
inspection that this is so], and is the easiest to "translate" to
earlier versions of Python.

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Hi,
> I am working with the Python 2.5 running on the command line version
> of Linux Ubuntu 7.04. This means NO X-windows, NO GTK/Gnome, NO
> computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output).
> 
> I would like to write some really light weighted GU interface. My
> concept is to have just few user screens (about 10) controlled via 4
> or 5 HW buttons connected to the GPIO pins they are available on the
> motherboard (the HW design and the SW concept of reading this buttons
> is already solved).
> 
> After some googling, I have found below mentioned can be usable, but
> first, I would like to ask here for your opinions/experiences/advices.
> 
> Best regards
> 
> Petr Jakes
> 
> http://www.libsdl.org/
> http://pyfltk.sourceforge.net/
> http://www.pygame.org/news.html
> http://pyui.sourceforge.net/
> http://pyglet.org/


pygame is based on sdl, pyui can render to pygame. So if you use that 
stack, it's a question of SDL being capable of directly rendering to 
something like SVGALib.

Pyglet is OpenGL, and fltk seems to need X.

But WHY aren't you just installing X? You don't need to run a 
full-fledged Desktop like gnome or kde on top of it - just use ratpoison 
or anything else as desktop manager & be happy.

After all, my first PC had 16MB of RAM and 133MHz - and ran X w/o any 
problems.

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


Re: Index of maximum element in list

2008-01-25 Thread Henry Baxter
Thanks Hexamorph and Neal. Somehow I didn't make the connection with using
'index', but I'm all sorted out now :)

On Jan 25, 2008 1:47 PM, Hexamorph <[EMAIL PROTECTED]> wrote:

> Henry Baxter wrote:
> > Oops, gmail has keyboard shortcuts apparently, to continue:
> >
> > def maxi(l):
> > m = max(l)
> > for i, v in enumerate(l):
> > if m == v:
> > return i
> >
>
> What's about l.index(max(l)) ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

python and multithreading problem

2008-01-25 Thread whatazor
Hi all,
I made an application that use multithreading (indifferently importing
thread or  threading module) , but when I call some wrapped modules
(with swig) from my application they run like there is only a single
thread (and my application gui ,made with wxPython, freezes). If I use
other modules not wrapped, but created for test that multithread
works, and gui is not freezing are ok.
Modules that wrap DLL are not my product but are created by another
developer with VS.NET, and the only thing I can think is that they're
builded without multithreaded compiler option. Can it be another cause
for this behaviour, can this explanation be correct? maybe also swig
have a multithreading option.

thank you in advance
w
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module/package hierarchy and its separation from file structure

2008-01-25 Thread Carl Banks
On Jan 25, 6:45 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Gabriel Genellina" <[EMAIL PROTECTED]> writes:
> > You can also put, in animal/__init__.py:
> > from monkey import Monkey
> > and now you can refer to it as org.lib.animal.Monkey, but keep the
> > implementation of Monkey class and all related stuff into
> > .../animal/monkey.py
>
> This (as far as I can understand) is exactly the solution the original
> poster desired to "shoot down", for reasons I still don't understand.

Come on, the OP explained it quite clearly in his original post.  Did
you guys even read it?

The module where org.lib.animal.Monkey is actually defined should be
an implementation detail of the library, but simply importing Monkey
into org.lib.animal doesn't quite make it one.

If a user pickles a Monkey class, and then the OP decides to refactor
the Monkey class into a new module (say
org.lib.animal.primate.monkey), then the user would not be able to
unpickle it.  Because, you see, pickles record the module a class is
defined in.  So, now the user has to worry about where Monkey is
actually defined.  It is not an implementation detail.

The solution is to modify the class's __module__ attribute as well as
importing it, as I've already pointed out:

from org.lib.animal.monkey import Monkey
Monkey.__module__ = 'org.lib.animal'

This should be enough to satisfy the OP's requirements, at least for
classes, without softening the one-to-one module-to-file relationship,
or using "hacks".

In fact, I'd say this is good practice.


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


Re: Email module, how to add header to the top of an email?

2008-01-25 Thread David Erickson
On Jan 25, 5:04 am, "Karlheinz Klingbeil"
<[EMAIL PROTECTED]> wrote:
> Am 25.01.2008, 06:21 Uhr, schrieb David Erickson <[EMAIL PROTECTED]>:
>
> > Bottom of the headers... but I am looking to insert at the top, and re-
> > ordering/inserting does matter depending on what type of header you
> > are, received headers for example must be inserted at the top of the
> > header list so you can watch the progression of the email.  I was
> > unable to find a clean way to do this via the API which seems very
> > strange to me.. but perhaps I am just missing something?
>
> I think your are really missing something. First, Email-headers are
> unordered
> and every relay can, and probably will,  rearrange them, add or delete
> headers.
> You therefore most definitely should not add any headers which are
> position-dependent.
> If you want to track mails somehow, add headers with timestamps.
> This way you can watch the progression of an email without being
> dependend on "sorted" headerlines.

This is incorrect, quoting directly from RFC 2822:

   It is important to note that the header fields are not guaranteed
to
   be in a particular order.  They may appear in any order, and they
   have been known to be reordered occasionally when transported over
   the Internet.  However, for the purposes of this standard, header
   fields SHOULD NOT be reordered when a message is transported or
   transformed.  More importantly, the trace header fields and resent
   header fields MUST NOT be reordered, and SHOULD be kept in blocks
   prepended to the message.  See sections 3.6.6 and 3.6.7 for more
   information.

Trace header fields are not to be ordered, and should be prepended
when added to a message.  Now that said I am not trying to track
anything, I simply want to prepend my additional headers onto the top
of the email, and seem to be unable to do that via the API, which I
think ought to be possible.  If for example I was writing some kind of
an SMTP server with Python and needed to add said trace headers they
would need to be prepended, and currently cannot be (without doing it
by hand).

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


Re: translating Python to Assembler

2008-01-25 Thread ajaksu
On Jan 25, 11:10 pm, [EMAIL PROTECTED] wrote:
> Once a python py file is compiled into a pyc file, I can disassemble
> it into assembler. Assembler is nothing but codes, which are
> combinations of 1's and 0's. You can't read a pyc file in a hex
> editor, but you can read it in a disassembler. It doesn't make a lot
> of sense to me right now, but if I was trying to trace through it with
> a debugger, the debugger would disassemble it into assembler, not
> python.


Please, tell me you're kidding...
-- 
http://mail.python.org/mailman/listinfo/python-list


pyfov Package Index link broken

2008-01-25 Thread Martin Manns
Hi,

I am looking for the code of pyfov, which is on the Package Index.
However, the link is broken and the author does not seem to respond to
e-mails.

Any chance to get hands on the code?

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


ElementTree.fromstring(unicode_html)

2008-01-25 Thread globophobe
This is likely an easy problem; however, I couldn't think of
appropriate keywords for google:

Basically, I have some raw data that needs to be preprocessed before
it is saved to the database e.g.

In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f
\u3044\r\n'

I need to turn this into an elementtree, but some of the data is
japanese whereas the rest is html. This string contains a .

In [2]: e = ET.fromstring('%s' % unicode_html)
In [2]: e.text
Out[3]: u'\u3055\u3080\u3044\uff0f\n\u3064\u3081\u305f\u3044\n'
In [4]: len(e)
Out[4]: 0

How can I decode the unicode html  into a string that
ElementTree can understand?

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


Re: translating Python to Assembler

2008-01-25 Thread Steven D'Aprano
On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote:

> It's even
> possible to write code with Python assembly and compile the Python
> assembly into byte code.

Really? How do you do that?

I thought it might be compile(), but apparently not.



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


Re: ElementTree.fromstring(unicode_html)

2008-01-25 Thread John Machin
On Jan 26, 1:11 pm, globophobe <[EMAIL PROTECTED]> wrote:
> This is likely an easy problem; however, I couldn't think of
> appropriate keywords for google:
>
> Basically, I have some raw data that needs to be preprocessed before
> it is saved to the database e.g.
>
> In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f
> \u3044\r\n'
>
> I need to turn this into an elementtree, but some of the data is
> japanese whereas the rest is html. This string contains a .

>>> import unicodedata as ucd
>>> s = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f\u3044\r\n'
>>> [ucd.name(c) if ord(c) >= 128 else c for c in s]
['HIRAGANA LETTER SA', 'HIRAGANA LETTER MU', 'HIRAGANA LETTER I',
'FULLWIDTH SOLIDUS', u'\r', u'\n', 'HIRAGANA LETTER TU', 'HIRAGANA
LETTER ME', 'HIRAGANA LETTER TA', 'HIRAGANA LETTER I', u'\r', u'\n']
>>>

Where in there is the  ??

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Chris Mellon
On Jan 25, 2008 5:17 PM, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 25 Jan, 22:06, "Lorenzo E. Danielsson"
> <[EMAIL PROTECTED]> wrote:
> >
> > What you need then is something like SVGAlib (http;//svgalib.org). Only
> > really old people like myself know that it exists. I've never heard of
> > any Python bindings for it, but that might be where you come in. I
> > haven't looked at SVGAlib for years, and I'm not sure about the state of
> > the video drivers. I suggest you look at that first.
>
> I believe that SVGAlib was superseded by GGI and other projects, and I
> recall that SVGAlib was considered to be something of a nightware with
> respect to how it handles various resources. Certainly, I haven't been
> very impressed by the behaviour of software using it.
>
> > You could also look at GGI (http://ggi-project.org). GGI has different
> > output targets. IIRC, one of them is directfb. To tell you the truth
> > I've never really used GGI. There seems to be a python wrapper for GGI,
> > although it is fairly old. Maybe you could look at the code for some ideas.
>
> I've had to build software using GGI, and the biggest problem has been
> getting packages for it. That said, it seemed to work fairly
> acceptably once built and installed. Meanwhile, some people favour
> Allegro [1] for this kind of work, and I've been confronted with newly
> developed software which uses Allegro, so it's arguably in a different
> maintenance state than something like SVGAlib or GGI.
>
> > You should also be able to compile SDL to be able to use directfb as a
> > target. If your libSDL handles it, then that should apply to wrapper
> > libraries as well, including pygame. I've never tried running SDL apps
> > this way, but if it works well, that would probably be your 'best' option.
>
> I'd agree with these sentiments; SDL seems to be the best supported
> technology of this kind in the Python universe, and one of the most
> widely deployed in general; I've felt quite comfortable building
> software against it. It would be very interesting to see whether a
> framebuffer-based SDL could support Pygame, and I imagine that the
> Pygame mailing list might already have some answers in its archives on
> this topic.
>


I agree that SDL is probably the best choice but for the sake of
completeness, Gtk can (at least in theory - I've never tried it) be
built against directfb and run without X.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-25 Thread Raymond Hettinger
On Jan 25, 1:47 pm, Hexamorph <[EMAIL PROTECTED]> wrote:
> Henry Baxter wrote:
> > Oops, gmail has keyboard shortcuts apparently, to continue:
>
> > def maxi(l):
> >     m = max(l)
> >     for i, v in enumerate(l):
> >         if m == v:
> >             return i
>
> What's about l.index(max(l)) ?

from itertools import izip, count
answer  = max(izip(l, count()))[1]


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


How can I use the up and down, left and right arrow keys to control a Python Pgm

2008-01-25 Thread jitrowia
I was wondering what kind of python code I would need to enable me to 
use the up and down, left and right arrow keys to control software 
programming decisions within a Python Program.

Any direction and advice would be greatly appreciated,

Thank You,
Rodney

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


Re: regular expression negate a word (not character)

2008-01-25 Thread Ben Morrow
[newsgroups line fixed, f'ups set to clpm]

Quoth Summercool <[EMAIL PROTECTED]>:
> On Jan 25, 5:16 pm, Summercool <[EMAIL PROTECTED]> wrote:
> > somebody who is a regular expression guru... how do you negate a word
> > and grep for all words that is
> >
> >   tire
> >
> > but not
> >
> >   snow tire
> >
> > or
> >
> >   snowtire
> 
> i could think of something like
> 
>   /[^s][^n][^o][^w]\s*tire/i
> 
> but what if it is not snow but some 20 character-word, then do we need
> to do it 20 times to negate it?  any shorter way?

This is no good, since 'snoo tire' fails to match even though you want
it to. You need something more like

/ (?: [^s]... | [^n].. | [^o]. | [^w] | ^ ) \s* tire /ix

but that gets *really* tedious for long strings, unless you generate it.

Ben

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


Re: regular expression negate a word (not character)

2008-01-25 Thread Mark Tolonen

"Summercool" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> somebody who is a regular expression guru... how do you negate a word
> and grep for all words that is
>
>  tire
>
> but not
>
>  snow tire
>
> or
>
>  snowtire
>
> so for example, it will grep for
>
>  winter tire
>  tire
>  retire
>  tired
>
> but will not grep for
>
>  snow tire
>  snow   tire
>  some snowtires
>
> need to do it in one regular expression
>

What you want is a negative lookbehind assertion:

>>> re.search(r'(?>> re.search(r'(?

Unfortunately you want variable whitespace:

>>> re.search(r'(?", line 1, in 
  File "C:\dev\python\lib\re.py", line 134, in search
return _compile(pattern, flags).search(string)
  File "C:\dev\python\lib\re.py", line 233, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
>>>

Python doesn't support lookbehind assertions that can vary in size.  This 
doesn't work either:

>>> re.search(r'(?

Here's some code (not heavily tested) that implements a variable lookbehind 
assertion, and a function to mark matches in a string to demonstrate it:

### BEGIN CODE ###

import re

def finditerexcept(pattern,notpattern,string):
for matchobj in 
re.finditer('(?:%s)|(?:%s)'%(notpattern,pattern),string):
if not re.match(notpattern,matchobj.group()):
yield matchobj

def markexcept(pattern,notpattern,string):
substrings = []
current = 0

for matchobj in finditerexcept(pattern,notpattern,string):
substrings.append(string[current:matchobj.start()])
substrings.append('[' + matchobj.group() + ']')
current = matchobj.end() #

substrings.append(string[current:])
return ''.join(substrings)

### END CODE ###

>>> sample='''winter tire
... tire
... retire
... tired
... snow tire
... snowtire
... some snowtires
... '''
>>> print markexcept('tire','snow\s*tire',sample)
winter [tire]
[tire]
re[tire]
[tire]d
snow tire
snowtire
some snowtires

--Mark

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


Re: translating Python to Assembler

2008-01-25 Thread Chris Mellon
On Jan 25, 2008 9:09 PM, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote:
>
> > It's even
> > possible to write code with Python assembly and compile the Python
> > assembly into byte code.
>
> Really? How do you do that?
>
> I thought it might be compile(), but apparently not.
>

There are tools for it in the undocumented compiler.pyassem module.
You have to pretty much know what you're doing already to use it - I
spent a fun (but unproductive) week figuring out how to use it and
generated customized bytecode for certain list comps. Malformed
hand-generated bytecode stuffed into code objects is one of the few
ways I know of to crash the interpreter without resorting to calling C
code, too.
-- 
http://mail.python.org/mailman/listinfo/python-list


finding child cpu usage of a running child

2008-01-25 Thread Karthik Gurusamy
Hi,

Wondering if there is a way to measure a child process's cpu usage
(sys and user) when the child is still running. I see os.times()
working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid
data only after the child has exited. When the child is alive,
os.times() data for child is zero for both child-sys and child-user
cpu.

My script (process P1) launches child process P2 (using
popen2.Popen3). P2 is a long running process (big compilation). Every
minute or so, from P1, I want to measure how much cpu P2 has consumed
and based on that I can make some estimate on the completion time of
P2 (I have a rough idea how much total cpu P2 needs to complete).

I understand it may be too expensive to update this information to the
parent process when any of the child/grand-child completes; but
wondering if any there is any way to get this info; the expensive
operations is on-demand only when the request is made.

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


Re: Index of maximum element in list

2008-01-25 Thread Scott David Daniels
Hexamorph wrote:
> ...
> What's about l.index(max(l)) ?
What about
max((x,i) for i,x in enumerate(lst))[1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by behaviour of class with empty constructor

2008-01-25 Thread Tim Rau
On Jan 25, 5:54 pm, [EMAIL PROTECTED] wrote:
> On Jan 25, 5:46 pm, Bjoern Schliessmann 
>
>
> [EMAIL PROTECTED]> wrote:
> > [EMAIL PROTECTED] wrote:
> > > print x.ends,y.ends,z.ends
> > > #
> > > Running the following code outputs:
> >  [(0, 2)] [(0, 2)] [(0, 2)]
>
> > > Can anyone explain this?
>
> > Yes. You bound a single list to the name "ends" inside the class.
> > This name is shared by all instances.
>
> > If you want the instances to each have separate lists, delete
> > the "ends" definition from class declaration and insert "self.ends
> > = []" into __init__.
>
> > I also suggest you to have a look at the tutorial.
>
> > Regards,
>
> > Björn
>
> > --
> > BOFH excuse #49:
>
> > Bogon emissions
>
> Björn,
>
> Thanks for the help.  I had misguidedly defined the members of all of
> my classes as in the example above; I never noticed the issue with any
> of the others because they did not have empty constructors.
>
> Thanks again for the correction.

Yeah! thanks all. I did not realize the distinction either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generational Interfaces

2008-01-25 Thread Paul Rubin
Carl Banks <[EMAIL PROTECTED]> writes:
> AirplaneInterface = InterfaceTracker("Airplane")
> ...
> set_up_initial_state()
> ...
> AirplaneInterface.report(self)

> Thoughts?  (Surely someone's thought to do this before.)

A decorator might express the idea a little more naturally.  

Also, I'd say the interface tracker really should be told explicitly
when something is part of the interface and when it's specific to a
particular class implementing the interface.  It shouldn't try to
guess this based on some operation appearing in more than one class.
Maybe there's some operation done on all jet planes and on no
propeller planes, that shouldn't be part of the top level airplane
interface.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Tim Rau
On Jan 25, 10:25 pm, [EMAIL PROTECTED] wrote:
> > I agree that SDL is probably the best choice but for the sake of
> > completeness, Gtk can (at least in theory - I've never tried it) be
> > built against directfb and run without X.
>
> from the Pygame Introduction: Pygame is a Python extension library
> that wraps the SDL library and it's helpers. So you mean, Pygame can
> run without X?
>
> BTW I have nothing against X, I just have not experiences on the GUI
> field, so my feeling was it can run faster without X on the 500MHz AMD
> Geode CPU.
>
> Petr

The problem is not with x: you should be able to run x just fine with
only 133MHZ and a few megs of ram. The performance issues on such a
machine come from things like kde and gnome. use one of the simpler
window managers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Doesn't know what it wants

2008-01-25 Thread Tim Rau
Traceback (most recent call last):
  File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
\sandbox.py", line 242, in 
player = ship()
  File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
\sandbox.py", line 121, in __init__
self.phyInit()
  File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
\sandbox.py", line 147, in phyInit
moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
ArgumentError: argument 4: : expected
vec2d instance instead of vec2d

As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't
seems like it doesn't know what it wants, but I thought only teenagers
did that, no programming languages. clearly, Im missing something.

Line 147 reads:
moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
-- 
http://mail.python.org/mailman/listinfo/python-list


Generational Interfaces

2008-01-25 Thread Carl Banks
While thinking about generational garbage collection, the thought of
generational interfaces occurred to me.  I'd thought I'd run it by you
guys.  I'm curious if there are any examples of this out there.

I've opined on this chat room before that interfaces are more often
cumbersome than helpful, especially in the early stages of a project
where lots of refactoring is (or ought to be) happening.  But as
projects mature, interfaces do too, and that made me think interfaces
could be generated automatically by monitoring the software over time.

As an example, say I'm writing a flight simulator, and I have a
abstract base class Airplane, that I want to have an interface
someday, but I don't know what it is yet.  So I define an

AirplaneInterface = InterfaceTracker("Airplane")

What this does is to open a sort of persistent database called
Airplane (details aren't important now).  The database tracks all
objects that claim to implement the interface.

So say the first airplane is a Piper Cherokee.  I'd write a class like
this:

class PiperCherokeeX1(object):
wingspan = 52.2
wingchord = 7.9
...
def __init__(self):
self.x = 0.0
self.y = 0.0
self.z = 0.0
...
set_up_initial_state()
...
AirplaneInterface.report(self)
def move_stick(self,dx,dy):
...
def move_thottle(self,ds):
...
def move_rudder_pedals(self,ddr):
...
def camera_matrix(self):
return self._quat_to_matrix(self.q0,self.q1,self.q2,self.q3)
def step(self,dt):
...

The key here is the call to AirplaneInterface.report() at the end of
__init__; this tells the interface tracker that, as of this call, this
object is implementing the Aircraft interface.

At this point, the interface tracker notes that PiperCherokeeX1 object
has certain methods (move_stick, move_throttle, etc), certain class
attributes, and certain instance attributes.  And that's all it does--
at first.  It just writes information into the database.

As time passes, and development continues, methods and data are added,
changed, reconfigured.  For instance, I might split up move_stick()
into move_stick_x() and move_stick_y() for some reason.  Then I might
get rid of these functions altogether in favor of a
move_control(self,n,dx).  And so on.  I add more classes that
implement the Aircraft interface, too.  They look almost nothing like
the original interface.

However, through all that, the class attribute "wingspan" remains
there.  Until one day when the project is quite mature I add a new
class, say Airbus380, that fails to define "wingspan".  When this
class calls AirplaneInterface.report(), it raises an
InterfaceException.

Basically, the InterfaceTracker decides, after some threshold of
nearly universal usage of a certain method or attribute, that it has
become a required part of the interface and starts raising exceptions
when it's not there.

Make sense?  Details can vary, but that's the basic idea.  In this
way, you can combine some of the openness that helps in early
development, but also have some of the benefits of stricter typing
when things mature and turn out to be pretty strictly useful, without
much effort.

Thoughts?  (Surely someone's thought to do this before.)


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


Re: translating Python to Assembler

2008-01-25 Thread Grant Edwards
On 2008-01-26, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Once a python py file is compiled into a pyc file, I can disassemble
> it into assembler.

No you can't.  It's not native machine code.  It's byte code
for a virtual machine.

> Assembler is nothing but codes, which are combinations of 1's
> and 0's. You can't read a pyc file in a hex editor, but you
> can read it in a disassembler.

NO YOU CAN'T.

> It doesn't make a lot of sense to me right now,

That's because IT'S NOT MACHINE CODE.

> but if I was trying to trace through it with a debugger,

That wouldn't work.

> the debugger would disassemble it into assembler,
> not python.

You can "disassemble" random bitstreams into assembler.  That
doesn't make it a useful thing to do.

[Honestly, I think you're just trolling.]


-- 
Grant Edwards   grante Yow!  Yow! Is this sexual
  at   intercourse yet?? Is it,
   visi.comhuh, is it??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread Tim Rau
On Jan 26, 1:41 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Jan 26, 4:20 pm, Tim Rau <[EMAIL PROTECTED]> wrote:
>
>
>
> > Traceback (most recent call last):
> >   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> > \sandbox.py", line 242, in 
> > player = ship()
> >   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> > \sandbox.py", line 121, in __init__
> > self.phyInit()
> >   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> > \sandbox.py", line 147, in phyInit
> > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
> > ArgumentError: argument 4: : expected
> > vec2d instance instead of vec2d
>
> > As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't
> > seems like it doesn't know what it wants, but I thought only teenagers
> > did that, no programming languages.
>
> It possibly means that it is expecting an instance of a class whose
> name is "vec2d"  but you have given it an instance of some *other*
> class whose name just happens to be "vec2d".
>
> > clearly, Im missing something.
>
> Yes, some information:
> 1. what is vec2d, class or function?
> 2. what do you believe vec2d((0, 0)) should return?
> 3. what is this belief based on?
> 4. what has it actually returned this time?
> 5. what do you believe that cp.cpMomentForCircle expects as argument
> 4?
> 6. what is this belief based on?
>
> The ArgumentError exception is raised by ctypes "when a foreign
> function call cannot convert one of the passed arguments". Based on
> guessin'n'googlin' the cp thing is a set of Python bindings to a
> library written in C++ ... have you considered asking the author of
> the bindings?

1. vec2d is a class, designed to hold and manipulte 2d vectors
2. it should return a vector with x=0 and y=0
3. That's what it's done before.
4. trying it in the interpreter seems to show that it returns a vec2d
with zero length. as it should.
5.cp.cpMomentForCircle seems to expect a vec2d. I'm baseing that on a
functioning demo that uses the exact same line.

I guess that the vec2d I've got is not the one it wants. How do I tell
the difference? I'll go look at all the imports.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread John Machin
On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
nomine.org> wrote:
> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>
> >Line 147 reads:
> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>
> I think it expects something like:
>
> # badly named variable, pick something better depending on context
> temp = vec2d(0, 0)
> cp.cpMomentForCircle(self.mass, .2, 0, temp)

That *cannot* give a different result in Python. The called function
will be presented with *exactly* the same object as the OP's code
does.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread Tim Rau
On Jan 26, 1:32 am, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
nomine.org> wrote:
> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>
> >Line 147 reads:
> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>
> I think it expects something like:
>
> # badly named variable, pick something better depending on context
> temp = vec2d(0, 0)
> cp.cpMomentForCircle(self.mass, .2, 0, temp)
>
> I am curious about your use of double braces for vec2d though. Why ((0,0)) and
> not (0, 0)?

the double parens are a tuple being passed as an argument. vec2d is
not a constructor that cares whether it gets a tuple or a pair of
ints. I choose tuple for consistency with the rest of my code.  Isn't
what it gets the value returned by the constructor, no matter whether
you assign it to an intermediate value first? I tried it, and the
result is the same.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "just like Java" (was :Re: translating Python to Assembler)

2008-01-25 Thread Christian Heimes
Paul Boddie wrote:
> Well, it is important to make distinctions when people are wondering,
> "If Python is 'so slow' and yet everyone tells me that the way it is
> executed is 'just like Java', where does the difference in performance
> come from?" Your responses seemed to focus more on waving that issue
> away and leaving the whole topic in the realm of mystery. The result:
> "Python is just like Java apparently, but it's slower and I don't know
> why."

Short answer: Python doesn't have a Just In Time (JIT) compiler. While
Java's JIT optimizes the code at run time Python executes the byte code
without additional optimizations.

Christian

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread petr . jakes . tpc

> I agree that SDL is probably the best choice but for the sake of
> completeness, Gtk can (at least in theory - I've never tried it) be
> built against directfb and run without X.

from the Pygame Introduction: Pygame is a Python extension library
that wraps the SDL library and it's helpers. So you mean, Pygame can
run without X?

BTW I have nothing against X, I just have not experiences on the GUI
field, so my feeling was it can run faster without X on the 500MHz AMD
Geode CPU.

Petr


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


Re: translating Python to Assembler

2008-01-25 Thread ajaksu
On Jan 25, 11:36 pm, ajaksu <[EMAIL PROTECTED]> wrote:
> On Jan 25, 11:10 pm, [EMAIL PROTECTED] wrote:
[...]

Gaah, is this what's going on?

[EMAIL PROTECTED]:~$ cat error.txt
This is not assembler...

[EMAIL PROTECTED]:~$ ndisasm error.txt
  54push sp
0001  686973push word 0x7369
0004  206973and [bx+di+0x73],ch
0007  206E6Fand [bp+0x6f],ch
000A  7420  jz 0x2c
000C  61popa
000D  7373  jnc 0x82
000F  656D  gs insw
0011  626C65bound bp,[si+0x65]
0014  722E  jc 0x44
0016  2Edb 0x2E
0017  2Edb 0x2E
0018  0Adb 0x0A

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


Re: translating Python to Assembler

2008-01-25 Thread over
On Thu, 24 Jan 2008 08:02:06 GMT, Tim Roberts <[EMAIL PROTECTED]> wrote:

>Bjoern Schliessmann <[EMAIL PROTECTED]> wrote:
>
>>Grant Edwards wrote:
>>
>>> Trying to find assembly language stuff to look at is futile.
>>> Python doesn't get compiled into assembly language.
>>
>>So, how do processors execute Python scripts? :)
>
>Is that a rhetorical question?  Grant is quite correct; Python scripts (in
>the canonical CPython) are NOT compiled into assembly language.  Scripts
>are compiled to an intermediate language.  Processors execute Python
>scripts when the interpreter, written in a high-level language and compiled
>to assembly, interprets the intermediate language created by the Python
>"compiler".

Intel processors can only process machine language, which is
essentially binary 1's and 0's. All  a processor understands is
voltages, either 0 Volts or 5 volts on older systems, or 3.3 volts and
less on newer systems. Generally, a positive voltage is a logical 1
and 0 volts is a logical 0. There's no way for a processor to
understand any higher level language, even assembler, since it is
written with hexadecimal codes and basic instructions like MOV, JMP,
etc. The assembler compiler can convert an assembler file to a binary
executable, which the processor can understand.

If you look at the Python interpreter, Python.exe, or Pythonw, the
Windows interface, or the Python24.dll, the main library for python,
you will see they are normal 32 bit PE files. That means they are
stored on disk in codes of 1's and 0's, and decompile into assembler.
You can't decompile them into Python directly, although I'm sure
someone is trying. No compiled file can be decompiled into it's
original format easily or automatically, although there are
decompilers that will convert them to a reasonable assembler
decompilation. 

If a Python script was understood directly by the processor, no
interpreter would be necessary. Ask yourself what the interpreter is
doing. It's taking the scripting language and converting to the
language of the operating system. However, it's the processor that
dictates how programs are written, not the OS. That's why a Linux OS
will run on an Intel machine, as a Windows OS does. Both Linux and
Windows compile down to binary files, which are essentially 1's and
0's arranged in codes that are meaningful to the processor. 

Once a python py file is compiled into a pyc file, I can disassemble
it into assembler. Assembler is nothing but codes, which are
combinations of 1's and 0's. You can't read a pyc file in a hex
editor, but you can read it in a disassembler. It doesn't make a lot
of sense to me right now, but if I was trying to trace through it with
a debugger, the debugger would disassemble it into assembler, not
python. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Mobile Phones, iPods EQ100 www.enmac.com.hk

2008-01-25 Thread Farooq
www.enmac.com.hk
GSM Mobile Phones, Digital iPods, Digital Clocks, Digital Pens,
Digital Quran. Enjoy these products with Islamic Features (Complete
Holy Quran with Text and Audio, Tafaseer books, Ahadees Books, Daily
Supplications, Universal Qibla Direction, Prayer Timing and much more)
visit our website for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: basic output question

2008-01-25 Thread Alan Isaac
John Deas wrote: 
> My problem is that f.read() outputs nothing

Since ``open`` did not give you an IOError,
you did get a handle to the files,
so this suggests that the files you read
are empty...

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


Re: find minimum associated values

2008-01-25 Thread Alan Isaac
[EMAIL PROTECTED] wrote:
> I'd use the first solution.

It can be speeded up a bit with
a try/except:

for k,v in kv:
try:
if d[k] > v:
d[k] = v
except KeyError:
d[k] = v

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Paul Boddie
On 25 Jan, 22:06, "Lorenzo E. Danielsson"
<[EMAIL PROTECTED]> wrote:
>
> What you need then is something like SVGAlib (http;//svgalib.org). Only
> really old people like myself know that it exists. I've never heard of
> any Python bindings for it, but that might be where you come in. I
> haven't looked at SVGAlib for years, and I'm not sure about the state of
> the video drivers. I suggest you look at that first.

I believe that SVGAlib was superseded by GGI and other projects, and I
recall that SVGAlib was considered to be something of a nightware with
respect to how it handles various resources. Certainly, I haven't been
very impressed by the behaviour of software using it.

> You could also look at GGI (http://ggi-project.org). GGI has different
> output targets. IIRC, one of them is directfb. To tell you the truth
> I've never really used GGI. There seems to be a python wrapper for GGI,
> although it is fairly old. Maybe you could look at the code for some ideas.

I've had to build software using GGI, and the biggest problem has been
getting packages for it. That said, it seemed to work fairly
acceptably once built and installed. Meanwhile, some people favour
Allegro [1] for this kind of work, and I've been confronted with newly
developed software which uses Allegro, so it's arguably in a different
maintenance state than something like SVGAlib or GGI.

> You should also be able to compile SDL to be able to use directfb as a
> target. If your libSDL handles it, then that should apply to wrapper
> libraries as well, including pygame. I've never tried running SDL apps
> this way, but if it works well, that would probably be your 'best' option.

I'd agree with these sentiments; SDL seems to be the best supported
technology of this kind in the Python universe, and one of the most
widely deployed in general; I've felt quite comfortable building
software against it. It would be very interesting to see whether a
framebuffer-based SDL could support Pygame, and I imagine that the
Pygame mailing list might already have some answers in its archives on
this topic.

Paul

[1] http://www.talula.demon.co.uk/allegro/
-- 
http://mail.python.org/mailman/listinfo/python-list


wx.EVT_RIGHT_UP strangeness?

2008-01-25 Thread JimT
I'm playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5

I ran the demo program found what may be a bug with the right mouse 
button up event.

The demo is ShapedWindow.py. Everthing thing seems to work fine except 
that right
clicking does not close the window. Tracing the program shows that the 
event never
fires.

Upon closer scrutiny I discovered if you bind the wx.EVT_RIGHT_DOWN event, the
wx.EVT_RIGHT_UP now fires. I tried this in a couple programs and the 
behavior is
consistent.

Is this the way it is supposed to work? If not, am I the only one with 
this problem?


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


Re: Generational Interfaces

2008-01-25 Thread Carl Banks
On Jan 26, 12:32 am, Paul Rubin  wrote:
> Carl Banks <[EMAIL PROTECTED]> writes:
> > AirplaneInterface = InterfaceTracker("Airplane")
> > ...
> > set_up_initial_state()
> > ...
> > AirplaneInterface.report(self)
> > Thoughts?  (Surely someone's thought to do this before.)
>
> A decorator might express the idea a little more naturally.

Details.  I didn't thoroughly map out the whole system in my head or
anything.


> Also, I'd say the interface tracker really should be told explicitly
> when something is part of the interface and when it's specific to a
> particular class implementing the interface.  It shouldn't try to
> guess this based on some operation appearing in more than one class.

Well, that kind of defeats the purpose, doesn't it?

If you're going to all that trouble, it's probably not too much more
trouble to just manually specify the whole interface and be done with
it.  Anyways you don't always know what's going to end up as part of
the interface in early stages.

It goes without saying there should be ways to manually override the
interface tracker's decision, but that falls more into the category
"So your interface tracker has guessed wrong".


> Maybe there's some operation done on all jet planes and on no
> propeller planes, that shouldn't be part of the top level airplane
> interface.

Well, then the interface tracker would see that some member (say,
"set_mixture") exists on some objects and not others, and would
consider it not part of the interface.  Only members that are defined
universally or nearly universally would be considered part of the
interface.

Now if you're concerned that you could implement a bunch of prop
planes, and then suddenly you throw a jet in there and it breaks
everything, there's a simple solution: convert the AirplaneInterface
to PropAirplaneInterface.  (Yeah, suck it up and replace it
everywhere.  If you haven't implemented any jets you shouldn't have
released the damn thing yet.)  Create a new JetAirplaneInterface
tracker and (if useful) define Airplane as the union of the two.

Obviously something like this could get really intelligent--it could
perhaps work out the difference between props and jets itself (using,
say, statistical correlation).  I bet there are some high-end code
analysis tools for various languages that do stuff like that.  (But I
doubt many of them factor time into it; my idea was to incorporate
time into it somehow.  Something does not become part of an interface
until it's universally used AND has been around for awhile.)


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


Re: Index of maximum element in list

2008-01-25 Thread Terry Reedy

"Henry Baxter" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Thanks Hexamorph and Neal. Somehow I didn't make the connection with 
using
| 'index', but I'm all sorted out now :)
|
| On Jan 25, 2008 1:47 PM, Hexamorph <[EMAIL PROTECTED]> wrote:
|
| > Henry Baxter wrote:
| > > Oops, gmail has keyboard shortcuts apparently, to continue:
| > >
| > > def maxi(l):
| > > m = max(l)
| > > for i, v in enumerate(l):
| > > if m == v:
| > > return i
| > >
| >
| > What's about l.index(max(l)) ?

Both of these methods scan the list twice.  The two given by RH and SDD do 
so just once.  Both of those will give the index of the of the last maximum 
value.  If you want the index of the first max value (you did not specify 
;-), write an explicit loop. 



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


Re: getting values from cache

2008-01-25 Thread nodrogbrown
also
if i were to write unit test for this method ,how shd i do it? shd i
be checking all values in the matrix created inside and so on?

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


Re: Index of maximum element in list

2008-01-25 Thread Paul Rubin
"Terry Reedy" <[EMAIL PROTECTED]> writes:
> | > What's about l.index(max(l)) ?
> 
> Both of these methods scan the list twice.  The two given by RH and SDD do 
> so just once.  Both of those will give the index of the of the last maximum 
> value.  If you want the index of the first max value (you did not specify 
> ;-), write an explicit loop. 

How about (corrected but still untested):

  -max((v,-i) for i,v in enumerate(l))[1]

I may have still missed something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I use the up and down, left and right arrow keys to control a Python Pgm

2008-01-25 Thread Tim Rau
On Jan 25, 10:48 pm, "jitrowia" <[EMAIL PROTECTED]> wrote:
> I was wondering what kind of python code I would need to enable me to
> use the up and down, left and right arrow keys to control software
> programming decisions within a Python Program.
>
> Any direction and advice would be greatly appreciated,
>
> Thank You,
> Rodney

"software programming decisions" is awfully vague. COuld oyu narrow
down exactly what you want to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread John Machin
On Jan 26, 4:20 pm, Tim Rau <[EMAIL PROTECTED]> wrote:
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 242, in 
> player = ship()
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 121, in __init__
> self.phyInit()
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 147, in phyInit
> moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
> ArgumentError: argument 4: : expected
> vec2d instance instead of vec2d
>
> As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't
> seems like it doesn't know what it wants, but I thought only teenagers
> did that, no programming languages.

It possibly means that it is expecting an instance of a class whose
name is "vec2d"  but you have given it an instance of some *other*
class whose name just happens to be "vec2d".

> clearly, Im missing something.

Yes, some information:
1. what is vec2d, class or function?
2. what do you believe vec2d((0, 0)) should return?
3. what is this belief based on?
4. what has it actually returned this time?
5. what do you believe that cp.cpMomentForCircle expects as argument
4?
6. what is this belief based on?

The ArgumentError exception is raised by ctypes "when a foreign
function call cannot convert one of the passed arguments". Based on
guessin'n'googlin' the cp thing is a set of Python bindings to a
library written in C++ ... have you considered asking the author of
the bindings?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread Jeroen Ruigrok van der Werven
-On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>Line 147 reads:
>moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))

I think it expects something like:

# badly named variable, pick something better depending on context
temp = vec2d(0, 0)
cp.cpMomentForCircle(self.mass, .2, 0, temp)

I am curious about your use of double braces for vec2d though. Why ((0,0)) and
not (0, 0)?

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
We have met the enemy and they are ours...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: read and readline hanging

2008-01-25 Thread Thomas Bellman
Olivier Lefevre <[EMAIL PROTECTED]> wrote:

>> 1. The subprocess has stopped producing output.

> Indeed, if I do this interactively, I can tell after 3 lines that I've
> gotten all there is to get right now and the fourth readline() call
> hangs.

Can you really?  How do you know if the program has finished or
if it is just taking a very long time to produce the next line in
its response?  Unless there is some way to differentiate between
the last line all the other lines of a response, you can't really
be sure.

> But how can I find out *programmatically* that there is no more
> input?

It is possible to check if there is something more to read at the
moment, but you can't check if the subprocess will produce more
to read in the future.

To check if there is something to read at this very moment, you
can use any of the following methods:

  - select.select()
  - the FIONREAD ioctl (the ioctl() function lives in the fcntl
module, and the FIONREAD constant is in the termios module)
  - set the underlying file descriptor in non-blocking mode:
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NDELAY)
After that, reads on the pipe will raise an IOError exception
with the errorcode EWOULDBLOCK.
  - start a thread that does blocking reads from the pipe, and
puts the chunks it reads on a queue for your main thread to
grab.

For the last approach, you might be interrested in my asyncproc
module, which does exactly that.  You can download it from
.

However, none of these approaches absolves you from the necessity
of knowing when one response ends.  You still need to solve that
problem.

The proper way is to define a protocol between your program and
the subprocess, in which you can clearly tell when you have
reached the end of a response.  Then you need to get the program
you are calling to adher to that protocol, of course...

The SMTP protocol is a good example of how this can look.  In
SMTP, each response to a command consists of a number of lines.
Each line has a three-digit response code, an "end of response"
flag, and a text message.  The "end of response" flag is a space
(" ") for the last line in the response, and a dash ("-") for all
the other lines.  The response to an EHLO command can look like
this:

250-sellafield Hello localhost [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-EXPN
250-VERB
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-DELIVERBY
250 HELP

Since there is a space instead of a dash after the "250" code in
the last line above, the SMTP client knows that there won't be
any more lines in response to its command.

If you can't get the program you are calling to follow some
protocol like this, then you can only make guesses.  Sometimes
you can make fairly good guesses, and sometimes it will be more
or less impossible...


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Life IS pain, highness.  Anyone who tells   !  bellman @ lysator.liu.se
 differently is selling something."  !  Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: basic output question

2008-01-25 Thread Wildemar Wildenburger
John Deas wrote:
> Hi, I am very new to Python (1 evening...)
> I need to process a series of files (toto-1.txt toto-2.txt toto-3.txt
> toto-4.txt), and as such I created a small program to go through the
> files in a directory. I want to call the script with arguments, like
> 
> python script.py toto- 1 1 4
> 
> my script is as follow :
> 
> import sys
> sys.argv
> header= sys.argv[1]
> start =eval(sys.argv[2])
> step  =eval(sys.argv[3])
> nbit  =eval(sys.argv[4])
> 
Style note: You should probably use int() instead of eval. Not only is 
this safer (as in security), it is also safer (as in robust), because it 
will throw an error early if you feed it something other than an int.


> for i in range(nbit):
>   filename=header+str(start+i*step)+'.txt'
>   f=open(filename,'r')
>   f.read()
>   f.close()
> 
> My problem is that f.read() outputs nothing, and should I print
> filename, I can check that they are well formed, and the files sits in
> the same directory as my script.
> 
f.read() spills the text into nothingness. You may want to write its 
output to a variable. ;)

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


Re: Doesn't know what it wants

2008-01-25 Thread John Machin
On Jan 26, 6:25 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 25 Jan 2008 22:53:16 -0800, John Machin wrote:
> > On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
> > nomine.org> wrote:
> >> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>
> >> >Line 147 reads:
> >> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>
> >> I think it expects something like:
>
> >> # badly named variable, pick something better depending on context
> >> temp = vec2d(0, 0)
> >> cp.cpMomentForCircle(self.mass, .2, 0, temp)
>
> > That *cannot* give a different result in Python. The called function
> > will be presented with *exactly* the same object as the OP's code does.
>
> Not quite. Look carefully at the difference.
>
> The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's
> version calls vec2d with two int arguments, 0 and 0.
>
> We don't know whether vec2d will treat those two things the same or not.

That was Jeroen's 2nd problem; I was addressing his first problem
(thinking that introducing a temp variable would work some magic).

Google is your friend:
"""
class vec2d(ctypes.Structure):
"""2d vector class, supports vector and scalar operators,
   and also provides a bunch of high level functions
   """
__slots__ = ['x', 'y']

def __init__(self, x_or_pair, y = None):

if y == None:
self.x = x_or_pair[0]
self.y = x_or_pair[1]
else:
self.x = x_or_pair
self.y = y
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a newbie regex question

2008-01-25 Thread Max Erickson
"Dotan Cohen" <[EMAIL PROTECTED]> wrote:
> Maybe you mean:
> for match in re.finditer(r'\([A-Z].+[a-z])\', contents):
> Note the last backslash was in the wrong place.

The location of the backslash in the orignal reply is correct, it is 
there to escape the closing paren, which is a special character:

>>> import re
>>> s='Abcd\nabc (Ab), (ab)'
>>> re.findall(r'\([A-Z].+[a-z]\)', s)
['(Ab), (ab)']

Putting the backslash at the end of the string like you indicated 
results in a syntax error, as it escapes the closing single quote of 
the raw string literal: 

>>> re.findall(r'\([A-Z].+[a-z])\', s)
   
SyntaxError: EOL while scanning single-quoted string
>>> 


max


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


Pickling dynamically generated classes

2008-01-25 Thread George Sakkis
The Fine Manual mentions that pickle works for classes that are
defined at the top level of a module. Is there a way to extend this
behavior so that I can pickle and unpickle instances of dynamically
generated classes ?

Longer version: I have a function RecordTypeFactory(fields, ...) that
dynamically generates and caches a record-like class based on the
passed fields and other info (or returns the cached class if it has
been created before). Although I am able to pickle instances of the
various generated classes (records) by writing the gen. class in
globals(), I cannot unpickle them from a different process unless
RecordTypeFactory is called with the same arguments so that "the same"
class is generated in the other process as well. Essentially what I'm
missing is a hook to call RecordTypeFactory with the same fields when
an instance of the gen. class is to be unpickled.

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


Re: python and multithreading problem

2008-01-25 Thread Diez B. Roggisch
whatazor schrieb:
> Hi all,
> I made an application that use multithreading (indifferently importing
> thread or  threading module) , but when I call some wrapped modules
> (with swig) from my application they run like there is only a single
> thread (and my application gui ,made with wxPython, freezes). If I use
> other modules not wrapped, but created for test that multithread
> works, and gui is not freezing are ok.
> Modules that wrap DLL are not my product but are created by another
> developer with VS.NET, and the only thing I can think is that they're
> builded without multithreaded compiler option. Can it be another cause
> for this behaviour, can this explanation be correct? maybe also swig
> have a multithreading option.


There is something called Global Interpreter Lock (GIL) that causes such 
behavior. It will ensure that python-code won't interfere with each 
other in multiple threads.

However, for C-extensions it is common to release that GIL when a thread 
enters the extenison, and grab it again when finished. I don't know if 
SWIG does so, but to me it looks as if that is the problem. You might 
consider googling swig + gil or something to learn more about it.

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


Re: Doesn't know what it wants

2008-01-25 Thread Steven D'Aprano
On Fri, 25 Jan 2008 22:53:16 -0800, John Machin wrote:

> On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
> nomine.org> wrote:
>> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>>
>> >Line 147 reads:
>> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>>
>> I think it expects something like:
>>
>> # badly named variable, pick something better depending on context 
>> temp = vec2d(0, 0)
>> cp.cpMomentForCircle(self.mass, .2, 0, temp)
> 
> That *cannot* give a different result in Python. The called function
> will be presented with *exactly* the same object as the OP's code does.

Not quite. Look carefully at the difference.

The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's 
version calls vec2d with two int arguments, 0 and 0.

We don't know whether vec2d will treat those two things the same or not.

Personally, my bet is that the OP has shadowed vec2d, and has got two 
different classes floating around with the same class.__name__.

Either that, or a bug in cp.cpMomentForCircle. I'd really like to see the 
code of that function in phyInit. I'm suspicious about the exception 
raised:

ArgumentError: argument 4: : expected vec2d 
instance instead of vec2d

What's with the TypeError in there? I'm guessing it's not a hard coded 
string.



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


getting values from cache

2008-01-25 Thread nodrogbrown
hi
i am writing code to check a folder containing images and then process
thir vals using PIL and do some calc to create a matrix of values .if
the folder has any new imgs added the program will do all calc again
and dump the values into a cachefile.If the folder contents remain
unaltered the program should not do calc but load the vals from
cachefile..it is assumed that malicious alterations are not made on
the folder and so i wont be doing any thorogh check but just checking
if contents of folder have changed..i do something like this


def checkCache(self):
   filenameslist=getfilenameslist() # made by parsing folder before
this
   try:
  f=open(cachefile)

   except IOError:
#no cache found ,do all calc
mynumpymatrix1,imgwdth,imght=docalculations()
f2=open(cachefile,"w")
#dump values as tuple
pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f2)
f2.close()
   else:
#cache exists, need to check if folder contents changed
oldfilenameslist,wd,ht, mynumpymatrix1=pickle.load(f)
f.close()

if(filenamelist==oldfilelist):
#if oldfilenamelst same,it means folder hasn't changed
#use the vals from cache.
else:
#folder changed
mynumpymatrix1,imgwdth,imght=docalculations()
f3=open(cachefile,"w")
 
pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f3)
f3.close()

 this works and does what i need in my code..but i want to know if a
more elegant solution is possible
 i am not worried about someone deliberately renaming files like
.jpeg to aaa.jped and a.jpeg to deceive the checking
 since it is assumed that noone has permission to modify the folder
except a trusted admin/code

 will be grateful for your suggestions
 tia
-- 
http://mail.python.org/mailman/listinfo/python-list


How to modify the content of an email

2008-01-25 Thread alejandro . valdez
Hello, I'm trying to make a python script that take an email in (raw)
text format, and add a footer to the text (or html) body of the email.

I'm aware of the email and email.mime modules, but I can't figure out
how to identify 'the main text (or html) content' from the email, and
how to be sure that I don't incorrectly identify a txt (or html)
attach as the main content of the email.

By 'main text (or html) content' I mean the text (or html) that is
showed by a Mail User Agent when it display the email to the
recipient.

Thanks in advance.

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


Re: Puzzled by behaviour of class with empty constructor

2008-01-25 Thread Tomek Paczkowski
[EMAIL PROTECTED] wrote:

> Hello,
> 
> I have a class called 'Axis' that I use as a base class for several
> types of axes that can be created by a grid generation program that I
> have written: equally-spaced grids, logarithmic grids, etc.  In any
> case, if I use this base class by itself, I see some puzzling
> behaviour:
> #
> class Axis:
> ends = []
> N = None
> def __init__(self):
> pass
> 
> x = Axis()
> y = Axis()
> z = Axis()
> 
> x.ends.append((0,2))
> 
> print x.ends,y.ends,z.ends
> #
> Running the following code outputs:
 [(0, 2)] [(0, 2)] [(0, 2)]
> 
> Can anyone explain this?

Well, you are using a class variable - Axis.ends. It's shared among all
instances of Axis class. To have it separate setup it in __init__ like:

class Axix:
def __init__(self):
self.ends = []
self.N = None

You see, code inside class, but outside methods is executed only once and
any variables are then linked with class, and not instances (more/less).
Take look at: http://docs.python.org/tut/node11.html

   ~TomekP

-- 
Someone whom you reject today, will reject you tomorrow.

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


Re: find minimum associated values

2008-01-25 Thread Alan Isaac
Alan Isaac wrote:
 
> #sort by id and then value
> kv_sorted = sorted(kv, key=lambda x: (id(x[0]),x[1]))
> #groupby: first element in each group is object and its min value
> d =dict( g.next() for k,g in groupby( kv_sorted, key=lambda x: x[0] ) )
> 
> Yes, that appears to be fastest and is
> pretty easy to read.

On average.
For the specified problem.
;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


CFP: DATICS 2008 - Design, Analysis and Tools for Integrated Circuits and Systems

2008-01-25 Thread DATICS2008
Apologies for any multiple copies received. We would appreciate it if
you could distribute
the following call for papers to any relevant mailing lists you know
of.

 CALL FOR PAPERS
===
Special Session: Design, Analysis and Tools for Integrated Circuits
and Systems

DATICS 2008

July 22-24, 2008 (Crete Island, Greece)
http://digilander.libero.it/systemcfl/datics
===

Aims and Scope
--
The main target of the Special Session: DATICS 2008 of the WSEAS CSCC
multi-conference
(http://www.wseas.org/conferences/2008/greece/icc/) is to bring
together software/hardware
engineering researchers, computer scientists, practitioners and people
from industry to
exchange theories, ideas, techniques and experiences related to all
areas of design, analysis and
tools for integrated circuits (e.g. digital, analog and mixed-signal
circuits) and
systems (e.g. real-time, hybrid and embedded systems).
The special session also focuses on the field of formal methods and
low power design methodologies for integrated circuits.

Topics
--
Topics of interest include, but are not limited to, the following:
* digital, analog, mixed-signal designs and test
* RF design and test
* design-for-testability and built-in self test methodologies
* reconfigurable system design
* high-level synthesis
* EDA tools for design, testing and verification
* low power design methodologies
* network and system on-a-chip
* application-specific SoCs
* specification languages: SystemC, SystemVerilog and UML
* all areas of modelling, simulation and verification
* formal methods and formalisms (e.g. process algebras, petri-nets,
automaton theory and BDDs)
* real-time, hybrid and embedded systems
* software engineering (including real-time Java, real-time UML and
performance metrics)

Industrial Collaborators:
---
DATICS 2008 is partnered with:
* CEOL: Centre for Efficiency-Oriented Languages "Towards improved
software timing",
  University College Cork, Ireland ( http://www.ceol.ucc.ie)
* International Software and Productivity Engineering Institute, USA
(http://www.intspei.com )
* Intelligent Support Ltd., United Kingdom (http://www.isupport-
ltd.co.uk)
* Solari, Hong Kong ( http://www.solari-hk.com)
* Minteos, Italy (http://www.minteos.com)
* M.O.S.T., Italy (http://www.most.it)

Technical Program Committee:
--
* Prof. Vladimir Hahanov, Kharkov National University of Radio
Electronics, Ukraine
* Prof. Paolo Prinetto, Politecnico di Torino, Italy
* Prof. Alberto Macii, Politecnico di Torino, Italy
* Prof. Joongho Choi, University of Seoul, South Korea
* Prof. Wei Li, Fudan University, China
* Prof. Michel Schellekens, University College Cork, Ireland
* Prof. Franco Fummi, University of Verona, Italy
* Prof. Jun-Dong Cho, Sung Kyun Kwan University, South Korea
* Dr. Emanuel Popovici, University College Cork, Ireland
* Dr. Jong-Kug Seon, Telemetrics Lab., LG Industrial Systems Co. Ltd.,
South Korea
* Dr. Umberto Rossi, STMicroelectronics, Italy
* Dr. Graziano Pravadelli, University of Verona, Italy
* Dr. Vladimir Pavlov, International Software and Productivity
Engineering Institute, USA
* Dr. Jinfeng Huang, Philips & LiteOn Digital Solutions Netherlands,
Advanced Research Centre,
The Netherlands
* Dr. Thierry Vallee, Georgia Southern University, Statesboro,
Georgia, USA
* Dr. Menouer Boubekeur, University College Cork, Ireland
* Dr. Ana Sokolova, University of Salzburg, Austria
* Dr. Sergio Almerares, STMicroelectronics, Italy
* Ajay Patel (Director), Intelligent Support Ltd, United Kingdom
* Monica Donno (Director), Minteos, Italy
* Alessandro Carlo (Manager), Research and Development Centre of FIAT,
Italy
* Yui Fai Lam (Manager), Microsystems Packaging Institute, Hong Kong
University of
   Science and Technology, Hong Kong

Important Dates
---
March 31, 2008: Deadline for submission of completed papers
May 1, 2008: Notification of acceptance/rejection to authors

Please visit our web-site for further information on the hosting
conference of DATICS,
submission guidelines, proceedings and publications and international
technical reviewers.

Best regards,

General Chair of DATICS: Dr. K.L. Man (University College Cork,
Ireland)
and
Organising Committee Chair: Miss Maria O'Keeffe (University College
Cork, Ireland)



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


Re: Index of maximum element in list

2008-01-25 Thread Hexamorph
Henry Baxter wrote:
> Oops, gmail has keyboard shortcuts apparently, to continue:
> 
> def maxi(l):
> m = max(l)
> for i, v in enumerate(l):
> if m == v:
> return i
> 

What's about l.index(max(l)) ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-25 Thread Henry Baxter
Oops, gmail has keyboard shortcuts apparently, to continue:

def maxi(l):
m = max(l)
for i, v in enumerate(l):
if m == v:
return i

But it seems like something that should be built in - or at least I should
be able to write a lambda function for it, but I'm not sure how to do that
either...Suggestions are very much welcome!

On Jan 25, 2008 1:37 PM, Henry Baxter <[EMAIL PROTECTED]> wrote:

> I apologize if this has already been discussed - funnily enough my
> googling did bring up a previous thread about it on this mailing list, but
> despite the promising subject line, seemed to mainly be concerned with
> whether python-list should its own FAQ...so I assume this has been asked
> many times before, but my apologies I cannot find the answer. Here is what I
> have:
>
> def maxi(l):
>
> it
> --
> Henry




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

Index of maximum element in list

2008-01-25 Thread Henry Baxter
I apologize if this has already been discussed - funnily enough my googling
did bring up a previous thread about it on this mailing list, but despite
the promising subject line, seemed to mainly be concerned with whether
python-list should its own FAQ...so I assume this has been asked many times
before, but my apologies I cannot find the answer. Here is what I have:

def maxi(l):

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

Re: Python ADO Date Time database fields

2008-01-25 Thread John Machin
On Jan 26, 12:48 am, goldtech <[EMAIL PROTECTED]> wrote:
> snip
>
>
>
> > try this:
>
> > val = oRS.Fields(dt).Value
> > print type(val)
>
> this gives:  
>
> > print float(val)
>
> yes, it gives 0.0
>
> But there should be a way to print what is *actually in the field*.

What is "actually in the field" is a bunch of bits -- in this case all
zero. What you *see* is quite another matter.

> When I open the DB table in Access I see: 12:00:00 AM.

And if you were to close Access, go Start / Control Panel / Regional
and Language settings, change the Time display format to HH:mm:ss, and
go back to look at your database, you'd see 00:00:00 ... send a copy
of your database to someone in another country and they'd likely see
something else again.

>
> That's what I want - the value, and the form of the value, exactly as
> seen in the field...

>
> As an aside, the roughly eqivalent code in Perl will print the
> "12:00:00 AM" - (the trick for the date types in Perl is to add: "use
> Win32::OLE::Variant;"
>
> There has to be a way:^)

C:\junk>type goldtech.py
def time_format_12(day_fraction):
assert 0.0 <= day_fraction < 1.0
seconds = int(day_fraction * 60 * 60 * 24)
minutes, second = divmod(seconds, 60)
hour, minute = divmod(minutes, 60)
if hour >= 12:
tag = 'PM'
else:
tag = 'AM'
hour12 = (hour - 1) % 12 + 1
return '%02d:%02d:%02d %s' % (hour12, minute, second, tag)

if __name__ == "__main__":
import sys
args = sys.argv[1:]
if args:
tests = map(float, args)
else:
tests = (
[0.0, 0.5, 0.999]
+ [(h + 0.99) / 24.0 for h in (0, 1, 11, 12, 13, 23)]
)
for test in tests:
print "%8.6f %s" % (test, time_format_12(test))

C:\junk>goldtech.py
0.00 12:00:00 AM
0.50 12:00:00 PM
1.00 11:59:59 PM
0.041250 12:59:24 AM
0.082917 01:59:24 AM
0.499583 11:59:23 AM
0.541250 12:59:24 PM
0.582917 01:59:24 PM
0.999583 11:59:23 PM

C:\junk>goldtech.py 0.1 0.01 0.001
0.10 02:24:00 AM
0.01 12:14:24 AM
0.001000 12:01:26 AM

C:\junk>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: read and readline hanging

2008-01-25 Thread Marc 'BlackJack' Rintsch
On Fri, 25 Jan 2008 17:31:16 +0100, Olivier Lefevre wrote:

> Thanks for the answer. Yes this is tricky. I have done it in Java
> before, where you can, e.g., set up a thread to pump stuff out of
> both stderr and stdout continuously but my python is too rudimentary
> for that.

The `trheading` module is modeled after Java's threading API.

> There is a key difference anyway: in Java you can write
> 
>  while (br.readLine() != null) {  }
> 
> where br is the buffered reader in which you've wrapped the stdout
> of the child process and it will not hang. But in python eventually
> stdout.readline() hangs. This is a real nuisance: why can't it just
> return None?

Because that would be quite annoying because most of the time people want
blocking behavior.

>> 1. The subprocess has stopped producing output.
> 
> Indeed, if I do this interactively, I can tell after 3 lines that I've
> gotten all there is to get right now and the fourth readline() call
> hangs. But how can I find out *programmatically* that there is no more
> input?

You can't.

>> If you are only reading its standard output, are you sure that the 
>  > subprocess is flushing its buffers so you can recognize it's time to
>  > provide more input?
> 
> The subprocess in a purely passive position: it is an interpreter: I
> send it commands and I read the answers. The python side is in charge.

This doesn't answer if the interpreter doesn't flush its output buffer
after every line.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is possible to get order of keyword parameters ?

2008-01-25 Thread rndblnch
On Jan 25, 9:01 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> rndblnch <[EMAIL PROTECTED]> wrote:
> > the following example should also
> > work:
> > size = Point(width=23, height=45)
> > w, h = size
>
> So you want the unpacking to depend on how the Point was initialised!
> Aaargh!

why not?
in

def f(*args):
return iter(args)

the order of the parameters do have a semantic,
i can predict the behaviour of:

x, y = f(1, 2)

to bad it's not possible with:

def g(**kwargs):
return kwargs.itervalues()

x, y = g(x=1, y=2)

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


  1   2   >