Re: Which is faster?

2008-08-30 Thread Gabriel Genellina
En Sat, 30 Aug 2008 03:15:30 -0300, Steven D'Aprano  
<[EMAIL PROTECTED]> escribi�:



On Fri, 29 Aug 2008 21:26:35 -0700, cnb wrote:


def averageGrade(self):
tot = 0
for review in self.reviews:
tot += review.grade
return tot / len(self.reviews)

def av_grade(self):
 return sum(review.grade for review in self.reviews) / \
  len(self.reviews)


Re-writing the functions so they can be tested alone:

def averageGrade(alist):
tot = 0.0
for x in alist:
tot += x
return tot/len(alist)


def av_grade(alist):
return sum(alist)/len(alist)



from timeit import Timer
# small amount of items

... alist = range(100)

Timer('averageGrade(alist)',

... 'from __main__ import alist, averageGrade').repeat(number=10)
[3.9559240341186523, 3.4910569190979004, 3.4856188297271729]


Timer('av_grade(alist)',

... 'from __main__ import alist, av_grade').repeat(number=10)
[2.0255107879638672, 1.0968310832977295, 1.0733180046081543]


The version with sum() is much faster. How about with lots of data?


alist = xrange(100)
Timer('averageGrade(alist)',

... 'from __main__ import alist, averageGrade').repeat(number=50)
[17.699107885360718, 18.182793140411377, 18.651514053344727]


Timer('av_grade(alist)',

... 'from __main__ import alist, av_grade').repeat(number=50)
[17.125216007232666, 15.72636890411377, 16.309713840484619]

sum() is still a little faster.


Mmm, in this last test you're measuring the long integer operations  
performance (because the sum exceeds largely what can be represented in a  
plain integer). Long integers are so slow that the difference between both  
loops becomes negligible.


I've tried again using float values:
alist = [float(x) for x in xrange(100)]
and got consistent results for any input size (the version using sum() is  
about twice as fast as the for loop)


--
Gabriel Genellina

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

Re: Interrupt python thread

2008-08-30 Thread Dieter Maurer
En Mon, 25 Aug 2008 05:00:07 -0300, BlueBird <[EMAIL PROTECTED]>
escribi╴:
> Unfortunately, this does not map very well with my program. Each of my
> threads are calling foreign code (still written in python though),
> which might be busy for 1 to 10 minutes with its own job.
>
> I wanted something to easily interrupt every thread to prevent my
> program to stall for 10 minutes if I want to stop it (getting tired of
> killing python all the time).

At the C level, Python has function to send an exception to a thread.
The threads will see the exception only when it executes Python code
(i.e. not when it is waiting or running in external (e.g. "C") code).

You may use (e.g.) "PyRex" to make a Python wrapper available
to your Python code.

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

Re: Date Comparison and Manipulation Functions?

2008-08-30 Thread Hendrik van Rooyen

John Machin  wrote:

>On Aug 30, 10:41 am, "W. eWatson"  wrote:
>
>> What I'm trying to do is adjust date-time stamped file names for date and
>> time errors. The software program collects through a period that roughly
>> coincides with night hours every day and according to the OS clock. It
>> sometimes happens that a user sets the clock to the wrong day or hour,
>> possibly both. Possibly even the month or year. I'm trying to allow a user
>> the opportunity to repair the problem. (Date-time stamp part of the name is
>> mmdd_hhmmss.) Correcting the date needs to be done easily and
>> accurately. For example, if on August 25, he mistakenly sets the date to
>> July 25, and discovers this problem on the real Oct. 5, he should be able to
>> shift all dates from July 25 through Sept. 5 to Aug. 25 through early Oct.,
>> allowing for day oddities in a month during the period. (I hope I got those
>> dates right; otherwise, I think you get the idea. In other words, he needs
>> to shift about 40 days of data to the correct dates.)
>
>... all of which is absolutely nothing to do with your surprise at the
>result of whatever.plus(months=6).
>
>So for some period from recorded date X to recorded date Y, the
>recorded dates of out of kilter by D days. X = Jul 25 2008, Y Sep 5
>2008, and D is 31 (days from Jul 25 to Aug 25). All you have to do is
>(pseudocode):
>
>if X <= recorded_date <= Y:
>new_recorded_date  = recorded_date.plus(days=D)
>

This will work nicely for negative values of D.
The case of positive D values is more of a toffee:

Its Wednesday and I make some observations.
Its Thursday and I "fix" my clock - system thinks its Wednesday again.
I make some observations - Either overwriting or adding to the
original Wednesdays stuff.
Its Friday and I spot the error - my D value is 1 day.
I need to split the "Wednesday" file into two bits, if I can,
and apply the correction to the second half, else I will have
a gap for Wednesday.

Depending on how the logging is done, it may be an unchewable toffee.

- Hendrik



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


How to place menu on the bottom

2008-08-30 Thread qxyuestc
#!/usr/bin/env python

import sys
import os

from tkinter import *

def callback(self):
#int this snippet, all menu entries use the same callback...
print("callback")


class DemoMenu():
def __init__(self):
self.dataTemp = ""
self.createWidgets()

def createWidgets(self): # create application GUI
self.rootWin = Tk()
self.rootWin.minsize(width=800, height=600)
self.rootWin.maxsize(width=800, height=600)
self.rootWin.title = ("JoeQ Menu test...")

self.mainFrame = Frame(self.rootWin)

self.createMenu()

def createMenu(self): # create menu
menuFrame = Frame(self.rootWin)
menuFrame.pack(side=BOTTOM, fill=X)

menuBar = Menu(menuFrame, tearoff=1)

filemenu = Menu(menuBar, tearoff=0)
filemenu.add_command(label="Open...", command=callback)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=callback)

menuBar.add_cascade(label="File", menu=filemenu)

self.rootWin.config(menu=menuBar)

return menuBar

def start(self):
self.rootWin.mainloop()


if __name__ == '__main__':
demomenu = DemoMenu()
demomenu.start()
##
I want to place the menu on the bottom (menuFrame.pack(side=BOTTOM,
fill=X)). But it does not work. Why?
--
http://mail.python.org/mailman/listinfo/python-list


Re: __stack_chk_fail_local

2008-08-30 Thread Marco Bizzarri
On Fri, Aug 29, 2008 at 7:53 PM, gianluca <[EMAIL PROTECTED]> wrote:
> hy list,
> I've built _libfoo.so and  libfoo.py library with swig and I've copied
> in /usr/lib/python2.5/lib-dynload/ but when import the module
>
>>>import libfoo
>
> I've that message
>
> Traceback (most recent call last):
>  File "", line 1, in 
> ImportError: /usr/lib/python2.5/lib-dynload/_libfoo.so: undefined
> symbol: __stack_chk_fail_local
>
> Could anybody help me?
>
> gianluca
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Have you tried to use ldd against the _libfoo.so to check if it is
able to get all the libraries it needs?

Regards
Marco

-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to place menu on the bottom

2008-08-30 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


self.rootWin.config(menu=menuBar)



I want to place the menu on the bottom (menuFrame.pack(side=BOTTOM,
fill=X)). But it does not work. Why?


menubars that are configured via the window menu option are rendered by 
the underlying window system.


to create a stand-alone menu bar, create a frame and pack or grid it 
where you want it, then add Menubutton widgets to it, and attach your 
pulldown menus to those buttons.


the following wrapper supports both menu styles; look at the "else" 
clauses in the various "if use_native_menus" statements for code samples:


http://svn.effbot.org/public/stuff/sandbox/tkinter/tkMenu.py



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


Re: Which is faster?

2008-08-30 Thread cnb
how does doing something twice not change complexity? yes it maybe
belongs to the same complexity-class but is still twice as slow no?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Date Comparison and Manipulation Functions?

2008-08-30 Thread W. eWatson

John Machin wrote:

On Aug 30, 10:41 am, "W. eWatson" <[EMAIL PROTECTED]> wrote:


What I'm trying to do is adjust date-time stamped file names for date and
time errors. The software program collects through a period that roughly
coincides with night hours every day and according to the OS clock. It
sometimes happens that a user sets the clock to the wrong day or hour,
possibly both. Possibly even the month or year. I'm trying to allow a user
the opportunity to repair the problem. (Date-time stamp part of the name is
mmdd_hhmmss.) Correcting the date needs to be done easily and
accurately. For example, if on August 25, he mistakenly sets the date to
July 25, and discovers this problem on the real Oct. 5, he should be able to
shift all dates from July 25 through Sept. 5 to Aug. 25 through early Oct.,
allowing for day oddities in a month during the period. (I hope I got those
dates right; otherwise, I think you get the idea. In other words, he needs
to shift about 40 days of data to the correct dates.)


... all of which is absolutely nothing to do with your surprise at the
result of whatever.plus(months=6).
Really? It opened new insights for me. The example above is not the only 
correction I need to deal with. Further, the author is likely to soon 
clarify some of the date rules in the tutorial that were not obvious or 
mentioned there.


So for some period from recorded date X to recorded date Y, the
recorded dates of out of kilter by D days. X = Jul 25 2008, Y Sep 5
2008, and D is 31 (days from Jul 25 to Aug 25). All you have to do is
(pseudocode):

if X <= recorded_date <= Y:
new_recorded_date  = recorded_date.plus(days=D)

HTH,
John




--
   W. Watson
 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Re: How to place menu on the bottom

2008-08-30 Thread qxyuestc
On Aug 30, 6:04 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> >         self.rootWin.config(menu=menuBar)
> > I want to place the menu on the bottom (menuFrame.pack(side=BOTTOM,
> > fill=X)). But it does not work. Why?
>
> menubars that are configured via the window menu option are rendered by
> the underlying window system.
>
> to create a stand-alone menu bar, create a frame and pack or grid it
> where you want it, then add Menubutton widgets to it, and attach your
> pulldown menus to those buttons.
>
> the following wrapper supports both menu styles; look at the "else"
> clauses in the various "if use_native_menus" statements for code samples:
>
> http://svn.effbot.org/public/stuff/sandbox/tkinter/tkMenu.py
>
> 

step1: I first create a widget "menuFrame" which is belong to the
rootWin
...menuFrame = Frame(self.rootWin)
step2: then I put the widget to the bottom of the rootWin
...menuFrame.pack(side=BOTTOM, fill=X)
step3: I create a menu belong to the menuFrame.
...menuBar = Menu(menuFrame, tearoff=1)
since menuFrame should be placed to the bottom, so does the menuBar in
my opinion. What the problem is?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which is faster?

2008-08-30 Thread Fredrik Lundh

cnb wrote:


how does doing something twice not change complexity? yes it maybe
belongs to the same complexity-class but is still twice as slow no?


doing two things quickly can still be faster than doing one thing slowly.



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


Re: How to place menu on the bottom

2008-08-30 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


What the problem is?


the menu is drawn by the window system when you use the "menu" option, 
not by Tkinter.




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


Re: How to check is something is a list or a dictionary or a string?

2008-08-30 Thread Ken Starks

George Sakkis wrote:

On Aug 29, 12:16 pm, [EMAIL PROTECTED] wrote:

Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)

where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?


if isinstance(item,basestring):
   # it's a string
...
else: # it should be a list
   # typically you don't have to check it explicitly;
   # even if it's not a list, it will raise an exception later anyway
if you call a list-specific method


HTH,
George


For a bit more explanation see, for example,

http://evanjones.ca/python-utf8.html

(Quote)
Working With Unicode Strings

Thankfully, everything in Python is supposed to treat Unicode strings 
identically to byte strings. However, you need to be careful in your own 
code when testing to see if an object is a string. Do not do this:


if isinstance( s, str ): # BAD: Not true for Unicode strings!

Instead, use the generic string base class, basestring:

if isinstance( s, basestring ): # True for both Unicode and byte strings
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to ignore the first line of the text read from a file

