Re: Colons, indentation and reformatting. (2)

2007-01-09 Thread Diez B. Roggisch
> Won't the following rules work when pasting complete Python statements
> and complete lines, after other lines in an editor:
> 
> lets call the line after which the block is to be pasted the paste
> line, and the original indent of the first line of the copied block to
> be pasted the copy indent.
> 
> If the paste line ends in a colon then the copy indent must be greater
> than the paste line indent, or the copy block should be re-indented on
> pasting to make it so.
> If the paste line does not end in a colon then the copy block indent
> should be equal too or less than the paste line indent. If this is not
> the case then the user should be asked wether to re-indent the copy
> block to be equal to, or de-dented w.r.t. the paste line indent prior
> to pasting.


Could be done that way - but is it a killer feature? I doubt it, but 
maybe you convince somebody to implement it.

Yet it certainly doesn't justify a wikipedia edit - the FAQ entry is 
right, and there is no way of auto-indenting python code that for some 
reason suffered from indention mix-up.

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


Re: Colons, indentation and reformatting. (2)

2007-01-09 Thread Paddy

OK, whilst colons are not sufficient to re-format a completely
mis-indented file. I'm thinking that they are sufficient for
reformatting most pasted code blocks when refactoring say?
- Paddy.

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


Re: help: code formatter?

2007-01-09 Thread siggi
Chuck wrote:

>  http://lacusveris.com/PythonTidy/PythonTidy.python

Wow, what a giant of a program! Trying to find out how this works.

Thank you,

siggi

"Chuck Rhode" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> siggi wrote this on Mon, Jan 08, 2007 at 03:33:21PM +0100.  My reply is 
> below.
>
>> Is there a simple code formatter that first removes all indentations
>> and then refomats correctly?
>
> Why, yes, there is:
>
>  http://lacusveris.com/PythonTidy/PythonTidy.python
>
> -- 
> .. Chuck Rhode, Sheboygan, WI, USA
> .. 1979 Honda Goldwing GL1000 (Geraldine)
> .. Weather:  http://LacusVeris.com/WX
> .. 26° - Wind W 17 mph
> 


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

Re: help: code formatter?

2007-01-09 Thread siggi
Thomas wrote:

> Tools\scripts\reindent.py in your Python distribution.

Thank you Thomas!

What a bucket full of toolsin \tools! I didn't know that.

siggi


"Thomas Heller" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> siggi schrieb:
>> Hi all,
>>
>> as a newbie I have problems with formatting code of downloaded programs,
>> because IDLE's reformatting capabilities are limited . Incorrect
>> indentation, mixing of TAB with BLANKs or eol are often very nasty to
>> correct.
>> Is there a simple code formatter that first removes all indentations and
>> then refomats correctly?
>>
>> Please help!
>
>
> Tools\scripts\reindent.py in your Python distribution.
>
> Thomas 


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


line duplication using logging to file

2007-01-09 Thread seb
Hi, I am writing to a file some basic information using the logging
module.  It is working but in the log file some line are printed
several time. I had put some print debugging messages in the logging
function (so they appear on the consile) and they are called once only.
Obviously there is some understantding of the logging module that I am
missing.

My simple logging program (see below) is called by several processes.
In this way I can collect the information from various sources (and not
use the network enabled logging module)

I am using python 2.4 on WinXP SP2.

Do you have any idea ? Thanks in advance.

Seb.

*
The very simple "logging program ":
*
import logging, logging.handlers
import time

def write_log(level, message):
# Utilisation de l'API pour le Handler global
print "time.asctime()",time.asctime(),"received level=",level,"message
=",message
nom_logger="main_log_file"
logger=logging.getLogger(nom_logger)
logger.setLevel(logging.DEBUG)
prefix = "pix_main_log_file"
#fh=logging.handlers.RotatingFileHandler(prefix + "_log.txt", 'a',
100,10)
fh=logging.FileHandler("main_log.txt")
fh.setLevel(logging.DEBUG)
#formater = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s")
formater = logging.Formatter("%(asctime)s -  %(levelname)s -
%(message)s")
fh.setFormatter(formater)
logger.addHandler(fh)
#logger.info("* debut")


#message = main(url,conf_file,logger)
#message="hello seb"
if str(level).lower() == "info" :
print "logger info"
logger.info(str(message))
elif str(level).lower() =="error":
print "logger error"
logger.error(str(message))
elif str(level).lower()=="warning" :
print "logger warning"
logger.warning(str(message))
elif str(level).lower() =="critical":
print "logger critical"
logger.critical(str(message))
elif str(level).lower() == "exception":
print "logger exception"
logger.exception(str(message))
else :
logger.info("niveau inconnu "+str(message))

print "_",message
#print dir(logger)
return

*
Example of the log file with duplicated line.
**

2007-01-08 18:26:19,578 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version
simple\thread_RS232.py___init_rs232initrs232_openCOM1
2007-01-08 18:26:19,578 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version
simple\thread_RS232.py___runthread lance
2007-01-08 18:26:19,578 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version
simple\thread_RS232.py___runthread lance
2007-01-08 18:26:32,015 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:32,015 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:32,015 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:42,483 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:42,483 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:42,483 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:42,483 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:53,750 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:53,750 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:53,750 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:53,750 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:26:53,750 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:27:03,092 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:27:03,092 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:27:03,092 -  INFO - C:\Documents and
Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST
1 = OK
2007-01-08 18:27:03,092 -  INFO - C:\Documents and

Re: private variables

2007-01-09 Thread Bruno Desthuilliers
belinda thom a écrit :
> Hello,
> 
> In what version of python were private variables added?

Which private variables ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: private variables

2007-01-09 Thread belinda thom

On Jan 9, 2007, at 12:20 AM, Bruno Desthuilliers wrote:

> belinda thom a écrit :
>> Hello,
>>
>> In what version of python were private variables added?
>
> Which private variables ?

Haha.

The ones that are provided for convenience (via name mangling) that  
aren't really private if you wish to violate convention.

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


Re: Module to read svg

2007-01-09 Thread Tim Roberts
Robert Kern <[EMAIL PROTECTED]> wrote:

>Martin v. Löwis wrote:
>> [EMAIL PROTECTED] schrieb:
>>> Does anyone know if there's an actual free implementation of this?
>> 
>> For the dom module in it, xml.dom.minidom should work. Depending on
>> your processing needs, that might be sufficient.
>
>I don't think it quite fits what the OP is asking for. SVG defines some non-XML
>structure for some of its contents. For example:
>
>  

Why is that non-XML?
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Execute binary code

2007-01-09 Thread Hendrik van Rooyen

 "Chris Mellon" <[EMAIL PROTECTED]> wrote:


>  Repost. Is there any chance at all that ML could set the
> reply-to to the list instead of the sender?

+1 

- I regularly hit "reply all", delete the OP, and then I get :

"Message has a suspicious header"

- Hendrik


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


Re: recursive function

2007-01-09 Thread Hendrik van Rooyen

"cesco" <[EMAIL PROTECTED]> wrote:

> 
> Neil Cerutti wrote:
> > On 2007-01-08, cesco <[EMAIL PROTECTED]> wrote:
> > > Hi,
> > >
> > > I have a dictionary of lists of tuples like in the following example:
> > > dict = {1: [(3, 4), (5, 8)],
> > > 2: [(5, 4), (21, 3), (19, 2)],
> > > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]]
> > >
> > > In this case I have three lists inside the dict but this number
> > > is known only at runtime. I have to write a function that
> > > considers all the possible combinations of tuples belonging to
> > > the different lists and return a list of tuples of tuples for
> > > which the sum of the first element of the most inner tuple is
> > > equal to N.
> > >
> > > For example, assuming N = 24, in this case it should return:
> > > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19,
> > > 2), (0, 2))]
> >
> > What do you mean by "most inner tuple"?
> >
> > > A simple list comprehension would be enough if only I knew the
> > > number of keys/lists beforehand
> >
> > len(dict.keys()).
> 
> What I mean is that the number of keys/lists is not known until runtime
> and it changes randomly from time to time which means I would have to
> write every time a different list comprehension (or a different number
> of nested loops) to accomplish the same thing.
> In the example the result of the search should be a list containing
> three tuples each of which contains again three tuple (the most inner
> tuples). If you consider the first element of each tuple the sum is 24
> (like in 3+5+16, or 3+21+0 or 5+19+0).
> 
> Any other help will be appreciated


Is there any reliable structure in the data? 
- for instance in your example, the first list
has two tuples, the second one three, and the 
third one four - Is this a pattern?

- Hendrik


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


Re: Bitwise expression

2007-01-09 Thread Hendrik van Rooyen
"Gigs_" <[EMAIL PROTECTED]> wrote:


> Can someone explain me bitwise expression?
> few examples for every expression will be nice
>
> x << y Left shift
> x >> y Right shift
> x & y Bitwise AND
> x | y Bitwise OR
> x ^ y Bitwise XOR (exclusive OR)
> ~x Bitwise negation

The short, and possibly weird, but true, answer is:

If you have to ask this question, you should avoid
using these things. - Think of them as "Advanced Magic"

But this is unhelpful, so a slightly longer answer is:

Computer memory is like a long string of flip-flops that can
take on one of two states - "on" or "True" represented normally by
a digit 1, and "off" or "False" - a digit 0.   Hence the term binary.

Binary means "two valued", just like a Bicycle has two wheels.

These flip-flops are the smallest element of memory, and one
of them is called a "bit".  The plural is "bits".  "plural" means
"more than one of".

Eight bits are called a Byte.
Half a Byte is a Nibble - four bits (sometimes spelt Nybble by
people who are trying to be cute).
There is a concept called a "Word" of memory which is ill defined.
Sometimes it is one or two Bytes, sometimes three nibbles, sometimes
four, eight or sixteen bytes - depends on the hardware's bus width.

No, I am not going to explain what a bus is.

You can think of a python number as a word of eight bytes long,
and a python string as a number of bytes of arbitrary length.

I am also not going to explain big and little endian representation.
Yahoo for it.

Now the logic operators, as applied to nibbles:

1110  <<  0111   - shifted left, filled with zero from right
(multiply by two - seven to fourteen)
0010  >>  0100   - shifted right, filled with zero from left
(divide by two - four to two)
0100  =0101 & 1110   - true if both bits true, false otherwise
(used for masking, clearing bits)
1101  =0101  |  1100   - false if both bits false, true otherwise
(True if either bit true - used to set
bits)
1001  =0101  ^ 1100   - true if only one of the bits true, else false
(anything xored with itself is all zero)
(used to toggle bits, identity testing)
1001  ~0110   - inversion "not"  - not true is false, not false
is true

Also yahoo for "Boolean algebra" and "De Morgan" and "IEEE floating point
representation"

hth - Hendrik


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


Re: code formatter?

2007-01-09 Thread Hendrik van Rooyen
"siggi" <[EMAIL PROTECTED]> wrote:

> Is there a simple code formatter that first removes all indentations and
> then refomats correctly?

tabnanny ?

- Hendrik



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


Re: Why less emphasis on private data?

2007-01-09 Thread Hendrik van Rooyen
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote:


> On Mon, 08 Jan 2007 13:11:14 +0200, Hendrik van Rooyen wrote:
>
> > When you hear a programmer use the word "probability" -
> > then its time to fire him, as in programming even the lowest
> > probability is a certainty when you are doing millions of
> > things a second.
>
> That is total and utter nonsense and displays the most appalling
> misunderstanding of probability, not to mention a shocking lack of common
> sense.

Really?

Strong words.

If you don't understand you need merely ask, so let me elucidate:

If there is some small chance of something occurring at run time that can
cause code to fail - a "low probability" in all the accepted senses of the
word - and a programmer declaims - "There is such a low probability of
that occurring and its so difficult to cater for that I won't bother"
- then am I supposed to congratulate him on his wisdom and outstanding
common sense?

Hardly. - If anything can go wrong, it will. - to paraphrase Murphy's law.

To illustrate:
If there is one place in any piece of code that is critical and not protected,
even if its in a relatively rarely called routine, then because of the high
speed of operations, and the fact that time is essentially infinite, it WILL
fail, sooner or later, no matter how miniscule the apparent probability
of it occurring on any one iteration is.

How is this a misunderstanding of probability?  - probability applies to any one
trial, so in a series of trials, when the number of trials is large enough - in
the
order of the inverse of the probability, then ones expectation must be that the
rare occurrence should occur...

There is a very low probability that any one gas molecule will collide with any
other one in a container - and  "Surprise!  Surprise! " there is nevertheless
something like the mean free path...

