Re: WebError documentation?

2009-02-07 Thread Ron Garret
In article <498de947$0$24412$426a7...@news.free.fr>,
 Bruno Desthuilliers  wrote:

> Ron Garret a écrit :
> > In article ,
> >  Chris Rebert  wrote:
> > 
> >> On Thu, Feb 5, 2009 at 12:52 PM, Ron Garret  wrote:
> >>> Is there any?  Where is it?  Extensive Googling has proven fruitless.
> >> It's not a standard Python exception. A third-party library you're
> >> using must be raising it. Check the exception traceback.
> > 
> > I see I did not make myself clear.
> 
> Now *that* is an understatement...
> 
>  >  I meant the Python software package
> > called "weberror", not a generic web error.
> > 
> > http://pypi.python.org/pypi/WebError
> 
> Google is your friend:
> http://bel-epa.com/docs/thirdparty/weberror/

Thanks!

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


Re: Python on TV-centric platforms

2009-02-07 Thread alex23
On Feb 8, 9:23 am, Vitaliy Yermolenko  wrote:
> Any chance to see Python to be ready for "Widget Development Kit (WDK)
> to third-party developers to create applications and services for
> viewing on TVs [...]

The excellent XBMC[1] has had Python support for years.

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


Re: MacPython 2.5 IDLE font size

2009-02-07 Thread Vincent Davis
There is a option menu in idle but you may not be able to see it.
Try launching idle via terminal. For me it was located
/Library/Frameworks/Python/Versions/Current/bin/idle2.5
When I did this I had the option menu, I guess this is a known bug. I assume
there is a font option once you get the menu.

Vincent Davis



On Sat, Feb 7, 2009 at 4:03 PM,  wrote:

> Hi,
> Is there a way to adjust the default font size in IDLE, in MacPython
> 2.5? The default now is too tiny.
> I have to use this version of MacPython. As far as I searched, I can't
> find how I do this.
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple web app, where to start

2009-02-07 Thread Vincent Davis
Thanks http://www.cherrypy.org/ looks like a good and simple option.
Thanks
Vincent Davis



On Sat, Feb 7, 2009 at 5:09 PM,  wrote:

> On Fri, Feb 06, 2009 at 09:16:02PM -0700, Vincent Davis wrote:
> > I have a simple script that takes a few input values and returns a csv
> file
> > and a few stats. If I wanted to host this on the web how would I. I have
> no
> > idea where to begin. If someone could point me in the right direction
> like
> > maybe a tutorial, tools I will need, functions. I would appreciate
> it.I
> > know a little html but am not sure how to integrate python or know what
> > servers will handle it .
> >
> > Thanks
> > Vincent Davis
>
> I'd suggest CherryPy[1]. It's fairly welcoming to newbies, because the
> web server and the framework and bundled together.
>
> 1: http://www.cherrypy.org/
>
> HTH,
> Nick
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


sortable table in python 3.0

2009-02-07 Thread Peter Pei
In one of my program, I used something called MultiColumnList, which is one 
of the sortable table widgets done in python. However 3.0 sort is different. 
I googled and found couple of other implementations, but all in python 
3.0 -.


Does anyone know any solution in 3.0? or anything that has already been 
upgraded to 3.0? Thanks. 


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


Re: Trouble with regular expressions

2009-02-07 Thread MRAB

John Machin wrote:

On Feb 8, 10:15 am, MRAB  wrote:

John Machin wrote:

On Feb 8, 1:37 am, MRAB  wrote:

LaundroMat wrote:

Hi,
I'm quite new to regular expressions, and I wonder if anyone here
could help me out.
I'm looking to split strings that ideally look like this: "Update: New
item (Household)" into a group.
This expression works ok: '^(Update:)?(.*)(\(.*\))$' - it returns
("Update", "New item", "(Household)")
Some strings will look like this however: "Update: New item (item)
(Household)". The expression above still does its job, as it returns
("Update", "New item (item)", "(Household)").

Not quite true; it actually returns
('Update:', ' New item (item) ', '(Household)')
However ignoring the difference in whitespace, the OP's intention is
clear. Yours returns
('Update:', ' New item ', '(item) (Household)')

The OP said it works OK, which I took to mean that the OP was OK with
the extra whitespace, which can be easily stripped off. Close enough!


As I said, the whitespace difference [between what the OP said his
regex did and what it actually does] is not the problem. The problem
is that the OP's "works OK" included (item) in the 2nd group, whereas
yours includes (item) in the 3rd group.


Ugh, right again!

That just shows what happens when I try to post while debugging! :-)


It does not work however when there is no text in parentheses (eg
"Update: new item"). How can I get the expression to return a tuple
such as ("Update:", "new item", None)?

You need to make the last group optional and also make the middle group
lazy: r'^(Update:)?(.*?)(?:(\(.*\)))?$'.

Why do you perpetuate the redundant ^ anchor?

The OP didn't say whether search() or match() was being used. With the ^
it doesn't matter.


It *does* matter. re.search() is suboptimal; after failing at the
first position, it's not smart enough to give up if the pattern has a
front anchor.

[win32, 2.6.1]
C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
*'x'" "assert not rx.match(txt)"
100 loops, best of 3: 1.17 usec per loop

C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
0*'x'" "assert not rx.match(txt)"
100 loops, best of 3: 1.17 usec per loop

C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
*'x'" "assert not rx.search(txt)"
10 loops, best of 3: 4.37 usec per loop

C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
0*'x'" "assert not rx.search(txt)"
1 loops, best of 3: 34.1 usec per loop

Corresponding figures for 3.0 are 1.02, 1.02, 3.99, and 32.9


On my PC the numbers for Python 2.6 are:

C:\Python26>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=100*'x'" "assert not rx.match(txt)"

100 loops, best of 3: 1.02 usec per loop

C:\Python26>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=1000*'x'" "assert not rx.match(txt)"

100 loops, best of 3: 1.04 usec per loop

C:\Python26>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=100*'x'" "assert not rx.search(txt)"

10 loops, best of 3: 3.69 usec per loop

C:\Python26>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=1000*'x'" "assert not rx.search(txt)"

1 loops, best of 3: 28.6 usec per loop

I'm currently working on the re module and I've fixed that problem:

C:\Python27>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=100*'x'" "assert not rx.match(txt)"

100 loops, best of 3: 1.28 usec per loop

C:\Python27>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=1000*'x'" "assert not rx.match(txt)"

100 loops, best of 3: 1.23 usec per loop

C:\Python27>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=100*'x'" "assert not rx.search(txt)"

100 loops, best of 3: 1.21 usec per loop

C:\Python27>python -mtimeit -s"import 
re;rx=re.compile('^frobozz');txt=1000*'x'" "assert not rx.search(txt)"

100 loops, best of 3: 1.21 usec per loop

Hmm. Needs more tweaking...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月8日, 上午8时51分, Terry  wrote:
> On 2月8日, 上午12时20分, Benjamin Peterson  wrote:
>
> > Terry  gmail.com> writes:
>
> > > On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> > > > Do you by any chance have a few examples of these? There is a lot of
> > > > idiomatic code in python to e.g. acquire and release the GIL or doing
> > > > refcount-stuff. If that happens to be done with rather generic names as
> > > > arguments, I can well imagine that as being the cause.
> > > Starting at line 5119 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c
>
> > This isn't really fair because Python-ast.c is auto generated. ;)
>
> Oops! I don't know that! Then the analysis will not be valid, since
> too many duplications are from there.

Hey!

I have to say sorry because I found I made a mistake. Because Python-
ast.c is auto-generated and shouldn't be counted here, the right
duplication rate of Python3.0 is very small (5%).
And I found the duplications are quite trivial, I wound not say that
all of them are acceptable, but certainly not a strong enough evident
for code quality.

I have made the same analysis to some commercial source code, the
dup60 rate is quite often significantly larger than 15%.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月8日, 上午12时20分, Benjamin Peterson  wrote:
> Terry  gmail.com> writes:
>
> > On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> > > Do you by any chance have a few examples of these? There is a lot of
> > > idiomatic code in python to e.g. acquire and release the GIL or doing
> > > refcount-stuff. If that happens to be done with rather generic names as
> > > arguments, I can well imagine that as being the cause.
> > Starting at line 5119 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c
>
> This isn't really fair because Python-ast.c is auto generated. ;)

Oops! I don't know that! Then the analysis will not be valid, since
too many duplications are from there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python on TV-centric platforms

2009-02-07 Thread Diez B. Roggisch

Vitaliy Yermolenko schrieb:

Hi,

Any chance to see Python to be ready for "Widget Development Kit (WDK)
to third-party developers to create applications and services for
viewing on TVs, or to move applications to the TV from the PC viewing
environment" as on
http://www.intelconsumerelectronics.com/Consumer-Electronics-3.0/Widget-Channel-Overview.aspx?
Thoughts/ideas?



Given that the site shows not much more but marketing statements for 
otherwise technically unspecified systems (mentioning only a few 
buzzwords like JS & AJAX), I guess the answer is: sure python is ready. 
It is for example used in superkaramba, a widget-application even older 
than the OSX variant of the same concept.


But unless you have a concrete system in mind, with a toolchain and 
actual WDK, the answer can't possibly be final.


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


Re: Portable way to refer to the null device?

2009-02-07 Thread Jean-Paul Calderone

On Sat, 7 Feb 2009 15:56:45 -0800, n...@stinemates.org wrote:

On Fri, Feb 06, 2009 at 07:32:20PM -0800, Roy Smith wrote:

I need to run a command using subprocess.Popen() and have stdin
connected to the null device.  On unix, I would do:

self.process = subprocess.Popen(argv,
env=new_env,
stdout=open(outfile, 'w'),
stderr=open(errfile, 'w'),
stdin=open('/dev/null')
)

but that's not portable to windows.  Does Python have a portable way
to get a file object connected to the null device, regardless of what
operating system you're running on?


I normally just implement my own object:

class DevNull:
   def write(self, str):
   pass


I bet this won't work.  It needs to be a "real" file - have a file
descriptor or a handle or something.

Instead, try opening os.devnull.

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


Re: simple web app, where to start

2009-02-07 Thread nick
On Fri, Feb 06, 2009 at 09:16:02PM -0700, Vincent Davis wrote:
> I have a simple script that takes a few input values and returns a csv file
> and a few stats. If I wanted to host this on the web how would I. I have no
> idea where to begin. If someone could point me in the right direction like
> maybe a tutorial, tools I will need, functions. I would appreciate it.I
> know a little html but am not sure how to integrate python or know what
> servers will handle it .
> 
> Thanks
> Vincent Davis

I'd suggest CherryPy[1]. It's fairly welcoming to newbies, because the
web server and the framework and bundled together.

1: http://www.cherrypy.org/

HTH,
Nick

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


Re: Portable way to refer to the null device?

2009-02-07 Thread nick
On Fri, Feb 06, 2009 at 07:32:20PM -0800, Roy Smith wrote:
> I need to run a command using subprocess.Popen() and have stdin
> connected to the null device.  On unix, I would do:
> 
> self.process = subprocess.Popen(argv,
> env=new_env,
> stdout=open(outfile, 'w'),
> stderr=open(errfile, 'w'),
> stdin=open('/dev/null')
> )
> 
> but that's not portable to windows.  Does Python have a portable way
> to get a file object connected to the null device, regardless of what
> operating system you're running on?

I normally just implement my own object:

class DevNull:
def write(self, str):
pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with regular expressions

2009-02-07 Thread John Machin
On Feb 8, 10:15 am, MRAB  wrote:
> John Machin wrote:
> > On Feb 8, 1:37 am, MRAB  wrote:
> >> LaundroMat wrote:
> >>> Hi,
> >>> I'm quite new to regular expressions, and I wonder if anyone here
> >>> could help me out.
> >>> I'm looking to split strings that ideally look like this: "Update: New
> >>> item (Household)" into a group.
> >>> This expression works ok: '^(Update:)?(.*)(\(.*\))$' - it returns
> >>> ("Update", "New item", "(Household)")
> >>> Some strings will look like this however: "Update: New item (item)
> >>> (Household)". The expression above still does its job, as it returns
> >>> ("Update", "New item (item)", "(Household)").
>
> > Not quite true; it actually returns
> >     ('Update:', ' New item (item) ', '(Household)')
> > However ignoring the difference in whitespace, the OP's intention is
> > clear. Yours returns
> >     ('Update:', ' New item ', '(item) (Household)')
>
> The OP said it works OK, which I took to mean that the OP was OK with
> the extra whitespace, which can be easily stripped off. Close enough!