2008-08-30 Thread josh logan
On Aug 28, 3:47 am, Santiago Romero <[EMAIL PROTECTED]> wrote:
> > I want to read text line-by-line from a text file, but want to ignore
> > only the first line. I know how to do it in Java (Java has been my
> > primary language for the last couple of years) and following is what I
> > have in Python, but I don't like it and want to learn the better way
> > of doing it.
>
>  Why don't you read and discard the first line before processing the
> rest of the file?
>
>  file = open(filename, 'r')
>  file.readline()
>  for line in file: print line,
>
>  (It works).

# You could also do the following:

from itertools import islice

f = open(filename)

for each_line in islice(f, 1, None):
print line
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check is something is a list or a dictionary or a string?

2008-08-30 Thread josh logan
But this changes with Python 3, right?

On Aug 30, 7:15 am, Ken Starks <[EMAIL PROTECTED]> wrote:
> George Sakkis wrote:
> > On Aug 29, 12:16 pm, [EMAIL PROTECTED] wrote:
> >> Hi,
>
> >> How to check if something is a list or a dictionary or just a string?
> >> Eg:
>
> >> for item in self.__libVerDict.itervalues():
> >>             self.cbAnalysisLibVersion(END, item)
>
> >> where __libVerDict is a dictionary that holds values as strings or
> >> lists. So now, when I iterate this dictionary I want to check whether
> >> the item is a list or just a string?
>
> > if isinstance(item,basestring):
> >    # it's a string
> >     ...
> > else: # it should be a list
> >    # typically you don't have to check it explicitly;
> >    # even if it's not a list, it will raise an exception later anyway
> > if you call a list-specific method
>
> > HTH,
> > George
>
> For a bit more explanation see, for example,
>
> http://evanjones.ca/python-utf8.html
>
> (Quote)
> Working With Unicode Strings
>
> Thankfully, everything in Python is supposed to treat Unicode strings
> identically to byte strings. However, you need to be careful in your own
> code when testing to see if an object is a string. Do not do this:
>
> if isinstance( s, str ): # BAD: Not true for Unicode strings!
>
> Instead, use the generic string base class, basestring:
>
> if isinstance( s, basestring ): # True for both Unicode and byte strings

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


Re: Which is faster?

2008-08-30 Thread Diez B. Roggisch

cnb schrieb:

how does doing something twice not change complexity? yes it maybe
belongs to the same complexity-class but is still twice as slow no?


Because big O notation is not about constant factors. Or even subterms 
with lower powers.


http://en.wikipedia.org/wiki/Big_O_notation

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


Advice on the style to use in imports

2008-08-30 Thread Marco Bizzarri
Hi all.

I read the PEP8 and the "importing Python Modules" article. However,
I'm still a little confused on what should the general rules for
importing modules.

I'm showing what I used in my current project, and will accept your
advices on how I should change them.

The style is consistently the following:

from package.subpackge.module import MyClass

Is this an accepted way to write imports? According to what I
understood in articles, I don't think so.

If I understand it correctly, it should be:

import module

and then use

module.MyClass

( in case of a flat module)

or

from package.subpackage import module

and then use

module.MyClass

(( for a package/subpackage structure ))

Thank you all for your attention

Regards
Marco

-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
http://notenotturne.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Segmentation Fault on CDLL reloading

2008-08-30 Thread Marcus.CM

Hi,

I use the following ctype to load a .so library in Linux.

vr = ctypes.CDLL(sstr)  

And the following to release it so that i can reload the library without 
quiting the python script.


_ctypes.dlclose(vr._handle)

These calls are guarded by a writer lock and access to it guarded by a 
reader lock which i got from recipe : 
http://code.activestate.com/recipes/413393/
  
The problem is during the re-loading of the library occasionally the 
python script will abort with "Segmentation Fault". This is like 1 out 
of 10 times it can happen and that

is good enough to kill the application.

Is there any reason to this or how to do i prevent it?


Marcus .CM




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


Re: Advice on the style to use in imports

2008-08-30 Thread Fredrik Lundh

Marco Bizzarri wrote:


I'm showing what I used in my current project, and will accept your
advices on how I should change them.

The style is consistently the following:

from package.subpackge.module import MyClass

Is this an accepted way to write imports? According to what I
understood in articles, I don't think so.


importing objects instead of the module (namespace) they live in can 
cause all sorts of aliasing and dependency issues.  avoid unless you 
know exactly what you're doing.




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


Re: Fastest way to write huge files

2008-08-30 Thread Larry Bates

Mohamed Yousef wrote:

Thanks all ,
but there is still something i forget to state -sorry - all
communication will be via Http with a server
so data is received via Http
so local network solutions won't work
the problem really starts after receiving data in storing them without
much of a CPU/Memory usage and with a good speed

@James Mills : didn't understand fully what you mean and how it will
improve writting effciency

Thanks,

Regards,
Mohamed Yousef

2008/8/29 Tim Golden <[EMAIL PROTECTED]>:

Terry Reedy wrote:


Mohamed Yousef wrote:

let's say , I'm moving large files through network between devices
what is the fastest way to do this ?
what i came up with :-

Use your OS's network copy command.  On unix, that was once uucp.  On
Windows, I drag-and-drop to/from a Network Neighborhood location, including
to a printer, so I don't know whether you can use copy and if so how.

For completeness' sake, on Windows you could use any of the following
techniques with a UNC as the destination (and/or source):

http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html

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



If connection is over Internet via HTTP the connection speed is so slow in 
relation to the speed of your CPU that it doesn't really matter.  You are 
prematurely optimizing your application.  Get it working first and then see if 
the file writing is the bottleneck (it probably won't be).


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


Re: How to check is something is a list or a dictionary or a string?

2008-08-30 Thread Ken Starks

josh logan wrote:

But this changes with Python 3, right?



right!

see
http://docs.python.org/dev/3.0/whatsnew/3.0.html

(quote)
Strings and Bytes

* There is only one string type; its name is str but its behavior 
and implementation are like unicode in 2.x.
* The basestring superclass has been removed. The 2to3 tool 
replaces every occurrence of basestring with str.
* PEP 3137: There is a new type, bytes, to represent binary data 
(and encoded text, which is treated as binary data until you decide to 
decode it). The str and bytes types cannot be mixed; you must always 
explicitly convert between them, using the str.encode() (str -> bytes) 
or bytes.decode() (bytes -> str) methods.
* All backslashes in raw strings are interpreted literally. This 
means that Unicode escapes are not treated specially.


* PEP 3112: Bytes literals, e.g. b"abc", create bytes instances.
* PEP 3120: UTF-8 default source encoding.
* PEP 3131: Non-ASCII identifiers. (However, the standard library 
remains ASCII-only with the exception of contributor names in comments.)
* PEP 3116: New I/O Implementation. The API is nearly 100% 
backwards compatible, but completely reimplemented (currently mostly in 
Python). Also, binary files use bytes instead of strings.
* The StringIO and cStringIO modules are gone. Instead, import 
io.StringIO or io.BytesIO.

* '\U' and '\u' escapes in raw strings are not treated specially.





On Aug 30, 7:15 am, Ken Starks <[EMAIL PROTECTED]> wrote:

George Sakkis wrote:

On Aug 29, 12:16 pm, [EMAIL PROTECTED] wrote:

Hi,
How to check if something is a list or a dictionary or just a string?
Eg:
for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)
where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?

if isinstance(item,basestring):
   # it's a string
...
else: # it should be a list
   # typically you don't have to check it explicitly;
   # even if it's not a list, it will raise an exception later anyway
if you call a list-specific method
HTH,
George

For a bit more explanation see, for example,

http://evanjones.ca/python-utf8.html

(Quote)
Working With Unicode Strings

Thankfully, everything in Python is supposed to treat Unicode strings
identically to byte strings. However, you need to be careful in your own
code when testing to see if an object is a string. Do not do this:

if isinstance( s, str ): # BAD: Not true for Unicode strings!

Instead, use the generic string base class, basestring:

if isinstance( s, basestring ): # True for both Unicode and byte strings



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


Re: __stack_chk_fail_local

2008-08-30 Thread gianluca
On 30 Ago, 12:05, "Marco Bizzarri" <[EMAIL PROTECTED]> wrote:
> On Fri, Aug 29, 2008 at 7:53 PM, gianluca <[EMAIL PROTECTED]> wrote:
> > hy list,
> > I've built _libfoo.so and  libfoo.py library with swig and I've copied
> > in /usr/lib/python2.5/lib-dynload/ but when import the module
>
> >>>import libfoo
>
> > I've that message
>
> > Traceback (most recent call last):
> >  File "", line 1, in 
> > ImportError: /usr/lib/python2.5/lib-dynload/_libfoo.so: undefined
> > symbol: __stack_chk_fail_local
>
> > Could anybody help me?
>
> > gianluca
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Have you tried to use ldd against the _libfoo.so to check if it is
> able to get all the libraries it needs?
>
> Regards
> Marco
>
> --
> Marco Bizzarrihttp://iliveinpisa.blogspot.com/

I've tried with ldd and the library aren't loaded. I don't use my *.i
interface so is quite difficult modify it (realy, the libraru is
supplied with make).

Any suggests?
gianluca
--
http://mail.python.org/mailman/listinfo/python-list


Re: Segmentation Fault on CDLL reloading

2008-08-30 Thread Diez B. Roggisch

Marcus.CM schrieb:

Hi,

I use the following ctype to load a .so library in Linux.

vr = ctypes.CDLL(sstr) 
And the following to release it so that i can reload the library without 
quiting the python script.


_ctypes.dlclose(vr._handle)

These calls are guarded by a writer lock and access to it guarded by a 
reader lock which i got from recipe : 

  The problem is during the re-loading of the library 
occasionally the python script will abort with "Segmentation Fault". 
This is like 1 out of 10 times it can happen and that

is good enough to kill the application.

Is there any reason to this or how to do i prevent it?


Short answer: yes, there is a reason, no, you can't prevent it.

Of course there is a reason for this. Segfaults don't happen by 
chance... And one can't prevent segfaults from killing the interpreter, 
because the OS is responsible for that.


Now what would I do?

 - don't care. Or does the DLL frequently change when the program is 
deployed? Or to ask different: why do you need unloading/reloading at all?


 - debug it. Write a script that exposes the behavior. The fire up GDB 
with python, do "set args " and run. When the segfault occurs, 
look into the traceback with "bt". If the problem is in the DLL-code, 
see what's causing it. If it's in ctypes (or the python-interpreter) - 
well, there is a ctypes mailing lisk to ask for help.


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


Re: microsoft terminal server

2008-08-30 Thread Larry Bates

Tim Golden wrote:

[EMAIL PROTECTED] wrote:

HI,
i would like to know if there is a way to create a python script for
automate mstsc.exe username and pwd credential, i mean i would create
a script that first open mstsc.exe and in the same time is able to
fill [computer+username+pwd].


Haven't tried it, but in principle you should be
able to use the win32cred package from pywin32
to store your username / password and use an .rdp
file to automate the rest of the settings, including
the server.

TJG


Use Remote Desktop Connection to create/save an .rdp file that can connect to 
your remote computer.  Then use os.startfile(''.rdp).  It will call 
mstsc for you.


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


Re: How to check is something is a list or a dictionary or a string?

2008-08-30 Thread Larry Bates

[EMAIL PROTECTED] wrote:

Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)


where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?


Thanks,
Rajat


Are you sure that is what you want to do or do you want to make sure that 
"something" is an iterable.  What if someone passed in a generator or a class 
instance that is iterable, do you really want to fail?


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


Re: __stack_chk_fail_local

2008-08-30 Thread Marco Bizzarri
The ldd should point you to the library which is not loaded.

Maybe the library you need is not in one of the normal locations in
your Linux/Unix path.

Normally, the linker looks for library under /lib and /usr/lib, and
maybe other paths specified in /etc/ld.so.conf