That kind of covers the math, albeit in a non algebraic way, so as not to
confuse what Newton used to call "Little Smatterers"...

Now how does all this show a shocking lack of common sense?

- Hendrik


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


Re: Module to read svg

2007-01-09 Thread Robert Kern
Tim Roberts wrote:
> Robert Kern <[EMAIL PROTECTED]> wrote:
> 
>> Martin v. Löwis wrote:
>>> [EMAIL PROTECTED] schrieb:
 Does anyone know if there's an actual free implementation of this?
>>> For the dom module in it, xml.dom.minidom should work. Depending on
>>> your processing needs, that might be sufficient.
>> I don't think it quite fits what the OP is asking for. SVG defines some 
>> non-XML
>> structure for some of its contents. For example:
>>
>>  
> 
> Why is that non-XML?

Oh, it's valid XML, certainly. However, the data inside the attribute is not
just a bunch of arbitrary characters; it needs to be parsed with a non-XML
parser to get the actual list of points. And unfortunately, "for
space-efficiency" the grammar that describes that data is full of tricks and
shortcuts to save a few characters here and there (actually, I think point lists
are fine; path definitions, though are nuts). See the SVG spec for the full EBNF
grammar.

-- 
Robert Kern

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

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

Re: recursive function

2007-01-09 Thread cesco

Hendrik van Rooyen wrote:
> "cesco" <[EMAIL PROTECTED]> wrote:
>
> >
> > Neil Cerutti wrote:
> > > On 2007-01-08, cesco <[EMAIL PROTECTED]> wrote:
> > > > Hi,
> > > >
> > > > I have a dictionary of lists of tuples like in the following example:
> > > > dict = {1: [(3, 4), (5, 8)],
> > > > 2: [(5, 4), (21, 3), (19, 2)],
> > > > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]]
> > > >
> > > > In this case I have three lists inside the dict but this number
> > > > is known only at runtime. I have to write a function that
> > > > considers all the possible combinations of tuples belonging to
> > > > the different lists and return a list of tuples of tuples for
> > > > which the sum of the first element of the most inner tuple is
> > > > equal to N.
> > > >
> > > > For example, assuming N = 24, in this case it should return:
> > > > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19,
> > > > 2), (0, 2))]
> > >
> > > What do you mean by "most inner tuple"?
> > >
> > > > A simple list comprehension would be enough if only I knew the
> > > > number of keys/lists beforehand
> > >
> > > len(dict.keys()).
> >
> > What I mean is that the number of keys/lists is not known until runtime
> > and it changes randomly from time to time which means I would have to
> > write every time a different list comprehension (or a different number
> > of nested loops) to accomplish the same thing.
> > In the example the result of the search should be a list containing
> > three tuples each of which contains again three tuple (the most inner
> > tuples). If you consider the first element of each tuple the sum is 24
> > (like in 3+5+16, or 3+21+0 or 5+19+0).
> >
> > Any other help will be appreciated
>
>
> Is there any reliable structure in the data?
> - for instance in your example, the first list
> has two tuples, the second one three, and the
> third one four - Is this a pattern?

Hi Hendrik,

there is no such a pattern (I just happened to insert that ascending
number of lists). Anyway the answer from [EMAIL PROTECTED] was
quite satisfactory:-)

regards
Cesco

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


Re: Colons, indentation and reformatting.

2007-01-09 Thread Leif K-Brooks
Paddy wrote:
> Thinking about it a little, it seems that a colon followed by
> non-indented code that has just been pasted in could also be used by a
> Python-aware editor as a flag to re-indent the pasted code.


How would it reindent this code?

if foo:
print "Foo!"
if bar:
print "Bar!"

Like this?

if foo:
 print "Foo!"
if bar:
 print "Bar!"

Or like this?

if foo:
 print "Foo!"
 if bar:
 print "Bar!"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write temporary data to file?

2007-01-09 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Thomas Ploch
wrote:

> d = {
>   'url1': {
>   'emails': ['a', 'b', 'c',...],
>   'matches': ['d', 'e', 'f',...]
>   },
>   'url2': {...
> }
> 
> This dictionary will get _very_ big, so I want to write it somehow to a
> file after it has grown to a certain size.
> 
> How would I achieve that?

If you want easy access to single 'url' keys then `shelve` might be an
alternative to pickling the whole thing as one big object.

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


formattazione cifra con decimali

2007-01-09 Thread Nuke
Ho cercato un poco sulla documentazione di python senza trovare una
risposta soddisfacente al mio problema, quindi spero di trovare un
aiuto qui.
Ho creato un programmino che mi fa alcuni calcoli e riepiloghi
personali e vorrei visualizzare i totali numerici in euro con la
formattazione comprensiva dei separatori decimali.

Per esempio ho un totale scritto attualmente così:   50320,12  e
vorrei che si visualizzasse cosi: 50.320,12

esiste già una qualche funzione che mi formatta il numero (o la
stringa eventualmente) in questo modo?

Grazie a chi saprà darmi una risposta in merito.

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


Re: How to write temporary data to file?

2007-01-09 Thread Laszlo Nagy
Thomas Ploch írta:
> Hi folks,
>
> I have a data structure that looks like this:
>
> d = {
>   'url1': {
>   'emails': ['a', 'b', 'c',...],
>   'matches': ['d', 'e', 'f',...]
>   },
>   'url2': {...
> }
>
> This dictionary will get _very_ big, so I want to write it somehow to a
> file after it has grown to a certain size.
>
> How would I achieve that?
>   
How about dbm/gdbm? Since urls are strings, you can store this dict in a 
database instance and actually use it from your program as it were a dict?

   Laszlo

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


Re: formattazione cifra con decimali

2007-01-09 Thread Nuke

Nuke ha scritto:

> Ho cercato un poco sulla documentazione di python senza trovare una
> risposta soddisfacente al mio problema, quindi spero di trovare un
> aiuto qui.
> Ho creato un programmino che mi fa alcuni calcoli e riepiloghi
> personali e vorrei visualizzare i totali numerici in euro con la
> formattazione comprensiva dei separatori decimali.
>
> Per esempio ho un totale scritto attualmente così:   50320,12  e
> vorrei che si visualizzasse cosi: 50.320,12
>
> esiste già una qualche funzione che mi formatta il numero (o la
> stringa eventualmente) in questo modo?
>
> Grazie a chi saprà darmi una risposta in merito.


Sorry for the language, i think the group was in italian language...
sorry :(
I try to explain my problem in english:

I need to visualize a number (or a string of that number) using the
decimal separator.
i have this number visualized: 50320,12 and i need that the
visualization of this number is: 50.320,13.
There is a function that directly convert the number (or the string) ?

Thank in advance, and sorry again for the language used before.

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


Re: General Question About Python

2007-01-09 Thread Torabisu
I think the best I've heard is, "Programming in Python is like writing
poetry".

Its really a beautiful language, so simple, short, powerful and to the
point.

We use it in conjunction with Django to implement a web based device
management solution for our products.

We've also written a multi-threaded gateway / modem pool server that
assists us with data calls, sms'ing, and gprs based communication.

Its quite weird, we're looking for Python skills but are battling to
find at the moment...  Normally Python on its own will probably not
land you a job, but the last two companies I've worked for are doing
indepth Python development, so hopefully the tables are turning a bit.

Enteng wrote:
> To those who program in python, what programs do you do?
> Also what community projects are you involved in(OSS probably)?
> Will mastering the language land me a job?
>
> I'm thinking about learning the language as a hobby. Just curious :)

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


Re: line duplication using logging to file

2007-01-09 Thread Vinay Sajip
seb wrote:

> Hi, I am writing to a file some basic information using the logging
> module.  It is working but in the log file some line are printed
> several time. I had put some print debugging messages in the logging
> function (so they appear on the consile) and they are called once only.
> Obviously there is some understantding of the logging module that I am
> missing.
>
> My simple logging program (see below) is called by several processes.
> In this way I can collect the information from various sources (and not
> use the network enabled logging module)
>
> I am using python 2.4 on WinXP SP2.
>
> Do you have any idea ? Thanks in advance.
>

I copied your two scripts into "appel_main.py" and "appel_log.py" and
when I run, I get a single line in main_log.txt:

2007-01-09 10:01:42,766 -  INFO -C:\temp\appel_main.py___?something

On the console is printed:

time.asctime() Tue Jan 09 10:04:25 2007 received level= info message=
C:\temp\appel_main.py___?something
logger info
_ C:\temp\appel_main.py___?something

I didn't see any repetitions. Perhaps it's to do with multiple
processes in your environment?

If you call write_log several times you will add a handler several
times - this is not a normal pattern of use. You should separate setup
of Loggers/Handlers/Formatters from actually logging events via
debug(), info() etc.

Best regards,

Vinay Sajip

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


Re: General Question About Python

2007-01-09 Thread billie
Torabisu wrote:

> Its quite weird, we're looking for Python skills but are battling to
> find at the moment...  Normally Python on its own will probably not
> land you a job, but the last two companies I've worked for are doing
> indepth Python development, so hopefully the tables are turning a bit.

I can tell the same for Italy.
Where are you from?

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


A simple array in Python

2007-01-09 Thread bg_ie
Hi,

I have the following enum -

class State:
Fire = 0
Water = 1
Earth = 2

And I want a variable which holds a value for each of these states,
something like -

myState1[State.Fire] = 10
myState1[State.Earth] = 4

myState2[State.Fire] = 20
myState2[State.Earth] = 24

How do I do this?

Thanks Barry.

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


Re: A simple array in Python

2007-01-09 Thread Laszlo Nagy
[EMAIL PROTECTED] wrote:
> Hi,
>
> I have the following enum -
>
> class State:
>   Fire = 0
>   Water = 1
>   Earth = 2
>
> And I want a variable which holds a value for each of these states,
> something like -
>   

class State:
Fire = 0
Water = 1
Earth = 2


myState = {} # It is a dictionary, see 
http://docs.python.org/tut/node7.html#SECTION00750
myState[State.Fire] = 20
myState[State.Earth] = 24
print myState

{0: 20, 2: 24}


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


[ANN] html5lib 0.2

2007-01-09 Thread James Graham
DESCRIPTION

HTML parsing library based on the WHATWG Web Applications 1.0 "HTML5"
specification[1]. The parser is designed to work with all existing 
flavors of HTML and implements well-defined error recovery that has been 
specified though analysis of the behavior of modern desktop web browsers.

html5lib currently allows parsing to both a custom "simpletree" format 
and to an ElementTree, if available. Future releases will include 
support for at least one DOM implementation, and it is possible to 
implement custom treebuilders although the API should not yet be 
considered stable.

DOWNLOAD

http://html5lib.googlecode.com/files/html5lib-0.2.zip

BUGS

This is the first release of html5lib and it is considered alpha quality 
software. However, it ships with over 230 passing unit tests covering 
most of the specified behavior. Bugs should be reported on the issue 
tracker [2]

KNOWN ISSUES

Error handling does not yet conform to the specification; not all errors 
are reported and the error messages are not informative.

PROJECT PAGE

More information about the project including documentation and 
information on getting involved is available on the project page:
http://code.google.com/p/html5lib/

[1] http://whatwg.org/specs/web-apps/current-work/
[2] http://code.google.com/p/html5lib/issues/list
-- 
http://mail.python.org/mailman/listinfo/python-list


I compile the Pychm in windows,But meet a lot of errors......

2007-01-09 Thread boyeestudio

The Error is show as below:

D:\Downloads\pychm-0.8.4>python setup.py build
running build
running build_py
running build_ext
building 'chm._chmlib' extension
D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe /DLL
/nologo
/INCREMENTAL:NO /LIBPATH:D:\Python24\libs /LIBPATH:D:\Python24\PCBuild
chm.lib
/EXPORT:init_chmlib build\temp.win32-2.4\Release\chm/swig_chm.obj/OUT:build\lib
.win32-2.4\chm\_chmlib.pyd /IMPLIB:build\temp.win32-
2.4\Release\chm\_chmlib.lib
LIBC.lib(crt0init.obj) : error LNK2005: ___xc_z 已经在 MSVCRT.lib(cinitexe.obj)
中定义
LIBC.lib(crt0init.obj) : error LNK2005: ___xc_a 已经在 MSVCRT.lib(cinitexe.obj)
中定义
LIBC.lib(crt0init.obj) : error LNK2005: ___xi_z 已经在 MSVCRT.lib(cinitexe.obj)
中定义
LIBC.lib(crt0init.obj) : error LNK2005: ___xi_a 已经在 MSVCRT.lib(cinitexe.obj)
中定义
LIBC.lib(crt0init.obj) : warning LNK4006: ___xc_z 已在 MSVCRT.lib(cinitexe.obj
)
中定义;已忽略第二个定义
LIBC.lib(crt0init.obj) : warning LNK4006: ___xc_a 已在 MSVCRT.lib(cinitexe.obj
)
中定义;已忽略第二个定义
LIBC.lib(crt0init.obj) : warning LNK4006: ___xi_z 已在 MSVCRT.lib(cinitexe.obj
)
中定义;已忽略第二个定义
LIBC.lib(crt0init.obj) : warning LNK4006: ___xi_a 已在 MSVCRT.lib(cinitexe.obj
)
中定义;已忽略第二个定义
  正在创建库 build\temp.win32-2.4\Release\chm\_chmlib.lib 和对象 build\temp.win
32-2.4\Release\chm\_chmlib.exp
LINK : warning LNK4098: 默认库"MSVCRT"与其他库的使用冲突;使用 /NODEFAULTLIB:l
ibrary
LINK : warning LNK4098: 默认库"LIBC"与其他库的使用冲突;使用 /NODEFAULTLIB:lib
rary
build\lib.win32-2.4\chm\_chmlib.pyd : fatal error LNK1169: 找到一个或多个多重定
义的符号
error: command '"D:\Program Files\Microsoft Visual Studio .NET
2003\Vc7\bin\link
.exe"' failed with exit status 1169

How to fix this problem???
PS: if someone has compile it successfully in windows,Please send me a
copy!!!
Thanks a lot!!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: General Question About Python

2007-01-09 Thread [EMAIL PROTECTED]
Enteng wrote:
> To those who program in python, what programs do you do?

Some Unix TCP servers, some data-driven command line apps, and some web
stuff.

> Also what community projects are you involved in(OSS probably)?

None that are Python-based, aside from the occasional patch to support
new Python features in Vim or keep it working with newer versions.

> Will mastering the language land me a job?

Maybe.  My last 3 jobs have been for people with experience in C and
Python, or with substantial programming experience and a willingness to
learn C and Python.

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


Re: Why less emphasis on private data?

2007-01-09 Thread sturlamolden

[EMAIL PROTECTED] wrote:

> I let the user change the internal state of the engine, I have no
> assurances that my product (the engine) is doing its job...

How would you proceed to protect this inner states? In C++ private
members they can be accessed through a cast to void pointer. In Java it
can be done through introspection. In C# it can be done through
introspection or casting to void pointer in an 'unsafe' block. There is
no way you can protect inner states of an object, it is just an
illusion you may have.

Python have properties as well. Properties has nothing to do with
hiding attributes.

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


Re: Colons, indentation and reformatting. (2)

2007-01-09 Thread Paul McGuire
"Paddy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> If this is not
> the case then the user should be asked wether to re-indent the copy
> block to be equal to, or de-dented w.r.t. the paste line indent prior
> to pasting.
>

How would the user know this?  Every dedent is ambiguous, since there is no 
punctuation to indicate it.

-- Paul 


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


Re: Maths error

2007-01-09 Thread Nick Maclaren

|> Rory Campbell-Lange wrote:
|> 
|> > Is using the decimal module the best way around this? (I'm
|> > expecting the first sum to match the second). It seem
|> > anachronistic that decimal takes strings as input, though.

As Dan Bishop says, probably not.  The introduction to the decimal
module makes exaggerated claims of accuracy, amounting to propaganda.
It is numerically no better than binary, and has some advantages
and some disadvantages.

|> Also check the recent thread "bizarre floating point output".

No, don't.  That is about another matter entirely, and will merely
confuse you.  I have a course on computer arithmetic, and am just
now writing one on Python numerics, and confused people may contact
me - though I don't guarantee to help.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Colons, indentation and reformatting. (2)

2007-01-09 Thread Jorgen Grahn
On 8 Jan 2007 23:57:29 -0800, Paddy <[EMAIL PROTECTED]> wrote:
>
> OK, whilst colons are not sufficient to re-format a completely
> mis-indented file. I'm thinking that they are sufficient for
> reformatting most pasted code blocks when refactoring say?

Let's put it this way: if the formatter can assume the original code is
valid (i.e. has the intended indentation) then it can do all kinds of nifty
things to it.

Personally, I'm happy with what Emacs' python-mode offers: suggested indents
as I type, and a command to indent/de-dent the highlighted block one step.

/Jorgen

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


Re: Bitwise expression

2007-01-09 Thread Gigs_
Hendrik van Rooyen wrote:
> "Gigs_" <[EMAIL PROTECTED]> wrote:
> 
> 
>> Can someone explain me bitwise expression?
>> few examples for every expression will be nice
>>
>> x << y Left shift
>> x >> y Right shift
>> x & y Bitwise AND
>> x | y Bitwise OR
>> x ^ y Bitwise XOR (exclusive OR)
>> ~x Bitwise negation
> 
> The short, and possibly weird, but true, answer is:
> 
> If you have to ask this question, you should avoid
> using these things. - Think of them as "Advanced Magic"
> 
> But this is unhelpful, so a slightly longer answer is:
> 
> Computer memory is like a long string of flip-flops that can
> take on one of two states - "on" or "True" represented normally by
> a digit 1, and "off" or "False" - a digit 0.   Hence the term binary.
> 
> Binary means "two valued", just like a Bicycle has two wheels.
> 
> These flip-flops are the smallest element of memory, and one
> of them is called a "bit".  The plural is "bits".  "plural" means
> "more than one of".
> 
> Eight bits are called a Byte.
> Half a Byte is a Nibble - four bits (sometimes spelt Nybble by
> people who are trying to be cute).
> There is a concept called a "Word" of memory which is ill defined.
> Sometimes it is one or two Bytes, sometimes three nibbles, sometimes
> four, eight or sixteen bytes - depends on the hardware's bus width.
> 
> No, I am not going to explain what a bus is.
> 
> You can think of a python number as a word of eight bytes long,
> and a python string as a number of bytes of arbitrary length.
> 
> I am also not going to explain big and little endian representation.
> Yahoo for it.
> 
> Now the logic operators, as applied to nibbles:
> 
> 1110  <<  0111   - shifted left, filled with zero from right
> (multiply by two - seven to fourteen)
> 0010  >>  0100   - shifted right, filled with zero from left
> (divide by two - four to two)
> 0100  =0101 & 1110   - true if both bits true, false otherwise
> (used for masking, clearing bits)
> 1101  =0101  |  1100   - false if both bits false, true otherwise
> (True if either bit true - used to set
> bits)
> 1001  =0101  ^ 1100   - true if only one of the bits true, else false
> (anything xored with itself is all 
> zero)
> (used to toggle bits, identity 
> testing)
> 1001  ~0110   - inversion "not"  - not true is false, not 
> false
> is true
> 
> Also yahoo for "Boolean algebra" and "De Morgan" and "IEEE floating point
> representation"
> 
> hth - Hendrik
> 
> 

hey I know about bit, bits things, just didn't know how to use bitwise 
expression (didn't try it and didn't know what it means). so I just 
needed some examples.
Now is all clearer thanks to [EMAIL PROTECTED] and Hendrick van Rooyen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: line duplication using logging to file

2007-01-09 Thread Paul McGuire
"seb" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi, I am writing to a file some basic information using the logging
> module.  It is working but in the log file some line are printed
> several time. I had put some print debugging messages in the logging
> function (so they appear on the consile) and they are called once only.
> Obviously there is some understantding of the logging module that I am
> missing.
>
> My simple logging program (see below) is called by several processes.
> In this way I can collect the information from various sources (and not
> use the network enabled logging module)
>
> I am using python 2.4 on WinXP SP2.
>
> Do you have any idea ? Thanks in advance.
>
> Seb.
>

A quick tally of log messages by timestamp and comment gives this data:

('2007-01-08 18:26:19,578', '___init_rs232initrs232_openCOM1') : 1
('2007-01-08 18:26:19,578', '___runthread lance') : 2
('2007-01-08 18:26:32,015', '___test1TEST 1 = OK') : 3
('2007-01-08 18:26:42,483', '___test1TEST 1 = OK') : 4
('2007-01-08 18:26:53,750', '___test1TEST 1 = OK') : 5
('2007-01-08 18:27:03,092', '___test1TEST 1 = OK') : 6
('2007-01-08 18:27:13,671', '___test1TEST 1 = OK') : 7
('2007-01-08 18:27:14,796', '___run___fin dans le run car continue = 0') : 8
('2007-01-08 18:27:14,890', "___stopthread demande d'arret") : 9
('2007-01-09 08:51:26,562', '___init_rs232initrs232_openCOM1') : 1
('2007-01-09 08:51:26,733', '___runthread lance') : 2
('2007-01-09 08:51:39,453', '___test1TEST 1 = OK') : 3
('2007-01-09 08:51:48,280', '___test1TEST 1 = OK') : 4
('2007-01-09 08:51:58,750', '___test1TEST 1 = OK') : 5
('2007-01-09 08:52:09,812', '___test1TEST 1 = OK') : 6
('2007-01-09 08:52:19,078', '___test1TEST 1 = OK') : 7
('2007-01-09 08:52:22,078', '___run___fin dans le run car continue = 0') : 8
('2007-01-09 08:52:22,125', "___stopthread demande d'arret") : 8
('2007-01-09 08:52:22,125', "___stopthread demande d'arret ") : 1

Does this suggest anything to you?

-- Paul


(BTW, here is the pyparsing program I used to do this analysis)

from pyparsing import 
Word,nums,Combine,alphas,oneOf,Literal,SkipTo,restOfLine

# create pyparsing grammar definition for a log line
date = Word(nums,exact=4)+'-'+Word(nums,exact=2)+'-'+Word(nums,exact=2)
time = Word(nums,exact=2)+':'+Word(nums,exact=2)+':'+Word(nums,exact=2)+ \
','+Word(nums,exact=3)
timestamp = Combine(date + ' ' + time)
severity = oneOf( ["INFO","WARNING"] ) # not complete, but enough for this 
data
backslash = Literal("\\")
fileref = Combine(Word(alphas,exact=1)+":" + backslash + SkipTo(".py") + 
".py")
logline = ( timestamp.setResultsName("timestamp") + "-" +
severity.setResultsName("severity") + "-" +
fileref.setResultsName("fileref") +
restOfLine.setResultsName("comment") )

# create list of ParseResults, with addressable log line elements by results 
name
logEntries = [ logline.parseString(line) for line in logdata ]

# tally up log lines by timestamp and comment
tallyByTimestamp = {}
for entry in logEntries:
tallyKey = (entry.timestamp, entry.comment)
tallyByTimestamp[tallyKey] = tallyByTimestamp.get(tallyKey,0) + 1

for ts in sorted( tallyByTimestamp.items() ):
print "%s : %d" % ts


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


Re: Execute binary code

2007-01-09 Thread Jorgen Grahn
On 8 Jan 2007 12:29:36 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> [EMAIL PROTECTED] wrote:
>> Is it possible to execute a binary string stored within a python script
>> as executable code ?
>>
>> The script is run under Windows, and the binary code (a full executable
>> file) is stored in a variable in the script.
>>
>> I know I can use os.system() or os.popen() to run an external file, but
>> these functions take as argument a string evaluated as command-line.
>>
>> I also know I could save the binary code as a temporary file, execute
>> it and delete it afterwards, but this is not an alternative.
>>
>> Thanks.
>
> It's not impossible, that's basically what I did on a smaller scale in
> pyasm:

For what it's worth[1], under Unix it /is/ impossible. The only way to bring in
new code (short of dynamic libraries) is to call exec(2) or its variations,
and all need a file system object to load the code from.

/Jorgen
[1] Not much to the OP, I'd think.

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


Re: A simple array in Python

2007-01-09 Thread Paul McGuire
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi,
>
> I have the following enum -
>
> class State:
> Fire = 0
> Water = 1
> Earth = 2
>
> And I want a variable which holds a value for each of these states,
> something like -
>
> myState1[State.Fire] = 10
> myState1[State.Earth] = 4
>
> myState2[State.Fire] = 20
> myState2[State.Earth] = 24
>
> How do I do this?
>
> Thanks Barry.
>
How about (arrays are sooo last century):

class State(object):
def __init__(self,**kwargs):
self.__dict__.update(kwargs)

myState1 = State(Fire=10, Earth=4)
myState2 = State(Fire=20, Earth=24)

print myState1.Fire
print myState2.Earth

-- Paul


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


PyCFunction_New requires a pointer to a static PyMethodDef?

2007-01-09 Thread Ben Sizer
In following the example given at
, I find
that if I instead try to create PyMethodDef instances on the stack and
create methods that way, rather than providing pointers to a static
array of them, executing the method later raises an exception from
PyCFunction_Call.

Is it required that the PyMethodDef persists throughout the execution
of the Python program? If so, why isn't the information just copied
instead? I was hoping to just create a temporary PyMethodDef on the
stack purely for the duration of creating the method.

(Google doesn't find any instance of "PyCFunction_Call" on
docs.python.org. This might explain the Cookbook's comment that "one
hardly ever sees Python class objects built in C extensions"!)

-- 
Ben Sizer

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


Re: how to find the longst element list of lists

2007-01-09 Thread Peter Otten
Steven D'Aprano wrote:

> On Mon, 08 Jan 2007 13:55:40 +0100, Peter Otten wrote:
> 
>>> The precise results depend on the version of Python you're running, the
>>> amount of memory you have, other processes running, and the details of
>>> what's in the list you are trying to sort. But as my test shows, sort
>>> has some overhead that makes it a trivial amount slower for sufficiently
>>> small lists, but for everything else you're highly unlikely to beat it.
>> 
>> Try again with tN.timeit(1) and a second list that is random.shuffle()d
>> and copied to L before each measurement. list.sort() treats already
>> sorted lists specially.
> 
> Or, simply shuffle the list itself. Why copy it?

To feed the same data to every algorithm. This is an act of fairness, though
with negligable impact on the benchmark results, I suspect :-)
 
> In my tests, sorting still wins, and by roughly the same factor.
 
> One optimization that might shift the balance would be to remove the
> list copying in the non-sort code (list_of_lists[1:]). That's going to be
> very time consuming for big lists.
 
With the tweak that you suggest above the loop wins for 100 items on my
machine...

 N   loop  iloopmax   sort
 1   0.08   0.19   0.12   0.10
10   0.08   0.08   0.09   0.13
   100   0.95   0.37   0.28   0.88
  1000   0.000374   0.000341   0.001304   0.001204
  5000   0.001930   0.001719   0.001212   0.007062

if you can trust the timings for small values of N. 
The script to generate this table has become somewhat baroque :-)

import random
import timeit

timers = []
def bench(f):
t = timeit.Timer("getlongest(L)", "from __main__ import %s as
getlongest, L, items; L[:] = items" % f.__name__)
t.name = f.__name__.split("_")[-1]
t.function = f
timers.append(t)
return f

@bench
def getlongest_loop(lists):
longest_list = lists[0]
longest_length = len(longest_list)
for a_list in lists[1:]:
a_length = len(a_list)
if a_length > longest_length:
longest_list, longest_length = a_list, a_length
return longest_list

@bench
def getlongest_iloop(lists):
lists = iter(lists)
longest_list = lists.next()
longest_length = len(longest_list)
for a_list in lists:
a_length = len(a_list)
if a_length > longest_length:
longest_list, longest_length = a_list, a_length
return longest_list

@bench
def getlongest_max(lists):
return max(lists, key=len)

@bench
def getlongest_sort(lists):
lists.sort(key=len)
return lists[-1]

def make_list_of_lists(length):
lol = [[None]*i for i in xrange(length)]
random.shuffle(lol)
return lol

def measure(N):
print "%10d" % N,
for t in timers:
print "%10.6f" % t.timeit(1),
print

if __name__ == "__main__":
import sys
if "--test" in sys.argv:
L = make_list_of_lists(100)
expected = [None]*99
for t in timers:
assert t.function(L[:]) == expected
raise SystemExit
L = []
print "N".rjust(10),
print " ".join(t.name.rjust(10) for t in timers)
for N in [1, 10, 100, 1000, 5000]:
items = make_list_of_lists(N)
measure(N)

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


Re: Non-blocking pipes during subprocess handling

2007-01-09 Thread Nick Craig-Wood
Tom Plunket <[EMAIL PROTECTED]> wrote:
>  I'm using subprocess to launch, well, sub-processes, but now I'm
>  stumbling due to blocking I/O.
> 
>  Is there a way for me to know that there's data on a pipe, and possibly
>  how much data is there so I can get it?

You might want to check out this modification to subprocess which does
non-blocking pipes.

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

I personally think something like that should be built into subprocess

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


Re: General Question About Python

2007-01-09 Thread Michele Simionato

Enteng wrote:
> To those who program in python, what programs do you do?
> Also what community projects are you involved in(OSS probably)?
> Will mastering the language land me a job?

Well, I few years ago I decided to learn Python to get a job and it
worked. Of course,
you should think of something to get yourself visibile  (i.e.
contribute to some OSS
project, write articles, partecipate to conferences, etc.)

   Michele Simionato

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


Re: line duplication using logging to file

2007-01-09 Thread seb
Hi,

Thanks for the help.
Meanwhile I have written the logging function from scratch and it works
without the multiple lines.

This means that the multiple line copy is not due to the multiple
processes (or thread) trying to access the log file but to something
else.

Thanks.
Sebastien.

the new function :


import logging
import time

def write_log(level, message):
nom_logger="main_log_file.txt"
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename=nom_logger,
filemode='w')

if str(level).lower() == "info" :
logging.info(str(message))
elif str(level).lower() =="error":
logging.error(str(message))
elif str(level).lower()=="warning" :
logging.warning(str(message))
elif str(level).lower() =="critical":
logging.critical(str(message))
elif str(level).lower() == "exception":
logging.exception(str(message))
else :
logging.INFO(str(message))

return







Paul McGuire a écrit :
> "seb" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Hi, I am writing to a file some basic information using the logging
> > module.  It is working but in the log file some line are printed
> > several time. I had put some print debugging messages in the logging
> > function (so they appear on the consile) and they are called once only.
> > Obviously there is some understantding of the logging module that I am
> > missing.
> >
> > My simple logging program (see below) is called by several processes.
> > In this way I can collect the information from various sources (and not
> > use the network enabled logging module)
> >
> > I am using python 2.4 on WinXP SP2.
> >
> > Do you have any idea ? Thanks in advance.
> >
> > Seb.
> >
>
> A quick tally of log messages by timestamp and comment gives this data:
>
> ('2007-01-08 18:26:19,578', '___init_rs232initrs232_openCOM1') : 1
> ('2007-01-08 18:26:19,578', '___runthread lance') : 2
> ('2007-01-08 18:26:32,015', '___test1TEST 1 = OK') : 3
> ('2007-01-08 18:26:42,483', '___test1TEST 1 = OK') : 4
> ('2007-01-08 18:26:53,750', '___test1TEST 1 = OK') : 5
> ('2007-01-08 18:27:03,092', '___test1TEST 1 = OK') : 6
> ('2007-01-08 18:27:13,671', '___test1TEST 1 = OK') : 7
> ('2007-01-08 18:27:14,796', '___run___fin dans le run car continue = 0') : 8
> ('2007-01-08 18:27:14,890', "___stopthread demande d'arret") : 9
> ('2007-01-09 08:51:26,562', '___init_rs232initrs232_openCOM1') : 1
> ('2007-01-09 08:51:26,733', '___runthread lance') : 2
> ('2007-01-09 08:51:39,453', '___test1TEST 1 = OK') : 3
> ('2007-01-09 08:51:48,280', '___test1TEST 1 = OK') : 4
> ('2007-01-09 08:51:58,750', '___test1TEST 1 = OK') : 5
> ('2007-01-09 08:52:09,812', '___test1TEST 1 = OK') : 6
> ('2007-01-09 08:52:19,078', '___test1TEST 1 = OK') : 7
> ('2007-01-09 08:52:22,078', '___run___fin dans le run car continue = 0') : 8
> ('2007-01-09 08:52:22,125', "___stopthread demande d'arret") : 8
> ('2007-01-09 08:52:22,125', "___stopthread demande d'arret ") : 1
>
> Does this suggest anything to you?
>
> -- Paul
>
>
> (BTW, here is the pyparsing program I used to do this analysis)
>
> from pyparsing import
> Word,nums,Combine,alphas,oneOf,Literal,SkipTo,restOfLine
>
> # create pyparsing grammar definition for a log line
> date = Word(nums,exact=4)+'-'+Word(nums,exact=2)+'-'+Word(nums,exact=2)
> time = Word(nums,exact=2)+':'+Word(nums,exact=2)+':'+Word(nums,exact=2)+ \
> ','+Word(nums,exact=3)
> timestamp = Combine(date + ' ' + time)
> severity = oneOf( ["INFO","WARNING"] ) # not complete, but enough for this
> data
> backslash = Literal("\\")
> fileref = Combine(Word(alphas,exact=1)+":" + backslash + SkipTo(".py") +
> ".py")
> logline = ( timestamp.setResultsName("timestamp") + "-" +
> severity.setResultsName("severity") + "-" +
> fileref.setResultsName("fileref") +
> restOfLine.setResultsName("comment") )
>
> # create list of ParseResults, with addressable log line elements by results
> name
> logEntries = [ logline.parseString(line) for line in logdata ]
>
> # tally up log lines by timestamp and comment
> tallyByTimestamp = {}
> for entry in logEntries:
> tallyKey = (entry.timestamp, entry.comment)
> tallyByTimestamp[tallyKey] = tallyByTimestamp.get(tallyKey,0) + 1
>
> for ts in sorted( tallyByTimestamp.items() ):
> print "%s : %d" % ts

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

Re: Execute binary code

2007-01-09 Thread [EMAIL PROTECTED]

Jorgen Grahn wrote:

> On 8 Jan 2007 12:29:36 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> For what it's worth[1], under Unix it /is/ impossible. The only way to bring 
> in
> new code (short of dynamic libraries) is to call exec(2) or its variations,
> and all need a file system object to load the code from.

That's totally untrue, how do you think a JIT compiler works? For
example you can generate x86 assembler on the fly and call it using
pyASM see http://mysite.verizon.net/olsongt/usersGuide.html

Cheers

Rich.

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


Using with CSV library in Python 2.2!!!

2007-01-09 Thread mohan
Hi Guys,

I'm back one more basic question, this time on using CSV (Comma
Seperated Value) library with Python 2.2. At my workplace I have Python
2.2 installed and am using PythonWin 2.2.1 IDE from Mark Hammond.

I want to use the CSV library module for reading data from the .csv
files and when I try to import the module, I get the error "CSV module
is not found". The reason, CSV module is missing from the Python root
directories. Now my first question is,

1. Does Python 2.2 come with CSV library module or not? If yes, have I
lost it somewhere??

2. If Python 2.2 does not come with CSV module, is it possible to add
the CSV module to the Python root and start working??

3. If yes, where do I get this module from??

Would be glad to have an answer for these questions. Thanks in advance.

Cheers,
Mohan.

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


Re: Colons, indentation and reformatting.

2007-01-09 Thread Neil Cerutti
On 2007-01-09, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
> Paddy wrote:
>> Thinking about it a little, it seems that a colon followed by
>> non-indented code that has just been pasted in could also be
>> used by a Python-aware editor as a flag to re-indent the
>> pasted code.
>
> How would it reindent this code?
>
> if foo:
> print "Foo!"
> if bar:
> print "Bar!"
>
> Like this?
>
> if foo:
>  print "Foo!"
> if bar:
>  print "Bar!"
>
> Or like this?
>
> if foo:
>  print "Foo!"
>  if bar:
>  print "Bar!"

That's the key issue. The colon gives the editor an easy clue
where a block starts, but the there's no simply way to determine
where the block is supposed to end.

-- 
Neil Cerutti
Remember in prayer the many who are sick of our church and community. --Church
Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: formattazione cifra con decimali

2007-01-09 Thread Jerry Hill
On 9 Jan 2007 01:43:41 -0800, Nuke <[EMAIL PROTECTED]> wrote:
> I need to visualize a number (or a string of that number) using the
> decimal separator.
> i have this number visualized: 50320,12 and i need that the
> visualization of this number is: 50.320,13.
> There is a function that directly convert the number (or the string) ?

I'm not very familiar with locale-aware programming in Python, but
this may get you started:

>>> import locale

>>> locale.setlocale(locale.LC_ALL, 'it')
'Italian_Italy.1252'

>>> locale.format("%0.2f", 50320.12, grouping=True)
'50.320,12'

See http://docs.python.org/lib/module-locale.html for documentation on
the locale module.

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


pyExcelerator big integer values

2007-01-09 Thread Gacha
I use pyExcelerator to import some data from xml file. One column
contains integer values like:
4750456000708
4750456000715
4750456000333
...
But when I do import the pyExcelerator converts them to something like
this:
4.7504560002e+12
4.7504560007e+12
4.7504560007e+12
4.7504560003e+12

How I understand it's because the integer value is too big. If the type
of the items was string, then all would be fine, but I can't control
the file content.

The question is, how can I import the integers in normal format.

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


Re: Maths error

2007-01-09 Thread Carsten Haese
On Tue, 2007-01-09 at 11:38 +, Nick Maclaren wrote:
> |> Rory Campbell-Lange wrote:
> |> 
> |> > Is using the decimal module the best way around this? (I'm
> |> > expecting the first sum to match the second). It seem
> |> > anachronistic that decimal takes strings as input, though.
> 
> As Dan Bishop says, probably not.  The introduction to the decimal
> module makes exaggerated claims of accuracy, amounting to propaganda.
> It is numerically no better than binary, and has some advantages
> and some disadvantages.

Please elaborate. Which exaggerated claims are made, and how is decimal
no better than binary?

-Carsten


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


mxODBC problems

2007-01-09 Thread Sean Davis
I have just installed mxODBC on my x86_64 suse linux machine, where I
use unixODBC for connection.  Running queries from isql or DataManager
works fine for the DSN that I am using.  However, under mxODBC, I can
get a connection object and a cursor object, but all attempts to
execute even the simplest selects result in empty resultsets.  Any
ideas on what might be wrong?

>>> from mx.ODBC.unixODBC import *
>>> con = connect('Postgresql',user='username',password='passwd')
>>> cur = con.cursor()
>>> cur.execute('SELECT * FROM g_rif')
>>> rs = cur.execute('SELECT * FROM g_rif')
>>> rs
>>> cur.execute('SELECT * FROM g_rif').fetchall()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'NoneType' object has no attribute 'fetchall'

Thanks,
Sean

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


Re: re.sub and re.MULTILINE

2007-01-09 Thread nyenyec

Paddy wrote:
> Check the arguments to re.sub.
>
> >>> re.sub('(?m)^foo', 'bar', '\nfoo', count=0)
> '\nbar'
> 
> - Paddy.

Duh! :) I appreciate it, thanks.