As I said, the whitespace difference [between what the OP said his
regex did and what it actually does] is not the problem. The problem
is that the OP's "works OK" included (item) in the 2nd group, whereas
yours includes (item) in the 3rd group.

>
> >>> It does not work however when there is no text in parentheses (eg
> >>> "Update: new item"). How can I get the expression to return a tuple
> >>> such as ("Update:", "new item", None)?
> >> You need to make the last group optional and also make the middle group
> >> lazy: r'^(Update:)?(.*?)(?:(\(.*\)))?$'.
>
> > Why do you perpetuate the redundant ^ anchor?
>
> The OP didn't say whether search() or match() was being used. With the ^
> it doesn't matter.

It *does* matter. re.search() is suboptimal; after failing at the
first position, it's not smart enough to give up if the pattern has a
front anchor.

[win32, 2.6.1]
C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
*'x'" "assert not rx.match(txt)"
100 loops, best of 3: 1.17 usec per loop

C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
0*'x'" "assert not rx.match(txt)"
100 loops, best of 3: 1.17 usec per loop

C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
*'x'" "assert not rx.search(txt)"
10 loops, best of 3: 4.37 usec per loop

C:\junk>\python26\python -mtimeit -s"import re;rx=re.compile
('^frobozz');txt=100
0*'x'" "assert not rx.search(txt)"
1 loops, best of 3: 34.1 usec per loop

Corresponding figures for 3.0 are 1.02, 1.02, 3.99, and 32.9

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


Python on TV-centric platforms

2009-02-07 Thread Vitaliy Yermolenko
Hi,

Any chance to see Python to be ready for "Widget Development Kit (WDK)
to third-party developers to create applications and services for
viewing on TVs, or to move applications to the TV from the PC viewing
environment" as on
http://www.intelconsumerelectronics.com/Consumer-Electronics-3.0/Widget-Channel-Overview.aspx?
Thoughts/ideas?

WBR, Vitaliy.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with regular expressions

2009-02-07 Thread MRAB

John Machin wrote:

On Feb 8, 1:37 am, MRAB  wrote:

LaundroMat wrote:

Hi,
I'm quite new to regular expressions, and I wonder if anyone here
could help me out.
I'm looking to split strings that ideally look like this: "Update: New
item (Household)" into a group.
This expression works ok: '^(Update:)?(.*)(\(.*\))$' - it returns
("Update", "New item", "(Household)")
Some strings will look like this however: "Update: New item (item)
(Household)". The expression above still does its job, as it returns
("Update", "New item (item)", "(Household)").


Not quite true; it actually returns
('Update:', ' New item (item) ', '(Household)')
However ignoring the difference in whitespace, the OP's intention is
clear. Yours returns
('Update:', ' New item ', '(item) (Household)')


The OP said it works OK, which I took to mean that the OP was OK with
the extra whitespace, which can be easily stripped off. Close enough!



It does not work however when there is no text in parentheses (eg
"Update: new item"). How can I get the expression to return a tuple
such as ("Update:", "new item", None)?

You need to make the last group optional and also make the middle group
lazy: r'^(Update:)?(.*?)(?:(\(.*\)))?$'.


Why do you perpetuate the redundant ^ anchor?


The OP didn't say whether search() or match() was being used. With the ^
it doesn't matter.


(?:...) is the non-capturing version of (...).


Why do you use
(?:(subpattern))?
instead of just plain
(subpattern)?
?


Oops, you're right. I was distracted by the \( and \)! :-)
--
http://mail.python.org/mailman/listinfo/python-list


MacPython 2.5 IDLE font size

2009-02-07 Thread chohazel
Hi,
Is there a way to adjust the default font size in IDLE, in MacPython
2.5? The default now is too tiny.
I have to use this version of MacPython. As far as I searched, I can't
find how I do this.
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


TkInter: Problem with propagation of resize events through geometry manager hierarchy?

2009-02-07 Thread Randy Smith


Hi!  I'm looking for help with a Tkinter program's handling of resize.
I'm trying to do a fairly simple widget that shows a cropped part of a
larger image, and let's you navigate within the larger image through a
variety of methods.  The widget hierarchy is:

root
  ImageWidget (my class)
Label (contains the image)
Horizontal Scroll Bar
Vertical scroll bar

The cropping and scrolling works fine.  But when I try to add
responding to resize events, I get into trouble.  Specifically:
* When I naively change the size of the image shown to be borderwidth
  less than the size indicated in the configure event, the size of the
  image shown grows gradually but inexorably when I start the test
  app.  (Sorta scary, actually :-})
* When I fiddle a bit to figure out what the actual difference in size
  is between the Configure event and the image that can be displayed,
  I get a vibrating, jagged display of the image.

Investigation suggests that multiple configure events are hitting the
label in response to each user resize with different sizes.  I'm
guessing that when I resize the image in response to those different
events, that creates new resize events propagating through the window
manager hierarchy, which creates new configure events, which means my
handler changes the image size, which ... you get the idea.  However,
everything seems to work fine if I leave out the scroll bars and just
have a label in a frame inside the root window; the image resizes
fine.  If the scroll bars are in place but I don't have the image
resize bound to the configure event, I get two sets of resize events
propagaing through the system on startup; without, I just get one.

Event lists and code included below.  Any help would be appreciated.
Thanks!

  -- Randy Smith

-- Event list on startup with scroll bars:

: width height
root :  220 220
root :  1 1
iwidget :  220 220
root :  220 220
vscroll :  16 204
root :  16 204
hscroll :  204 16
root :  204 16
ilabel :  204 204
root :  204 204
vscroll :  15 205
root :  15 205
hscroll :  205 15
root :  205 15
ilabel :  205 205
root :  205 205
root :  219 219
ilabel :  205 205
root :  205 205
hscroll :  205 15
root :  205 15
vscroll :  15 205
root :  15 205
iwidget :  219 219
root :  219 219
vscroll :  15 204
root :  15 204
hscroll :  204 15
root :  204 15
ilabel :  204 204
root :  204 204

-- Event list on startup without scroll bars

root :  204 204
root :  1 1
iwidget :  204 204
root :  204 204
ilabel :  204 204
root :  204 204

-- Code, without image resize.  If you want to see the vibration,
   uncomment the line
self.label.bind("", self.reconfigure, "+")
   To actually run it you'll need an image "test.tiff" in the current
   directory (any image of size > 200x200 will do) and access to the
   python imaging library (PIL), but I hope the code is pretty clear
   (other than the math transforming between various coordinate
   systems, which I don't believe is relevant; focus on
   reconfigure(), refresh, and __init__).

#!/usr/bin/python

import traceback
from Tkinter import *
from PIL import Image
import ImageTk

debug = 4

def display_args(*args):
print "Args: ", args

def display_event(event):
print event.__dict__

def display_tag_and_size(tag, event):
print tag, ": ", event.width, event.height

class NotYetImplemented(Exception): pass

def mapnum(x, fromrange, torange):
assert fromrange[0] <= x < fromrange[1], (fromrange[0], x,  
fromrange[1])

assert torange[0] < torange[1], (torange[0], torange[1])
## Need to force floating point
x *= 1.0
return (x - fromrange[0]) / (fromrange[1] - fromrange[0]) *  
(torange[1] - torange[0]) + torange[0]


class ImageWidget(Frame):
def __init__(self, parent, gfunc, image_size,
 starting_zoom=1,
 starting_ul=(0,0),
 starting_size = None):
"""Create an Image Widget which will display an image based  
on the
function passed.  That function will be called with the  
arguments

(zoom_factor, (xstart, xend), (ystart, yend)) and must return a
TkInter PhotoImage object of size (xend-xstart, yend-ystart).
IMAGE_SIZE describes the "base size" of the image being  
backed by

gfunc.
starting_* describes the starting window on the image."""

## Default starting size to whole image
if not starting_size: starting_size = image_size

## Init parent
Frame.__init__(self, parent)
self.bind("",
  lambda e, t="iwidget": display_tag_and_size(t, e))
## Base image parameters
self.generator_func = gfunc
self.isize = image_size

## Modifier of base image size for coords currently working in
self.zoom = starting_zoom

## Interval of augmented (zoomed) image currently shown
## Note that these must be integers; these map directly to  
pixels

self.xint = [starting

Re: Newbie SWMixer / numpy help - AssertionError

2009-02-07 Thread Robert Kern

On 2009-02-07 08:46, Peter Chant wrote:

Hello,

I'm a bit of a python newby.  I want to play and record sound
simultaneously.  SWMixer seems able to do this but the examples use WAV
files.  I'm trying to play a test tone.  Can anyone give me a steer as to
why this fails?


Looking at the SWMixer docs, you probably want

  snd = swmixer.Sound(data=tone_data)

Well, sort of. You probably need to scale your data and convert it to int16 
format. It's currently in floating point format.


When asking about why something fails, it helps a lot if you specify exactly how 
it fails and what you expected to happen. Copy-and-paste any error messages exactly.


If you need more help with SWMixer's API, I recommend asking the author. It's 
not in widespread use, so he can probably give you better and faster help than 
we can.


If you need more help with numpy, specifically, you can ask on the 
numpy-discussion mailing list. numpy *is* in widespread use, but there's a 
higher concentration of helpful numpy users over there.


  http://www.scipy.org/Mailing_Lists

--
Robert Kern

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

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Martin v. Löwis
> yet the general tone of the responses has been more defensive than i would
> have expected.  i don't really understand why.  nothing really terrible,
> given the extremes you get on the net in general, but still a little
> disappointing.

I think this is fairly easy to explain. The OP closes with the question
"Does that say something about the code quality of Python3.0?"
thus suggesting that the quality of Python 3 is poor.

Nobody likes to hear that the quality of his work is poor. He then goes
on saying

"But it seems that the stable & successful software releases tend to
have relatively stable duplication rate."

suggesting that Python 3.0 cannot be successful, because it doesn't have
a relatively stable duplication rate.

Nobody likes to hear that a project one has put many month into cannot
be successful.

Hence the defensive responses.

> i'm not saying there is such a solution.  i'm not even saying that there
> is certainly a problem.  i'm just making the quiet observation that the
> original information is interesting, might be useful, and should be
> welcomed.

The information is interesting. I question whether it is useful as-is,
as it doesn't tell me *what* code got duplicated (and it seems it is
also incorrect, since it includes analysis of generated code). While I
can welcome the information, I cannot welcome the conclusion that the
OP apparently draws from them.

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


Re: Flattening lists

2009-02-07 Thread mmanns
On Sat, 7 Feb 2009 12:50:22 -0800 (PST)
Rhamphoryncus  wrote:

> On Feb 7, 1:39 pm,  wrote:
> > On Sat, 7 Feb 2009 01:06:06 -0800 (PST)
> > Rhamphoryncus  wrote:
> >
> > > What usecase do you have for such inconsistently structured data?
> >
> > I have a similar use case in pyspread, which is a Python spreadsheet
> > that employs numpy object arrays. Since the Python objects in the
> > numpy arrays are derived from user input, they can be anything,
> > including nested lists as well as strings, etc.
> >
> > Since I consider my work-around that treats strings as a special
> > case a rather ugly hack, I would welcome a robust, generic approach
> > to the OP's problem.
> 
> Can you explain this in a little more detail?

In the application, there is one main numpy array of type "O".
Each element of the array corresponds to one cell in a grid. The user
may enter a Python expression into the grid cell. The input is
evaled and the result is stored in the numpy array (the actual process
is a bit more complicated). Therefore, the object inside a numpy array
element may be an inconsistent, nested, iterable type.

The user now may access the result grid via __getitem__. When doing
this, a numpy array that is as flat as possible while comprising the
maximum possible data depth is returned, i.e.:

1. Non-string and non-unicode iterables of similar length for each of
the cells form extra dimensions.

2. In order to remove different container types, the result is
flattened, cast into a numpy.array and re-shaped.

3. Dimensions of length 1 are eliminated.

Therefore, the user can conveniently use numpy ufuncs on the results.