If you know the library is installed in your system, you can force the
linker to look for it, either modifying your /etc/ld.so.conf (better
if you know what you're doing, however) or, just setting the
LD_LIBRARY_PATH variable:

export LD_LIBRARY_PATH=/some/non/standard/lib/dir/

python -c "import foo"

Another possibility, which you can check googling a little, is that
you've two different versions of the libarary around your system, and
that you're loading the wrong one (i.e., python is looking at the
wrong one)

again, setting the LD_LIBRARY_PATH should help

Regards
Marco

On Sat, Aug 30, 2008 at 2:33 PM, gianluca <[EMAIL PROTECTED]> wrote:
> On 30 Ago, 12:05, "Marco Bizzarri" <[EMAIL PROTECTED]> wrote:
>> On Fri, Aug 29, 2008 at 7:53 PM, gianluca <[EMAIL PROTECTED]> wrote:
>> > hy list,
>> > I've built _libfoo.so and  libfoo.py library with swig and I've copied
>> > in /usr/lib/python2.5/lib-dynload/ but when import the module
>>
>> >>>import libfoo
>>
>> > I've that message
>>
>> > Traceback (most recent call last):
>> >  File "", line 1, in 
>> > ImportError: /usr/lib/python2.5/lib-dynload/_libfoo.so: undefined
>> > symbol: __stack_chk_fail_local
>>
>> > Could anybody help me?
>>
>> > gianluca
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>>
>> Have you tried to use ldd against the _libfoo.so to check if it is
>> able to get all the libraries it needs?
>>
>> Regards
>> Marco
>>
>> --
>> Marco Bizzarrihttp://iliveinpisa.blogspot.com/
>
> I've tried with ldd and the library aren't loaded. I don't use my *.i
> interface so is quite difficult modify it (realy, the libraru is
> supplied with make).
>
> Any suggests?
> gianluca
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fastest way to write huge files

2008-08-30 Thread Mohamed Yousef
>
> If connection is over Internet via HTTP the connection speed is so slow in
> relation to the speed of your CPU that it doesn't really matter.
this is not always true , espicially when using a localhost or a local
netwtork server
the problem is the increase in cpu and memory usage make it a painful bug
such that downloading a big file (say 1 GB ) would introduce a big cpu
usage (already tested)

Thanks ,

Regards,
Mohamed Yousef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ensure only single application instance.

2008-08-30 Thread Larry Bates

Cameron Laird wrote:

In article <[EMAIL PROTECTED]>,
Uberman  <[EMAIL PROTECTED]> wrote:

On Fri, Aug 29, 2008 at 6:51 AM, Heston James <[EMAIL PROTECTED]> wrote:

Good afternoon all.

I have an application/script which is launched by crontab on a regular
basis. I need an effective and accurate way to ensure that only one instance
of the script is running at any one time.

You could create a named pipe in /tmp with a unique (static) name and
permissions that disallow any kind of read/write access.  Then simply have
your script check for its existence when it starts.  If it exists, then
another instance of your script is running, and just terminate.  Make sure
your original instance removes the pipe when it exits.


I'll write an article on this subject this fall.  The
essentials are:
A.  There's no canonical answer; every apparent solution
has problems;
B.  The suggestions offered you are certainly among the
popular ones;
C.  My personal favorite is to open a (network) socket
server.  For reasons I'll eventually explain, this
has particularly apt semantics under Unix.


Cameron,