-- nyenyec

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


Re: Using with CSV library in Python 2.2!!!

2007-01-09 Thread skip

mohan> 1. Does Python 2.2 come with CSV library module or not? If yes,
mohan>have I lost it somewhere??

As the docs for the csv module indicate, it was new in 2.3.

mohan> 2. If Python 2.2 does not come with CSV module, is it possible to
mohan>add the csv module to the Python root and start working??

You might find that it will work with 2.2, though you might have to make
some source code changes to _csv.c to get it to compile.

mohan> 3. If yes, where do I get this module from??

You can get both csv.py and _csv.c via ViewCVS:


http://svn.python.org/view/*checkout*/python/tags/r236/Modules/_csv.c?content-type=text%2Fplain&rev=52574

http://svn.python.org/view/*checkout*/python/tags/r236/Lib/csv.py?content-type=text%2Fplain&rev=52574

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


Re: Using with CSV library in Python 2.2!!!

2007-01-09 Thread mohan

[EMAIL PROTECTED] wrote:
> mohan> 1. Does Python 2.2 come with CSV library module or not? If yes,
> mohan>have I lost it somewhere??
>
> As the docs for the csv module indicate, it was new in 2.3.
>
> mohan> 2. If Python 2.2 does not come with CSV module, is it possible to
> mohan>add the csv module to the Python root and start working??
>
> You might find that it will work with 2.2, though you might have to make
> some source code changes to _csv.c to get it to compile.
>
> mohan> 3. If yes, where do I get this module from??
>
> You can get both csv.py and _csv.c via ViewCVS:
>
> 
> http://svn.python.org/view/*checkout*/python/tags/r236/Modules/_csv.c?content-type=text%2Fplain&rev=52574
> 
> http://svn.python.org/view/*checkout*/python/tags/r236/Lib/csv.py?content-type=text%2Fplain&rev=52574
>
> Skip