I am referring to the flatten operation in step 2

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread andrew cooke
Steve Holden wrote:
>> You'd best hope the copied section was thoroughly reviewed otherwise
>> you're
>> duplicating a flaw across X other sections. And then you also best hope
>> that
>> whoever finds said flaw and fixes it is also smart enough to check for
>> similar constructs around the code base.
>>
> This is probably preferable to five different developers solving the
> same problem five different ways and introducing three *different* bugs,
> no?

someone posted some numbers that suggested that more code than normal was
copied in python 3.0.  that seems reasonable, as others have said, because
it's a new major release.  but as far as i know, this is the first time
it's been raised.  so it seems like a useful piece of information that
might help improve python in some way.  which should be welcomed.

yet the general tone of the responses has been more defensive than i would
have expected.  i don't really understand why.  nothing really terrible,
given the extremes you get on the net in general, but still a little
disappointing.

the email quoted above is a typical example.  as i said - nothing
terrible, just a misleading false dichotomy.  yes, five people solving it
five different ways would be worse, but that doesn't mean there isn't some
better solution.  surely it would be preferable if there was one way, that
didn't involve copying code, that everyone could use?

i'm not saying there is such a solution.  i'm not even saying that there
is certainly a problem.  i'm just making the quiet observation that the
original information is interesting, might be useful, and should be
welcomed.

andrew


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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Jeroen Ruigrok van der Werven
-On [20090207 21:07], Steve Holden (st...@holdenweb.com) wrote:
>This is probably preferable to five different developers solving the
>same problem five different ways and introducing three *different* bugs, no?

I guess the answer would be 'that depends', but in most cases you would be
correct, yes.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
Earth to earth, ashes to ashes, dust to dust...
--
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe and distutils

2009-02-07 Thread Maxim Demenko

Thomas Heller schrieb:

Maxim Demenko schrieb:

Hi,
i have installed Python 2.5.4 on WinXP, setuptools-0.6c9 and py2exe 0.6.9
Now i can't list installed modules, here is the stacktrace:

[...]

Any suggestion, how to fix this issue?

Thomas Heller schrieb:

Looks like a setuptools problem to me.  Here's the output on my system:


Actually, I don't know where the problem is.  Maybe pydoc?


Thomas


Thank you Thomas,
i found http://thread.gmane.org/gmane.comp.python.distutils.devel/3340
and tried to import setuptools first - indeed, in this case the problem 
seems to be solved, however, would like to know, how to persist it.

If i put it into py2exe.__init__.py - is it a very bad idea?

Best regards

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Martin v. Löwis
> This is probably preferable to five different developers solving the
> same problem five different ways and introducing three *different* bugs, no?

With the examples presented, I'm not convinced that there is actually
significant code duplication going on in the first place.

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


Re: Flattening lists

2009-02-07 Thread Rhamphoryncus
On Feb 7, 1:39 pm,  wrote:
> On Sat, 7 Feb 2009 01:06:06 -0800 (PST)
> Rhamphoryncus  wrote:
>
> > What usecase do you have for such inconsistently structured data?
>
> I have a similar use case in pyspread, which is a Python spreadsheet
> that employs numpy object arrays. Since the Python objects in the numpy
> arrays are derived from user input, they can be anything, including
> nested lists as well as strings, etc.
>
> Since I consider my work-around that treats strings as a special case a
> rather ugly hack, I would welcome a robust, generic approach to the
> OP's problem.

Can you explain this in a little more detail?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where to host a (Python) project?

2009-02-07 Thread alex goretoy
If you don't mind changing dns entries. You can also use Google App Engine.
It's really nice.

http://code.google.com/appengine/docs/python/tools/webapp/overview.html

-Alex Goretoy
http://www.alexgoretoy.com



On Fri, Feb 6, 2009 at 1:07 AM, alex goretoy wrote:

> I use google code.
> http://code.google.com/p/pynutbutter
>
> -Alex Goretoy
> http://www.alexgoretoy.com
>
>
>
>
> On Thu, Feb 5, 2009 at 6:55 PM, Ben Finney <
> bignose+hates-s...@benfinney.id.au 
> >wrote:
>
>> a...@pythoncraft.com (Aahz) writes:
>>
>> > In article <
>> 6dcb8ce5-c93e-458c-9047-e5db60f27...@v18g2000pro.googlegroups.com>,
>> > andrew cooke   wrote:
>> > >hi, just fyi, i investigated this and you can join any publicly
>> > >readable group by sending an email to the "-subscribe" address. you
>> > >do not need a google login for this and, as far as i can tell, it
>> > >then operates for you like a normal mailing list.
>> >
>> > The same thing is theoretically true for Yahoo groups, but I've
>> > heard from people over the years about various difficulties fixing
>> > problems with list subscriptions in the absence of a real Yahoo
>> > login and I'm not particularly interested in finding out that the
>> > same thing ends up being true for Google lists.
>>
>> Indeed it does. I have succeeded in subscribing to Google mailing
>> lists in the absence of a Google account, but *managing* that
>> subscription thereafter in the absence of a Google account is
>> obnoxiously difficult. Your caution is well advised.
>>
>> --
>>  \"I got fired from my job the other day. They said my |
>>  `\  personality was weird. … That's okay, I have four more." |
>> _o__)   —Bug-Eyed Earl, _Red Meat_ |
>> Ben Finney
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with regular expressions

2009-02-07 Thread John Machin
On Feb 8, 1:37 am, MRAB  wrote:
> LaundroMat wrote:
> > Hi,
>
> > I'm quite new to regular expressions, and I wonder if anyone here
> > could help me out.
>
> > I'm looking to split strings that ideally look like this: "Update: New
> > item (Household)" into a group.
> > This expression works ok: '^(Update:)?(.*)(\(.*\))$' - it returns
> > ("Update", "New item", "(Household)")
>
> > Some strings will look like this however: "Update: New item (item)
> > (Household)". The expression above still does its job, as it returns
> > ("Update", "New item (item)", "(Household)").

Not quite true; it actually returns
('Update:', ' New item (item) ', '(Household)')
However ignoring the difference in whitespace, the OP's intention is
clear. Yours returns
('Update:', ' New item ', '(item) (Household)')


> > It does not work however when there is no text in parentheses (eg
> > "Update: new item"). How can I get the expression to return a tuple
> > such as ("Update:", "new item", None)?
>
> You need to make the last group optional and also make the middle group
> lazy: r'^(Update:)?(.*?)(?:(\(.*\)))?$'.

Why do you perpetuate the redundant ^ anchor?

> (?:...) is the non-capturing version of (...).

Why do you use
(?:(subpattern))?
instead of just plain
(subpattern)?
?

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


Re: Flattening lists

2009-02-07 Thread mmanns
On Sat, 7 Feb 2009 01:06:06 -0800 (PST)
Rhamphoryncus  wrote:

> On Feb 6, 10:21 pm, rdmur...@bitdance.com wrote:
> > Quoth Mensanator :
> > > def flatten(listOfLists):
> > >     return list(chain.from_iterable(listOfLists))
> >
> >     Python 2.6.1 (r261:67515, Jan  7 2009, 17:09:13)
> >     [GCC 4.3.2] on linux2
> >     Type "help", "copyright", "credits" or "license" for more
> > information. >>> from itertools import chain
> >     >>> list(chain.from_iterable([1, 2, [3, 4]]))
> >     Traceback (most recent call last):
> >       File "", line 1, in 
> >     TypeError: 'int' object is not iterable
> >     >>> list(chain(*[1, 2, [3, 4]]))
> >     Traceback (most recent call last):
> >       File "", line 1, in 
> >     TypeError: 'int' object is not iterable
> >     >>> list(chain.from_iterable(['abcd', 'efg', [3, 4]]))
> >     ['a', 'b', 'c', 'd', 'e', 'f', 'g', 3, 4]
> 
> What usecase do you have for such inconsistently structured data?

I have a similar use case in pyspread, which is a Python spreadsheet
that employs numpy object arrays. Since the Python objects in the numpy
arrays are derived from user input, they can be anything, including
nested lists as well as strings, etc.

Since I consider my work-around that treats strings as a special case a
rather ugly hack, I would welcome a robust, generic approach to the
OP's problem.

Martin

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


Re: py2exe and distutils

2009-02-07 Thread Thomas Heller
> Maxim Demenko schrieb:
>> Hi,
>> i have installed Python 2.5.4 on WinXP, setuptools-0.6c9 and py2exe 0.6.9
>> Now i can't list installed modules, here is the stacktrace:
[...]
>> Any suggestion, how to fix this issue?
> 
Thomas Heller schrieb:
> Looks like a setuptools problem to me.  Here's the output on my system:

Actually, I don't know where the problem is.  Maybe pydoc?

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


Re: py2exe and distutils

2009-02-07 Thread Thomas Heller
Maxim Demenko schrieb:
> Hi,
> i have installed Python 2.5.4 on WinXP, setuptools-0.6c9 and py2exe 0.6.9
> Now i can't list installed modules, here is the stacktrace:
> 
> 
> 
> help> modules
> 
> Please wait a moment while I gather a list of all available modules...
> 
> Traceback (most recent call last):
>File "", line 1, in 
>File "C:\Programme\Python25\lib\site.py", line 346, in __call__
>  return pydoc.help(*args, **kwds)
>File "C:\Programme\Python25\lib\pydoc.py", line 1649, in __call__
>  self.interact()
>File "C:\Programme\Python25\lib\pydoc.py", line 1667, in interact
>  self.help(request)
>File "C:\Programme\Python25\lib\pydoc.py", line 1683, in help
>  elif request == 'modules': self.listmodules()
>File "C:\Programme\Python25\lib\pydoc.py", line 1804, in listmodules
>  ModuleScanner().run(callback)
>File "C:\Programme\Python25\lib\pydoc.py", line 1855, in run
>  for importer, modname, ispkg in pkgutil.walk_packages():
>File "C:\Programme\Python25\lib\pkgutil.py", line 110, in walk_packages
>  __import__(name)
>File 
> "C:\Programme\Python25\Lib\site-packages\setuptools\__init__.py", line 
> 2, in 
>  from setuptools.extension import Extension, Library
>File 
> "C:\Programme\Python25\Lib\site-packages\setuptools\extension.py", line 
> 2, in 
>  from dist import _get_unpatched
>File "C:\Programme\Python25\Lib\site-packages\setuptools\dist.py", 
> line 27, in 
>  _Distribution = _get_unpatched(_Distribution)
>File "C:\Programme\Python25\Lib\site-packages\setuptools\dist.py", 
> line 23, in _get_unpatched
>  "distutils has already been patched by %r" % cls
> AssertionError: distutils has already been patched by  py2exe.Distribution at 0x011B4F90>
> 
> Any suggestion, how to fix this issue?

Looks like a setuptools problem to me.  Here's the output on my system:

>>> help("modules")

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

Traceback (most recent call last):
  File "", line 1, in 
  File "c:\python25\lib\site.py", line 346, in __call__
return pydoc.help(*args, **kwds)
  File "c:\python25\lib\pydoc.py", line 1645, in __call__
self.help(request)
  File "c:\python25\lib\pydoc.py", line 1682, in help
elif request == 'modules': self.listmodules()
  File "c:\python25\lib\pydoc.py", line 1803, in listmodules
ModuleScanner().run(callback)
  File "c:\python25\lib\pydoc.py", line 1854, in run
for importer, modname, ispkg in pkgutil.walk_packages():
  File "c:\python25\lib\pkgutil.py", line 125, in walk_packages
for item in walk_packages(path, name+'.', onerror):
  File "c:\python25\lib\pkgutil.py", line 110, in walk_packages
__import__(name)
  File 
"c:\python25\lib\site-packages\pyopengl-3.0.0b1-py2.5.egg\OpenGL\Tk\__init__.py",
 line 87, in 
_default_root.tk.call('package', 'require', 'Togl')
_tkinter.TclError: can't find package Togl
>>> ^Z

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Steve Holden
Jeroen Ruigrok van der Werven wrote:
> -On [20090207 18:25], Scott David Daniels (scott.dani...@acm.org) wrote:
>> This analysis overlooks the fact that 3.0 _was_ a major change, and is
>> likely to grow cut-and-paste solutions to some problems as we switch to
>> Unicode strings from byte strings.
> 
> You'd best hope the copied section was thoroughly reviewed otherwise you're
> duplicating a flaw across X other sections. And then you also best hope that
> whoever finds said flaw and fixes it is also smart enough to check for
> similar constructs around the code base.
> 
This is probably preferable to five different developers solving the
same problem five different ways and introducing three *different* bugs, no?

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: WebError documentation?

2009-02-07 Thread Bruno Desthuilliers

Ron Garret a écrit :

In article ,
 Chris Rebert  wrote:


On Thu, Feb 5, 2009 at 12:52 PM, Ron Garret  wrote:

Is there any?  Where is it?  Extensive Googling has proven fruitless.

It's not a standard Python exception. A third-party library you're
using must be raising it. Check the exception traceback.


I see I did not make myself clear.


Now *that* is an understatement...

>  I meant the Python software package

called "weberror", not a generic web error.

http://pypi.python.org/pypi/WebError


Google is your friend:
http://bel-epa.com/docs/thirdparty/weberror/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Java to Python

2009-02-07 Thread Aleksandar Radulovic
Hi,

On Sat, Feb 7, 2009 at 5:28 PM, zaheer agadi  wrote:
> Thanks Alex,
>
>  Can you provide me more details on httplib and urllib ?

The details can be found in Python documentation (http://python.org/doc),
on these pages:
http://docs.python.org/library/httplib.html

I'm sure you can figure out the location of the documentation for the urllib2
module. Documentation includes examples too.


Regards,
alex.
-- 
a lex 13 x
http://www.a13x.info
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Jeroen Ruigrok van der Werven
-On [20090207 18:25], Scott David Daniels (scott.dani...@acm.org) wrote:
>This analysis overlooks the fact that 3.0 _was_ a major change, and is
>likely to grow cut-and-paste solutions to some problems as we switch to
>Unicode strings from byte strings.

You'd best hope the copied section was thoroughly reviewed otherwise you're
duplicating a flaw across X other sections. And then you also best hope that
whoever finds said flaw and fixes it is also smart enough to check for
similar constructs around the code base.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
Earth to earth, ashes to ashes, dust to dust...
--
http://mail.python.org/mailman/listinfo/python-list


Re: isfifo?

2009-02-07 Thread rdmurray
=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=  wrote:
> rdmur...@bitdance.com wrote:
> > I've googled and looked through os.path, but I don't see a method for
> > determining if a path points to a FIFO.  Anyone know of a simple way to
> > do so?
> 
> def isfifo(fn):
>   return stat.S_ISFIFO(os.stat(fn).st_mode)

Thanks.  I should have thought of looking in os.stat.  Odd that S_ISFIFO
didn't come up in my google search.

--RDM

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


Re: isfifo?

2009-02-07 Thread Martin v. Löwis
rdmur...@bitdance.com wrote:
> I've googled and looked through os.path, but I don't see a method for
> determining if a path points to a FIFO.  Anyone know of a simple way to
> do so?

def isfifo(fn):
  return stat.S_ISFIFO(os.stat(fn).st_mode)

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Martin v. Löwis
> But the duplication are always not very big, from about 100 lines
> (rare) to less the 5 lines. As you can see the Rate30 is much bigger
> than Rate60, that means there are a lot of small duplications.

I don't find that important for code quality. It's the large chunks
that I would like to see de-duplicated (unless, of course, they are
in generated code, in which case I couldn't care less).

Unfortunately, none of the examples you have posted so far are
- large chunks, and
- new in 3.0.

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Martin v. Löwis
> And I'm not saying that you can not have duplication in code. But it
> seems that the stable & successful software releases tend to have
> relatively stable duplication rate.

So if some software has an instable duplication rate, it probably
means that it is either not stable, or not successful.

In the case of Python 3.0, it's fairly obvious which one it is:
it's not stable. Indeed, Python 3.0 is a significant change from
Python 2.x. Of course, anybody following the Python 3 development
process could have told you see even without any code metrics.

I still find the raw numbers fairly useless. What matters more to
me is what specific code duplications have been added. Furthermore,
your Dup30 classification is not important to me, but I'm rather
after the nearly 2000 new chunks of code that has more than 60
subsequent tokens duplicated.

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


Re: "Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread andrew cooke

there's a justification for this awful mess here -
http://mail.python.org/pipermail/python-3000/2006-March/000104.html

i didn't know about this, and even after reading steven's broken (i
assume) example, managed to get it backwards.

the else is if there *isn't* a break and is for search loops (see link
above).

(it's still in 3).

andrew


Steven D'Aprano wrote:
> Andreas Waldenburger wrote:
>
>> It seems that there is a for...else construct. Replacing the inner if
>> with pass seems to confirm this. The else clause is still executed.
>
> Yes, there is a for...else construct.
>
> The else block runs if the for loop exits *without* a break.
>
> for i in range(20):
> if i == 10: break
> else:
> print "no break here"
>
> for i in range(20):
> if i == 100: break
> else:
> print "no break here"
>
>
>> What's broken here: Python or my brain?
>
> Perhaps we should not answer that question.
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Scott David Daniels

Terry wrote:

... I'm not saying that you can not have duplication in code. But it
seems that the stable & successful software releases tend to have
relatively stable duplication rate.


This analysis overlooks the fact that 3.0 _was_ a major change, and is
likely to grow cut-and-paste solutions to some problems as we switch to
Unicode strings from byte strings.  You are comparing a .0 version to
.5 versions.  I expect the polishing that follows as we go up through
.1, .2, and so on will lower those redundancy measures.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: isfifo?

2009-02-07 Thread Albert Hopkins
On Sat, 2009-02-07 at 17:12 +, rdmur...@bitdance.com wrote:
> I've googled and looked through os.path, but I don't see a method for
> determining if a path points to a FIFO.  Anyone know of a simple way to
> do so?

import os
import stat

st_mode = os.stat(path)[0]
isfifo = stat.S_ISFIFO(st_mode)


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


isfifo?

2009-02-07 Thread rdmurray
I've googled and looked through os.path, but I don't see a method for
determining if a path points to a FIFO.  Anyone know of a simple way to
do so?

--RDM

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


Re: Java to Python

2009-02-07 Thread Aleksandar Radulovic
Hi,

This looks like a perfect job for httplib and urllib2 modules.

On Sat, Feb 7, 2009 at 4:49 PM, zaheer agadi  wrote:
> Hi Thanks for replying ..
> I am actually looking for the pure Python options
>
> Are there any equivalent clasees  for the following
>
> import org.apache.commons.httpclient.HttpClient;
> import org.apache.commons.httpclient.HttpException;
> import
> org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
> import org.apache.commons.httpclient.methods.GetMethod;
> import org.apache.commons.httpclient.protocol.Protocol;
>
>
> Thanks for your help
> -Zaheer
>
> On Sat, Feb 7, 2009 at 9:57 PM, Banibrata Dutta 
> wrote:
>>
>> Jython is not an option ?
>>
>> On Sat, Feb 7, 2009 at 9:54 PM,  wrote:
>>>
>>> Hi
>>>
>>> I have a following class that is written Java and makes use of apache
>>> http client library,I am new to python can any one suggest me a python
>>> equivalent of this following class,
>>>
>>> Thanks ,
>>>
>>> public class Authenticate{
>>>
>>>  private String storageUserName=null;
>>>private String storagePassword=null;
>>>private String authorization=null;
>>>private String identityHostName = null;
>>>private String identityPortNumber = null;
>>>
>>>private String accessKey=null;
>>>private String secretKey=null;
>>>
>>>public String getStoragePassword() {
>>>return storagePassword;
>>>}
>>>
>>>public void setStoragePassword(String storagePassword) {
>>>this.storagePassword = storagePassword;
>>>}
>>>
>>>public String getStorageUserName() {
>>>return storageUserName;
>>>}
>>>
>>>public void setStorageUserName(String storageUserName) {
>>>this.storageUserName = storageUserName;
>>>}
>>>
>>>public String getIdentityHostName() {
>>>return identityHostName;
>>>}
>>>
>>>public void setIdentityHostName(String identityHostName) {
>>>this.identityHostName = identityHostName;
>>>}
>>>
>>>public String getIdentityPortNumber() {
>>>return identityPortNumber;
>>>}
>>>
>>>public void setIdentityPortNumber(String identityPortNumber) {
>>>this.identityPortNumber = identityPortNumber;
>>>}
>>>
>>>public String getAccessKey() {
>>>return accessKey;
>>>}
>>>
>>>public void setAccessKey(String accessKey) {
>>>this.accessKey = accessKey;
>>>}
>>>
>>>public String getSecretKey() {
>>>return secretKey;
>>>}
>>>
>>>public void setSecretKey(String secretKey) {
>>>this.secretKey = secretKey;
>>>}
>>>
>>>
>>> /**
>>> * Convenience string for Base 64 encoding.
>>> */
>>>private static final String BASE64_CHARS =
>>>"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
>>>"abcdefghijklmnopqrstuvwxyz" +
>>>"0123456789+/";
>>>
>>>/**
>>> * Encode the specified credentials into a String as required
>>> by
>>> * HTTP Basic Authentication (http://www.ietf.org/rfc/
>>> rfc2617.txt">RFC 2617).
>>> *
>>> * @param username Username to be encoded
>>> * @param password Password to be encoded
>>> * @return String string containing encoded username and password.
>>> */
>>>public String encodeCredentialsBasic(String username, String
>>> password) {
>>>String encode = username + ":" + password;
>>>int paddingCount = (3 - (encode.length() % 3)) % 3;
>>>encode += "\0\0".substring(0, paddingCount);
>>>StringBuilder encoded = new StringBuilder();
>>>
>>>for (int i = 0; i < encode.length(); i += 3) {
>>>}
>>>return encoded.toString();
>>>}
>>>
>>>public void fetchDetails(){
>>>HttpClient client=new HttpClient();
>>>//reqDetails = new RequestDetails();
>>>//String identityURL=MessageUtil.getMessage
>>> ("IDENTITY_INSTANCE");
>>>//int portNumber=Integer.parseInt(MessageUtil.getMessage
>>> ("IDENTITY_PORT"));
>>>authorization="Basic " + encodeCredentialsBasic
>>> (storageUserName, storagePassword);
>>>String url="https://"+identityHostName+
>>>":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
>>> +"/attributes/";
>>>
>>>Protocol https=null;
>>>//try {
>>>https = new Protocol("https", new
>>> EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
>>>/*} catch (GeneralSecurityException ex) {
>>>Logger.getLogger(Authenticate.class.getName()).log
>>> (Level.SEVERE, null, ex);
>>>} catch (IOException ex) {
>>>Logger.getLogger(Authenticate.class.getName()).log
>>> (Level.SEVERE, null, ex);
>>>}*/
>>>Protocol.registerProtocol("https", https);
>>>GetMethod method=new GetMethod(url);
>>>method.setRequestHeader("Authorization",authorization);
>>>method.setRequestHeader("Accept","application/xml");
>>>try {
>>>int responseCode=client.executeMethod(method);
>>>

Re: Java to Python

2009-02-07 Thread zaheer agadi
Hi Thanks for replying ..
I am actually looking for the pure Python options

Are there any equivalent clasees  for the following

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import
org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.protocol.Protocol;


Thanks for your help
-Zaheer

On Sat, Feb 7, 2009 at 9:57 PM, Banibrata Dutta
wrote:

> Jython is not an option ?
>
> On Sat, Feb 7, 2009 at 9:54 PM,  wrote:
>
>> Hi
>>
>> I have a following class that is written Java and makes use of apache
>> http client library,I am new to python can any one suggest me a python
>> equivalent of this following class,
>>
>> Thanks ,
>>
>> public class Authenticate{
>>
>>  private String storageUserName=null;
>>private String storagePassword=null;
>>private String authorization=null;
>>private String identityHostName = null;
>>private String identityPortNumber = null;
>>
>>private String accessKey=null;
>>private String secretKey=null;
>>
>>public String getStoragePassword() {
>>return storagePassword;
>>}
>>
>>public void setStoragePassword(String storagePassword) {
>>this.storagePassword = storagePassword;
>>}
>>
>>public String getStorageUserName() {
>>return storageUserName;
>>}
>>
>>public void setStorageUserName(String storageUserName) {
>>this.storageUserName = storageUserName;
>>}
>>
>>public String getIdentityHostName() {
>>return identityHostName;
>>}
>>
>>public void setIdentityHostName(String identityHostName) {
>>this.identityHostName = identityHostName;
>>}
>>
>>public String getIdentityPortNumber() {
>>return identityPortNumber;
>>}
>>
>>public void setIdentityPortNumber(String identityPortNumber) {
>>this.identityPortNumber = identityPortNumber;
>>}
>>
>>public String getAccessKey() {
>>return accessKey;
>>}
>>
>>public void setAccessKey(String accessKey) {
>>this.accessKey = accessKey;
>>}
>>
>>public String getSecretKey() {
>>return secretKey;
>>}
>>
>>public void setSecretKey(String secretKey) {
>>this.secretKey = secretKey;
>>}
>>
>>
>> /**
>> * Convenience string for Base 64 encoding.
>> */
>>private static final String BASE64_CHARS =
>>"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
>>"abcdefghijklmnopqrstuvwxyz" +
>>"0123456789+/";
>>
>>/**
>> * Encode the specified credentials into a String as required
>> by
>> * HTTP Basic Authentication (http://www.ietf.org/rfc/
>> rfc2617.txt ">RFC 2617).
>> *
>> * @param username Username to be encoded
>> * @param password Password to be encoded
>> * @return String string containing encoded username and password.
>> */
>>public String encodeCredentialsBasic(String username, String
>> password) {
>>String encode = username + ":" + password;
>>int paddingCount = (3 - (encode.length() % 3)) % 3;
>>encode += "\0\0".substring(0, paddingCount);
>>StringBuilder encoded = new StringBuilder();
>>
>>for (int i = 0; i < encode.length(); i += 3) {
>>}
>>return encoded.toString();
>>}
>>
>>public void fetchDetails(){
>>HttpClient client=new HttpClient();
>>//reqDetails = new RequestDetails();
>>//String identityURL=MessageUtil.getMessage
>> ("IDENTITY_INSTANCE");
>>//int portNumber=Integer.parseInt(MessageUtil.getMessage
>> ("IDENTITY_PORT"));
>>authorization="Basic " + encodeCredentialsBasic
>> (storageUserName, storagePassword);
>>String url="https://"+identityHostName+
>>":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
>> +"/attributes/";
>>
>>Protocol https=null;
>>//try {
>>https = new Protocol("https", new
>> EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
>>/*} catch (GeneralSecurityException ex) {
>>Logger.getLogger(Authenticate.class.getName()).log
>> (Level.SEVERE, null, ex);
>>} catch (IOException ex) {
>>Logger.getLogger(Authenticate.class.getName()).log
>> (Level.SEVERE, null, ex);
>>}*/
>>Protocol.registerProtocol("https", https);
>>GetMethod method=new GetMethod(url);
>>method.setRequestHeader("Authorization",authorization);
>>method.setRequestHeader("Accept","application/xml");
>>try {
>>int responseCode=client.executeMethod(method);
>>if(responseCode==200){
>>InputStream is=method.getResponseBodyAsStream();
>>BufferedReader bis=new BufferedReader(new
>> InputStreamReader(is));
>>String temp=null,sKey=null, aKey=null;
>> 

Beginner Python OpenGL difficulties

2009-02-07 Thread David Nuttall
Hi Mike,

I am just getting into OPENGL from Python. But I am having
problems. Each time I try to run some OPENGL code I get the following sort
of error:

 

Traceback (most recent call last):

  File "C:\Documents and Settings\Owner\My Documents\My Work\Python
Modules\PyOpenGL-Demo-3.0.0b6\PyOpenGL-Demo\NeHe\lesson1.py", line 142, in


main()

  File "C:\Documents and Settings\Owner\My Documents\My Work\Python
Modules\PyOpenGL-Demo-3.0.0b6\PyOpenGL-Demo\NeHe\lesson1.py", line 97, in
main

glutInit(sys.argv)

  File "C:\Python25\Lib\site-packages\OpenGL\GLUT\special.py", line 316, in
glutInit

_base_glutInit( ctypes.byref(count), holder )

  File "C:\Python25\Lib\site-packages\OpenGL\GLUT\special.py", line 57, in
_base_glutInit

return __glutInitWithExit(pargc, argv, _exitfunc)

  File "C:\Python25\Lib\site-packages\OpenGL\platform\baseplatform.py", line
280, in __call__

self.__name__, self.__name__,

NullFunctionError: Attempt to call an undefined function __glutInitWithExit,
check for bool(__glutInitWithExit) before calling

 

I can only think that the installation might be wrong. I have an AMD machine
running Win32 - XP.

 

Hope you can help me?

 

Best regards

 

Dave

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


Re: Java to Python

2009-02-07 Thread Banibrata Dutta
Jython is not an option ?

On Sat, Feb 7, 2009 at 9:54 PM,  wrote:

> Hi
>
> I have a following class that is written Java and makes use of apache
> http client library,I am new to python can any one suggest me a python
> equivalent of this following class,
>
> Thanks ,
>
> public class Authenticate{
>
>  private String storageUserName=null;
>private String storagePassword=null;
>private String authorization=null;
>private String identityHostName = null;
>private String identityPortNumber = null;
>
>private String accessKey=null;
>private String secretKey=null;
>
>public String getStoragePassword() {
>return storagePassword;
>}
>
>public void setStoragePassword(String storagePassword) {
>this.storagePassword = storagePassword;
>}
>
>public String getStorageUserName() {
>return storageUserName;
>}
>
>public void setStorageUserName(String storageUserName) {
>this.storageUserName = storageUserName;
>}
>
>public String getIdentityHostName() {
>return identityHostName;
>}
>
>public void setIdentityHostName(String identityHostName) {
>this.identityHostName = identityHostName;
>}
>
>public String getIdentityPortNumber() {
>return identityPortNumber;
>}
>
>public void setIdentityPortNumber(String identityPortNumber) {
>this.identityPortNumber = identityPortNumber;
>}
>
>public String getAccessKey() {
>return accessKey;
>}
>
>public void setAccessKey(String accessKey) {
>this.accessKey = accessKey;
>}
>
>public String getSecretKey() {
>return secretKey;
>}
>
>public void setSecretKey(String secretKey) {
>this.secretKey = secretKey;
>}
>
>
> /**
> * Convenience string for Base 64 encoding.
> */
>private static final String BASE64_CHARS =
>"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
>"abcdefghijklmnopqrstuvwxyz" +
>"0123456789+/";
>
>/**
> * Encode the specified credentials into a String as required
> by
> * HTTP Basic Authentication (http://www.ietf.org/rfc/
> rfc2617.txt">RFC 2617).
> *
> * @param username Username to be encoded
> * @param password Password to be encoded
> * @return String string containing encoded username and password.
> */
>public String encodeCredentialsBasic(String username, String
> password) {
>String encode = username + ":" + password;
>int paddingCount = (3 - (encode.length() % 3)) % 3;
>encode += "\0\0".substring(0, paddingCount);
>StringBuilder encoded = new StringBuilder();
>
>for (int i = 0; i < encode.length(); i += 3) {
>}
>return encoded.toString();
>}
>
>public void fetchDetails(){
>HttpClient client=new HttpClient();
>//reqDetails = new RequestDetails();
>//String identityURL=MessageUtil.getMessage
> ("IDENTITY_INSTANCE");
>//int portNumber=Integer.parseInt(MessageUtil.getMessage
> ("IDENTITY_PORT"));
>authorization="Basic " + encodeCredentialsBasic
> (storageUserName, storagePassword);
>String url="https://"+identityHostName+
>":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
> +"/attributes/";
>
>Protocol https=null;
>//try {
>https = new Protocol("https", new
> EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
>/*} catch (GeneralSecurityException ex) {
>Logger.getLogger(Authenticate.class.getName()).log
> (Level.SEVERE, null, ex);
>} catch (IOException ex) {
>Logger.getLogger(Authenticate.class.getName()).log
> (Level.SEVERE, null, ex);
>}*/
>Protocol.registerProtocol("https", https);
>GetMethod method=new GetMethod(url);
>method.setRequestHeader("Authorization",authorization);
>method.setRequestHeader("Accept","application/xml");
>try {
>int responseCode=client.executeMethod(method);
>if(responseCode==200){
>InputStream is=method.getResponseBodyAsStream();
>BufferedReader bis=new BufferedReader(new
> InputStreamReader(is));
>String temp=null,sKey=null, aKey=null;
>String accessKeySearchString="AccessKey Name>";
>String secretKeySearchString="SecretKey Name>";
>int searchStringLength=0;
>while((temp=bis.readLine())!=null){
>if(temp.indexOf(accessKeySearchString)!=-1){
>int beginIndex=temp.indexOf
> (accessKeySearchString);
>searchStringLength=accessKeySearchString.length
> ();
>int endIndex=temp.indexOf(" Value>",beginIndex);
>aKey=temp.substring(beginIndex
> +searchStringLength,endIndex);
>}
>if(temp.indexOf(secretKeySearchString)!=-1){
> 

Java to Python

2009-02-07 Thread zaheer . agadi
Hi

I have a following class that is written Java and makes use of apache
http client library,I am new to python can any one suggest me a python
equivalent of this following class,

Thanks ,

public class Authenticate{

 private String storageUserName=null;
private String storagePassword=null;
private String authorization=null;
private String identityHostName = null;
private String identityPortNumber = null;

private String accessKey=null;
private String secretKey=null;

public String getStoragePassword() {
return storagePassword;
}

public void setStoragePassword(String storagePassword) {
this.storagePassword = storagePassword;
}

public String getStorageUserName() {
return storageUserName;
}

public void setStorageUserName(String storageUserName) {
this.storageUserName = storageUserName;
}

public String getIdentityHostName() {
return identityHostName;
}

public void setIdentityHostName(String identityHostName) {
this.identityHostName = identityHostName;
}

public String getIdentityPortNumber() {
return identityPortNumber;
}

public void setIdentityPortNumber(String identityPortNumber) {
this.identityPortNumber = identityPortNumber;
}

public String getAccessKey() {
return accessKey;
}

public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}

public String getSecretKey() {
return secretKey;
}

public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}


 /**
 * Convenience string for Base 64 encoding.
 */
private static final String BASE64_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789+/";

/**
 * Encode the specified credentials into a String as required
by
 * HTTP Basic Authentication (http://www.ietf.org/rfc/
rfc2617.txt">RFC 2617).
 *
 * @param username Username to be encoded
 * @param password Password to be encoded
 * @return String string containing encoded username and password.
 */
public String encodeCredentialsBasic(String username, String
password) {
String encode = username + ":" + password;
int paddingCount = (3 - (encode.length() % 3)) % 3;
encode += "\0\0".substring(0, paddingCount);
StringBuilder encoded = new StringBuilder();

for (int i = 0; i < encode.length(); i += 3) {
}
return encoded.toString();
}

public void fetchDetails(){
HttpClient client=new HttpClient();
//reqDetails = new RequestDetails();
//String identityURL=MessageUtil.getMessage
("IDENTITY_INSTANCE");
//int portNumber=Integer.parseInt(MessageUtil.getMessage
("IDENTITY_PORT"));
authorization="Basic " + encodeCredentialsBasic
(storageUserName, storagePassword);
String url="https://"+identityHostName+
":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
+"/attributes/";

Protocol https=null;
//try {
https = new Protocol("https", new
EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
/*} catch (GeneralSecurityException ex) {
Logger.getLogger(Authenticate.class.getName()).log
(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Authenticate.class.getName()).log
(Level.SEVERE, null, ex);
}*/
Protocol.registerProtocol("https", https);
GetMethod method=new GetMethod(url);
method.setRequestHeader("Authorization",authorization);
method.setRequestHeader("Accept","application/xml");
try {
int responseCode=client.executeMethod(method);
if(responseCode==200){
InputStream is=method.getResponseBodyAsStream();
BufferedReader bis=new BufferedReader(new
InputStreamReader(is));
String temp=null,sKey=null, aKey=null;
String accessKeySearchString="AccessKey";
String secretKeySearchString="SecretKey";
int searchStringLength=0;
while((temp=bis.readLine())!=null){
if(temp.indexOf(accessKeySearchString)!=-1){
int beginIndex=temp.indexOf
(accessKeySearchString);
searchStringLength=accessKeySearchString.length
();
int endIndex=temp.indexOf("",beginIndex);
aKey=temp.substring(beginIndex
+searchStringLength,endIndex);
}
if(temp.indexOf(secretKeySearchString)!=-1){
int beginIndex=temp.indexOf
(secretKeySearchString);
searchStringLength=secretKeySearchString.length
();
int endIndex=temp.indexOf("",beginIndex);
sKey=temp.subs

Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Benjamin Peterson
Terry  gmail.com> writes:
> On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> > Do you by any chance have a few examples of these? There is a lot of
> > idiomatic code in python to e.g. acquire and release the GIL or doing
> > refcount-stuff. If that happens to be done with rather generic names as
> > arguments, I can well imagine that as being the cause.

> Starting at line 5119 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c

This isn't really fair because Python-ast.c is auto generated. ;)




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


Re: Tkinter w.pack()?

2009-02-07 Thread W. eWatson

MRAB wrote:

W. eWatson wrote:

...
I thought some months ago, I found Google commands that would operate 
in the browser link window. Guess not.


BTW, isn't there an O'Reilly book on Google hacks of this sort? Where 
else does one find out about these Google tools?



Google? :-)

http://www.google.com/support/websearch/bin/answer.py?hl=en&answer=136861

Thanks. I may have that book marked from many, many months ago. If so, I see 
why I'd never find it. The BM entry does not show "Google". It does now. ;-)


--
   W. eWatson

 (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

Web Page: 

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


Re: "Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread Diez B. Roggisch

Peter Otten schrieb:

Andreas Waldenburger wrote:


I've found something in the spirit of the following (in the epydoc
sources, if you care):

if True:
print "outer if"
for t in range(2):
if True:
print "for if"
else:
print "phantom else"

For the life of me I can't place the "else". Which if clause does it
belong to? None, it would seem from running the above snippet:

outer if
For if
For if
Phantom else

It seems that there is a for...else construct. Replacing the inner if
with pass seems to confirm this. The else clause is still executed.

What's broken here: Python or my brain?


Your rtfm sensor?

http://docs.python.org/reference/compound_stmts.html#the-for-statement

In short, the else suite is executed unless the for-loop is left
via 'break':


Or exceptions of course. Might be obvious, but for completeness' sake.

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


Re: Is c.l.py becoming less friendly?

2009-02-07 Thread floatingpeanut
On Feb 7, 2:37 am, Terry Reedy  wrote:
>   So I think python-list has become more friendly since.

I've experienced the same sort of thing. About a year ago (I think)
there were one or more regulars here who were often somewhat rude,
unfriendly, or snobbish (not naming any names). Trouble was, they were
experienced and often helpful too so the behaviour was mostly
tolerated.

Haven't seen that sort of thing in a while though. c.l.py is a very
friendly place these days.
--
http://mail.python.org/mailman/listinfo/python-list


BaseHTTPRequestHandler freezes while writing to self.wfile after installing Python 3.0

2009-02-07 Thread mail
Hey guys,

I'm starting to lose my head with this one.

I have a class that extends BaseHTTPRequestHandler. It works fine on
Python 2.5. And yesterday I was curious and decided to install Python
3.0 on my Mac (I followed this tutorial, to be sure I wasn't messing
things up: 
http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/
). I tried my application on Python 3.0 and the code just freezed on
this line:

self.wfile.write(f.read())

I searched and got to this bug http://bugs.python.org/issue3826 . I
couldn't understand if there's already a fix for that. But, the
strangest thing was that, when I tried my application on 2.5, it
started freezing on the same spot! I then removed everything I
installed from 3.0, fixed the paths, and it still gives me the error.
I don't know what else to do.

The app works fine on 2.5, because I tried it on another computer.

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


Newbie SWMixer / numpy help - AssertionError

2009-02-07 Thread Peter Chant
Hello,

I'm a bit of a python newby.  I want to play and record sound
simultaneously.  SWMixer seems able to do this but the examples use WAV
files.  I'm trying to play a test tone.  Can anyone give me a steer as to
why this fails?

import sys
import swmixer
import numpy


swmixer.init(samplerate=44100, chunksize=1024, stereo=False,
microphone=True)
#snd = swmixer.Sound("test1.wav")
time = 1
freq = 440
time = numpy.linspace(0,1,44100*time)   # 44100 numbers between 0 and 1
tone_data = numpy.sin(time*2*numpy.pi*freq) # A above Middle C
snd = swmixer.Sound(tone_data)

snd.play(loops=-1)

I know this may be in a little at the deep end for someone who has just
started to learn python, but I find I learn a lot faster if I try to do
something that is useful.

Pete


-- 
http://www.petezilla.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread MRAB

Andreas Waldenburger wrote:

On Sun, 08 Feb 2009 01:28:00 +1100 Steven D'Aprano
 wrote:


Andreas Waldenburger wrote:


It seems that there is a for...else construct. Replacing the inner
if with pass seems to confirm this. The else clause is still
executed.

Yes, there is a for...else construct.


That's something. In 6+ years of Python programming I've never seen or
heard of this thing. This might be useful, apparently.


One use case is:

for x in list_of_items:
if x.value == desired_value:
desired_name = x.name
break
else:
   print "Couldn't find %s" % x.value




[snip]


What's broken here: Python or my brain?

Perhaps we should not answer that question.


I did phrase that rather provocatively, didn't I?

Well thanks. I'll try to learn less noisily in the future. :)



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


Re: Trouble with regular expressions

2009-02-07 Thread MRAB

LaundroMat wrote:

Hi,

I'm quite new to regular expressions, and I wonder if anyone here
could help me out.

I'm looking to split strings that ideally look like this: "Update: New
item (Household)" into a group.
This expression works ok: '^(Update:)?(.*)(\(.*\))$' - it returns
("Update", "New item", "(Household)")

Some strings will look like this however: "Update: New item (item)
(Household)". The expression above still does its job, as it returns
("Update", "New item (item)", "(Household)").

It does not work however when there is no text in parentheses (eg
"Update: new item"). How can I get the expression to return a tuple
such as ("Update:", "new item", None)?

You need to make the last group optional and also make the middle group 
lazy: r'^(Update:)?(.*?)(?:(\(.*\)))?$'.


(?:...) is the non-capturing version of (...).

If you don't make the middle group lazy then it'll capture the rest of 
the string and the last group would never match anything!

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


Re: "Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread Andreas Waldenburger
On Sun, 08 Feb 2009 01:28:00 +1100 Steven D'Aprano
 wrote:

> Andreas Waldenburger wrote:
> 
> > It seems that there is a for...else construct. Replacing the inner
> > if with pass seems to confirm this. The else clause is still
> > executed.
> 
> Yes, there is a for...else construct.
> 
That's something. In 6+ years of Python programming I've never seen or
heard of this thing. This might be useful, apparently.


> [snip]
> 
> > What's broken here: Python or my brain?
> 
> Perhaps we should not answer that question.
> 
I did phrase that rather provocatively, didn't I?

Well thanks. I'll try to learn less noisily in the future. :)

/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread Peter Otten
Andreas Waldenburger wrote:

> I've found something in the spirit of the following (in the epydoc
> sources, if you care):
> 
> if True:
> print "outer if"
> for t in range(2):
> if True:
> print "for if"
> else:
> print "phantom else"
> 
> For the life of me I can't place the "else". Which if clause does it
> belong to? None, it would seem from running the above snippet:
> 
> outer if
> For if
> For if
> Phantom else
> 
> It seems that there is a for...else construct. Replacing the inner if
> with pass seems to confirm this. The else clause is still executed.
> 
> What's broken here: Python or my brain?

Your rtfm sensor?

http://docs.python.org/reference/compound_stmts.html#the-for-statement

In short, the else suite is executed unless the for-loop is left
via 'break':

>>> for i in [1]:
... break
... else:
... print "else"
...
>>> for i in [1]:
... pass
... else:
... print "else"
...
else
>>>

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


py2exe and distutils

2009-02-07 Thread Maxim Demenko

Hi,
i have installed Python 2.5.4 on WinXP, setuptools-0.6c9 and py2exe 0.6.9
Now i can't list installed modules, here is the stacktrace:



help> modules

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

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Programme\Python25\lib\site.py", line 346, in __call__
return pydoc.help(*args, **kwds)
  File "C:\Programme\Python25\lib\pydoc.py", line 1649, in __call__
self.interact()
  File "C:\Programme\Python25\lib\pydoc.py", line 1667, in interact
self.help(request)
  File "C:\Programme\Python25\lib\pydoc.py", line 1683, in help
elif request == 'modules': self.listmodules()
  File "C:\Programme\Python25\lib\pydoc.py", line 1804, in listmodules
ModuleScanner().run(callback)
  File "C:\Programme\Python25\lib\pydoc.py", line 1855, in run
for importer, modname, ispkg in pkgutil.walk_packages():
  File "C:\Programme\Python25\lib\pkgutil.py", line 110, in walk_packages
__import__(name)
  File 
"C:\Programme\Python25\Lib\site-packages\setuptools\__init__.py", line 
2, in 

from setuptools.extension import Extension, Library
  File 
"C:\Programme\Python25\Lib\site-packages\setuptools\extension.py", line 
2, in 

from dist import _get_unpatched
  File "C:\Programme\Python25\Lib\site-packages\setuptools\dist.py", 
line 27, in 

_Distribution = _get_unpatched(_Distribution)
  File "C:\Programme\Python25\Lib\site-packages\setuptools\dist.py", 
line 23, in _get_unpatched

"distutils has already been patched by %r" % cls
AssertionError: distutils has already been patched by py2exe.Distribution at 0x011B4F90>


Any suggestion, how to fix this issue?

Best regards

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


Re: "Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread Steven D'Aprano
Andreas Waldenburger wrote:

> It seems that there is a for...else construct. Replacing the inner if
> with pass seems to confirm this. The else clause is still executed.

Yes, there is a for...else construct.

The else block runs if the for loop exits *without* a break.

for i in range(20):
if i == 10: break
else:
print "no break here"

for i in range(20):
if i == 100: break
else:
print "no break here"


> What's broken here: Python or my brain?

Perhaps we should not answer that question.


-- 
Steven

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


Re: "Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread Andreas Waldenburger
On Sat, 7 Feb 2009 15:21:22 +0100 Andreas Waldenburger
 wrote:

> outer if
> For if
> For if
> Phantom else
> 
Geez, I'm a moron. This is obviously not the output from the snippet.
But if you fix the capitalization, it is. Sorry for that.

/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Flattening lists

2009-02-07 Thread rdmurray
Rhamphoryncus  wrote:
> On Feb 6, 10:21=A0pm, rdmur...@bitdance.com wrote:
> > Quoth Mensanator :
> > > def flatten(listOfLists):
> > > =A0 =A0 return list(chain.from_iterable(listOfLists))
> >
> > =A0 =A0 Python 2.6.1 (r261:67515, Jan =A07 2009, 17:09:13)
> > =A0 =A0 [GCC 4.3.2] on linux2
> > =A0 =A0 Type "help", "copyright", "credits" or "license" for more informa=
> tion.
> > =A0 =A0 >>> from itertools import chain
> > =A0 =A0 >>> list(chain.from_iterable([1, 2, [3, 4]]))
> > =A0 =A0 Traceback (most recent call last):
> > =A0 =A0 =A0 File "", line 1, in 
> > =A0 =A0 TypeError: 'int' object is not iterable
> > =A0 =A0 >>> list(chain(*[1, 2, [3, 4]]))
> > =A0 =A0 Traceback (most recent call last):
> > =A0 =A0 =A0 File "", line 1, in 
> > =A0 =A0 TypeError: 'int' object is not iterable
> > =A0 =A0 >>> list(chain.from_iterable(['abcd', 'efg', [3, 4]]))
> > =A0 =A0 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 3, 4]
> 
> What usecase do you have for such inconsistently structured data?
> 
> If I'm building a tree I use my own type for the nodes, keeping them
> purely internal, so I can always use isinstance without worrying about
> getting something inconvenient passed in.

I don't have any use cases myself, I'm just pointing out that this
doesn't answer the concerns of the OP, who presumably does.

--RDM

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


"Weird" Indentation? (Or: is there a for...else construct?)

2009-02-07 Thread Andreas Waldenburger
I've found something in the spirit of the following (in the epydoc
sources, if you care):

if True:
print "outer if"
for t in range(2):
if True:
print "for if"
else:
print "phantom else"

For the life of me I can't place the "else". Which if clause does it
belong to? None, it would seem from running the above snippet:

outer if
For if
For if
Phantom else

It seems that there is a for...else construct. Replacing the inner if
with pass seems to confirm this. The else clause is still executed.

What's broken here: Python or my brain?

/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with regular expressions

2009-02-07 Thread John Machin
On Feb 7, 11:18 pm, LaundroMat  wrote:
> Hi,
>
> I'm quite new to regular expressions, and I wonder if anyone here
> could help me out.
>
> I'm looking to split strings that ideally look like this: "Update: New
> item (Household)" into a group.
> This expression works ok: '^(Update:)?(.*)(\(.*\))$' - it returns
> ("Update", "New item", "(Household)")
>
> Some strings will look like this however: "Update: New item (item)
> (Household)". The expression above still does its job, as it returns
> ("Update", "New item (item)", "(Household)").
>
> It does not work however when there is no text in parentheses (eg
> "Update: new item"). How can I get the expression to return a tuple
> such as ("Update:", "new item", None)?

I don't see how it can be done without some post-matching adjustment.
Try this:

C:\junk>type mathieu.py
import re

tests = [
"Update: New item (Household)",
"Update: New item (item) (Household)",
"Update: new item",
"minimal",
"parenthesis (plague) (has) (struck)",
]

regex = re.compile("""
(Update:)?  # optional prefix
\s* # ignore whitespace
([^()]*)# any non-parentheses stuff
(\([^()]*\))?   # optional (blahblah)
\s*# ignore whitespace
(\([^()]*\))?   # another optional (blahblah)
$
""", re.VERBOSE)

for i, test in enumerate(tests):
print "Test #%d: %r" % (i, test)
m = regex.match(test)
if not m:
print "No match"
else:
g = m.groups()
print g
if g[3] is not None:
x = (g[0], g[1] + g[2], g[3])
else:
x = g[:3]
print x
print

C:\junk>mathieu.py
Test #0: 'Update: New item (Household)'
('Update:', 'New item ', '(Household)', None)
('Update:', 'New item ', '(Household)')

Test #1: 'Update: New item (item) (Household)'
('Update:', 'New item ', '(item)', '(Household)')
('Update:', 'New item (item)', '(Household)')

Test #2: 'Update: new item'
('Update:', 'new item', None, None)
('Update:', 'new item', None)

Test #3: 'minimal'
(None, 'minimal', None, None)
(None, 'minimal', None)

Test #4: 'parenthesis (plague) (has) (struck)'
No match

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


urllib2: problem of handling space in parameter

2009-02-07 Thread rdmurray
Quoth Muddy Coder :
> Hi Folks,
> 
> I encrountered a problem of using urllib2: the space handling. Look at
> the code below:
> 
> import urllib2
> url = r'http://somedomain.com/a.cgi?name=muddy coder&password=foobar
> cgi_back = urllib2.urlopen(url).read()
> 
> In this cgi_back, I saw field password worked fine, but field name
> not, only muddy was picked up by CGI. So, I had to cover the space, by
> using syntax name=muddy-coder, it went through. So, I presume urllib2
> may have an approach of handling white space in this regard. Can
> anybody help? Thanks!

urllib.urlencode.  Unecoded spaces aren't actually valid in a URL.

--David

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


typedef (type alias) and ctypes

2009-02-07 Thread Yosifov Pavel
I try to create type aliases, like typedef in C (a specially aliases
to ctypes objects). This case:

>>> some_type = c_ulong
>>> oth_type = c_ulong

works in all cases but not with type qualification:

>>> t1 = c_ulong # reference to c_ulong, nothing else :(
>>> t2 = c_ulong
>>> x = t1()
>>> y = t2()
>>> type(x)==type(y)
True

This trivial way for typedef doesn't allow to determine real type and
it's absolutely right :)

>>> t1 = type('t1',(c_ulong,),{})
>>> t2 = type('t2',(c_ulong,),{})
>>> x = t1()
>>> y = t2()
>>> type(x)==type(y)
False

The problem:
1st way work in complex using of ctypes (interfacing with some DLLs),
but doesn't allow to determine real type!
2st way allows to determine real type, but "access violation reading
0x000C'" occurs in some DLL calls!

Question: what "warts", errors are in 2nd way (may be reason of access
violation)?

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


urllib2: problem of handling space in parameter

2009-02-07 Thread Muddy Coder
Hi Folks,

I encrountered a problem of using urllib2: the space handling. Look at
the code below:

import urllib2
url = r'http://somedomain.com/a.cgi?name=muddy coder&password=foobar
cgi_back = urllib2.urlopen(url).read()

In this cgi_back, I saw field password worked fine, but field name
not, only muddy was picked up by CGI. So, I had to cover the space, by
using syntax name=muddy-coder, it went through. So, I presume urllib2
may have an approach of handling white space in this regard. Can
anybody help? Thanks!

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> Terry schrieb:
>
> > On 2月7日, 下午3时36分, "Martin v. Löwis"  wrote:
> >>> Does that say something about the code quality of Python3.0?
> >> Not necessarily. IIUC, copying a single file with 2000 lines
> >> completely could already account for that increase.
>
> >> It would be interesting to see what specific files have gained
> >> large numbers of additional files, compared to 2.5.
>
> >> Regards,
> >> Martin
>
> > But the duplication are always not very big, from about 100 lines
> > (rare) to less the 5 lines. As you can see the Rate30 is much bigger
> > than Rate60, that means there are a lot of small duplications.
>
> Do you by any chance have a few examples of these? There is a lot of
> idiomatic code in python to e.g. acquire and release the GIL or doing
> refcount-stuff. If that happens to be done with rather generic names as
> arguments, I can well imagine that as being the cause.
>
> Diez

And I'm not saying that you can not have duplication in code. But it
seems that the stable & successful software releases tend to have
relatively stable duplication rate.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> Terry schrieb:
>
> > On 2月7日, 下午3时36分, "Martin v. Löwis"  wrote:
> >>> Does that say something about the code quality of Python3.0?
> >> Not necessarily. IIUC, copying a single file with 2000 lines
> >> completely could already account for that increase.
>
> >> It would be interesting to see what specific files have gained
> >> large numbers of additional files, compared to 2.5.
>
> >> Regards,
> >> Martin
>
> > But the duplication are always not very big, from about 100 lines
> > (rare) to less the 5 lines. As you can see the Rate30 is much bigger
> > than Rate60, that means there are a lot of small duplications.
>
> Do you by any chance have a few examples of these? There is a lot of
> idiomatic code in python to e.g. acquire and release the GIL or doing
> refcount-stuff. If that happens to be done with rather generic names as
> arguments, I can well imagine that as being the cause.
>
> Diez

Example of a even small one (30 token duplicated):
Found a 11 line (30 tokens) duplication in the following files:
Starting at line 2551 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c
Starting at line 3173 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c

if (PyObject_SetAttrString(result, "ifs", value) == -1)
goto failed;
Py_DECREF(value);
return result;
failed:
Py_XDECREF(value);
Py_XDECREF(result);
return NULL;
}

PyObject*

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> Terry schrieb:
>
> > On 2月7日, 下午3时36分, "Martin v. Löwis"  wrote:
> >>> Does that say something about the code quality of Python3.0?
> >> Not necessarily. IIUC, copying a single file with 2000 lines
> >> completely could already account for that increase.
>
> >> It would be interesting to see what specific files have gained
> >> large numbers of additional files, compared to 2.5.
>
> >> Regards,
> >> Martin
>
> > But the duplication are always not very big, from about 100 lines
> > (rare) to less the 5 lines. As you can see the Rate30 is much bigger
> > than Rate60, that means there are a lot of small duplications.
>
> Do you by any chance have a few examples of these? There is a lot of
> idiomatic code in python to e.g. acquire and release the GIL or doing
> refcount-stuff. If that happens to be done with rather generic names as
> arguments, I can well imagine that as being the cause.
>
> Diez

Example of a small one (61 token duplicated):
Found a 19 line (61 tokens) duplication in the following files:
Starting at line 132 of D:\DOWNLOADS\Python-3.0\Python\modsupport.c
Starting at line 179 of D:\DOWNLOADS\Python-3.0\Python\modsupport.c

PyTuple_SET_ITEM(v, i, w);
}
if (itemfailed) {
/* do_mkvalue() should have already set an error */
Py_DECREF(v);
return NULL;
}
if (**p_format != endchar) {
Py_DECREF(v);
PyErr_SetString(PyExc_SystemError,
"Unmatched paren in format");
return NULL;
}
if (endchar)
++*p_format;
return v;
}

static PyObject *

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> Terry schrieb:
>
> > On 2月7日, 下午3时36分, "Martin v. Löwis"  wrote:
> >>> Does that say something about the code quality of Python3.0?
> >> Not necessarily. IIUC, copying a single file with 2000 lines
> >> completely could already account for that increase.
>
> >> It would be interesting to see what specific files have gained
> >> large numbers of additional files, compared to 2.5.
>
> >> Regards,
> >> Martin
>
> > But the duplication are always not very big, from about 100 lines
> > (rare) to less the 5 lines. As you can see the Rate30 is much bigger
> > than Rate60, that means there are a lot of small duplications.
>
> Do you by any chance have a few examples of these? There is a lot of
> idiomatic code in python to e.g. acquire and release the GIL or doing
> refcount-stuff. If that happens to be done with rather generic names as
> arguments, I can well imagine that as being the cause.
>
> Diez

Example 2:
Found a 16 line (106 tokens) duplication in the following files:
Starting at line 4970 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c
Starting at line 5015 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c
Starting at line 5073 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c
Starting at line 5119 of D:\DOWNLOADS\Python-3.0\Python\Python-ast.c

PyErr_Format(PyExc_TypeError,
"GeneratorExp field \"generators\" must be a list, not a %.200s", tmp-
>ob_type->tp_name);
goto failed;
}
len = PyList_GET_SIZE(tmp);
generators = asdl_seq_new(len, arena);
if (generators == NULL) goto failed;
for (i = 0; i < len; i++) {
comprehension_ty value;
res = obj2ast_comprehension
(PyList_GET_ITEM(tmp, i), &value, arena);
if (res != 0) goto failed;
asdl_seq_SET(generators, i, value);
}
Py_XDECREF(tmp);
tmp = NULL;
} else {
PyErr_SetString(PyExc_TypeError, "required
field \"generators\" missing from GeneratorExp");

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月7日, 下午7时10分, "Diez B. Roggisch"  wrote:
> Terry schrieb:
>
> > On 2月7日, 下午3时36分, "Martin v. Löwis"  wrote:
> >>> Does that say something about the code quality of Python3.0?
> >> Not necessarily. IIUC, copying a single file with 2000 lines
> >> completely could already account for that increase.
>
> >> It would be interesting to see what specific files have gained
> >> large numbers of additional files, compared to 2.5.
>
> >> Regards,
> >> Martin
>
> > But the duplication are always not very big, from about 100 lines
> > (rare) to less the 5 lines. As you can see the Rate30 is much bigger
> > than Rate60, that means there are a lot of small duplications.
>
> Do you by any chance have a few examples of these? There is a lot of
> idiomatic code in python to e.g. acquire and release the GIL or doing
> refcount-stuff. If that happens to be done with rather generic names as
> arguments, I can well imagine that as being the cause.
>
> Diez

Example 1:
Found a 64 line (153 tokens) duplication in the following files:
Starting at line 73 of D:\DOWNLOADS\Python-3.0\Python\thread_pth.h
Starting at line 222 of D:\DOWNLOADS\Python-3.0\Python
\thread_pthread.h

return (long) threadid;
#else
return (long) *(long *) &threadid;
#endif
}

static void
do_PyThread_exit_thread(int no_cleanup)
{
dprintf(("PyThread_exit_thread called\n"));
if (!initialized) {
if (no_cleanup)
_exit(0);
else
exit(0);
}
}

void
PyThread_exit_thread(void)
{
do_PyThread_exit_thread(0);
}

void
PyThread__exit_thread(void)
{
do_PyThread_exit_thread(1);
}

#ifndef NO_EXIT_PROG
static void
do_PyThread_exit_prog(int status, int no_cleanup)
{
dprintf(("PyThread_exit_prog(%d) called\n", status));
if (!initialized)
if (no_cleanup)
_exit(status);
else
exit(status);
}

void
PyThread_exit_prog(int status)
{
do_PyThread_exit_prog(status, 0);
}

void
PyThread__exit_prog(int status)
{
do_PyThread_exit_prog(status, 1);
}
#endif /* NO_EXIT_PROG */

#ifdef USE_SEMAPHORES

/*
 * Lock support.
 */

PyThread_type_lock
PyThread_allocate_lock(void)
{

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


PyCon 2009 Tutorial Days

2009-02-07 Thread gslindstrom
Registration for PyCon 2009  (US) is
open.  Because of the popularity of the tutorials in years past, this year
features 2 days of tutorials  (32 total
class on Wednesday, March 25 and Thursday, March 26) including:

   - 2 tracks on Introduciton to Python
   - Working with Excel
spreadsheets
   - GIS with Python 
   - Django 
   - Concurrency  and
   Kamaelia 
   - Testing 
   - SQLAlchemy 
   - Advanced topics
   
   - much, much more 

These classes are being presented by some of the smartest cookies in the
Python community and are 3-hours each (with break).  You get to rub
shoulders with other Python programmers who share your interests and all
sessions have time for you to ask questions.  There is a (modest) cost to
attend, but you will get great training as well as class notes.  We even
feed you lunch and provide snacks during the breaks.

Click http://us.pycon.org/2009/about/ for more information.  Questions?
Email us at pycon-tutori...@python.org.

Greg Lindstrom
Tutorial Coordinator
--
http://mail.python.org/mailman/listinfo/python-list


Re: Running all unit tests

2009-02-07 Thread Jason Voegele
Ben Finney wrote:
> Jason Voegele  writes:
> 
>> What's the recommended approach for Python programs? I'm sure I
>> could write a shell script (or a Python script even) that scans my
>> "test" directory for test cases and runs them, but I'm wondering if
>> there's something already built in that could do this for me.
> 
> The lack of a built-in ???collect and run all the tests in this working
> tree??? in the Python unit test system is a known problem; discussions
> are ongoing what to do about it.
> 
> Meanwhile, the third-party ???nose??? system
> http://somethingaboutorange.com/mrl/projects/nose/> provides this
> and much more, while remaining compatible with both testing systems in
> the standard library.
> 
> I generally set up a ???test??? target in my Makefile, such that it will
> use ???nosetests??? to collect and run all the tests; then I just run
> ???make test??? in a loop that is triggered by any filesystem change in my
> project working tree.

Thanks to all for the helpful responses.  It's good to know I'm not the only 
one that has thought of this as a shortcoming.

-- 
Jason Voegele
Different all twisty a of in maze are you, passages little.


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


Trouble with regular expressions

2009-02-07 Thread LaundroMat
Hi,

I'm quite new to regular expressions, and I wonder if anyone here
could help me out.

I'm looking to split strings that ideally look like this: "Update: New
item (Household)" into a group.
This expression works ok: '^(Update:)?(.*)(\(.*\))$' - it returns
("Update", "New item", "(Household)")

Some strings will look like this however: "Update: New item (item)
(Household)". The expression above still does its job, as it returns
("Update", "New item (item)", "(Household)").

It does not work however when there is no text in parentheses (eg
"Update: new item"). How can I get the expression to return a tuple
such as ("Update:", "new item", None)?

Thanks in advance,

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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Diez B. Roggisch

Terry schrieb:

On 2月7日, 下午3时36分, "Martin v. Löwis"  wrote:

Does that say something about the code quality of Python3.0?

Not necessarily. IIUC, copying a single file with 2000 lines
completely could already account for that increase.

It would be interesting to see what specific files have gained
large numbers of additional files, compared to 2.5.

Regards,
Martin


But the duplication are always not very big, from about 100 lines
(rare) to less the 5 lines. As you can see the Rate30 is much bigger
than Rate60, that means there are a lot of small duplications.


Do you by any chance have a few examples of these? There is a lot of 
idiomatic code in python to e.g. acquire and release the GIL or doing 
refcount-stuff. If that happens to be done with rather generic names as 
arguments, I can well imagine that as being the cause.


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


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-07 Thread Terry
On 2月7日, 下午3时36分, "Martin v. Löwis"  wrote:
> > Does that say something about the code quality of Python3.0?
>
> Not necessarily. IIUC, copying a single file with 2000 lines
> completely could already account for that increase.
>
> It would be interesting to see what specific files have gained
> large numbers of additional files, compared to 2.5.
>
> Regards,
> Martin

But the duplication are always not very big, from about 100 lines
(rare) to less the 5 lines. As you can see the Rate30 is much bigger
than Rate60, that means there are a lot of small duplications.
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess returncode windows

2009-02-07 Thread Duncan Booth
Andrew  wrote:

> As well as not using that and removing "endlocal" which
> I admit I have no clue what that does.

Python isn't the only system in the world to include a help command.

C:\>help endlocal
Ends localization of environment changes in a batch file.
Environment changes made after ENDLOCAL has been issued are
not local to the batch file; the previous settings are not
restored on termination of the batch file.

ENDLOCAL

If Command Extensions are enabled ENDLOCAL changes as follows:

If the corresponding SETLOCAL enable or disabled command extensions
using the new ENABLEEXTENSIONS or DISABLEEXTENSIONS options, then
after the ENDLOCAL, the enabled/disabled state of command extensions
will be restored to what it was prior to the matching SETLOCAL
command execution.
--
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 performance on windows, usb connection

2009-02-07 Thread dq

MRAB wrote:

dq wrote:

MRAB wrote:

dq wrote:

dq wrote:

MRAB wrote:

dq wrote:

Martin v. Löwis wrote:
So does anyone know what the deal is with this?  Why is the 
same code so much slower on Windows?  Hope someone can tell me 
before a holy war erupts :-)


Only the holy war can give an answer here. It certainly has
 *nothing* to do with Python; Python calls the operating system 
functions to read from the network and write to the disk almost 
directly. So it must be the operating system itself that slows 
it down.


To investigate further, you might drop the write operating,
 and measure only source.read(). If that is slower, then, for 
some reason, the network speed is bad on Windows. Maybe
 you have the network interfaces misconfigured? Maybe you are 
using wireless on Windows, but cable on Linux? Maybe you have 
some network filtering software running on Windows? Maybe it's 
just that Windows sucks?-)


If the network read speed is fine, but writing slows down,
 I ask the same questions. Perhaps you have some virus scanner 
installed that filters all write operations? Maybe

 Windows sucks?

Regards, Martin



Thanks for the ideas, Martin.  I ran a couple of experiments
 to find the culprit, by downloading the same 20 MB file from
 the same fast server. I compared:

1.  DL to HD vs USB iPod. 2.  AV on-access protection on vs.
 off 3.  "source. read()" only vs.  "file.write(
source.read() )"

The culprit is definitely the write speed on the iPod.  That is, 
everything runs plenty fast (~1 MB/s down) as long as I'm
not writing directly to the iPod.  This is kind of odd, because 
if I copy the file over from the HD to the iPod using
 windows (drag-n-drop), it takes about a second or two, so about 
10 MB/s.


So the problem is definitely partially Windows, but it also seems 
that Python's file.write() function is not without blame. It's 
the combination of Windows, iPod and Python's data stream that is 
slowing me down.


I'm not really sure what I can do about this.  I'll experiment a 
little more and see if there's any way around this bottleneck.  
If anyone has run into a problem like this,

 I'd love to hear about it...

You could try copying the file to the iPod using the command line, 
or copying data from disk to iPod in, say, C, anything but Python. 
This would allow you to identify whether Python itself has 
anything to do with it.


Well, I think I've partially identified the problem. target.write( 
source.read() ) runs perfectly fast, copies 20 megs

 in about a second, from HD to iPod.  However, if I run the same
 code in a while loop, using a certain block size, say 
target.write( source.read(4096) ), it takes forever (or at least

 I'm still timing it while I write this post).

The mismatch seems to be between urllib2's block size and the write 
speed of the iPod, I might try to tweak this a little in the code 
and see if it has any effect.


Oh, there we go:   20 megs in 135.8 seconds.  Yeah... I might want 
to try to improve that...


After some tweaking of the block size, I managed to get the DL speed 
up to about 900 Mb/s.  It's still not quite Ubuntu, but it's

 a good order of magnitude better.  The new DL code is pretty much
 this:

""" blocksize = 2 ** 16# plus or minus a power of 2 source = 
urllib2.urlopen( 'url://string' ) target = open( pathname, 'wb') 
fullsize = float( source.info()['Content-Length'] ) DLd = 0 while 
DLd < fullsize: DLd = DLd + blocksize # optional:  write some DL 
progress info # somewhere, e.g. stdout target.close() source.close() 
"""


I'd like to suggest that the block size you add to 'DLd' be the 
actual size of the returned block, just in case the read() doesn't 
return all you asked for (it might not be guaranteed, and the chances

 are that the final block will be shorter, unless 'fullsize' happens
 to be a multiple of 'blocksize').

If less is returned by read() then the while-loop might finish before
 all the data has been downloaded, and if you just add 'blocksize' 
each time it might end up > 'fullsize', ie apparently >100% downloaded!


Interesting.  I'll if to see if any of the downloaded files end 
prematurely :)


btw, I forgot the most important line of the code!

"""
blocksize = 2 ** 16# plus or minus a power of 2
source = urllib2.urlopen( 'url://string' )
target = open( pathname, 'wb')
fullsize = float( source.info()['Content-Length'] )
DLd = 0
while DLd < fullsize:
#  +++
target.write( source.read( blocksize ) )  # +++
#  +++
DLd = DLd + blocksize
# optional:  write some DL progress info
# somewhere, e.g. stdout
target.close()
source.close()
"""

Using that, I'm not quite sure where I can grab onto the value of how 
much was actually read from the block.  I suppose I could use an 
intermediate variable, read the data into it, measure the size, and 
then write it to the file stream, but I'm not sure it would be worth 
the overhead.  Or is there some other magic I should know about?


If I start to get that

Re: Flattening lists

2009-02-07 Thread Rhamphoryncus
On Feb 6, 10:21 pm, rdmur...@bitdance.com wrote:
> Quoth Mensanator :
> > def flatten(listOfLists):
> >     return list(chain.from_iterable(listOfLists))
>
>     Python 2.6.1 (r261:67515, Jan  7 2009, 17:09:13)
>     [GCC 4.3.2] on linux2
>     Type "help", "copyright", "credits" or "license" for more information.
>     >>> from itertools import chain
>     >>> list(chain.from_iterable([1, 2, [3, 4]]))
>     Traceback (most recent call last):
>       File "", line 1, in 
>     TypeError: 'int' object is not iterable
>     >>> list(chain(*[1, 2, [3, 4]]))
>     Traceback (most recent call last):
>       File "", line 1, in 
>     TypeError: 'int' object is not iterable
>     >>> list(chain.from_iterable(['abcd', 'efg', [3, 4]]))
>     ['a', 'b', 'c', 'd', 'e', 'f', 'g', 3, 4]

What usecase do you have for such inconsistently structured data?

If I'm building a tree I use my own type for the nodes, keeping them
purely internal, so I can always use isinstance without worrying about
getting something inconvenient passed in.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is c.l.py becoming less friendly?

2009-02-07 Thread James Stroud

Tim Chase wrote:

Is this where we tell you to shut up?  ;-)


Don't you mean STFU?



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

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


Re: WebError documentation?

2009-02-07 Thread Ron Garret
In article ,
 Chris Rebert  wrote:

> On Thu, Feb 5, 2009 at 12:52 PM, Ron Garret  wrote:
> > Is there any?  Where is it?  Extensive Googling has proven fruitless.
> 
> It's not a standard Python exception. A third-party library you're
> using must be raising it. Check the exception traceback.

I see I did not make myself clear.  I meant the Python software package 
called "weberror", not a generic web error.

http://pypi.python.org/pypi/WebError


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