I found this recipe (http://code.activestate.com/recipes/474070/) on 
ActiveState's site that had a working version of a single instance class for 
Windows that I've used quite successfully.  Since I also work a lot Linux, I 
wrote and donated this version (http://code.activestate.com/recipes/546512/) for 
Linux that also seems to work well for me.


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


Re: __stack_chk_fail_local

2008-08-30 Thread [EMAIL PROTECTED]
Thanks!
I've resolved the problem with libraries but... I've still error with this 
message:
ImportError: ./_python_grass6.so: undefined symbol: __stack_chk_fail_local

exuse me, I'm not a guru.

Gianluca

-- Initial Header ---

>From  : "Marco Bizzarri" [EMAIL PROTECTED]
To  : "gianluca" [EMAIL PROTECTED]
Cc  : python-list@python.org
Date  : Sat, 30 Aug 2008 14:45:05 +0200
Subject : Re: __stack_chk_fail_local







> The ldd should point you to the library which is not loaded.
> 
> Maybe the library you need is not in one of the normal locations in
> your Linux/Unix path.
> 
> Normally, the linker looks for library under /lib and /usr/lib, and
> maybe other paths specified in /etc/ld.so.conf
> 
> If you know the library is installed in your system, you can force the
> linker to look for it, either modifying your /etc/ld.so.conf (better
> if you know what you're doing, however) or, just setting the
> LD_LIBRARY_PATH variable:
> 
> export LD_LIBRARY_PATH=/some/non/standard/lib/dir/
> 
> python -c "import foo"
> 
> Another possibility, which you can check googling a little, is that
> you've two different versions of the libarary around your system, and
> that you're loading the wrong one (i.e., python is looking at the
> wrong one)
> 
> again, setting the LD_LIBRARY_PATH should help
> 
> Regards
> Marco
> 
> On Sat, Aug 30, 2008 at 2:33 PM, gianluca <[EMAIL PROTECTED]> wrote:
> > On 30 Ago, 12:05, "Marco Bizzarri" <[EMAIL PROTECTED]> wrote:
> >> On Fri, Aug 29, 2008 at 7:53 PM, gianluca <[EMAIL PROTECTED]> wrote:
> >> > hy list,
> >> > I've built _libfoo.so and  libfoo.py library with swig and I've copied
> >> > in /usr/lib/python2.5/lib-dynload/ but when import the module
> >>
> >> >>>import libfoo
> >>
> >> > I've that message
> >>
> >> > Traceback (most recent call last):
> >> >  File "", line 1, in 
> >> > ImportError: /usr/lib/python2.5/lib-dynload/_libfoo.so: undefined
> >> > symbol: __stack_chk_fail_local
> >>
> >> > Could anybody help me?
> >>
> >> > gianluca
> >> > --
> >> >http://mail.python.org/mailman/listinfo/python-list
> >>
> >> Have you tried to use ldd against the _libfoo.so to check if it is
> >> able to get all the libraries it needs?
> >>
> >> Regards
> >> Marco
> >>
> >> --
> >> Marco Bizzarrihttp://iliveinpisa.blogspot.com/
> >
> > I've tried with ldd and the library aren't loaded. I don't use my *.i
> > interface so is quite difficult modify it (realy, the libraru is
> > supplied with make).
> >
> > Any suggests?
> > gianluca
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> 
> 
> 
> -- 
> Marco Bizzarri
> http://iliveinpisa.blogspot.com/
> 

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


Re: Fastest way to write huge files

2008-08-30 Thread Larry Bates

Mohamed Yousef wrote:

If connection is over Internet via HTTP the connection speed is so slow in
relation to the speed of your CPU that it doesn't really matter.

this is not always true , espicially when using a localhost or a local
netwtork server
the problem is the increase in cpu and memory usage make it a painful bug
such that downloading a big file (say 1 GB ) would introduce a big cpu
usage (already tested)

Thanks ,

Regards,
Mohamed Yousef


I disagree.  There is very little overhead in file writing if you stream your 
writes to disk in small blocks as they arrive via HTTP.  Don't wait for the 
entire 1Gb to arrive and then write it.  Python can write small to a file 
blazingly fast with normal file writing I/O. Any extra CPU overhead you may see 
is probably due to reading the entire 1Gb into memory and seeing swapping to 
disk as you exhaust main memory.  Interleaving your HTTP reading with file 
writing should be very fast.


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


Re: __stack_chk_fail_local

2008-08-30 Thread Marco Bizzarri
On Sat, Aug 30, 2008 at 3:03 PM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Thanks!
> I've resolved the problem with libraries but... I've still error with this 
> message:
> ImportError: ./_python_grass6.so: undefined symbol: __stack_chk_fail_local
>
> exuse me, I'm not a guru.
>
> Gianluca
>

I'm not a guru either, Gianluca ;)

I made a little search on Google; the first link is the following:

http://ubuntuforums.org/showthread.php?t=352642

can you apply the suggestion?

I think you should give a little more context on your problem, also,
because I think it has to do with your setup (not that you setup
something in the wrong way: just to have context).

Regards
Marco




-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


How to delete elements from Tix Combo Box?

2008-08-30 Thread dudeja . rajat
HI,

I'm using a Tix combo box (I call it combo2), the contents of which
are loaded depeding on the selection in another Tix combo box(I call
it combo1)
I have used the commands:

self.cbAnalysisLibVersion.insert(END, results)

to insert elements to the combo box.

I'm looking for some similar option to delete elements from the combo
box. I mean, as soon as I change selection in
combo1 the previous elements in the combo2 should get cleared up( or
deleted) and | shall be able to the above insert command to add new
elements to the combo2 ( depending upon selection in combo1)

Please suggest how can I clear up the ( delete the entries) in combo2.

Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to delete elements from Tix Combo Box?

2008-08-30 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


I'm using a Tix combo box (I call it combo2), the contents of which
are loaded depeding on the selection in another Tix combo box(I call
it combo1)
I have used the commands:

self.cbAnalysisLibVersion.insert(END, results)

to insert elements to the combo box.

I'm looking for some similar option to delete elements from the combo
box. I mean, as soon as I change selection in
combo1 the previous elements in the combo2 should get cleared up( or
deleted) and | shall be able to the above insert command to add new
elements to the combo2 ( depending upon selection in combo1)

Please suggest how can I clear up the ( delete the entries) in combo2.


no time to test this, but iirc, the combobox content is held in an 
ordinary listbox widget, so you should be able to use the subwidget 
method to fetch that widget, and then use ordinary listbox methods to 
change the content.  Something like this:


lb = w.subwidget("listbox")
lb.delete(0, END) # delete all items



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


Re: Advice on the style to use in imports

2008-08-30 Thread Marco Bizzarri
On Sat, Aug 30, 2008 at 2:20 PM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>
> importing objects instead of the module (namespace) they live in can cause
> all sorts of aliasing and dependency issues.  avoid unless you know exactly
> what you're doing.
>
> 
>

Thanks Fredrik; I understand that is the underlying message of your article.

I'm just confused because PEP8 seems to suggest that the from module
import Class style is acceptable; is there a big "if you know what are
doing" before, which I'm unable to see?

Regards
Marco


-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
http://notenotturne.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to delete elements from Tix Combo Box?

2008-08-30 Thread dudeja . rajat
On Sat, Aug 30, 2008 at 2:32 PM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
>> I'm using a Tix combo box (I call it combo2), the contents of which
>> are loaded depeding on the selection in another Tix combo box(I call
>> it combo1)
>> I have used the commands:
>>
>> self.cbAnalysisLibVersion.insert(END, results)
>>
>> to insert elements to the combo box.
>>
>> I'm looking for some similar option to delete elements from the combo
>> box. I mean, as soon as I change selection in
>> combo1 the previous elements in the combo2 should get cleared up( or
>> deleted) and | shall be able to the above insert command to add new
>> elements to the combo2 ( depending upon selection in combo1)
>>
>> Please suggest how can I clear up the ( delete the entries) in combo2.
>
> no time to test this, but iirc, the combobox content is held in an ordinary
> listbox widget, so you should be able to use the subwidget method to fetch
> that widget, and then use ordinary listbox methods to change the content.
>  Something like this:
>
>lb = w.subwidget("listbox")
>lb.delete(0, END) # delete all items
>
> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Fredrik, Thanks so much. That worked.

Following this, I can now see that my combo2 has no previous elements
and contains only the elements relevant to selection in combo1.

Now, as soon as I select something in combo 2 and go back to change
selection in combo1 the combo2 must get its history cleared up (i.e
the previous selection in combo2's entry subwidget)

I used the command before I delete the entires :
self.combo2.config(history = False)

But this does not seem to be working;

Here is my code snippet:

Inside the callback function of combo1:

for libName, libResults in self.__libVerDict.items():
if libName == selectedLibName:
#Get the list of labelled results
resultsVer = self.__libVerDict[libName]
self.combo2.config(state = NORMAL)
self.combo2.config(history = False)
#Delete the previous entries from the listbox
#subwidget of combo box
subLB = self.combo2.subwidget("listbox")
subLB.delete(0, END)
#Add the results to the combo box
for results in resultsVer:
self.combo2.insert(END, results)


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


Re: Advice on the style to use in imports

2008-08-30 Thread bearophileHUGS
Marco Bizzarri:
> I'm just confused because PEP8 seems to suggest that the from module
> import Class style is acceptable; is there a big "if you know what are
> doing" before, which I'm unable to see?

from somemodule import somename

is often acceptable IHMO, but there are some things to consider:
- you and the person that reads your code have to remember where
somename comes from. So you can do it for well known names like izip
or imap, but if you import lots of names from lots of modules, things
may become too much complex. So often it can be better to import just
the modules, and use somemodule.somename.
- somemodule.somename is longer to write and to read, and if it's
repeated many times it may worsen the program readability, making
lines of code and expressions too much long and heavy. So you have to
use your brain (this means that you may have to avoid standard
solutions). Note that you can use a compromise, shortening the module
name like this:
import somemodule as sm
Then you can use:
sm.somename
- somemodule.somename requires an extra lookup, so in long tight loops
(if you don't use Psyco) it slows down the code. This can be solved
locally, assigning a local name into a function/method (or even in
their argument list, but that's a hack to be used only once in a
while):
localname = somemodule.somename

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: When to use try and except?

2008-08-30 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Carl Banks  <[EMAIL PROTECTED]> wrote:
.
.
.
>> Basically, there's a general principle (EAFP: Easier to ask
>> forgiveness than permission) in Python to just "try" something and
>> then catch the exception if something goes wrong. This is in contrast
>> to e.g. C where you're supposed to "Look before you leap" (LBYL) and
>> check for possible error conditions before performing the operation.
>
>I wouldn't say that the possibility of EAFP in Python makes it
>obsolute to use LBYL.  (Error checking seems to be too broad a subject
>to apply the One Obvious Way maxim to.)  C isn't always LBYL anyway;
>sometimes it's DFTCFE "Don't forget to check for errors".
>
>I tend to use EAFP to check if something "wrong" happened (a missing
>file, invalid input, etc.), and LBYL for expected conditions that can
>occur with valid input, even when that condition could be tested with
>a try...except.  For instance, I'd write something like this:
.
.
.
I'll reinforce what Carl tells:  a wise developer knows how to
work in different styles in different circumstances.  In a retail
C program, for example, it might be wisest to emphasize ahead-of-
time diagnostics such as, "the configuration file ... is {missing,
inaccessible,locked, ...}", while a system-level library making
what apparently is the same call needs to check return values
carefully, to guard against the possibility that the system's
state has changed while executing consecutive statements.
--
http://mail.python.org/mailman/listinfo/python-list


boxsizer inside a panel

2008-08-30 Thread Gandalf
the following code's panel elements doesn't react like a table though
is haze boxsizer
What is wrong here? :


   panel3=wx.Panel(self,-1,(10,10), style=wx.SIMPLE_BORDER,
size=(370, 150))
   panel3.SetBackgroundColour("#ff")
   text1=wx.StaticText(panel3, -1, 'Hello')
   text2=wx.StaticText(panel3, -1, 'text text text
text')
   box = wx.BoxSizer(wx.HORIZONTAL)

   box.Add(text1, 1, wx.ALIGN_LEFT)
   box.Add(text2, 1, wx.ALIGN_RIGHT)

   self.SetAutoLayout(True)
   panel3.SetSizer(box)


   self.Layout()


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


Writing to ms excel

2008-08-30 Thread Marin Brkic
Hello all,

please, let me apologize in advance. English is not my first language
(not even my second one), so excuse any errors with which I'm about to
embarass myself in front of the general public. Second, I'm relatively
new to python, so sorry if this seems like a stupid question.

I'm trying to find a way to write data to excel cells (or to be more
specific to an .xls file), let's say for the sake of argument, data
readen from a file (although it will be calculated in the process).
I've been searching, but couldn't find any examples which allows that.

Do anyone knows of any ? All help is appreciated on this matter.
Tutorials? Anything ...


Best regards
Marin
--
http://mail.python.org/mailman/listinfo/python-list


starting gazpacho on windows

2008-08-30 Thread nntpman68

Hi,

I wanted to play with gazpacho ( no urgent need, but I was curious)
I went to http://gazpacho.sicem.biz/ (is thios the official home page?)



I downloaded the windows installer for Kiwi
and the Windowsinstaller for Gazpacho.

I started both, und they installed, but I even don't know where to.

The web page contains instructions of how to run gazpacho under linux or 
how to untar and run gazpacho under linux without installing.


No hint for windows.

So does anybody use Gazpacho under XP and knows how to start it?

Thanks in advance and bye


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


Re: Advice on the style to use in imports

2008-08-30 Thread Eric Wertman
> I read the PEP8 and the "importing Python Modules" article. However,
> I'm still a little confused on what should the general rules for
> importing modules.
>
> I'm showing what I used in my current project, and will accept your
> advices on how I should change them.

> import module
>
> and then use
>
> module.MyClass
>
> ( in case of a flat module)
>
> or
>
> from package.subpackage import module
>
> and then use
>
> module.MyClass
>
> (( for a package/subpackage structure ))

My opinion is that this is the preffered way, generally speaking.  Not
only does it avoid namespace issues as effbot pointed out, but it also
makes code easier to read later.  As examples, I tend to break those
rules frequently with these :

from pprint import pprint  # Because pprint.pprint is just redundant
from lxml import etree # Actually I guess this doesn't break the rule.
from datetime import datetime  # This might be a bad idea... I haven't
had problems yet though.  datetime.datetime gets on my nerves though.

just my .02

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


Nokia N85 and N79 official, no surprises

2008-08-30 Thread javed044
Nokia N85 is a quad-band GSM and tri-band UMTS dual slider, inspired
by the controversial design of the Nokia N81..

http://helpmobilebd.blogspot.com/search/label/NEWS
--
http://mail.python.org/mailman/listinfo/python-list


How to clear the Entry subwidget of Tix Combo box?

2008-08-30 Thread dudeja . rajat
Hi,

In my combo box taken from Tix, how can I delete item in Entry subwiget?

My case is like this:

I have a check button which when made un-ticked should clear the entry
from combo box (i. anything selected in combo box previously)

I used the following commands:
subEntry = self.cbAnalysisLibVersion.subwidget("entry")
subEntry.delete(0,END)


This does not seem to be working?

-- 
Regrads,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to ms excel

2008-08-30 Thread Eric Wertman
> I'm trying to find a way to write data to excel cells (or to be more
> specific to an .xls file), let's say for the sake of argument, data
> readen from a file (although it will be calculated in the process).
> I've been searching, but couldn't find any examples which allows that.

The answer will depend on your base os.. if you are on windows there
will be some options using the COM interfaces I bet.. but I don't know
anything about them.

If you are on a unix based os, your choices are limited.  If you can,
I would just write to a csv file and open it with Excel.  If you have
to interface with an exsisting excel file, you can try
http://pypi.python.org/pypi/xlrd , but it may not support writing xls
files, still.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-30 Thread Fredrik Lundh

Roy Smith wrote:

Yowza, you're right (at least for the one case I tried).  This must be a 
new development (where "new development" is defined as, "It wasn't legal in 
the original K&R C I learned when I was a pup").


the C 89 grammar appears to be:

initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }

initializer-list:
designation-opt initializer
initializer-list , designation-opt initializer

so a trailing comma has been allowed for around twenty years.



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


Re: Process "Killed"

2008-08-30 Thread Eric Wertman
> I'm doing some simple file manipulation work and the process gets
> "Killed" everytime I run it. No traceback, no segfault... just the
> word "Killed" in the bash shell and the process ends. The first few
> batch runs would only succeed with one or two files being processed
> (out of 60) before the process was "Killed". Now it makes no
> successful progress at all. Just a little processing then "Killed".

This is the behavior you'll see when your os has run out of some
memory resource.  The kernel sends a 9 signal.  I'm pretty sure that
if you exceed a soft limit your program will abort with out of memory
error.

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


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-30 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> Roy Smith wrote:
> 
> > Yowza, you're right (at least for the one case I tried).  This must be a 
> > new development (where "new development" is defined as, "It wasn't legal in 
> > the original K&R C I learned when I was a pup").
> 
> the C 89 grammar appears to be:
> 
>  initializer:
>  assignment-expression
>  { initializer-list }
>  { initializer-list , }
> 
>  initializer-list:
>  designation-opt initializer
>  initializer-list , designation-opt initializer
> 
> so a trailing comma has been allowed for around twenty years.
> 
> 

C89 came out about 10 years after I first learned C :-)
--
http://mail.python.org/mailman/listinfo/python-list


Most pythonic way of weighted random selection

2008-08-30 Thread Manuel Ebert

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Dear list,

who's got aesthetic advice for the following problem? I've got some  
joint probabilities of two distinct events Pr(X=x, Y=y), stored in a  
list of lists of floats, where every row represents a possible  
outcome of X and every float in a row a possible outcome of Y (which  
I will now call my matrix, altough I can't use numpy or numeric for  
this), so e.g. m = [[0.2, 0.4, 0.05], [0.1, 0.05, 0.2]]. All lists in  
the list are equally long and the values of the flattened list add up  
to 1.0, i.e. sum([sum(row) for row in m]) == 1. In practice, this  
'matrix' is about 20x40, i.e. a list with 20 lists á 40 floats each.


Now the task is to select one outcome for X and Y based on the joint  
probabilites, and afterwards check that the outcomes fullfill certain  
criteria. If it doesn't fulfill some criteria a new pair of outcomes  
has to be selected, for other criteria it will still be selected with  
a certain probability. My approach was to choose a random number, and  
then walk through the list adding the values together until the  
accumulated sum is greater than my random threshold:


import random
r = random.random()
s = 0.0
p = 0.2 # probability of selecting outcome if it doesn't fulfill  
criterion 2

break_loop = False
while not break_loop:
for row_index in range(len(m)):
for col_index in range(len(row)):
s += m[row_index][col_index]
if s >= r:
if not fulfills_criterion_a(row_index, 
col_index):
break_loop = True
elif not fulfills_criterion_b(row_index, 
col_index):
if random.random() <= p:
return row_index, col_index
else:
break_loop = True
else:
return row_index, col_index
if break_loop: break
if break_loop: break
break_loop = False


Now that looks plain ugly, and I wonder whether you might find a  
slightly more elegant way of doing it without using numpy and the like.


Bests,
Manuel
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (Darwin)

iD8DBQFIuWoncZ70OCIgLecRArV4AJ9ynhC/McegMIYTWOOOW4p44t3rWgCbBjvm
1JRHy5kp1qIGLDaCTXXFcSs=
=X6Sv
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Picking up resource forks and extended attributes on Mac OS X ?!

2008-08-30 Thread Miles
Mitrokhin wrote:
> Also (dare I ask for this too) If some nice soul could point me in the
> right direction for picking up files with extended attributes under OS
> X I'd be really gratefull to. Should it be done the same way, ie. via
> os. calls or perhaps by way of a popen or ... ?

Mac OS X 10.5 comes with a Python "xattr" package pre-installed, which
the xattr command-line utility is built on top of.  Furthermore, the
resource fork can be accessed as an extended attribute
(xattr.XATTR_RESOURCEFORK_NAME).  This might also be true of Mac OS X
10.4, but I don't recall for sure and I don't have access to it to
check.

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


Wanted: python script to convert to/from UTF-8 to/from XML Entities

2008-08-30 Thread Siegfried Heintze
Does someone have a little python script that will read a file in 
UTF-8/UTF-16/UTF-32 (my choice) and search for all the characters between 
0x7f-0xff and convert them to an ASCII digit string that begins with 
"&#" and ends with ";" and output the whole thing? If not, could someone 
tell me how to write one?

How about a script to do the inverse?

Thanks!
siegfried 


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


Re: Wanted: python script to convert to/from UTF-8 to/from XML Entities

2008-08-30 Thread Fredrik Lundh

Siegfried Heintze wrote:

Does someone have a little python script that will read a file in 
UTF-8/UTF-16/UTF-32 (my choice) and search for all the characters between 
0x7f-0xff and convert them to an ASCII digit string that begins with 
"&#" and ends with ";" and output the whole thing? If not, could someone 
tell me how to write one?


file = open("filename.txt", "rb")
text = file.read()
text = unicode(text, "utf-8")
text = text.encode("ascii", "xmlcharrefreplace")
print text

tweak as necessary.



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


Re: Which is faster?

2008-08-30 Thread Lie
On Aug 30, 5:30 pm, cnb <[EMAIL PROTECTED]> wrote:
> how does doing something twice not change complexity? yes it maybe
> belongs to the same complexity-class but is still twice as slow no?

Who is doing something twice? Definitely not sum().

sum() does not create intermediate list, and if you pass generator
expressions in it you wouldn't make any intermediate list at all, thus
simple looping but in interpreter code. sum() that is passed a list
comprehension should be faster for extremely small numbers of values
to sum, but we don't care about small things, do we? But using
intermediate list should be fast enough for even large numbers of
values, the time when it can't cope anymore would be when the
intermediate list takes half of your memory (how often is that for
regular applications?).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Most pythonic way of weighted random selection

2008-08-30 Thread bearophileHUGS
Manuel Ebert, this may be related/useful:
http://code.activestate.com/recipes/498229/

Note that numpy has a bisection method/function that are probably
quite faster.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which is faster?

2008-08-30 Thread Fredrik Lundh

Lie wrote:


how does doing something twice not change complexity? yes it maybe
belongs to the same complexity-class but is still twice as slow no?


Who is doing something twice? Definitely not sum().


nobody's claiming that -- but as mentioned above, even if sum() had done 
two passes over the source sequence, it'd still be O(n).




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


Re: Advice on the style to use in imports

2008-08-30 Thread Marco Bizzarri
Hi bearophile

On Sat, Aug 30, 2008 at 4:04 PM,  <[EMAIL PROTECTED]> wrote:


>
> from somemodule import somename
>
> is often acceptable IHMO, but there are some things to consider:
> - you and the person that reads your code have to remember where
> somename comes from. So you can do it for well known names like izip
> or imap, but if you import lots of names from lots of modules, things
> may become too much complex. So often it can be better to import just
> the modules, and use somemodule.somename.

Yes, that's true; but when I see that I need so many symbols from
another module, I take that as an hint that either my module is doing
too many things, and it should be splitted, or it is tightly coupled
to that module... actually, being forced to write all the imports in
that way was a tool into inspecting the dependencies in our project.

> - somemodule.somename is longer to write and to read, and if it's
> repeated many times it may worsen the program readability, making
> lines of code and expressions too much long and heavy. So you have to
> use your brain (this means that you may have to avoid standard
> solutions). Note that you can use a compromise, shortening the module
> name like this:
> import somemodule as sm
> Then you can use:
> sm.somename

it is not a problem to have special cases, as long as they are
"special"; I'm looking for more or less accepted solutions; of course
any project has some area where it is better to follow readability
over standards; I'm just trying to understand the standards, then I
will deviate from them.

I feel like I'm learning to drive: first I learn the rules, then I
learn the exceptions ;)

> - somemodule.somename requires an extra lookup, so in long tight loops

The slowdown was what in the first place made me import all the names
directly; but I'm not afraid too much from that, right now.


> (if you don't use Psyco) it slows down the code. This can be solved
> locally, assigning a local name into a function/method (or even in
> their argument list, but that's a hack to be used only once in a
> while):
> localname = somemodule.somename
>
> Bye,
> bearophile
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks again for sharing your thoughts with me, bearophile.


-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
http://notenotturne.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Advice on the style to use in imports

2008-08-30 Thread Marco Bizzarri
On Sat, Aug 30, 2008 at 4:53 PM, Eric Wertman <[EMAIL PROTECTED]> wrote:
>> I read the PEP8 and the "importing Python Modules" article. However,
>> I'm still a little confused on what should the general rules for
>> importing modules.
>>
>> I'm showing what I used in my current project, and will accept your
>> advices on how I should change them.
>
>> import module
>>
>> and then use
>>
>> module.MyClass
>>
>> ( in case of a flat module)
>>
>> or
>>
>> from package.subpackage import module
>>
>> and then use
>>
>> module.MyClass
>>
>> (( for a package/subpackage structure ))
>
> My opinion is that this is the preffered way, generally speaking.  Not
> only does it avoid namespace issues as effbot pointed out, but it also
> makes code easier to read later.  As examples, I tend to break those
> rules frequently with these :
>
> from pprint import pprint  # Because pprint.pprint is just redundant
> from lxml import etree # Actually I guess this doesn't break the rule.
> from datetime import datetime  # This might be a bad idea... I haven't
> had problems yet though.  datetime.datetime gets on my nerves though.
>
> just my .02
>
> Eric
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks Eric; your 02 cents are worthy for me ;)

Regards
Marco



-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
http://notenotturne.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Date Comparison and Manipulation Functions?

2008-08-30 Thread W. eWatson

W. eWatson wrote:

John Machin wrote:

On Aug 30, 10:41 am, "W. eWatson" <[EMAIL PROTECTED]> wrote:

What I'm trying to do is adjust date-time stamped file names for date 
and

time errors. The software program collects through a period that roughly
coincides with night hours every day and according to the OS clock. It
sometimes happens that a user sets the clock to the wrong day or hour,
possibly both. Possibly even the month or year. I'm trying to allow a 
user
the opportunity to repair the problem. (Date-time stamp part of the 
name is

mmdd_hhmmss.) Correcting the date needs to be done easily and
accurately. For example, if on August 25, he mistakenly sets the date to
July 25, and discovers this problem on the real Oct. 5, he should be 
able to
shift all dates from July 25 through Sept. 5 to Aug. 25 through early 
Oct.,
allowing for day oddities in a month during the period. (I hope I got 
those
dates right; otherwise, I think you get the idea. In other words, he 
needs

to shift about 40 days of data to the correct dates.)


... all of which is absolutely nothing to do with your surprise at the
result of whatever.plus(months=6).
Really? It opened new insights for me. The example above is not the only 
correction I need to deal with. Further, the author is likely to soon 
clarify some of the date rules in the tutorial that were not obvious or 
mentioned there.


So for some period from recorded date X to recorded date Y, the
recorded dates of out of kilter by D days. X = Jul 25 2008, Y Sep 5
2008, and D is 31 (days from Jul 25 to Aug 25). All you have to do is
(pseudocode):

if X <= recorded_date <= Y:
new_recorded_date  = recorded_date.plus(days=D)

HTH,
John





Strange how my post got hooked into this side spur. I'll re-post.

--
   W. Watson
 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Re: Writing to ms excel

2008-08-30 Thread Marco Bizzarri
On Sat, Aug 30, 2008 at 4:41 PM, Marin Brkic <[EMAIL PROTECTED]> wrote:
> Hello all,
>

>
> I'm trying to find a way to write data to excel cells (or to be more
> specific to an .xls file), let's say for the sake of argument, data
> readen from a file (although it will be calculated in the process).
> I've been searching, but couldn't find any examples which allows that.

Is it suitable for you to use a python program talking with a running
instance of openoffice? in that case, pyuno could help you.


-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Date Comparison and Manipulation Functions?

2008-08-30 Thread W. eWatson

John Machin wrote:

On Aug 30, 10:41 am, "W. eWatson" <[EMAIL PROTECTED]> wrote:


What I'm trying to do is adjust date-time stamped file names for date and
time errors. The software program collects through a period that roughly
coincides with night hours every day and according to the OS clock. It
sometimes happens that a user sets the clock to the wrong day or hour,
possibly both. Possibly even the month or year. I'm trying to allow a user
the opportunity to repair the problem. (Date-time stamp part of the name is
mmdd_hhmmss.) Correcting the date needs to be done easily and
accurately. For example, if on August 25, he mistakenly sets the date to
July 25, and discovers this problem on the real Oct. 5, he should be able to
shift all dates from July 25 through Sept. 5 to Aug. 25 through early Oct.,
allowing for day oddities in a month during the period. (I hope I got those
dates right; otherwise, I think you get the idea. In other words, he needs
to shift about 40 days of data to the correct dates.)


... all of which is absolutely nothing to do with your surprise at the
result of whatever.plus(months=6).
Really? It opened new insights for me. The example above is not the only 
correction I need to deal with. Further, the author is likely to soon 
clarify some of the date rules in the tutorial that were not obvious nor 
mentioned there.


So for some period from recorded date X to recorded date Y, the
recorded dates of out of kilter by D days. X = Jul 25 2008, Y Sep 5
2008, and D is 31 (days from Jul 25 to Aug 25). All you have to do is
(pseudocode):

if X <= recorded_date <= Y:
new_recorded_date  = recorded_date.plus(days=D)

HTH,
John




--
   W. Watson
 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Counting Elements in an xml file

2008-08-30 Thread Ouray Viney
Hi All:

I am looking at writing a python script that will let me parse a
TestSuite xml file that contains n number of TestCases.

My goal is to be able to count the  elements base on a key
value pair in the xml node.

Example



I would like to be able to count the number of TestCases that contain
the "execute=true" but not the ones that contain "execute=false".

I have review the python docs and various python ebooks.

Does anyone have any experience with this sort of thing?  If so, could
you suggest a good library and possibly some samples?

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


Re: Date Comparison and Manipulation Functions?

2008-08-30 Thread W. eWatson

The author has updated the Tutorial and added a flex method.

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


Re: Counting Elements in an xml file

2008-08-30 Thread Marco Bizzarri
On Sat, Aug 30, 2008 at 7:37 PM, Ouray Viney <[EMAIL PROTECTED]> wrote:
> Hi All:
>
> I am looking at writing a python script that will let me parse a
> TestSuite xml file that contains n number of TestCases.
>
> My goal is to be able to count the  elements base on a key
> value pair in the xml node.
>
> Example
>
> 
>
> I would like to be able to count the number of TestCases that contain
> the "execute=true" but not the ones that contain "execute=false".
>
> I have review the python docs and various python ebooks.
>
> Does anyone have any experience with this sort of thing?  If so, could
> you suggest a good library and possibly some samples?

Isn't the SAX part of this howto

http://pyxml.sourceforge.net/topics/howto/xml-howto.html

enough for you to create your parser?


Regards
Marco

-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
http://notenotturne.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Counting Elements in an xml file

2008-08-30 Thread Fredrik Lundh

Ouray Viney wrote:


I am looking at writing a python script that will let me parse a
TestSuite xml file that contains n number of TestCases.

My goal is to be able to count the  elements base on a key
value pair in the xml node.

Example



I would like to be able to count the number of TestCases that contain
the "execute=true" but not the ones that contain "execute=false".


import xml.etree.ElementTree as ET

tree = ET.parse("filename.xml")

count = 0

for elem in tree.findall(".//Testcase"):
if elem.get("execute") == "true":
count += 1

print "found", count, "test cases"

# tweak as necessary



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


Re: Tkinter event loop question

2008-08-30 Thread gordon
On Aug 29, 10:46 pm, "Russell E. Owen" <[EMAIL PROTECTED]> wrote:
you
> can safely compute stuff with a background thread and display it from> the 
> main thread). But cross that bridge later.>
> -- Russell

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


Importing module with name given as a variable

2008-08-30 Thread Sean Davis
What is the "best practice" for importing an arbitrary module given
that the name is stored in a variable?  The context is a simple web
application with URL dispatching to a module and function.  I know of
__import__(), the imp module, and exec.  For each of these, is there a
way to make them work "just like" the normal import call?

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


Re: Counting Elements in an xml file

2008-08-30 Thread Paul Boddie
On 30 Aug, 19:37, Ouray Viney <[EMAIL PROTECTED]> wrote:
>
> 
>
> I would like to be able to count the number of TestCases that contain
> the "execute=true" but not the ones that contain "execute=false".

With XPath-capable libraries, it should be enough to execute an XPath
query on the document. For example:

  import libxml2dom
  d = libxml2dom.parse(filename)
  number_of_cases = d.xpath("count(//[EMAIL PROTECTED]'true'])")

This applies the XPath count function to all Testcase elements in the
document having an execute attribute with a value of 'true', thus
returning the number of matching elements.

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


Relative imports and "import X as Y"

2008-08-30 Thread OKB (not okblacke)
I was looking at PEP 328.  It says that relative imports with the 
dot syntax will only be allowed with the "from" import variety (e.g., 
"from ..somemodule import somename").  The reason given for this in the 
PEP is that after import xxx.yyy, "xxx.yyy" is usable in an expression, 
but the leading period syntax is inconsistent with this (you can't use 
".somepackage.somemodule" in an expression).

However, this reasoning doesn't apply to "import X as Y", as long 
as Y is an ordinary name.  As a few recent posts here have touched on, 
there are actual differences between the "import X (as Y)" and "from X 
import name" varieties, most notably that the second form binds name in 
the importing namespace whereas the first does not.

So, will relative imports in Python 3.0 allow things like "import 
..relative.importing.path as prettyname"?  If not, why not?

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
--
http://mail.python.org/mailman/listinfo/python-list


Customizing code.InteractiveConsole

2008-08-30 Thread Leonhard Vogt

Hello

I have subclassed code.InteractiveInterpreter for testing
an "interpreter" i have written myself.

The interpreter is a function (evaluate) that can raise
MyError exceptions. I want these to be reported with an
indication of the position (^) as in the python interactive
interpreter.

The code below does this, but I don't like the raise-catch
of the syntax error before using self.showsyntaxerror().
How could I improve this? Should I subclass from SyntaxError?

The other thing is that the ^ is shown to the left of the
faulty character, I could easily correct that, but why is this?


Leo


import code

class MyError(Exception):
def __init__(self, msg, pos):
Exception.__init__(self, msg)
self.pos = pos

def evaluate(source):
for (pos,c) in enumerate(source):
if not c in "0123456789":
raise MyError("Unexpected Symbol %s" % c, pos)
return int(source)

class MyConsole(code.InteractiveConsole):
def raw_input(self, prompt):
return code.InteractiveConsole.raw_input(self, 'abc '+prompt)

def runsource(self, source, filename=''):
try:
print evaluate(source)
except MyError, e:
try:
se = SyntaxError(str(e), ('', 1, e.pos, source))
raise se
except:
self.showsyntaxerror()


if __name__ == '__main__':
MyConsole().interact()

===
And here what it shows on the console:


[EMAIL PROTECTED]:~/mypy$ python cons.py
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(MyConsole)
abc >>> 1234
1234
abc >>> 12e4
  File "", line 1
12e4
 ^
SyntaxError: Unexpected Symbol e
abc >>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Importing module with name given as a variable

2008-08-30 Thread Wojtek Walczak
On Sat, 30 Aug 2008 11:02:03 -0700 (PDT), Sean Davis wrote:
> What is the "best practice" for importing an arbitrary module given
> that the name is stored in a variable?  The context is a simple web
> application with URL dispatching to a module and function.  I know of
> __import__(), the imp module, and exec.  For each of these, is there a
> way to make them work "just like" the normal import call?

It all depends on your needs. If you have to deal with user
input to get the name of the module, better use __import__
than exec. __import__ works just like the normal import call:

import sys

is equal to:

sys = __import__('sys')

If you need, let's say, to search for a module that lies
outside sys.module paths, then use imp's functions.

HTH.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Advice on the style to use in imports

2008-08-30 Thread Bruno Desthuilliers

Marco Bizzarri a écrit :

Hi all.

I read the PEP8 and the "importing Python Modules" article. However,
I'm still a little confused on what should the general rules for
importing modules.

I'm showing what I used in my current project, and will accept your
advices on how I should change them.

The style is consistently the following:

from package.subpackge.module import MyClass

Is this an accepted way to write imports?


Yes, BUT : it means that if package.subpackge.module.MyClass is rebound 
during program execution (ie: after you imported it), your own code 
won't see that change.



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


Re: Importing module with name given as a variable

2008-08-30 Thread Bruno Desthuilliers

Sean Davis a écrit :

What is the "best practice" for importing an arbitrary module given
that the name is stored in a variable?  The context is a simple web
application with URL dispatching to a module and function.  I know of
__import__(), the imp module, and exec.  For each of these, is there a
way to make them work "just like" the normal import call?


IIRC, this is documented in the __import__ function's doc.

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


Re: When to use try and except?

2008-08-30 Thread Carl Banks
On Aug 30, 2:03 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Carl Banks wrote:
> > I wouldn't say that the possibility of EAFP in Python makes it
> > obsolute to use LBYL.
>
> when using CPython, EAFP at the Python level always involve LBYL at the
> C level.

I don't think that's true.  For example, here is the code that
actually opens a file within the open() function:

if (NULL == f->f_fp && NULL != name) {
Py_BEGIN_ALLOW_THREADS
f->f_fp = fopen(name, newmode);
Py_END_ALLOW_THREADS
}

if (f->f_fp == NULL) {

Clearly it tries to open the file, and handles the error if it fails.
EAFP, even though it wasn't using an exception.

Of course, underneath fopen there could be LBYL somewhere, but that's
at either the the system library level or the OS level.  Perhaps it's
part of what you meant by C level, since those guys probably are
written in C.

But then I still don't think we call say LBYP *always* occurs at the C
level, since in some cases the library and system calls that Python
wraps rely on processor exceptions and stuff like that.  Which means
any LBYPing is going on inside the CPU, so it's at the hardware level.

I realize all of this is tangential to your point.


> and it should be obvious to any programmer that checking for
> the same thing twice is quite often a waste of time and resources.

Well if there's a section where performance is important I'd use
EAFP.  It's no big deal.


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


Re: Writing to ms excel

2008-08-30 Thread Leonhard Vogt

Marin Brkic schrieb:

I'm trying to find a way to write data to excel cells (or to be more
specific to an .xls file), let's say for the sake of argument, data
readen from a file (although it will be calculated in the process).
I've been searching, but couldn't find any examples which allows that.


If you have Excel installed you can use COM to access Excel and to
"remote-control" it in order to save a .xls file.

I have no Windows nor Excel at the moment, so I can only write something
approximative. Searching for win32com will help.

win32com.Coinitialize(...)
excel = win32com.client.Dispatch("Excel.Application")
wbook = excel.NewDocument()
sheet = wbook.Worksheets("Sheet1")
sheet.Cells(1,1) = "Abc"
wbook.Saveas("filename")
excel.close() or destroy()
win32com.coUninitialize()

The objects available are very similar to the VBA objects, so recording
a macro and translating its VBA source to python should not be hard.

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


Re: Writing to ms excel

2008-08-30 Thread Tino Wildenhain

Marin Brkic wrote:

Hello all,

please, let me apologize in advance. English is not my first language
(not even my second one), so excuse any errors with which I'm about to
embarass myself in front of the general public. Second, I'm relatively
new to python, so sorry if this seems like a stupid question.

I'm trying to find a way to write data to excel cells (or to be more
specific to an .xls file), let's say for the sake of argument, data
readen from a file (although it will be calculated in the process).
I've been searching, but couldn't find any examples which allows that.

Do anyone knows of any ? All help is appreciated on this matter.
Tutorials? Anything ...


Its quite easy, a little googling brings:

http://sourceforge.net/projects/pyexcelerator

which comes with examples and all. Works on any platform (python
only code). I'm using it to generate excel reports for all the
damnd ms office adicts in the company...

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Writing to ms excel

2008-08-30 Thread Tino Wildenhain

Marin Brkic wrote:

Hello all,

please, let me apologize in advance. English is not my first language
(not even my second one), so excuse any errors with which I'm about to
embarass myself in front of the general public. Second, I'm relatively
new to python, so sorry if this seems like a stupid question.

I'm trying to find a way to write data to excel cells (or to be more
specific to an .xls file), let's say for the sake of argument, data
readen from a file (although it will be calculated in the process).
I've been searching, but couldn't find any examples which allows that.

Do anyone knows of any ? All help is appreciated on this matter.
Tutorials? Anything ...


Its quite easy, a little googling brings:

http://sourceforge.net/projects/pyexcelerator

which comes with examples and all. Works on any platform (python
only code). I'm using it to generate excel reports for all the
damnd ms office adicts in the company...

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Counting Elements in an xml file

2008-08-30 Thread Ouray Viney
On Aug 30, 2:17 pm, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 30 Aug, 19:37, Ouray Viney <[EMAIL PROTECTED]> wrote:
>
>
>
> > 
>
> > I would like to be able to count the number of TestCases that contain
> > the "execute=true" but not the ones that contain "execute=false".
>
> With XPath-capable libraries, it should be enough to execute an XPath
> query on the document. For example:
>
>   import libxml2dom
>   d = libxml2dom.parse(filename)
>   number_of_cases = d.xpath("count(//[EMAIL PROTECTED]'true'])")
>
> This applies the XPath count function to all Testcase elements in the
> document having an execute attribute with a value of 'true', thus
> returning the number of matching elements.
>
> Paul

Hi All:

Thank you very much for all your valuable input.  All the examples
provided are exactly what I need to get started.

Enjoy the long weekend (for those in North America).

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


Re: Relative imports and "import X as Y"

2008-08-30 Thread Terry Reedy


	So, will relative imports in Python 3.0 allow things like "import 
..relative.importing.path as prettyname"?  If not, why not?


Download the latest beta for your system and give it a try.

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


Re: Writing to ms excel

2008-08-30 Thread Ken Starks

Marin Brkic wrote:

Hello all,

please, let me apologize in advance. English is not my first language
(not even my second one), so excuse any errors with which I'm about to
embarass myself in front of the general public. Second, I'm relatively
new to python, so sorry if this seems like a stupid question.

I'm trying to find a way to write data to excel cells (or to be more
specific to an .xls file), let's say for the sake of argument, data
readen from a file (although it will be calculated in the process).
I've been searching, but couldn't find any examples which allows that.

Do anyone knows of any ? All help is appreciated on this matter.
Tutorials? Anything ...


Best regards
Marin


Not specific to python, but if you have a recent version of excel, you
could write to the Excel xml format (if not, you could consider
the (or one of the) gnumeric xml formats.


The Excel format is verbose, but you can copy and paste most of it.
The critical bit you need your software to write looks
something like this:


 
  x:FullColumns="1"

   x:FullRows="1">
   
number
square
   
   
1
1
   
   
2
4
   
   
3
9
   
   
4
16
   
  
  
   
   

 3
 5
 1

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


Re: Which is faster?

2008-08-30 Thread Raymond Hettinger
On Aug 29, 9:26 pm, cnb <[EMAIL PROTECTED]> wrote:
> def av_grade(self):
>      return sum(review.grade for review in self.reviews) / \
>               len(self.reviews)

Minor point.  Consider making the divisor:  float(len(self.reviews)).
It would be a bummer to throw-off the average because of floor
division.

Also consider an itertools approach:
sum(itertools.imap(operator.itemgetter('review'), self.reviews))

BTW, the sum() in Py2.6 is *much* faster than before.  It should run
circles around any other approach.

As Effbot says, if you really care about speed, then just time both
approaches.  However, it's a good run of thumb that builtins are hard
to beat by simulating them in pure python (unless you're using Psyco
as an optimizer).


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


Re: Most pythonic way of weighted random selection

2008-08-30 Thread duncan smith
Manuel Ebert wrote:
> Dear list,
> 
> who's got aesthetic advice for the following problem? I've got some
> joint probabilities of two distinct events Pr(X=x, Y=y), stored in a
> list of lists of floats, where every row represents a possible outcome
> of X and every float in a row a possible outcome of Y (which I will now
> call my matrix, altough I can't use numpy or numeric for this), so e.g.
> m = [[0.2, 0.4, 0.05], [0.1, 0.05, 0.2]]. All lists in the list are
> equally long and the values of the flattened list add up to 1.0, i.e.
> sum([sum(row) for row in m]) == 1. In practice, this 'matrix' is about
> 20x40, i.e. a list with 20 lists á 40 floats each.
> 
> Now the task is to select one outcome for X and Y based on the joint
> probabilites, and afterwards check that the outcomes fullfill certain
> criteria. If it doesn't fulfill some criteria a new pair of outcomes has
> to be selected, for other criteria it will still be selected with a
> certain probability. My approach was to choose a random number, and then
> walk through the list adding the values together until the accumulated
> sum is greater than my random threshold:
> 

[snip]

For a list of cumulative probabilities you could use the bisect module
to find the insertion point for a 0,1 uniform variate (which you could
then map back to a cell index).

Alternatively you could use an alias table,
http://amath.colorado.edu/courses/7400/2004fall/002/Web/SS-10.ppt.

You could produce a probability table that takes into account your
criteria, so that you don't need to check them.  i.e. Each cell that
does not satisfy criterion a has probability 0 of being selected.  Each
other cell has a probability of being selected proportional to its
original value if it satisfies criterion b, or its original value * p
otherwise.  Normalise the resulting values to sum to 1 and you're done
with the need to check against criteria.

So, preprocess your table, create a corresponding list of cumulative
probabilities and use the bisect model (is one possibility).

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


Re: Writing to ms excel

2008-08-30 Thread John Machin
On Aug 31, 12:41 am, Marin Brkic <[EMAIL PROTECTED]> wrote:
>
> I'm trying to find a way to write data to excel cells (or to be more
> specific to an .xls file), let's say for the sake of argument, data
> readen from a file (although it will be calculated in the process).
> I've been searching, but couldn't find any examples which allows that.
>
> Do anyone knows of any ? All help is appreciated on this matter.
> Tutorials? Anything ...

It helps in situations like this to mention details of your
environment
(1) what version of what operating system (Linux, OS X, Windows, etc)
(2) what version of Python
as the available solutions are often dependent on the answers.

For Python version 2.[345] on any platform, you can use xlwt, which is
as simple as this for writing a 1-worksheet Excel 97-to-2003 XLS file
(without any formatting):

def write_xls(file_name, sheet_name, data):
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet(sheet_name)
rowx = 0
for row in data:
rowx += 1
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
book.save(file_name)
# data can be any of the following Python types: int, long, float,
decimal.Decimal, datetime.date, datetime.datetime, bool, str, and
unicode.

xlwt is available from https://secure.simplistix.co.uk/svn/xlwt/trunk

I suggest that you join the python-excel group (http://
groups.google.com.au/group/python-excel?hl=en) or at least read some
of the questions and responses.

HTH,

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


Re: Which is faster?

2008-08-30 Thread Steven D'Aprano
On Sat, 30 Aug 2008 04:11:33 -0300, Gabriel Genellina wrote:

> Mmm, in this last test you're measuring the long integer operations
> performance (because the sum exceeds largely what can be represented in
> a plain integer). Long integers are so slow that the difference between
> both loops becomes negligible.

Nicely caught, and thank you for pointing that out.


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


Re: Writing to ms excel

2008-08-30 Thread John Machin
On Aug 31, 12:57 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
> If you have
> to interface with an exsisting excel file, you can try 
> http://pypi.python.org/pypi/xlrd, but it may not support writing xls
> files, still.

That remark appears to be an inverted cousin of the old joke question
"Have you stopped beating your wife?" :-)

xlrd is still doing what it was designed to do: read (not "interface
with") Excel xls files. There is a currently active project to add
support for reading the xlsx (x=XML) files produced by Excel 2007.
This may be followed by Excel 2007 xlsb (b=binary) files and
OpenOffice ods files. Writing is not on the agenda.

Cheers,
John

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


SAXReaderNotAvailble: No parsers found

2008-08-30 Thread josh logan
> Vincent Yau <[EMAIL PROTECTED]> writes:
> > I am trying to use Python SAX API to parse XML files.  I do see expat.py
> > somewhere underneath my Python 2.1.1 installation (on Solaris).
> > But I got this error when invoking the xml.sax.make_parser() call.  Any
> > tip/help much appreciated.
>
> You should install Expat before building Python. Best, you edit
> Modules/Setup to build pyexpat explicitly.
>
> Regards,
> Martin

Fast-forward to 2008

I installed Python 3.0b2 on a Windows Vista laptop (after having
previously installed Python 2.5), and I am getting this same error:

Traceback (most recent call last):
  File "Programming\Python\monkeys.py", line 24, in 
test_parse(sys.argv[1])
  File "Programming\Python\monkeys.py", line 21, in test_parse
xml.sax.parse(f, handler)
  File "C:\Python30\lib\xml\sax\__init__.py", line 30, in parse
parser = make_parser()
  File "C:\Python30\lib\xml\sax\__init__.py", line 90, in make_parser
raise SAXReaderNotAvailable("No parsers found", None)
xml.sax._exceptions.SAXReaderNotAvailable: No parsers found

I see a pyexpat.lib in the C:\Python30\libs folder.
I also see a pyexpat.pyd in the C:\Python30\DLLs folder.

It works in Python 2.5. I installed Python 3.0b2 as admin.
Does anyone know what is wrong and how to fix it?

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


Re: starting gazpacho on windows

2008-08-30 Thread Alan Franzoni
nntpman68 was kind enough to say:

[cut]

I didn't check, but if c:\python25 is your python install dir, you'll very
likely find it in c:\python2.5\bin or c:\python25\scripts.


-- 
Alan Franzoni <[EMAIL PROTECTED]>
-
Remove .xyz from my email in order to contact me.
-
GPG Key Fingerprint:
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to ms excel

2008-08-30 Thread Eric Wertman
Yes sorry, that's a really poorly formed sentence all the way
around... not a dig on xlrd, but a warning to the OP that they may not
find what they are looking for there.


> On Aug 31, 12:57 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
>> If you have
>> to interface with an exsisting excel file, you can try 
>> http://pypi.python.org/pypi/xlrd, but it may not support writing xls
>> files, still.
>
> That remark appears to be an inverted cousin of the old joke question
> "Have you stopped beating your wife?" :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to ms excel

2008-08-30 Thread Marin Brkic
On Sat, 30 Aug 2008 17:18:19 -0700 (PDT), John Machin
<[EMAIL PROTECTED]> wrote:


Hello John (and everyone else), thanks for answering.

>It helps in situations like this to mention details of your
>environment
>(1) what version of what operating system (Linux, OS X, Windows, etc)
>(2) what version of Python
>as the available solutions are often dependent on the answers.

Yes, of course. I sometimes forget the most essential of things.
- winxp, sp2
- python 2.5.2

>
>For Python version 2.[345] on any platform, you can use xlwt, which is
>as simple as this for writing a 1-worksheet Excel 97-to-2003 XLS file
>(without any formatting):

Actually, that might work. What I was needing (aiming for) was a way
to write to excel 2003 files. Formatting is not necessary, since what
I'm trying to write is some tabular data; results from fortran-python
simulation (I can explain, but the details seem irrelevant for this
case).
I'm trying to avoid the text file - import to excel - mechanism, since
there is quite a lot of files written.
>
>def write_xls(file_name, sheet_name, data):
>import xlwt
>book = xlwt.Workbook()
>sheet = book.add_sheet(sheet_name)
>rowx = 0
>for row in data:
>rowx += 1
>for colx, value in enumerate(row):
>sheet.write(rowx, colx, value)
>book.save(file_name)
># data can be any of the following Python types: int, long, float,
>decimal.Decimal, datetime.date, datetime.datetime, bool, str, and
>unicode.
>
>xlwt is available from https://secure.simplistix.co.uk/svn/xlwt/trunk
>
>I suggest that you join the python-excel group (http://
>groups.google.com.au/group/python-excel?hl=en) or at least read some
>of the questions and responses.

Please, one more question. As you have noticed, I posted my message to
comp.lang.python, using a newsreader. Is there a way to access google
groups through a similiar interface program as a newsreader. Never
used them before, and getting a lot of messages to my email every day
does not sound very appealing to me.

Best regards
Marin

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


Re: Writing to ms excel

2008-08-30 Thread Marin Brkic
On Sat, 30 Aug 2008 19:37:16 +0200, "Marco Bizzarri"
<[EMAIL PROTECTED]> wrote:

>
>Is it suitable for you to use a python program talking with a running
>instance of openoffice? in that case, pyuno could help you.

Hello Marco, thanks for answering,

no, sorry. As much as I like OOffice, several other people will be
using the program I'm working on, and I can't cound on them having the
OOffice installed.
MS, as much as I hate to admit it, is the industry standard (or, at
least that's the one we're stuck with at the present time ;-)





Best regards
Marin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to ms excel

2008-08-30 Thread Marin Brkic
On Sun, 31 Aug 2008 03:36:39 +0200, Marin Brkic
<[EMAIL PROTECTED]> wrote:

>On Sat, 30 Aug 2008 19:37:16 +0200, "Marco Bizzarri"
><[EMAIL PROTECTED]> wrote:
>
>>
>>Is it suitable for you to use a python program talking with a running
>>instance of openoffice? in that case, pyuno could help you.
>
>Hello Marco, thanks for answering,
>
>no, sorry. As much as I like OOffice, several other people will be
>using the program I'm working on, and I can't cound on them having the
*count*
--
http://mail.python.org/mailman/listinfo/python-list


Re: Most pythonic way of weighted random selection

2008-08-30 Thread Steven D'Aprano
On Sat, 30 Aug 2008 17:41:27 +0200, Manuel Ebert wrote:

> Dear list,
> 
> who's got aesthetic advice for the following problem? 

...

[ugly code removed]
> Now that looks plain ugly, and I wonder whether you might find a
> slightly more elegant way of doing it without using numpy and the like.

Never be afraid to factor out pieces of code into small functions. 
Writing a single huge while loop that does everything is not only hard to 
read, hard to write and hard to debug, but it can also run slower. (It 
depends on a number of factors.) 

Anyway, here's my attempt to solve the problem, as best as I can 
understand it:


import random

def eq(x, y, tol=1e-10):
# floating point equality within some tolerance
return abs(x-y) <= tol

M = [[0.2, 0.4, 0.05], [0.1, 0.05, 0.2]]
# the sums of each row must sum to 1.0
assert eq(1.0, sum([sum(row) for row in M]))

# build a cumulative probability matrix
CM = []
for row in M:
for p in row:
CM.append(p)  # initialize with the raw probabilities

for i in range(1, len(CM)):
CM[i] += CM[i-1]  # and turn into cumulative probabilities

assert CM[0] >= 0.0
assert eq(CM[-1], 1.0)

def index(data, p):
"""Return the index of the item in data
which is no smaller than float p.
"""
# Note: this uses a linear search. If it is too slow,
# you can re-write it using the bisect module.
for i, x in enumerate(data):
if x >= p:
return i
return len(data-1)

def index_to_rowcolumn(i, num_columns):
"""Convert a linear index number i into a (row, column) tuple."""
# When converting [ [a, b, c, ...], [...] ] into a single
# array [a, b, c, ... z] we have the identity:
# index number = row number * number of columns + column number
return divmod(i, num_columns)

# Now with these two helper functions, we can find the row and column 
# number of the first entry in M where the cumulative probability 
# exceeds some given value.

# You will need to define your own fulfills_criterion_a and
# fulfills_criterion_b, but here's a couple of mock functions 
# for testing with:

def fulfills_criterion_a(row, column):
return random.random() < 0.5

fulfills_criterion_b = fulfills_criterion_a

def find_match(p=0.2):
while True:
r = random.random()
i = index(CM, r)
row, column = index_to_rowcolumn(i, len(M[0]))
if fulfills_criterion_a(row, column) or \
fulfills_criterion_b(row, column):
return row, column
else:
if random.random() <= p:
return row, column


And here's my test:

>>> find_match()
(1, 2)


Hope this helps.


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


Re: Writing to ms excel

2008-08-30 Thread Steven D'Aprano
On Sun, 31 Aug 2008 03:36:39 +0200, Marin Brkic wrote:

> On Sat, 30 Aug 2008 19:37:16 +0200, "Marco Bizzarri"
> <[EMAIL PROTECTED]> wrote:
> 
> 
>>Is it suitable for you to use a python program talking with a running
>>instance of openoffice? in that case, pyuno could help you.
> 
> Hello Marco, thanks for answering,
> 
> no, sorry. As much as I like OOffice, several other people will be using
> the program I'm working on, and I can't cound on them having the OOffice
> installed.

Of course you can. You could simply tell them that you need the 
programming interface to OpenOffice and that's the format you will be 
supplying the data. If they want your data, they will use what you tell 
them to use *if you give them no choice*.

If they want your data, most people will just accept that OpenOffice is a 
strange mysterious programming requirement, like all the other strange 
mysterious things programmers and sys admins install on their PC. The 
requirements are "a computer, Python and OpenOffice" instead of "a 
computer and Python".

If there are exceptions who know enough to insist that Excel can do 
everything OpenOffice can do (more or less), and they don't want to use 
OpenOffice, then don't argue. Just say that you're working on support for 
Excel, but it will take a few weeks, but as a temporary measure they can 
use OpenOffice until the code is ready. You will be *amazed* at how much 
people will accept change if you tell them it's only temporary.

You might even discover that by the time Excel support is ready, they 
will prefer OpenOffice.



> MS, as much as I hate to admit it, is the industry standard (or, at
> least that's the one we're stuck with at the present time ;-)

Only because we treat it as standard. You had no hesitation to write code 
that relies on people having Excel installed, and yet you didn't want to 
rely on an open source free software package that anyone with a fast 
Internet connection or a CD drive can install in just a couple of 
minutes. You don't even need to reboot the PC.



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


Re: Writing to ms excel

2008-08-30 Thread Marin Brkic
On 31 Aug 2008 02:37:16 GMT, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
>
>Of course you can. You could simply tell them that you need the 
>programming interface to OpenOffice and that's the format you will be 
>supplying the data. If they want your data, they will use what you tell 
>them to use *if you give them no choice*.
>
>If they want your data, most people will just accept that OpenOffice is a 
>strange mysterious programming requirement, like all the other strange 
>mysterious things programmers and sys admins install on their PC. The 
>requirements are "a computer, Python and OpenOffice" instead of "a 
>computer and Python".
>
>If there are exceptions who know enough to insist that Excel can do 
>everything OpenOffice can do (more or less), and they don't want to use 
>OpenOffice, then don't argue. Just say that you're working on support for 
>Excel, but it will take a few weeks, but as a temporary measure they can 
>use OpenOffice until the code is ready. You will be *amazed* at how much 
>people will accept change if you tell them it's only temporary.
>
>You might even discover that by the time Excel support is ready, they 
>will prefer OpenOffice.
>
>
>
>> MS, as much as I hate to admit it, is the industry standard (or, at
>> least that's the one we're stuck with at the present time ;-)
>
>Only because we treat it as standard. You had no hesitation to write code 
>that relies on people having Excel installed, and yet you didn't want to 
>rely on an open source free software package that anyone with a fast 
>Internet connection or a CD drive can install in just a couple of 
>minutes. You don't even need to reboot the PC.

As much as a lot of the above is true, and I agree with some of it,
things are not more often than not that simple. It would be true if I
was, for example, working in a private owned company where we could
choose what we use, install our own stuff, have liberties and people
generally interested in learning new software and ... that approach.

On the other hand, when you work in an institution that has people
with their own problems (technical, but not computer related) - on
which they want to spend their time, and not installing and adapting
to new software solutions; when you have system engineers who decide
what you use, and generally who maintain the computers we work on, and
when all licences are gotten and sponsored by someone else, ... then,
well, then it's a little different situation.
Rules exist - exceptions can be made, and are made if there is a need
for them, but switching to open office just for me, when everyone has
gotten used to this one, and ... well, let's just say that one's not
going to be on the exception list :-)

I remember an older coleague who said; "open, free and whatever
licence type ...  software is free, only up to some amount of $$/per
hour". After that you just want things to work, and if they don't
work, there are people who are paid $/per hour to make it work.
And generally, when you look at the industry sector, ms IS the
standard - not because we treat it, but because for now, it just is.
When OOffice is used by 60% of all people I deal with, then maybe it
will be the standard.
Sorry for a little rough-but-straight-to-the-point-explanation, but
it's usually the quickest way to deal with
free-vs-commercial-starting-to-arise-flame-war :) which usually
happens after a post like this. 

Best regards
Marin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to ms excel

2008-08-30 Thread Benjamin Kaplan
On Sat, Aug 30, 2008 at 9:32 PM, Marin Brkic <[EMAIL PROTECTED]>wrote:

> On Sat, 30 Aug 2008 17:18:19 -0700 (PDT), John Machin
> <[EMAIL PROTECTED]> wrote:
>
>
> Hello John (and everyone else), thanks for answering.
>
> >It helps in situations like this to mention details of your
> >environment
> >(1) what version of what operating system (Linux, OS X, Windows, etc)
> >(2) what version of Python
> >as the available solutions are often dependent on the answers.
>
> Yes, of course. I sometimes forget the most essential of things.
> - winxp, sp2
> - python 2.5.2
>
> >
> >For Python version 2.[345] on any platform, you can use xlwt, which is
> >as simple as this for writing a 1-worksheet Excel 97-to-2003 XLS file
> >(without any formatting):
>
> Actually, that might work. What I was needing (aiming for) was a way
> to write to excel 2003 files. Formatting is not necessary, since what
> I'm trying to write is some tabular data; results from fortran-python
> simulation (I can explain, but the details seem irrelevant for this
> case).
> I'm trying to avoid the text file - import to excel - mechanism, since
> there is quite a lot of files written.
> >
> >def write_xls(file_name, sheet_name, data):
> >import xlwt
> >book = xlwt.Workbook()
> >sheet = book.add_sheet(sheet_name)
> >rowx = 0
> >for row in data:
> >rowx += 1
> >for colx, value in enumerate(row):
> >sheet.write(rowx, colx, value)
> >book.save(file_name)
> ># data can be any of the following Python types: int, long, float,
> >decimal.Decimal, datetime.date, datetime.datetime, bool, str, and
> >unicode.
> >
> >xlwt is available from https://secure.simplistix.co.uk/svn/xlwt/trunk
> >
> >I suggest that you join the python-excel group (http://
> >groups.google.com.au/group/python-excel?hl=en) or at least read some
> >of the questions and responses.
>
> Please, one more question. As you have noticed, I posted my message to
> comp.lang.python, using a newsreader. Is there a way to access google
> groups through a similiar interface program as a newsreader. Never
> used them before, and getting a lot of messages to my email every day
> does not sound very appealing to me.
>
>
You can register for google groups, subscribe to the group, and go to My
Account -> Manage Subscriptions and select "No Email" for the subscription
type. That way, you can do everything (post, read, etc.) from
groups.google.com and not have to worry about filling up your email inbox.

>
> Best regards
> Marin
>
> >
> >HTH,
> >
> >John
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Mako --> Genshi

2008-08-30 Thread Chris Babcock
Is there a cheap way to convert Myghty/Mako templates to Kid/Genshi?
There's some code written for Pylons that I want to incorporate into a
TurboGears 2 project and Genshi templates are more likely to behave
themselves with the tools I'm used to.

Chris


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


Re: Writing to ms excel

2008-08-30 Thread Steven D'Aprano
On Sun, 31 Aug 2008 05:12:01 +0200, Marin Brkic wrote:

> I remember an older coleague who said; "open, free and whatever licence
> type ...  software is free, only up to some amount of $$/per hour".
> After that you just want things to work, and if they don't work, there
> are people who are paid $/per hour to make it work. 

And that applies *exactly* the same to Excel as OpenOffice, except that 
you're not paying the cost for the software and the licences and tracking 
the licences.

If you can find a package that "just works" for writing to Excel, great. 
Otherwise you have to build it yourself. And that's when you have to 
decide whether you want to spend 40 hours of programmer time (less than 
one programmer-week) trying to get write support for Excel in order to 
save two hours of support time for OpenOffice.



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


Re: Writing to ms excel

2008-08-30 Thread John Machin
On Aug 31, 11:32 am, Marin Brkic <[EMAIL PROTECTED]> wrote:
> On Sat, 30 Aug 2008 17:18:19 -0700 (PDT), John Machin
>
> <[EMAIL PROTECTED]> wrote:

> >For Python version 2.[345] on any platform, you can use xlwt, which is
> >as simple as this for writing a 1-worksheet Excel 97-to-2003 XLS file
> >(without any formatting):
>
> Actually, that might work. What I was needing (aiming for) was a way
> to write to excel 2003 files.

"write to a file" has connotations of updating an existing file;
"write a file" or "create a file" are less ambiguous.

>  Formatting is not necessary, since what
> I'm trying to write is some tabular data; results from fortran-python
> simulation (I can explain, but the details seem irrelevant for this
> case).
> I'm trying to avoid the text file - import to excel - mechanism, since
> there is quite a lot of files written.
>
> >I suggest that you join the python-excel group (http://
> >groups.google.com.au/group/python-excel?hl=en) or at least read some
> >of the questions and responses.
>
> Please, one more question. As you have noticed, I posted my message to
> comp.lang.python, using a newsreader.

I hadn't noticed; what makes you think so?

> Is there a way to access google
> groups through a similiar interface program as a newsreader.

I don't know (question has never arisen before).

>  Never
> used them before, and getting a lot of messages to my email every day
> does not sound very appealing to me.

Either (1) you have not looked at the messages at the link that I gave
you or (2) your idea of "a lot of messages" every day differs wildly
from mine. Email alternatives are (a) one message per posting (b)
daily digest (c) none (use your web browser).

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


Re: Writing to ms excel

2008-08-30 Thread John Machin
On Aug 31, 12:37 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

> Only because we treat it as standard. You had no hesitation to write code
> that relies on people having Excel installed, and yet you didn't want to
> rely on an open source free software package that anyone with a fast
> Internet connection or a CD drive can install in just a couple of
> minutes. You don't even need to reboot the PC.

Consider that there are parallel universes to yours, where big brother
severely limits access to the Internet, where staff have to sign
rather draconian agreements about their use of the company facilities,
where desktops are scanned nightly for contraband (the finding of
which will cause the brownshirts to drop in for a quick game of hands-
knees-and-bump-your-exe), where even the mention of seditious material
like OpenOffice might result in a trip to the desert provinces for re-
education ... the cause is better advanced IMHO by staying under the
radar and crawling under the wire; tub-thumping soapbox-mounting
ranters however correct and righteous are likely to suffer a fate
similar to that of Michael Servetus.

Marin is allowed to use Python; he's doing very well compared to some.

They-scrubbed-all-programming-languages-off-the-production-machine-
that's-why-I-have-csv-routines-written-in-awk-ly yours,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relative imports and "import X as Y"

2008-08-30 Thread OKB (not okblacke)
Terry Reedy wrote:

> 
>>  So, will relative imports in Python 3.0 allow things like
>>  "import 
>> ..relative.importing.path as prettyname"?  If not, why not? 
> 
> Download the latest beta for your system and give it a try.

Thanks for the advice, but I'd really rather not deal with 
installing the entire thing alongside my existing version, possibly 
causing conflicts in who knows what ways.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
--
http://mail.python.org/mailman/listinfo/python-list