Hi Skip,

Thanks man. What kind of source code changes should I do to "_csv.c"
file , have you any idea on that too??

Otherwise upgrading to Python 2.4 would be the easiest choice.

Thanks again.

cheers,
Mohan.

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


Survey respondents needed for masters thesis

2007-01-09 Thread luffmusse
We are two students from the Royal Institute of Technology in
Stockholm, Sweden (http://www.kth.se/eng/). We are currently doing our
masters thesis in Applied Information Technology where we specialize in
security. As a part of this thesis we will do a survey where we compare
general information about software organizations and software projects
with certain aspects and activities specific for the creation of secure
software.

We would really appreciate if you participated in this survey to help
us with this masters thesis. Please feel free to spread information
about this survey to your colleagues or any friends you have in the
software industry. All answers we can get are helpful to us!

The survey is available at
http://support.objectplanet.com/opinio/s?s=12074

Gustav Ringbom (gringbom [at] kth.se)
Christoffer Bergman (chr83 [at] kth.se)

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


Determine an object is a subclass of another

2007-01-09 Thread abcd
How can tell if an object is a subclass of something else?

Imagine...

class Thing:
pass

class Animal:
pass

class Dog:
pass

d = Dog()

I want to find out that 'd' is a Dog, Animal and Thing.  Such as...

d is a Dog
d is a Animal
d is a Thing

Thanks

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


Re: Using with CSV library in Python 2.2!!!

2007-01-09 Thread skip

mohan> Thanks man. What kind of source code changes should I do to
mohan> "_csv.c" file , have you any idea on that too??

I've no particular ideas.  There are sometimes small C API changes between
feature releases though.  If you read through the What's New document for
version 2.3 (google for it) you;ll probably have a pretty good idea of any
such changes.

mohan> Otherwise upgrading to Python 2.4 would be the easiest choice.

Oh, you didn't mention that.  By all means, upgrade to 2.4 or 2.5 instead of
trying to backport the csv module to an outdated Python version.

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


Re: Determine an object is a subclass of another

2007-01-09 Thread Neil Cerutti
On 2007-01-09, abcd <[EMAIL PROTECTED]> wrote:
> How can tell if an object is a subclass of something else?
>
> Imagine...
>
> class Thing:
> pass
>
> class Animal:
> pass
>
> class Dog:
> pass
>
> d = Dog()
>
> I want to find out that 'd' is a Dog, Animal and Thing.  Such
> as...
>
> d is a Dog
> d is a Animal
> d is a Thing

isinstance(d, Dog)
isinstance(d, Animal)
isinstance(d, Thing)

Note that in your example d is not an instance of anything but
Dog. If you want a hierarchy, you must say so. Python doesn't
even try to make educated guesses.

class Thing:
  pass

class Animal(Thing):
  pass

class Dog(Animal):
  pass

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


Re: Determine an object is a subclass of another

2007-01-09 Thread Matimus
First you need to subclass the classes so that Dog actually is a
subclass of Animal which is a subclass of thing...

class Thing:
  pass

class Animal(Thing):
  pass

class Dog(Animal):
  pass

class Weapon(Thing):
  pass

class Gun(Weapon):
  pass

Then you can use 'isinstance'

>>>d = Dog()
>>>isinstance(d,Thing)
True
>>>isinstance(d,Animal)
True
>>>isinstance(d,Weapon)
False
>>>isinstance(d,Gun)
False

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


Re: How to write temporary data to file?

2007-01-09 Thread Thomas Ploch
Laszlo Nagy schrieb:
> Thomas Ploch írta:
>> Hi folks,
>>
>> I have a data structure that looks like this:
>>
>> d = {
>> 'url1': {
>> 'emails': ['a', 'b', 'c',...],
>> 'matches': ['d', 'e', 'f',...]
>> },
>> 'url2': {...
>> }
>>
>> This dictionary will get _very_ big, so I want to write it somehow to a
>> file after it has grown to a certain size.
>>
>> How would I achieve that?
>>   
> How about dbm/gdbm? Since urls are strings, you can store this dict in a
> database instance and actually use it from your program as it were a dict?
> 
>   Laszlo
> 

Well, but how do I save the nested dict values? I don't want to eval
them, so this is no option for me.

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


Internet Survey

2007-01-09 Thread octabox
Hello all,

I represent Octabox, an Internet Start-up developing a wide-scale
platform for Internet services.  We are very interested to know your
thoughts on Internet productivity and how it might be improved, and to
that end we have set up a short survey at our website -
http://www.octabox.com/productivity_poll.php
We would very much appreciate if you would take a couple of minutes to
fill it up and influence our direction and empahsis.
 
Thanks in advance,
Octabox Development Team

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


Internet Survey

2007-01-09 Thread octabox
Hello all,

I represent Octabox, an Internet Start-up developing a wide-scale
platform for Internet services.  We are very interested to know your
thoughts on Internet productivity and how it might be improved, and to
that end we have set up a short survey at our website -
http://www.octabox.com/productivity_poll.php
We would very much appreciate if you would take a couple of minutes to
fill it up and influence our direction and empahsis.
 
Thanks in advance,
Octabox Development Team

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


Re: How to write temporary data to file?

2007-01-09 Thread Thomas Ploch
Thomas Ploch schrieb:
> Laszlo Nagy schrieb:
>> Thomas Ploch írta:
>>> Hi folks,
>>>
>>> I have a data structure that looks like this:
>>>
>>> d = {
>>> 'url1': {
>>> 'emails': ['a', 'b', 'c',...],
>>> 'matches': ['d', 'e', 'f',...]
>>> },
>>> 'url2': {...
>>> }
>>>
>>> This dictionary will get _very_ big, so I want to write it somehow to a
>>> file after it has grown to a certain size.
>>>
>>> How would I achieve that?
>>>   
>> How about dbm/gdbm? Since urls are strings, you can store this dict in a
>> database instance and actually use it from your program as it were a dict?
>>
>>   Laszlo
>>
> 
> Well, but how do I save the nested dict values? I don't want to eval
> them, so this is no option for me.
> 
> Thomas

I just saw shelve is the module to go for.

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


Re: Determine an object is a subclass of another

2007-01-09 Thread abcd
yea i meant to have animal extend thing and dog extend animalmy
mistake.

anyways, is there a way to check without having an instance of the
class?

such as,

isinstance(Dog, (Animal, Thing)) ??

thanks

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


Re: Execute binary code

2007-01-09 Thread sturlamolden

Jorgen Grahn wrote:

> For what it's worth[1], under Unix it /is/ impossible. The only way to bring 
> in
> new code (short of dynamic libraries) is to call exec(2) or its variations,
> and all need a file system object to load the code from.

The x86 processor cannot tell the difference between code segments and
data segments. If the executable code is stored in string, all you need
is a pointer to the string holding the code. You can cast the string
address to a function pointer (possibly through a void* if the compiler
complains), then dereference (call) the function pointer.

Trojans, viruses and JIT compilers do this all the time. Here is an
(untested) example:

static PyObject*
call_code_in_string(PyObject *self, PyObject *args)
{
char *s;
int size;
int arg1, arg2, arg3;
typedef int (*func_t)(int,int,int);
func_t pfunc;
if(!PyArg_ParseTuple(args, "s#(iii)", &s, &size, &arg1, &arg2,
&arg3)) return NULL;
pfunc = (func_t)((void *)s); /* if it fails, try
memcpy(&pfunc,&s,sizeof(void*)) instead */
return PyInt_FromLong((long)pfunc(arg1, arg2, arg3));
}

Another possibility would be to just return the string address, and
then make the call possibly using ctypes.

static PyObject*
get_string_addr(PyObject *self, PyObject *args)
{
char *s;
int size;
if(!PyArg_ParseTuple(args, "s#", &s, &size)) return NULL;
return PyInt_FromLong((long)((void*)s));
}

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


Re: Determine an object is a subclass of another

2007-01-09 Thread Bruno Desthuilliers
abcd a écrit :
> yea i meant to have animal extend thing and dog extend animalmy
> mistake.
> 
> anyways, is there a way to check without having an instance of the
> class?
> 
> such as,
> 
> isinstance(Dog, (Animal, Thing)) ??
> 
> 
issubclass(Dog, Animal)

Note that such tests should only be used in a very few specific cases - 
certainly not to try&implement some kind of static typing... In Python, 
inheritance is mostly about implementation.

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


Re: Internet Survey

2007-01-09 Thread zoara
On 9 Jan 2007 06:58:15 -0800, [EMAIL PROTECTED] wrote:

> Hello all,
> 
> I represent Octabox, an Internet Start-up developing a wide-scale
> platform for Internet services.  We are very interested to know your
> thoughts on Internet productivity and how it might be improved, and to
> that end we have set up a short survey at our website -
> http://www.octabox.com/productivity_poll.php
> We would very much appreciate if you would take a couple of minutes to
> fill it up and influence our direction and empahsis.

Well, that was too tempting to pass up. Amusing answers related to dirty
bastard time-wasting spammers duly entered and submitted.

-z-



-- 
Our team is conducting a benchmarking effort to gather an outside-in
view on development performance metrics and best practice approaches 
to issues of process and organization from companies involved in a 
variety of software development (and systems integration).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why less emphasis on private data?

2007-01-09 Thread Steven D'Aprano
On Tue, 09 Jan 2007 10:27:56 +0200, Hendrik van Rooyen wrote:

> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote:
> 
> 
>> On Mon, 08 Jan 2007 13:11:14 +0200, Hendrik van Rooyen wrote:
>>
>> > When you hear a programmer use the word "probability" -
>> > then its time to fire him, as in programming even the lowest
>> > probability is a certainty when you are doing millions of
>> > things a second.
>>
>> That is total and utter nonsense and displays the most appalling
>> misunderstanding of probability, not to mention a shocking lack of common
>> sense.
> 
> Really?
> 
> Strong words.
> 
> If you don't understand you need merely ask, so let me elucidate:
> 
> If there is some small chance of something occurring at run time that can
> cause code to fail - a "low probability" in all the accepted senses of the
> word - and a programmer declaims - "There is such a low probability of
> that occurring and its so difficult to cater for that I won't bother"
> - then am I supposed to congratulate him on his wisdom and outstanding
> common sense?
> 
> Hardly. - If anything can go wrong, it will. - to paraphrase Murphy's law.
> 
> To illustrate:
> If there is one place in any piece of code that is critical and not protected,
> even if its in a relatively rarely called routine, then because of the high
> speed of operations, and the fact that time is essentially infinite, 

Time is essentially infinite? Do you really expect your code will still be
in use fifty years from now, let alone a billion years?

I know flowcharts have fallen out of favour in IT, and rightly so -- they
don't model modern programming techniques very well, simply because modern
programming techniques would lead to a chart far too big to be practical.
But for the sake of the exercise, imagine a simplified flowchart of some
program, one with a mere five components, such that one could take any of
the following paths through the program:

START -> A -> B -> C -> D -> E
START -> A -> C -> B -> D -> E
START -> A -> C -> D -> B -> E
...
START -> E -> D -> C -> B -> A

There are 5! (five factorial) = 120 possible paths through the program.

Now imagine one where there are just fifty components, still quite a
small program, giving 50! = 3e64 possible paths. Now suppose that there is
a bug that results from following just one of those paths. That would
match your description of "lowest probability" -- any lower and it would
be zero.

If all of the paths are equally likely to be taken, and the program takes
a billion different paths each millisecond, on average it would take about
1.5e55 milliseconds to hit the bug -- or about 5e44 YEARS of continual
usage. If every person on Earth did nothing but run this program 24/7, it
would still take on average almost sixty million billion billion billion
years to discover the bug.

But of course in reality some paths are more likely than others. If the
bug happens to exist in a path that is executed often, or if it exists
in many paths, then the bug will be found quickly. On the other hand, if
the bug is in a path that is rarely executed, your buggy program may be
more reliable than the hardware you run it on. (Cynics may say that isn't
hard.)

You're project manager for the development team. Your lead developer tells
you that he knows this bug exists (never mind how, he's very clever) and
that the probability of reaching that bug in use is about 3e-64. 

If it were easy to fix, the developer wouldn't even have mentioned it.
This is a really hard bug to fix, it's going to require some major
changes to the program, maybe even a complete re-think of the program.
Removing this bug could even introduce dozens, hundreds of new bugs.

So okay Mister Project Manager. What do you do? Do you sack the developer,
like you said? How many dozens or hundreds of man-hours are you prepared
to put into this? If the money is coming out of your pocket, how much are
you willing to spend to fix this bug?


[snip]

> How is this a misunderstanding of probability?  - probability applies to
> any one trial, so in a series of trials, when the number of trials is
> large enough - in the
> order of the inverse of the probability, then ones expectation must be
> that the rare occurrence should occur...

"Even the lowest probability is a certainty" is mathematically nonsense:
it just isn't true -- no matter how many iterations, the probability is
always a little less than one. And you paper over a hole in your argument
with "when the number of trials is large enough" -- if the probability is
small enough, "large enough" could be unimaginably huge indeed.

Or, to put it another way, while anything with a non-zero probability
_might_ happen (you might drop a can of soft drink on your computer,
shorting it out and _just by chance_ causing it to fire off a perfectly
formatted email containing a poem about penguins) we are justified in
writing off small enough probabilities as negligible. It's not that they
can't happen, but the chances of doing so are so

Re: Execute binary code

2007-01-09 Thread Chris Mellon
On 9 Jan 2007 07:04:11 -0800, sturlamolden <[EMAIL PROTECTED]> wrote:
>
> Jorgen Grahn wrote:
>
> > For what it's worth[1], under Unix it /is/ impossible. The only way to 
> > bring in
> > new code (short of dynamic libraries) is to call exec(2) or its variations,
> > and all need a file system object to load the code from.
>
> The x86 processor cannot tell the difference between code segments and
> data segments. If the executable code is stored in string, all you need
> is a pointer to the string holding the code. You can cast the string
> address to a function pointer (possibly through a void* if the compiler
> complains), then dereference (call) the function pointer.
>
> Trojans, viruses and JIT compilers do this all the time. Here is an
> (untested) example:
>
> static PyObject*
> call_code_in_string(PyObject *self, PyObject *args)
> {
> char *s;
> int size;
> int arg1, arg2, arg3;
> typedef int (*func_t)(int,int,int);
> func_t pfunc;
> if(!PyArg_ParseTuple(args, "s#(iii)", &s, &size, &arg1, &arg2,
> &arg3)) return NULL;
> pfunc = (func_t)((void *)s); /* if it fails, try
> memcpy(&pfunc,&s,sizeof(void*)) instead */
> return PyInt_FromLong((long)pfunc(arg1, arg2, arg3));
> }
>
> Another possibility would be to just return the string address, and
> then make the call possibly using ctypes.
>
> static PyObject*
> get_string_addr(PyObject *self, PyObject *args)
> {
> char *s;
> int size;
> if(!PyArg_ParseTuple(args, "s#", &s, &size)) return NULL;
> return PyInt_FromLong((long)((void*)s));
> }
>

This works fine if the binary data is "pure" asm, but the impresssion
the OP gave is that it's a compiled binary, which you can't just "jump
into" this way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code formatter?

2007-01-09 Thread siggi
>tabnanny?
not quite!

"Hendrik van Rooyen" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> "siggi" <[EMAIL PROTECTED]> wrote:
>
>> Is there a simple code formatter that first removes all indentations and
>> then refomats correctly?
>
> tabnanny ?
>
> - Hendrik
>
>
> 


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


how to clean sys.path

2007-01-09 Thread siggi
Hi all,

when I do >>>sys.path in IDLE (winXP), i get a horrendously long list of 
paths, paths I may have used during a lot of trials and errors. How can I 
clean up sys.path? I mean, trim it of unnecessary paths?

So far, I know only the command >>>sys.path.append(r'c:etc...'), but how 
to delete or insert at the beginning of the list, I know not.

Thanks,

siggi


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


Re: Determine an object is a subclass of another

2007-01-09 Thread Felipe Almeida Lessa
On 9 Jan 2007 07:01:31 -0800, abcd <[EMAIL PROTECTED]> wrote:
> anyways, is there a way to check without having an instance of the
> class?

In [1]: class A:
   ...: pass
   ...:

In [2]: class B(A):
   ...: pass
   ...:

In [3]: issubclass(B, A)
Out[3]: True

In [4]: isinstance(B(), B)
Out[4]: True

In [5]: isinstance(B(), A)
Out[5]: True

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


Re: Xah's Edu Corner: Introduction to 3D Graphics Programing

2007-01-09 Thread hg
Xah Lee wrote:

> I don't know OpenGL, but i think it is a low-level crap, and have done
> the industry huge irreparable damage the same way unix has.

So you _are_ psychic ! is the end of the world be in 2007 ?




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


Re: Using with CSV library in Python 2.2!!!

2007-01-09 Thread Larry Bates
mohan wrote:
> Hi Guys,
> 
> I'm back one more basic question, this time on using CSV (Comma
> Seperated Value) library with Python 2.2. At my workplace I have Python
> 2.2 installed and am using PythonWin 2.2.1 IDE from Mark Hammond.
> 
> I want to use the CSV library module for reading data from the .csv
> files and when I try to import the module, I get the error "CSV module
> is not found". The reason, CSV module is missing from the Python root
> directories. Now my first question is,
> 
> 1. Does Python 2.2 come with CSV library module or not? If yes, have I
> lost it somewhere??
> 
> 2. If Python 2.2 does not come with CSV module, is it possible to add
> the CSV module to the Python root and start working??
> 
> 3. If yes, where do I get this module from??
> 
> Would be glad to have an answer for these questions. Thanks in advance.
> 
> Cheers,
> Mohan.
> 
Object Craft wrote the csv library that predated the one released in
Python 2.3.  You can still get it for earlier Python versions here:

http://www.object-craft.com.au/projects/csv/download.html

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


Re: mxODBC problems

2007-01-09 Thread Larry Bates
Sean Davis wrote:
> I have just installed mxODBC on my x86_64 suse linux machine, where I
> use unixODBC for connection.  Running queries from isql or DataManager
> works fine for the DSN that I am using.  However, under mxODBC, I can
> get a connection object and a cursor object, but all attempts to
> execute even the simplest selects result in empty resultsets.  Any
> ideas on what might be wrong?
> 
 from mx.ODBC.unixODBC import *
 con = connect('Postgresql',user='username',password='passwd')
 cur = con.cursor()
 cur.execute('SELECT * FROM g_rif')
 rs = cur.execute('SELECT * FROM g_rif')
 rs
 cur.execute('SELECT * FROM g_rif').fetchall()
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'NoneType' object has no attribute 'fetchall'
> 
> Thanks,
> Sean
> 
I think you will find that there result returned by the
cur.execute is None upon success.  You probably meant:

cur.execute('SELECT * FROM g_rif')
table=cur.fetchall()

Then process table.

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


Re: Internet Survey

2007-01-09 Thread Lawrence Statton XE2/N1GAK
zoara <[EMAIL PROTECTED]> writes:
Link NOT removed to encourage more abuse ... 

> >  http://www.octabox.com/productivity_poll.php

I somehow missed this the first time.

Thanks for the pointer -- I gave them some nice PDP-10 related
responses.   I truly hope to have my TOPS-20 productivity improved
soon, thanks to these people.

-- 
Lawrence Statton - [EMAIL PROTECTED] s/aba/c/g
Computer  software  consists of  only  two  components: ones  and
zeros, in roughly equal proportions.   All that is required is to
sort them into the correct order.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Internet Survey

2007-01-09 Thread Steve O'Hara-Smith
On Tue, 9 Jan 2007 15:25:43 +
zoara <[EMAIL PROTECTED]> wrote:

> On 9 Jan 2007 06:58:15 -0800, [EMAIL PROTECTED] wrote:
> 
> > Hello all,
> > 
> > I represent Octabox, an Internet Start-up developing a wide-scale



> Well, that was too tempting to pass up. Amusing answers related to dirty
> bastard time-wasting spammers duly entered and submitted.

Yes it was - and may they get many more similar responses :)

-- 
C:>WIN  |   Directable Mirror Arrays
The computer obeys and wins.| A better way to focus the sun
You lose and Bill collects. |licences available see
|http://www.sohara.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Maths error

2007-01-09 Thread Tim Peters
[Rory Campbell-Lange]
>>> Is using the decimal module the best way around this? (I'm
>>> expecting the first sum to match the second). It seem
>>> anachronistic that decimal takes strings as input, though.

[Nick Maclaren]
>> As Dan Bishop says, probably not.  The introduction to the decimal
>> module makes exaggerated claims of accuracy, amounting to propaganda.
>> It is numerically no better than binary, and has some advantages
>> and some disadvantages.

[Carsten Haese]
> Please elaborate. Which exaggerated claims are made,

Well, just about any technical statement can be misleading if not qualified 
to such an extent that the only people who can still understand it knew it 
to begin with <0.8 wink>.  The most dubious statement here to my eyes is 
the intro's "exactness carries over into arithmetic".  It takes a world of 
additional words to explain exactly what it is about the example given (0.1 
+ 0.1 + 0.1 - 0.3 = 0 exactly in decimal fp, but not in binary fp) that 
does, and does not, generalize.  Roughly, it does generalize to one 
important real-life use-case:  adding and subtracting any number of decimal 
quantities delivers the exact decimal result, /provided/ that precision is 
set high enough that no rounding occurs.

> and how is decimal no better than binary?

Basically, they both lose info when rounding does occur.  For example,

>>> import decimal
>>> 1 / decimal.Decimal(3)
Decimal("0.")
>>> _ * 3
Decimal("0.")

That is, (1/3)*3 != 1 in decimal.  The reason why is obvious "by eyeball", 
but only because you have a lifetime of experience working in base 10.  A 
bit ironically, the rounding in binary just happens to be such that (1/3)/3 
does equal 1:

>>> 1./3
0.1
>>> _ * 3
1.0

It's not just * and /.  The real thing at work in the 0.1 + 0.1 + 0.1 - 0.3 
example is representation error, not sloppy +/-:  0.1 and 0.3 can't be 
/represented/ exactly as binary floats to begin with.  Much the same can 
happen if you instead you use inputs exactly representable in base 2 but 
not in base 10 (and while there are none such if precision is infinite, 
precision isn't infinite):

>>> x = decimal.Decimal(1) / 2**90
>>> print x
8.077935669463160887416100508E-28
>>> print x + x + x - 3*x   # not exactly 0
1E-54

The same in binary f.p. is exact, because 1./2**90 is exactly representable 
in binary fp:

>>> x = 1. / 2**90
>>> print x  # this displays an inexact decimal approx. to 1./2**90
8.07793566946e-028
>>> print x + x + x - 3*x  # but the binary arithmetic is exact
0.0

If you boost decimal's precision high enough, then this specific example is 
also exact using decimal; but with the default precision of 28, 1./2**90 
can't be represented exactly in decimal to begin with; e.g.,

>>> decimal.Decimal(1) / 2**90 * 2**90
Decimal("0.")

All forms of fp are subject to representation and rounding errors.  The 
biggest practical difference here is that the `decimal` module is not 
subject to representation error for "natural" decimal quantities, provided 
precision is set high enough to retain all the input digits.  That's worth 
something to many apps, and is the whole ball of wax for some apps -- but 
leaves a world of possible "surprises" nevertheless.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Maths error

2007-01-09 Thread Bjoern Schliessmann
Nick Maclaren wrote:

> No, don't.  That is about another matter entirely, 

It isn't.

Regards,


Björn

-- 
BOFH excuse #366:

ATM cell has no roaming feature turned on, notebooks can't connect

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


Re: help: code formatter?

2007-01-09 Thread Bjoern Schliessmann
siggi wrote:
> Bjoern wrote:
 
>> Why don't you just write one? :)
> 
> Very funny! Just learning Python  :(

It isn't funny at all. You'll learn by doing and trying things.
That's how all programmers start.

Regards,


Björn

-- 
BOFH excuse #265:

The mouse escaped.

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


Question about using "with"

2007-01-09 Thread Steven W. Orr
>From the tutorial, they said that the following construct will 
automatically close a previously open file descriptor:

---
#! /usr/bin/python
import sys

for nn in range ( 1, len(sys.argv ) ):
 print "arg ", nn, "value = ", sys.argv[nn]
 with open(sys.argv[nn]) as f:
 for line in f:
 print line,
--

but when I run it (with args) I get:

591 > ./cat.py cat.py
   File "./cat.py", line 6
 with open(sys.argv[nn]) as f:
 ^
SyntaxError: invalid syntax
592 >

This example came from http://docs.python.org/tut/node10.html down in 
section 8.7

Am I missing something?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Maths error

2007-01-09 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Tim Peters <[EMAIL PROTECTED]> writes:
|> 
|> Well, just about any technical statement can be misleading if not qualified 
|> to such an extent that the only people who can still understand it knew it 
|> to begin with <0.8 wink>.  The most dubious statement here to my eyes is 
|> the intro's "exactness carries over into arithmetic".  It takes a world of 
|> additional words to explain exactly what it is about the example given (0.1 
|> + 0.1 + 0.1 - 0.3 = 0 exactly in decimal fp, but not in binary fp) that 
|> does, and does not, generalize.  Roughly, it does generalize to one 
|> important real-life use-case:  adding and subtracting any number of decimal 
|> quantities delivers the exact decimal result, /provided/ that precision is 
|> set high enough that no rounding occurs.

Precisely.  There is one other such statement, too: "Decimal numbers can
be represented exactly."  What it MEANS is that numbers with a short
representation in decimal can be represented exactly in decimal, which
is tautologous, but many people READ it to say that numbers that they
are interested in can be represented exactly in decimal.  Such as pi,
sqrt(2), 1/3 and so on 

|> > and how is decimal no better than binary?
|> 
|> Basically, they both lose info when rounding does occur.  For example,

Yes, but there are two ways in which binary is superior.  Let's skip
the superior 'smoothness', as being too arcane an issue for this group,
and deal with the other.  In binary, calculating the mid-point of two
numbers (a very common operation) is guaranteed to be within the range
defined by those numbers, or to over/under-flow.

Neither (x+y)/2.0 nor (x/2.0+y/2.0) are necessarily within the range
(x,y) in decimal, even for the most respectable values of x and y.
This was a MAJOR "gotcha" in the days before binary became standard,
and will clearly return with decimal.



Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about using "with"

2007-01-09 Thread Laszlo Nagy

>
> 591 > ./cat.py cat.py
>File "./cat.py", line 6
>  with open(sys.argv[nn]) as f:
>  ^
> SyntaxError: invalid syntax
> 592 >
>
> This example came from http://docs.python.org/tut/node10.html down in 
> section 8.7
>
> Am I missing something?
>   
Are you using python 2.5? The with statement is not available before 2.5.

   Laszlo

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


Re: how to clean sys.path

2007-01-09 Thread Laszlo Nagy

>
> So far, I know only the command >>>sys.path.append(r'c:etc...'), but how 
> to delete or insert at the beginning of the list, I know not.
>   
You can delete a slice. For example,

del sys.path[2:5]

More about slicing: http://docs.python.org/ref/slicings.html
sys.path is a regular list. List methods: 
http://docs.python.org/tut/node7.html

Best,

   Laszlo

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


Re: Maths error

2007-01-09 Thread Terry Reedy

"Carsten Haese" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| On Tue, 2007-01-09 at 11:38 +, Nick Maclaren wrote:
| > As Dan Bishop says, probably not.  The introduction to the decimal
| > module makes exaggerated claims of accuracy, amounting to propaganda.
| > It is numerically no better than binary, and has some advantages
| > and some disadvantages.
|
| Please elaborate. Which exaggerated claims are made, and how is decimal
| no better than binary?

As to the latter question: calculating with decimals instead of binaries 
eliminates conversion errors introduced when one has *exact* decimal 
inputs, such as in financial calculations (which were the motivating use 
case for the decimal module).  But it does not eliminate errors inherent in 
approximating reals with (a limited set of) ratrionals.  Nor does it 
eliminate errors inherent in approximation algorithms (such as using a 
finite number of terms of an infinite series.

Terry Jan Reedy



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


Re: Question about using "with"

2007-01-09 Thread Steven Bethard
Steven W. Orr wrote:
>> From the tutorial, they said that the following construct will 
> automatically close a previously open file descriptor:
> 
> ---
> #! /usr/bin/python
> import sys
> 
> for nn in range ( 1, len(sys.argv ) ):
> print "arg ", nn, "value = ", sys.argv[nn]
> with open(sys.argv[nn]) as f:
> for line in f:
> print line,
> --
> 
> but when I run it (with args) I get:
> 
> 591 > ./cat.py cat.py
>   File "./cat.py", line 6
> with open(sys.argv[nn]) as f:
> ^
> SyntaxError: invalid syntax
> 592 >
> 
> This example came from http://docs.python.org/tut/node10.html down in 
> section 8.7
> 
> Am I missing something?

You need to enable the with statement using a __future__ import::

 >>> with open('temp.txt', 'w') as f:
:1: Warning: 'with' will become a reserved keyword in Python 2.6
   File "", line 1
 with open('temp.txt', 'w') as f:
 ^
SyntaxError: invalid syntax
 >>> from __future__ import with_statement
 >>> with open('temp.txt', 'w') as f:
... f.write('hello')
...

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


Re: Yield

2007-01-09 Thread Mathias Panzenboeck
Fredrik Lundh schrieb:
> Danny Colligan wrote:
> 
>> Carsten mentioned that generators are more memory-efficient to use when
>> dealing with large numbers of objects.  Is this the main advantage of
>> using generators?  Also, in what other novel ways are generators used
>> that are clearly superior to alternatives?
> 
> the main advantage is that it lets you decouple the generation of data
> from the use of data; instead of inlining calculations, or using a pre-
> defined operation on their result (e.g printing them or adding them to a
> container), you can simply yield them, and let the user use whatever
> mechanism she wants to process them.  i.e. instead of
> 
> for item in range:
> calculate result
> print result
> 
> you'll write
> 
> def generate():
> for item in range:
> yield result
> 
> and can then use
> 
> for item in generate():
> print item
> 
> or
> 
>list(process(s) for s in generate())
> 
> or
> 
>sys.stdout.writelines(generate())
> 
> or
> 
>sum(generate())
> 
> etc, without having to change the generator.
> 
> you can also do various tricks with "endless" generators, such as the
> following pi digit generator, based on an algorithm by Python's grand-
> father Lambert Meertens:
> 
> def pi():
> k, a, b, a1, b1 = 2, 4, 1, 12, 4
> while 1:
> # Next approximation
> p, q, k = k*k, 2*k+1, k+1
> a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
> # Yield common digits
> d, d1 = a/b, a1/b1
> while d == d1:
> yield str(d)
> a, a1 = 10*(a%b), 10*(a1%b1)
> d, d1 = a/b, a1/b1
> 
> import sys
> sys.stdout.writelines(pi())
> 
> 
> 

or fibonacci:

def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b

now get the first 10 ones:

>>> from itertools import *
>>> list(islice(fib(),10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]


or primes:

def primes():
yield 1
yield 2

p  = 3
psofar = []

smallerPrimes = lambda: takewhile(lambda x: x+x <= p,psofar)

while True:
if all(p % n != 0 for n in smallerPrimes()):
psofar.append(p)
yield p

p += 2

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


Re: Question about using "with"

2007-01-09 Thread Peter Otten
Steven W. Orr wrote:

>>From the tutorial, they said that the following construct will
> automatically close a previously open file descriptor:
> 
> ---
> #! /usr/bin/python
> import sys
> 
> for nn in range ( 1, len(sys.argv ) ):
>  print "arg ", nn, "value = ", sys.argv[nn]
>  with open(sys.argv[nn]) as f:
>  for line in f:
>  print line,
> --
> 
> but when I run it (with args) I get:
> 
> 591 > ./cat.py cat.py
>File "./cat.py", line 6
>  with open(sys.argv[nn]) as f:
>  ^
> SyntaxError: invalid syntax
> 592 >
> 
> This example came from http://docs.python.org/tut/node10.html down in
> section 8.7
> 
> Am I missing something?

The with-statement only works in Python 2.5, and you have to enable it
explicitly:

>>> from __future__ import with_statement
>>> with open("tmp.txt") as f:
... print len(f.read())
...
15
>>> f.read()
Traceback (most recent call last):
  File "", line 1, in 
ValueError: I/O operation on closed file

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


Re: Question about using "with"

2007-01-09 Thread Duncan Booth
Laszlo Nagy <[EMAIL PROTECTED]> wrote:

> 
>>
>> 591 > ./cat.py cat.py
>>File "./cat.py", line 6
>>  with open(sys.argv[nn]) as f:
>>  ^
>> SyntaxError: invalid syntax
>> 592 >
>>
>> This example came from http://docs.python.org/tut/node10.html down in 
>> section 8.7
>>
>> Am I missing something?
>>   
> Are you using python 2.5? The with statement is not available before 2.5.
> 
and even in Python 2.5 it isn't available unless you enable it. Add the 
following line before the 'import sys' line:

from __future__ import with_statement
-- 
http://mail.python.org/mailman/listinfo/python-list


distutils and ctypes

2007-01-09 Thread [EMAIL PROTECTED]
Hi all,

I suspect that I'm doing something stupid, I would like some other
opinions though.
I'm getting started with ctypes and am trying to use distutils to help
build my module. At the moment I simply want distutils to build a
shared c library (not a python extension!). Under linux, the following
works, under windows xp id doesn't (which I guess is obvious, but the
linux success lead me on).
I have two files at the moment...

/* begin test.c */
int test(int i)
{
return i*i;
}
/* end test.c */

#begin setup.py
from distutils.core import setup, Extension
setup(name="test", version="0.0", ext_modules = [Extension("test",
["test.c"])])
# end setup.py

If I run:

python setup.py build

under linux, I get a nice shared c library under my build dir, which
can be imported by ctypes.
If I run it under windows I get the following:

running build
running build_ext
building 'test' extension
C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe
/DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\Python25\libs
/LIBPATH:C:\Python25\PCBuild /EXPORT:inittest
build\temp.win32-2.5\Release\test.obj /OUT:build\lib.win32-2.5\test.pyd
/IMPLIB:build\temp.win32-2.5\Release\test.lib
LINK : error LNK2001: unresolved external symbol inittest
build\temp.win32-2.5\Release\test.lib : fatal error LNK1120: 1
unresolved externals
LINK : fatal error LNK1141: failure during build of exports file

I can see the problem: python is trying to build an extension module
and is telling the linker to export "inittest", which doesn't exist.
This didn't happen under linux as you don't need to export interfaces
in shared c libraries on linux.

So finally, my question is, is there a way to get distutils to simply
build a shared library on windows so that I can use ctypes with them???

Thanks for your patience with this post, and thanks for any replies.
Best regards,
John Travers

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


A simple lexer

2007-01-09 Thread Neil Cerutti
I'm a royal n00b to writing translators, but you have to start
someplace.

In my Python project, I've decided that writing the dispatch code
to sit between the Glulx virtual machine and the Glk API will be
best done automatically, using the handy prototypes.

Below is the prototype of the lexer, and I'd like some comments
in case I'm doing something silly already.

My particular concern are: 

The loop checks for each possible lexeme one at a time, and has
rather lame error checking.

I made regexes for matching a couple of really trivial cases for
the sake of consistency. In general, is there a better way to use
re module for lexing.

Ultimately, I'm going to need to build up an AST from the lines,
and use that to generate Python code to dispatch Glk functions. I
realize I'm throwing away the id of the lexeme right now;
suggestions on the best way to store that information are
welcome.

I do know of and have experimented with PyParsing, but for now I
want to use the standard modules. After I understand what I'm
doing, I think a PyParsing solution will be easy to write.

import re

def match(regex, proto, ix, lexed_line):
m = regex.match(proto, ix)
if m:
lexed_line.append(m.group())
ix = m.end()
return ix

def parse(proto):
""" Return a lexed version of the prototype string. See the
Glk specification, 0.7.0, section 11.1.4

>>> parse('0:')
['0', ':']
>>> parse('1:Cu')
['1', ':', 'Cu']
>>> parse('2>> parse('4Iu&#![2SF]>+Iu:Is')
['4', 'Iu', '&#!', '[', '2', 'S', 'F', ']', '>+', 'Iu', ':', 'Is']
"""
arg_count = re.compile('\d+')
qualifier = re.compile('[&<>][+#!]*')
type_name = re.compile('I[us]|C[nus]|[SUF]|Q[a-z]')
o_bracket = re.compile('\\[')
c_bracket = re.compile('\\]')
colon = re.compile(':')
ix = 0
lexed_line = []
m = lambda regex, ix: match(regex, proto, ix, lexed_line)
while ix < len(proto):
old = ix
ix = m(arg_count, ix)
ix = m(qualifier, ix)
ix = m(type_name, ix)
ix = m(o_bracket, ix)
ix = m(c_bracket, ix)
ix = m(colon, ix)
if ix == old:
print "Parse error at %s of %s" % (proto[ix:], proto)
ix = len(proto)
return lexed_line

if __name__ == "__main__":
import doctest
doctest.testmod()

-- 
Neil Cerutti
We dispense with accuracy --sign at New York drug store
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: private variables

2007-01-09 Thread Gabriel Genellina

At Tuesday 9/1/2007 04:38, belinda thom wrote:


I knew it was a beehive, but I had hoped someone would know which
version they were released, so I can put the proper statement into my
tutorial (e.g. In version , Python provided some support for
private variables...). I've been avoiding getting stung b/c I see
both sides and have no preference for one vs. the other.


1.5, but I doubt anyone is still using a version earlier than 1.52 anymore.


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Maths error

2007-01-09 Thread Simon Brunning
On 1/9/07, Tim Peters <[EMAIL PROTECTED]> wrote:
> Well, just about any technical statement can be misleading if not qualified
> to such an extent that the only people who can still understand it knew it
> to begin with <0.8 wink>.

+1 QTOW

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Maths error

2007-01-09 Thread Robert Kern
Bjoern Schliessmann wrote:
> Nick Maclaren wrote:
> 
>> No, don't.  That is about another matter entirely, 
> 
> It isn't.

Actually it really is. That thread is about the difference between
str(some_float) and repr(some_float) and why str(some_tuple) uses the repr() of
its elements.

-- 
Robert Kern

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

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


Re: distutils and ctypes

2007-01-09 Thread Robert Kern
[EMAIL PROTECTED] wrote:

> So finally, my question is, is there a way to get distutils to simply
> build a shared library on windows so that I can use ctypes with them???

Not out-of-box, no. The OOF2 project has added a bdist_shlib command which
should do most of what you want, though. It's somewhat UNIX-oriented, and I
think it tries to install the shared library to a standard location (e.g.
/usr/local/lib). You might want to modify it to install the shared library in
the package so it is easy to locate at runtime.

  http://www.ctcms.nist.gov/oof/oof2/
  http://www.ctcms.nist.gov/oof/oof2/source/oof2-2.0.1.tar.gz

The code is in the shlib/ subdirectory.

-- 
Robert Kern

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

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


Re: distutils and ctypes

2007-01-09 Thread Robert Kern
Robert Kern wrote:
> [EMAIL PROTECTED] wrote:
> 
>> So finally, my question is, is there a way to get distutils to simply
>> build a shared library on windows so that I can use ctypes with them???
> 
> Not out-of-box, no. The OOF2 project has added a bdist_shlib command which
> should do most of what you want, though. It's somewhat UNIX-oriented, and I
> think it tries to install the shared library to a standard location (e.g.
> /usr/local/lib). You might want to modify it to install the shared library in
> the package so it is easy to locate at runtime.
> 
>   http://www.ctcms.nist.gov/oof/oof2/
>   http://www.ctcms.nist.gov/oof/oof2/source/oof2-2.0.1.tar.gz
> 
> The code is in the shlib/ subdirectory.

And if you do so, please let us know about it! This would be quite useful for
many other ctypes-using projects.

-- 
Robert Kern

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

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


Summarizing data by week

2007-01-09 Thread Mike Orr
What's the best way to summarize data by week?  I have a set of
timestamped records, and I want a report with one row for each week in
the time period, including zero rows if there are weeks with no
activity.  I was planning to use ISO weeks because datetime has a
convenient .isocalendar() method, but I want each output row to have a
label like this:

2006 week 5 (Feb)

However, to get the month (of the Thursday of that week) I have to
convert it back to an actual date,and I don't see a method to do that
in datetime or dateutil or mx.DateTime.

I was planning to use a dateutil.rrule to generate the weeks from the
minimum to maximum date, including any weeks that have no activity (so
they won't be in the dictionary).  But rrule sequences are based on an
actual start date, not an ISO week, so that won't work.  Unless perhaps
I take the minimum date and calculate the Thursday of that week, and
start from there.  Then all my conversions would be to iso_week rather
than from iso_week.

Is there a better way to do this?

--Mike

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


Newbie - converting csv files to arrays in NumPy

2007-01-09 Thread oyekomova
I would like to know how to convert a csv file with a header row into a
floating point array without the header row.

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


Re: Maths error

2007-01-09 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Robert Kern <[EMAIL PROTECTED]> writes:
|> > 
|> >> No, don't.  That is about another matter entirely, 
|> > 
|> > It isn't.
|> 
|> Actually it really is. That thread is about the difference between
|> str(some_float) and repr(some_float) and why str(some_tuple) uses the repr() 
of
|> its elements.

Precisely.  And it also applies to strings, which I had failed to
notice:

>>> print ("1","2")
('1', '2')
>>> print "1", "2"
1 2


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Internet Survey

2007-01-09 Thread Pete Fenelon
In comp.arch.embedded [EMAIL PROTECTED] wrote:
> Hello all,
> 
> I represent Octabox, an Internet Start-up developing a wide-scale

Hello. F*ck off, spammer.


pete
-- 
[EMAIL PROTECTED] "he just stuck to buying beer and pointing at other stuff"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie - converting csv files to arrays in NumPy

2007-01-09 Thread Robert Kern
oyekomova wrote:
> I would like to know how to convert a csv file with a header row into a
> floating point array without the header row.

Use the standard library module csv. Something like the following is a cheap and
cheerful solution:


import csv
import numpy

def float_array_from_csv(filename, skip_header=True):
f = open(filename)
try:
reader = csv.reader(f)
floats = []
if skip_header:
reader.next()
for row in reader:
floats.append(map(float, row))
finally:
f.close()

return numpy.array(floats)

-- 
Robert Kern

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

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


Re: Newbie - converting csv files to arrays in NumPy

2007-01-09 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, oyekomova
wrote:

> I would like to know how to convert a csv file with a header row into a
> floating point array without the header row.

Take a look at the `csv` module in the standard library.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: Maths error

2007-01-09 Thread Tim Peters
[Tim Peters]
...
>|> Well, just about any technical statement can be misleading if not
>|> qualified to such an extent that the only people who can still
>|> understand it knew it to begin with <0.8 wink>.  The most dubious
>|> statement here to my eyes is the intro's "exactness carries over
>|> into arithmetic".  It takes a world of additional words to explain
>|> exactly what it is about the example given (0.1 + 0.1 + 0.1 - 0.3 =
>|> 0 exactly in decimal fp, but not in binary fp) that does, and does
>|> not, generalize.  Roughly, it does generalize to one important
>|> real-life use-case:  adding and subtracting any number of decimal 
>|> quantities delivers the exact decimal result, /provided/ that
>|> precision is set high enough that no rounding occurs.

[Nick Maclaren]
> Precisely.  There is one other such statement, too: "Decimal numbers
> can be represented exactly."  What it MEANS is that numbers with a
> short representation in decimal can be represented exactly in decimal,
> which is tautologous, but many people READ it to say that numbers that
> they are interested in can be represented exactly in decimal.  Such as
> pi, sqrt(2), 1/3 and so on 

Huh.  I don't read it that way.  If it said "numbers can be ..." I 
might, but reading that way seems to requires effort to overlook the 
"decimal" in "decimal numbers can be ...".

[attribution lost]
>|>> and how is decimal no better than binary?
 
>|> Basically, they both lose info when rounding does occur.  For
>|> example, 

> Yes, but there are two ways in which binary is superior.  Let's skip
> the superior 'smoothness', as being too arcane an issue for this
> group,

With 28 decimal digits used by default, few apps would care about this 
anyway.

> and deal with the other.  In binary, calculating the mid-point
> of two numbers (a very common operation) is guaranteed to be within
> the range defined by those numbers, or to over/under-flow.
>
> Neither (x+y)/2.0 nor (x/2.0+y/2.0) are necessarily within the range
> (x,y) in decimal, even for the most respectable values of x and y.
> This was a MAJOR "gotcha" in the days before binary became standard,
> and will clearly return with decimal.

I view this as being an instance of "lose info when rounding does 
occur".  For example,

>>> import decimal as d
>>> s = d.Decimal("." + "9" * d.getcontext().prec)
>>> s
Decimal("0.")
>>> (s+s)/2
Decimal("1.000")
>>> s/2 + s/2
Decimal("1.000")

"The problems" there are due to rounding error:

>>> s/2  # "the problem" in s/2+s/2 is that s/2 rounds up to exactly 1/2
Decimal("0.5000")

>>> s+s # "the problem" in (s+s)/2 is that s+s rounds up to exactly 2
Decimal("2.000")

It's always something ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >