Re: Using XML w/ Python...

2005-12-12 Thread Jay
when putting excactly what you got, i got
>>> python -c "import amara; print dir(amara)"
Traceback (  File "", line 1
python -c "import amara; print dir(amara)"
 ^
SyntaxError: invalid syntax

when doing it seperately, i got>

>>> import amara
>>> print dir(amara)
['__builtins__', '__doc__', '__file__', '__name__', '__path__',
'__version__', 'binderytools', 'os', 'parse']
>>>

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


Re: Problem with Lexical Scope

2005-12-12 Thread [EMAIL PROTECTED]
Well, I think I found a nasty little hack to get around it, but I still
don't see why it doesn't work in the regular way.

def collect(fields, reducer):
def rule(record):
# Nasty hack b/c can't get lexical scoping of status to work
status = [True]
def _(x, y, s=status):
cstat = reducer(x, y)
if s[0] and not cstat:
s[0] = False
return y
reduce(_, [record[field] for field in fields])
return status[0]
return rule

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread Fredrik Lundh
Steven Bethard wrote:

> > I thought stuff like the following was idiomatic in GUI programming.
> > Do you really want separate names for all those callbacks?
> >
> > # generate calculator keypad buttons
> > Button(label='7', command=lambda: user_pressed(7)).grid(column=1, row=1)
> > Button(label='8', command=lambda: user_pressed(8)).grid(column=2, row=1)
> > Button(label='9', command=lambda: user_pressed(9)).grid(column=3, row=1)
> >
> > Button(label='4', command=lambda: user_pressed(4)).grid(column=1, row=2)
> > Button(label='5', command=lambda: user_pressed(5)).grid(column=2, row=2)
> > Button(label='6', command=lambda: user_pressed(6)).grid(column=3, row=2)
> > ...
>
> While I don't spend much time on GUIs, code like that would scream
> "refactor" to me, e.g. something like:
>
> class UserPressedButton(Button):
>  def __init__(self, i):
>  def command():
>  return user_pressed(i)
>  Button.__init__(self, label=str(i), command=command)
>
> Button(7).grid(column=1, row=1)
> Button(8).grid(column=2, row=1)
> Button(9).grid(column=3, row=1)
>
> Button(4).grid(column=1, row=2)
> Button(5).grid(column=2, row=2)
> Button(6).grid(column=3, row=2)

a temporary factory function should be sufficient:

def digit(label, x, y):
def callback():
# print "BUTTON PRESS", label # debug!
user_pressed(int(label))
Button(label=label, command=callback).grid(column=x, row=y)

# create numeric pad
digit("7", 1, 1); digit("8", 2, 1); digit("9", 3, 1)
digit("4", 1, 2); digit("5", 2, 2); digit("6", 3, 2)
digit("1", 1, 3); digit("2", 2, 3); digit("3", 3, 3)

are people still missing that local functions are inexpensive in Python ?





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


Re: Problem with Lexical Scope

2005-12-12 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> I am not completely knowledgable about the status of lexical scoping in
> Python, but it was my understanding that this was added in a long time
> ago around python2.1-python2.2
> 
> I am using python2.4 and the following code throws a "status variable"
> not found in the inner-most function, even when I try to "global" it.
> 
> def collect(fields, reducer):
> def rule(record):
> status = True
> def _(x, y):
> cstat = reducer(x, y)
> if status and not cstat:
> status = False
> return y
> return reduce(_, [record[field] for field in fields])
> return rule
> 
> What gives?
> 
What's happening is that the interpreter, when it compiles the inner 
function _(), sees an assignment to status and so assumes it is local to 
the _() function. Consequently, since you reference it inside _() before 
assignment you get (I presume) an exception reporting an unbound local 
variable.

The scoping rules do work when you obey them:

  >>> def f1(a, b):
  ...   s = a+b
  ...   def _(x):
  ... return s+x
  ...   return _
  ...
  >>> func = f1(12, 13)
  >>> func(10)
35
  >>>

Here the nested lexical scopes rule isn't that helpful given the 
overriding nature of assignment within an inner scope. Using global will 
simply put the status variable at *module* scope, which also isn't what 
you want.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread bonono

Steven Bethard wrote:
> Paul Rubin wrote:
> > Chris Mellon <[EMAIL PROTECTED]> writes:
> >
> >>As someone who does a tremendous amount of event-driven GUI
> >>programming, I'd like to take a moment to speak out against people
> >>using us as a testament to the virtues of lamda. Event handlers are
> >>the most important part of event-driven code, and  making them real
> >>functions with real names is crucial to maintainable code. The only
> >>reason to ever use a lamdba in Python is because you don't want to
> >>give a function a name, and that is just not a compelling use case for
> >>GUI events.
> >
> >
> > I thought stuff like the following was idiomatic in GUI programming.
> > Do you really want separate names for all those callbacks?
> >
> > # generate calculator keypad buttons
> > Button(label='7', command=lambda: user_pressed(7)).grid(column=1, row=1)
> > Button(label='8', command=lambda: user_pressed(8)).grid(column=2, row=1)
> > Button(label='9', command=lambda: user_pressed(9)).grid(column=3, row=1)
> >
> > Button(label='4', command=lambda: user_pressed(4)).grid(column=1, row=2)
> > Button(label='5', command=lambda: user_pressed(5)).grid(column=2, row=2)
> > Button(label='6', command=lambda: user_pressed(6)).grid(column=3, row=2)
> > ...
>
> While I don't spend much time on GUIs, code like that would scream
> "refactor" to me, e.g. something like:
>
> class UserPressedButton(Button):
>  def __init__(self, i):
>  def command():
>  return user_pressed(i)
>  Button.__init__(self, label=str(i), command=command)
>
> Button(7).grid(column=1, row=1)
> Button(8).grid(column=2, row=1)
> Button(9).grid(column=3, row=1)
>
> Button(4).grid(column=1, row=2)
> Button(5).grid(column=2, row=2)
> Button(6).grid(column=3, row=2)
>
Well, that depends. This kind of coding many times are result of quick
copy and paste. Whether it worths to abstract things out really depends
on the life span. If it ends up never got touch again, the advntage of
lambda is that I can just have it as is, it works, is clear to
understand and everything is in place. I thought that is one of the
advantage of python or quick prototyping.

This also is not a very good example as it shows some form of
repetitiveness that is "screaming for refactoring". Many times, these
fields are similar but have no common functionalities.

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


Re: slice notation as values?

2005-12-12 Thread Antoon Pardon
Op 2005-12-10, Devan L schreef <[EMAIL PROTECTED]>:
>
> Antoon Pardon wrote:
>> On 2005-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote:
> [snip]
>> >> I also think that other functions could benefit. For instance suppose
>> >> you want to iterate over every second element in a list. Sure you
>> >> can use an extended slice or use some kind of while. But why not
>> >> extend enumerate to include an optional slice parameter, so you could
>> >> do it as follows:
>> >>
>> >>   for el in enumerate(lst,::2)
>> >
>> > 'Why not'? Because it makes for a more complicated interface for something
>> > you can already do quite easily.
>>
>> Do you think so? This IMO should provide (0,lst[0]), (2,lst[2]),
>> (4,lst[4]) ...
>>
>> I haven't found a way to do this easily. Except for something like:
>>
>> start = 0:
>> while start < len(lst):
>>   yield start, lst[start]
>>   start += 2
>>
>> But if you accept this, then there was no need for enumerate in the
>> first place. So eager to learn something new, how do you do this
>> quite easily?
>
 lst = ['ham','eggs','bacon','spam','foo','bar','baz']
 list(enumerate(lst))[::2]
> [(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]

It is not about what is needed, but about convenience.

Now let me see, in order to just iterate over the even elements
of a list with the index of the element, you turned an iterator
into a list, which you use to create an other list which you
will finaly iterate over.

If this is the proposed answer, I wonder why iterators were introduced
in the first place. I thought iterator were went to avoid the need
to construct and copy list when all you want is iterate and when
I ask how to get a specific iterator you come with a construct that
makes rather heavily use of list constructions. 

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread Paul Rubin
"Fredrik Lundh" <[EMAIL PROTECTED]> writes:
> a temporary factory function should be sufficient:
> 
> def digit(label, x, y):
> def callback():
> # print "BUTTON PRESS", label # debug!
> user_pressed(int(label))
> Button(label=label, command=callback).grid(column=x, row=y)

Looking at the calculator program I wrote a while back (one of my
first Python programs, written just to play with tkinter), I see that
I actually did something like that for the buttons.  However, it also
contained (in the other order):

unops = {'sqrt': math.sqrt,
 'sin': math.sin,
 'cos': math.cos,
 'tan': math.tan,
 'ln': math.log,
 'log': lambda x: math.log(x)/math.log(10),
 'clr x': lambda x: 0
 }

binops = {'+': (lambda x,y: x+y),
  '-': (lambda x,y: x-y),
  '*': (lambda x,y: x*y),
  '/': (lambda x,y: x/y),
  '**': (lambda x,y: x**y)
  }

How would you refactor that, with no lambda?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JOB: Telecommute Python Programmer - IMMEDIATE NEED

2005-12-12 Thread Michael Bernstein
Beau Gould is the owner and moderator of what was until very recently
the 'pythonzopejobs' group on groups.yahoo.com. Two days ago, I got a
PHP/MySQL job from a Yahoo Groups address I didn't recognize.
Initially, I classified it as spam, and forgot about it.

Today, I had reason to search the archives of 'pythonzopejobs', and was
greeted by a message that the group didn't exist. A little
investigation showed that I was now subscribed to an
'allopensourcejobs' group, and that this was in fact the renamed
'pythonzopejobs' group, not to mention the souce of the PHP/MySQL
'spam' job posting.

I posted to the list and CC'd the owner/moderator (Mr. Gould), asking
why such a change had been made with no discussion or announcement.  I
soon realized that the group had become moderated again, and that my
email was not reaching the other group members.

After a few exchanges with Mr. Gould asking that the list be returned
to it's previous focus or that at the very least a message announcing
the change be sent to the group, it became clear (despite some
half-hearted and insincere reassurances on his part) that Mr. Gould now
considered the list his personal fiefdom, and that he was intent on
using it as an opt-out spam list to extract whatever value he could.

Mr. Gould then changed the name of the group again (this time to
'opensourcejobs'), possibly in a bid to make it even harder to
unsubscribe (though that is speculation on my part),  and I was banned
from the group. Further email from me to Mr. Gould has been ignored.

I have personally forwarded Mr. Gould's job postings from the
pythonzopejobs list to various candidates on several occasions in the
past, but I won't be doing that any more, and based on my experience
today I cannot recommend doing business with Mr. Gould or Superior
Staffing Services.

- Michael R. Bernstein
  michaelbernstein.com
  Author of Zope Bible

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread Paul Rubin
Paul Rubin  writes:
> binops = {'+': (lambda x,y: x+y),
>   '-': (lambda x,y: x-y),
>   '*': (lambda x,y: x*y),
>   '/': (lambda x,y: x/y),
>   '**': (lambda x,y: x**y)
>   }
> How would you refactor that, with no lambda?

Ok, with operator.add and so forth.  I don't remember if I knew about
those at the time.  You can easily see though, how additional such
simple functions might be wanted, that aren't in the operator module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Lexical Scope

2005-12-12 Thread [EMAIL PROTECTED]
That does make sense. So there is no way to modify a variable in an
outer lexical scope? Is the use of a mutable data type the only way?

I'm trying to think of a case that would create semantic ambiguity when
being able to modify a variable reference in an outer scope, but I
cannot (which is probably short-sighted). Is this behavior correct
because of performance or perhaps because of a certain design of the
interpreter?

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread bonono

Paul Rubin wrote:
> "Fredrik Lundh" <[EMAIL PROTECTED]> writes:
> > a temporary factory function should be sufficient:
> >
> > def digit(label, x, y):
> > def callback():
> > # print "BUTTON PRESS", label # debug!
> > user_pressed(int(label))
> > Button(label=label, command=callback).grid(column=x, row=y)
>
> Looking at the calculator program I wrote a while back (one of my
> first Python programs, written just to play with tkinter), I see that
> I actually did something like that for the buttons.  However, it also
> contained (in the other order):
>
> unops = {'sqrt': math.sqrt,
>  'sin': math.sin,
>  'cos': math.cos,
>  'tan': math.tan,
>  'ln': math.log,
>  'log': lambda x: math.log(x)/math.log(10),
>  'clr x': lambda x: 0
>  }
>
> binops = {'+': (lambda x,y: x+y),
>   '-': (lambda x,y: x-y),
>   '*': (lambda x,y: x*y),
>   '/': (lambda x,y: x/y),
>   '**': (lambda x,y: x**y)
>   }
>
> How would you refactor that, with no lambda?

Or, why would you want to refactor that ? The lambdas were used as the
quickest and the most straight forward way to have the solution back
then I believe. Refactoring is an aftermath(performance, frequent
change to the same module for feature changes etc.).
Without lambda, even the first version would force the programmer to
think more about how to factor it and it seems in this case, not
necessary and waste of precious programmer time.

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


Re: Problem with Lexical Scope

2005-12-12 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> I am using python2.4 and the following code throws a "status variable"
> not found in the inner-most function, even when I try to "global" it.
> 
> def collect(fields, reducer):
> def rule(record):
> status = True
> def _(x, y):
> cstat = reducer(x, y)
> if status and not cstat:
> status = False
> return y
> return reduce(_, [record[field] for field in fields])
> return rule
> 
> What gives?

You rebind status in the inner function. Binding to a name makes it local 
to that function (unless declared global). A name in an enclosing function 
is neither local nor global so you cannot rebind it.

Ways round this include storing the status in a mutable value, making it an 
attribute of a class, or rewriting the code to not require setting an outer 
variable in the first place.

The last of these is the easiest in this case: status is never actually 
used or returned anywhere so you could just remove all references to it 
with no impact on the code. In fact, so long as reducer has no side 
effects, you could just do this:

def collect(fields, reducer):
 def rule(record):
 if fields:
 return record[fields[-1]]
 return rule

Alternatively, if I assume you actually wanted rule to return the status as 
well as y, then the outer assignment disappears quite easily:

def collect(fields, reducer):
 def rule(record):
 def _((x, status), y):
 cstat = reducer(x, y)
 return (y, status and cstat)
 return reduce(_, [record[field] for field in fields], (0, True))
 return rule

If reducer has no side effects this can be further reduced:

def collect(fields, reducer):
 def rule(record):
 def _((x, status), y):
 return (y, status and reducer(x,y))
 return reduce(_, [record[field] for field in fields], (0, True))
 return rule

Given that the final y returned is simply the last record[field] maybe you 
only wanted the status value? In that case expanding the reduce and _ into 
inline code is likely to make things clearer:

def collect(fields, reducer):
 def rule(record):
prev = 0
for field in fields:
if not reducer(prev, record[field]):
return False
prev = record[field]
return True
 return rule
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mail attachment with non-ascii name

2005-12-12 Thread Bernard Delmée
Thank you Neil,

that is what I needed.

B.

Neil Hodgson wrote:
> 
>  >>> import email.Header
>  >>> x = '=?iso-8859-1?q?somefile=2ezip?='
>  >>> email.Header.decode_header(x)
> [('somefile.zip', 'iso-8859-1')]
> 
>Neil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Lexical Scope

2005-12-12 Thread [EMAIL PROTECTED]
Thanks for the example code. Definately provided a few different ways
of doing the construction.

Actually, the status variable was the only thing that mattered for the
inner function.  The first code post had a bug b/c I was first just
trying to use reduce. However, I realized that the boolean reducer
ended up using the boolean result instead of the next field for
subsequent operations.

The effect I was going for was was a logical AND of all the returned
values from reducer. However the inner function is supposed to use the
same type algorithm as the built-in reduce function.

reducer does have no side effects so I suppose short-circuting it would
be the best thing. I think the only thing about the last example is
that it starts things off with a zero. I think that would boink it.

The way that this thing works is it's a general algorithm for boolean
operations that are applied to fields in a dict.

def lt(*fields):
return collect(fields, lambda x, y: x < y)

data = {
  'birth_date' : 19740201,
  'hire_date' : 19840721,
  'fire_date' :   19850123
}

rule = lt('birth_date', 'hire_date')
assert rule(data) == True

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


Re: Problem with Lexical Scope

2005-12-12 Thread bonono

[EMAIL PROTECTED] wrote:
> That does make sense. So there is no way to modify a variable in an
> outer lexical scope? Is the use of a mutable data type the only way?
>
> I'm trying to think of a case that would create semantic ambiguity when
> being able to modify a variable reference in an outer scope, but I
> cannot (which is probably short-sighted). Is this behavior correct
> because of performance or perhaps because of a certain design of the
> interpreter?

That is by design and IMO a good thing as you don't need to declare
things(the '=' sort of done it for you) in python. I think you can do
something like globals()['s'] but that is ugly and should be
discouraged.

Just use a mutable object like s=[1] or a Ref class or whatever similar
implementation if you need this "shared write" functionality. Just
reading is perfectly fine.

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


how does exception mechanism work?

2005-12-12 Thread bobueland
Sometimes the best way to understand something is to understand the
mechanism behind it. Maybe that is true for exceptions. This is a model
I have right now (which probably is wrong)

1. When a runtime error occurs, some function (probably some class
method) in Python is called behind the scenes.
2. That function goes into a global table having error types in one
column and corresponding flags in another (and probably other columns
used for trace back information). It sets the flag for the error type
that occured.
3. Then the function looks if the error occured inside a try statement
(in the current function or the function that called the current
function, or the one that called that function and so on). If it did
occur inside a try statement it looks if the corresponding exception
handles the occured error type and if so it executes the statements
under the exception clause. The function also resets the type error
flag.
4. If no try statement is found in 3. (or no exception handling the
occured type error) then it is an unhandled error and the Python stops
the execution, prints an error message and resets the global type error
flag)

Is this model correct or wrong? Where can I read about the mechanism
behind exceptions?

Bob

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> > How would you refactor that, with no lambda?
> Or, why would you want to refactor that ?

I like it the way it was written.  I'm not the one saying lambda is bogus.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Lexical Scope

2005-12-12 Thread bonono

[EMAIL PROTECTED] wrote:
> Thanks for the example code. Definately provided a few different ways
> of doing the construction.
>
> Actually, the status variable was the only thing that mattered for the
> inner function.  The first code post had a bug b/c I was first just
> trying to use reduce. However, I realized that the boolean reducer
> ended up using the boolean result instead of the next field for
> subsequent operations.
>
> The effect I was going for was was a logical AND of all the returned
> values from reducer. However the inner function is supposed to use the
> same type algorithm as the built-in reduce function.
>
> reducer does have no side effects so I suppose short-circuting it would
> be the best thing. I think the only thing about the last example is
> that it starts things off with a zero. I think that would boink it.
>
> The way that this thing works is it's a general algorithm for boolean
> operations that are applied to fields in a dict.
>
> def lt(*fields):
> return collect(fields, lambda x, y: x < y)
>
> data = {
>   'birth_date' : 19740201,
>   'hire_date' : 19840721,
>   'fire_date' :   19850123
> }
>
> rule = lt('birth_date', 'hire_date')
> assert rule(data) == True

I usually solve this kind of thing by giving reduce a tuple(or n-uples)
as the accumulator then factor out only the needed final result sans
these "temp variables".

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


Re: slice notation as values?

2005-12-12 Thread Antoon Pardon
Op 2005-12-10, Brian Beck schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> Will it ever be possible to write things like:
>> 
>>   a = 4:9
>
> I made a silly recipe to do something like this a while ago, not that 
> I'd recommend using it. But I also think it wouldn't be too far-fetched
> to allow slice creation using a syntax like the above...

The point is that the syntax "4:9" is already used for slice creation.

The python grammer is essentally saying that something like 4:9 is a
literal, just like strings and numbers, but that this specific literal
can only be used in a subscription.

Look at the following:

>>> import dis
>>> def foo():
... lst[[2,3,5]]
... lst[8:13:21]
... 
>>> dis.dis(foo)
  2   0 LOAD_GLOBAL  0 (lst)
  3 LOAD_CONST   1 (2)
  6 LOAD_CONST   2 (3)
  9 LOAD_CONST   3 (5)
 12 BUILD_LIST   3
 15 BINARY_SUBSCR   
 16 POP_TOP 

  3  17 LOAD_GLOBAL  0 (lst)
 20 LOAD_CONST   4 (8)
 23 LOAD_CONST   5 (13)
 26 LOAD_CONST   6 (21)
 29 BUILD_SLICE  3
 32 BINARY_SUBSCR   
 33 POP_TOP 
 34 LOAD_CONST   0 (None)
 37 RETURN_VALUE

So you see that the slice is treated in an similar way
as the list. There is no reason why this shouldn't work
in case we want a slice in an assignment or a function
call.

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


Re: how does exception mechanism work?

2005-12-12 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> Is this model correct or wrong? Where can I read about the mechanism
> behind exceptions?

Usually you push exception handlers and "finally" clauses onto the
activation stack like you push return addresses for function calls.
When something raises an exception, you scan the activation stack
backwards, popping stuff from it as you scan and executing "finally"
clauses as you find them, until you find a handler for the raised
exception.

Good book: "Structure and Interpretation of Computer Programming"
by Abelson and Sussman,

  http://mitpress.mit.edu/sicp/

It explains all this stuff (uses a different language from Python, but
principles are similar).  Full text is online.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slice notation as values?

2005-12-12 Thread Antoon Pardon
Op 2005-12-11, Bengt Richter schreef <[EMAIL PROTECTED]>:
> On 10 Dec 2005 12:07:12 -0800, "Devan L" <[EMAIL PROTECTED]> wrote:
>
>>
>>Antoon Pardon wrote:
>>> On 2005-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote:
>>[snip]
>>> >> I also think that other functions could benefit. For instance suppose
>>> >> you want to iterate over every second element in a list. Sure you
>>> >> can use an extended slice or use some kind of while. But why not
>>> >> extend enumerate to include an optional slice parameter, so you could
>>> >> do it as follows:
>>> >>
>>> >>   for el in enumerate(lst,::2)
>>> >
>>> > 'Why not'? Because it makes for a more complicated interface for something
>>> > you can already do quite easily.
>>>
>>> Do you think so? This IMO should provide (0,lst[0]), (2,lst[2]),
>>> (4,lst[4]) ...
>>>
>>> I haven't found a way to do this easily. Except for something like:
>>>
>>> start = 0:
>>> while start < len(lst):
>>>   yield start, lst[start]
>>>   start += 2
>>>
>>> But if you accept this, then there was no need for enumerate in the
>>> first place. So eager to learn something new, how do you do this
>>> quite easily?
>>
> lst = ['ham','eggs','bacon','spam','foo','bar','baz']
> list(enumerate(lst))[::2]
>>[(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]
>>
>>No changes to the language necessary.
>>
> Or, without creating the full list intermediately,
>
> >>> lst = ['ham','eggs','bacon','spam','foo','bar','baz']
> >>> import itertools
> >>> list(itertools.islice(enumerate(lst), 0, None, 2))
>  [(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]

As far as I understand use of this idiom can turn an O(n)
algorithm into an O(n^2) algorithm.

Suppose I have a list with 10 000 elements and I want 
the sum of the first 100, the sum of the second 100 ...

One way to do that would be:

for i in xrange(0,1,100):
  sum(itertools.islice(lst, i, i+100))

But itertools.islice would each time start from the begining
of the list and iterate over i elements before giving 100
elements to sum. Which would make this implementation O(n^2)
instead of O(n).

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


Re: TypeError: no arguments expected

2005-12-12 Thread Steve Holden
Dennis Lee Bieber wrote:
> On Sun, 11 Dec 2005 22:00:55 -0500, shawn a <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
>>I havet these 2 files in the same dir. This is code im writing to learn 
>>pythong
>>mkoneurl.py:
>>#! /usr/bin/env python
>>
>>import make_ou_class
>>
>>run = make_ou_class.makeoneurl()
> 
> 
>   Okay, you've just defined a "run" object that contains an instance
> of "makeoneurl"... What do you expect it to do?
> 
Let's get the terminology right: sloppy terminology leads to sloppy 
thinking. The statement binds the name "run" to a newly-created 
"make_one_url" instance. Remember, "run" isn't an object, it's a 
reference to an object like all Python names.
> 
>>
>>make_ou_class.py:
>>
> 
>   Well, first off... You need to /supply/ a placeholder for "self".
> ALL methods of a class receive the instance as the first argument. So...
> 
Again you need to be a little careful here, since we now have class 
methods and static methods to cloud the picture. So it would be more 
accurate to say that "instance methods are all automatically called with 
a reference to the instance as the first argument; it is conventional to 
use the name 'self' to refer to the instance".
> 
[...]

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: slice notation as values?

2005-12-12 Thread bonono

Antoon Pardon wrote:
> Suppose I have a list with 10 000 elements and I want
> the sum of the first 100, the sum of the second 100 ...
>
> One way to do that would be:
>
> for i in xrange(0,1,100):
>   sum(itertools.islice(lst, i, i+100))
>
> But itertools.islice would each time start from the begining
> of the list and iterate over i elements before giving 100
> elements to sum. Which would make this implementation O(n^2)
> instead of O(n).
Can you use iter for this situation ?

a=iter(lst)
for i in xrange(0,1,100):
  sum(itertools.islice(a,100))

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


Re: slice notation as values?

2005-12-12 Thread Bengt Richter
On 12 Dec 2005 08:34:37 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:

>Op 2005-12-10, Devan L schreef <[EMAIL PROTECTED]>:
>>
>> Antoon Pardon wrote:
>>> On 2005-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote:
>> [snip]
>>> >> I also think that other functions could benefit. For instance suppose
>>> >> you want to iterate over every second element in a list. Sure you
>>> >> can use an extended slice or use some kind of while. But why not
>>> >> extend enumerate to include an optional slice parameter, so you could
>>> >> do it as follows:
>>> >>
>>> >>   for el in enumerate(lst,::2)

If you are willing to use square brackets, you can spell it

 >>> for el in enoomerate[lst, ::2]: print el,

(see below ;-)

>>> >
>>> > 'Why not'? Because it makes for a more complicated interface for something
>>> > you can already do quite easily.
>>>
>>> Do you think so? This IMO should provide (0,lst[0]), (2,lst[2]),
>>> (4,lst[4]) ...
>>>
>>> I haven't found a way to do this easily. Except for something like:
>>>
>>> start = 0:
>>> while start < len(lst):
>>>   yield start, lst[start]
>>>   start += 2
>>>
>>> But if you accept this, then there was no need for enumerate in the
>>> first place. So eager to learn something new, how do you do this
>>> quite easily?
>>
> lst = ['ham','eggs','bacon','spam','foo','bar','baz']
> list(enumerate(lst))[::2]
>> [(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]
>
>It is not about what is needed, but about convenience.
>
>Now let me see, in order to just iterate over the even elements
>of a list with the index of the element, you turned an iterator
>into a list, which you use to create an other list which you
>will finaly iterate over.
>
>If this is the proposed answer, I wonder why iterators were introduced
>in the first place. I thought iterator were went to avoid the need
>to construct and copy list when all you want is iterate and when
>I ask how to get a specific iterator you come with a construct that
>makes rather heavily use of list constructions. 
>
Just for you ;-)

 >>> import itertools
 >>> class enoomerate(object):
 ... def __getitem__(self, seq):
 ... if isinstance(seq, tuple):
 ... seq, slc = seq
 ... else:
 ... slc = slice(None)
 ... if not isinstance(slc, slice): slc = slice(None, slc)
 ... return itertools.islice(enumerate(seq), slc.start or 0, slc.stop, 
slc.step or 1)
 ...
 >>> enoomerate = enoomerate()
 >>>
 >>> import string
 >>> lst = list(string.ascii_lowercase) # legit list, though could use the 
 >>> string
 >>> for el in enoomerate[lst, ::2]: print el,
 ...
 (0, 'a') (2, 'c') (4, 'e') (6, 'g') (8, 'i') (10, 'k') (12, 'm') (14, 'o') 
(16, 'q') (18, 's') (
 20, 'u') (22, 'w') (24, 'y')
 >>> for el in enoomerate[lst, 3::3]: print el,
 ...
 (3, 'd') (6, 'g') (9, 'j') (12, 'm') (15, 'p') (18, 's') (21, 'v') (24, 'y')
 >>> for el in enoomerate[lst, 3]: print el,
 ...
 (0, 'a') (1, 'b') (2, 'c')
 >>> for el in enoomerate[lst, 3:6]: print el,
 ...
 (3, 'd') (4, 'e') (5, 'f')
 >>> for el in enoomerate[lst, 3:6:2]: print el,
 ...
 (3, 'd') (5, 'f')

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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-12 Thread Antoon Pardon
Op 2005-12-11, Rick Wotnaz schreef <[EMAIL PROTECTED]>:
>
> Because you're accustomed to one set of conventions, you 
> may find Python's set strange at first. Please try it, and 
> don't fight it. See if your objections don't fade away. If 
> you're like most Python newbies, you'll stop thinking about 
> brackets before long, and if you're like a lot of us, 
> you'll wonder what those funny squiggles mean when you are 
> forced to revert to one of those more primitive languages.

I think the suggestion that those who have some problem
with how python deals with compound statements - obligated
indentation, no end markers - are newbees, is getting
stale. I am not a newbee and I have problems with it.
I had problems with it when I was a newbee, grew used
to it and even liked it at some point and now again
have problems with it.

Well problems is probably too strong, would prefer
differently seems closer.

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread Bengt Richter
On Mon, 12 Dec 2005 09:15:38 +0100, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:

>Steven Bethard wrote:
>
>> > I thought stuff like the following was idiomatic in GUI programming.
>> > Do you really want separate names for all those callbacks?
>> >
>> > # generate calculator keypad buttons
>> > Button(label='7', command=lambda: user_pressed(7)).grid(column=1, row=1)
>> > Button(label='8', command=lambda: user_pressed(8)).grid(column=2, row=1)
>> > Button(label='9', command=lambda: user_pressed(9)).grid(column=3, row=1)
>> >
>> > Button(label='4', command=lambda: user_pressed(4)).grid(column=1, row=2)
>> > Button(label='5', command=lambda: user_pressed(5)).grid(column=2, row=2)
>> > Button(label='6', command=lambda: user_pressed(6)).grid(column=3, row=2)
>> > ...
>>
>> While I don't spend much time on GUIs, code like that would scream
>> "refactor" to me, e.g. something like:
>>
>> class UserPressedButton(Button):
>>  def __init__(self, i):
>>  def command():
>>  return user_pressed(i)
>>  Button.__init__(self, label=str(i), command=command)
>>
>> Button(7).grid(column=1, row=1)
>> Button(8).grid(column=2, row=1)
>> Button(9).grid(column=3, row=1)
>>
>> Button(4).grid(column=1, row=2)
>> Button(5).grid(column=2, row=2)
>> Button(6).grid(column=3, row=2)
>
>a temporary factory function should be sufficient:
>
>def digit(label, x, y):
>def callback():
># print "BUTTON PRESS", label # debug!
>user_pressed(int(label))
>Button(label=label, command=callback).grid(column=x, row=y)
>
># create numeric pad
>digit("7", 1, 1); digit("8", 2, 1); digit("9", 3, 1)
>digit("4", 1, 2); digit("5", 2, 2); digit("6", 3, 2)
>digit("1", 1, 3); digit("2", 2, 3); digit("3", 3, 3)
>
>are people still missing that local functions are inexpensive in Python ?

OTOH, (untested)

for label, x, y in ((str(d+1), d%3+1, 3-d//3) for d in xrange(9)):
Button(label=label, command=lambda 
d=int(label):user_pressed(d)).grid(column=x, row=y)

or

for tup in ((str(d+1), d%3+1,3-d//3) for d in xrange(9)): digit(*tup)

tweak 'til correct ;-)

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


Re: slice notation as values?

2005-12-12 Thread Antoon Pardon
Op 2005-12-12, Bengt Richter schreef <[EMAIL PROTECTED]>:
> On 12 Dec 2005 08:34:37 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
>>Op 2005-12-10, Devan L schreef <[EMAIL PROTECTED]>:
>>>
>>> Antoon Pardon wrote:
 On 2005-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote:
>>> [snip]
 >> I also think that other functions could benefit. For instance suppose
 >> you want to iterate over every second element in a list. Sure you
 >> can use an extended slice or use some kind of while. But why not
 >> extend enumerate to include an optional slice parameter, so you could
 >> do it as follows:
 >>
 >>   for el in enumerate(lst,::2)
>
> If you are willing to use square brackets, you can spell it

Hmm, I have to think about that.

> >>> for el in enoomerate[lst, ::2]: print el,
>
> (see below ;-)
>
>> [ ... ]

> Just for you ;-)

Thank you.

> >>> import itertools
> >>> class enoomerate(object):
>  ... def __getitem__(self, seq):
>  ... if isinstance(seq, tuple):
>  ... seq, slc = seq
>  ... else:
>  ... slc = slice(None)
>  ... if not isinstance(slc, slice): slc = slice(None, slc)
>  ... return itertools.islice(enumerate(seq), slc.start or 0, 
> slc.stop, slc.step or 1)
>  ...
> >>> enoomerate = enoomerate()
> >>>
> >>> import string
> >>> lst = list(string.ascii_lowercase) # legit list, though could use the 
> >>> string
> >>> for el in enoomerate[lst, ::2]: print el,

I am wondering a bit. Could this be turned into a decorator?

I don't have much experience with decorators, so I'll have to
think this through for a wgile. The idea would be a class
to be used as decorator that would turn a function returning
an iterator in a slicable iterator. Something like the following
maybe:

class SliceIterator(object):

def __init__(self,func):
self.func = func
  
def __getitem__(self, args):
if isinstance(args, tuple)
return self.func(*args)
else:
return self.func(args)
  
def __iter__(self):
return self.func(slice(None, None, None))

I could then write something like:

@SliceIterator
def srange(sl):
v = sl.stop
while v < sl.start:
yield v
v += sl.step


And use it as:

 for i in srange[23:67:3]:
 ...

Hmm, I have to play with this a bit. Thanks for the idea.

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


Re: Problem with Lexical Scope

2005-12-12 Thread Bengt Richter
On Mon, 12 Dec 2005 08:26:59 +, Steve Holden <[EMAIL PROTECTED]> wrote:
[...]
>
>The scoping rules do work when you obey them:
>
>  >>> def f1(a, b):
>  ...   s = a+b
>  ...   def _(x):
>  ... return s+x
>  ...   return _
>  ...
>  >>> func = f1(12, 13)
>  >>> func(10)
>35
>  >>>
>
>Here the nested lexical scopes rule isn't that helpful given the 
>overriding nature of assignment within an inner scope. Using global will 
>simply put the status variable at *module* scope, which also isn't what 
>you want.
>
Is external rebindability being considered at all ?

what if it were a new builtin that could do it in C, e.g. rebind(targetname, 
expr)
where target could be in any enclosing scope (including globals(),
but not extending to __builtins__) and it would be a NameError if target
didn't exist. Thus this would be possible (untested and currently impossible ;-)

def mkbumper(initval, incr):
def _():
rebind('initval', initval+incr) # vs initval := initval+incr
return initval
return _

bump3 = mkbumper(8, 3)
bump3() => 11
bump3() => 14

I wonder if a function would fly better than a punctuation tweak on
bare name assignment ;-)

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


Re: lambda (and reduce) are valuable

2005-12-12 Thread Paul Rubin
[EMAIL PROTECTED] (Bengt Richter) writes:
> 
> for tup in ((str(d+1), d%3+1,3-d//3) for d in xrange(9)): digit(*tup)
> 
> tweak 'til correct ;-)

GMTA.  See:

  http://www.nightsong.com/phr/python/calc.py

written a couple years ago.  It uses:

for i in xrange(1,10):
add_button(5+2-(i-1)/3, (i-1)%3, str(i))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance + classmethod question

2005-12-12 Thread Laszlo Zsolt Nagy
Mike Meyer wrote:

>Laszlo Zsolt Nagy <[EMAIL PROTECTED]> writes:
>  
>
>>Is it possible to tell, which instance was used to call the
>>classmethod that is currently running?
>>
>>
>
>Ok, I read through what got to my nntp server, and I'm still
>completely confused.
>
>A class method isn't necessarilry called by an instance. That's why
>it's a class method. What should happen in that case?
>  
>
Here is the answer (an example):

@ClassOrInstanceMethod
def process_create_table(cls_or_self,tabledef,processor):
"""Process the CREATE TABLE command.

@param tabledef: a L{TableDefinition} instance.
@param processor: a L{SQLProcessor} instance."""
hname = cls_or_self.hashident(tabledef.name)
if (isinstance(cls_or_self,type)) or (not 
cls_or_self.istableexists(hname)):
processor.addline("create table %s \n ("% hname)
for field in tabledef.fields:
if not (field() is None):

cls_or_self.process_create_table_field(field(),processor)
processor.addline(",")
processor.truncate_last_comma()
processor.addline("")
processor.addline(")")
cls_or_self.addtablespaceclause(tabledef,processor)
processor.processbuffer()

So if the method was called with an instance, it will check if the table 
exists and create the table only if it did not exist before.
But if the method was called with a class, it will create the table anyway.

The above method is just a short example. I have many methods for 
creating sequences, triggers, constraings etc.
The full pattern is:

def process_XXX(cls_or_self,defobject,processor):

   
   
   
   

There are two reasons why I do not want to create two methods (one 
instance and one class method).

1. If you look the above pattern, it is clear that the method does the 
same thing, just there are some conditions when I call it with an 
instance. I do not want to call "process_create_table_with_class" and 
"process_create_table_with_instance", because the name of the method 
should reflect what it does primarily. (BTW, I also looked at 
multimethods, but they are not exactly for this kind of problem.)

2. The pattern above makes it clear that I just can't easily split the 
method into elementary parts. Steven wrote this pattern:

>class C(object):
>...
>@classmethod
>def do_stuff(cls, *args):
>...
>def do_instance_stuff(self, *args):
># instance stuff
>...
>self.do_stuff(*args)
># more instance stuff
>  
>
But I cannot do this, because primarily I do class stuff, and in some 
cases, I can make use of an instance (but do not require it).
Comments welcome

   Les

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


Python is incredible!

2005-12-12 Thread Tolga
Hi everyone,

I am using Common Lisp for a while and nowadays I've heard so much
about Python that finally I've decided to give it a try becuase Python
is not very far away from Lisp family.

I cannot believe this! This snake is amazing, incredible and so
beautiful! You, Pythonists, why didn't you tell me about this before?
:-)

Actually I loved Lisp and still don't want to throw it away beacuse of
my interest of artificial intelligence, but using Python is not
programming, it IS a fun! It is so friendly and soft and nice and
blahblahblah

I'll be here!!!

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


Re: heartbeats

2005-12-12 Thread Chris Miles
Hi Yves,

You could try using EDDIE Tool's PORT directive to periodically make TCP 
connections to your clients and check the result matches what is 
expected.  The alert engine will make it easy for you to define actions 
to perform for failure conditions.

http://eddie-tool.net/

You could also do actual (icmp) pings and/or HTTP requests from it also, 
if that helps.

Cheers,
Chris

Yves Glodt wrote:
> I need to write a heartbeat solution to monitor some external clients, 
> and what is different as in the examples that I have seen so far is that 
> I want my central server to poll the clients, and not the clients 
> "pinging" the central server.
> 
> In detail I need a daemon on my central server which e.g. which in a 
> loop pings (not really ping but you know what I mean) each 20 seconds 
> one of the clients.

-- 
http://chrismiles.info/

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


Re: Python is incredible!

2005-12-12 Thread Sebastjan Trepca
Welcome to Python world :)


On 12 Dec 2005 03:44:13 -0800, Tolga <[EMAIL PROTECTED]> wrote:
> Hi everyone,
>
> I am using Common Lisp for a while and nowadays I've heard so much
> about Python that finally I've decided to give it a try becuase Python
> is not very far away from Lisp family.
>
> I cannot believe this! This snake is amazing, incredible and so
> beautiful! You, Pythonists, why didn't you tell me about this before?
> :-)
>
> Actually I loved Lisp and still don't want to throw it away beacuse of
> my interest of artificial intelligence, but using Python is not
> programming, it IS a fun! It is so friendly and soft and nice and
> blahblahblah
>
> I'll be here!!!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML and namespaces

2005-12-12 Thread Alan Kennedy
[Paul Boddie]
> It's
> interesting that minidom plus PrettyPrint seems to generate the xmlns
> attributes in the serialisation, though; should that be reported as a
> bug?

I believe that it is a bug.

[Paul Boddie]
> Well, with the automagic, all DOM users get the once in a lifetime
> chance to exchange those lead boots for concrete ones. I'm sure there
> are all sorts of interesting reasons for assigning namespaces to nodes,
> serialising the document, and then not getting all the document
> information back when parsing it, but I'd rather be spared all the
> "amusement" behind all those reasons and just have life made easier for
> just about everyone concerned. 

Well, if you have a fair amount of spare time and really want to improve 
things, I recommend that you consider implementing the DOM L3 namespace 
normalisation algorithm.

http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html

That way, everyone can have namespace well-formed documents by simply 
calling a single method, and not a line of automagic in sight: just 
standards-compliant XML processing.

> Anyway, thank you for your helpful commentary on this matter!

And thanks to you for actually informing yourself on the issue, and for 
taking the time to research and understand it. I wish that your 
refreshing attitude was more widespread!

now-i-really-must-get-back-to-work-ly'yrs,

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie question

2005-12-12 Thread Antoon Pardon
Op 2005-12-11, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> On Sat, 10 Dec 2005 15:46:35 +, Antoon Pardon wrote:
>
>>> But I *want* other classes to poke around inside my implementation.
>>> That's a virtue, not a vice. My API says:
>>>
>>> "In addition to the full set of methods which operate on the coordinate
>>> as a whole, you can operate on the individual ordinates via instance.x
>>> and instance.y which are floats."
>> 
>> Yikes. I would never do that. Doing so would tie my code unnecesary
>> close to yours and would make it too difficult to change to an other
>> class with a different implementation like one using tuples or lists
>> instead of a seperate x and y instances.
>
> Do you really think that my class and some other class written by
> another person will have the same API?

If both writers try to implement the same kind of object I would
think the API would be very similar yes.

> If you change from my class to
> another class, the chances are that the interfaces will be different
> unless the second class writer deliberately emulated my class interface.

So, lets say I have one class where you can do P1 + P2 and an other
class where you have to do P1.move(P2). If it is basically the
same kind of class but with a different API I just write a wrapper
and I am done unless of course I messed with the internals and
the internals in the second class are vastly different.

> To class users, there is *no* difference in consequences between me
> changing my published API by removing named attributes x and y from my
> class, and me changing my published API by removing or changing methods.

Yes there is. Methods are just names, if you just have different names
for the same functionality all you need is write a wrapper to translate
one name into an other.

If you no longer have an x and y attribute but a 2 element tuple,
then things aren't that easy to repair.

>>> Your API says:
>>>
>>> "In addition to the full set of methods which operate on the coordinate
>>> as a whole, you can operate on the individual ordinates via methods
>>> add_x, add_y, mult_x, mult_y, sub_x, sub_y, rsub_x, rsub_y, div_x,
>>> div_y, rdiv_x, rdiv_y, exp_x, exp_y, rexp_x, rexp_y...; the APIs of
>>> these methods are: ... "
>> 
>> Who in heavens name would need those? Maybe there is no x or y because
>> the implementation uses a list or a tuple, maybe the implementation uses
>> polar coordinates because that is more usefull for the application it
>> was planned for.
>
> And maybe it isn't a Coordinate class at all, hmmm?

Indeed it isn't. It is usually a Point class.

> An ordinary, Cartesian, real-valued Coordinate is a pair of ordinates, an
> X and Y ordinates. That's what it *is* -- a coordinate class without X and
> Y ordinates isn't a coordinate class, regardless of how they are
> implemented (via properties, named attributes, or a whole bucketful of
> helper functions).

That is why a coordinate class is a bad idea. It mentions an
implementation in what should be an abstract idea like a 2D point.

In that case if you find out that you are manipulating your objects
in ways, for which polar coordinates are better, you can transparantly
change the implementation.

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


how to catch error with system()

2005-12-12 Thread eight02645999
hi

i have a piece of python code extract that calls an external java
program
cmd = """java someclass someargs"""
try:
   ret = os.WEXITSTATUS(os.system(cmd))
except:
   print blah
else:
   dosomething(ret)

the thing is, the java class "someclass" produces it's own errors when
something goes wrong.
something like
java.io.FileNotFoundException: somefile (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:106)
at java.io.FileInputStream.(FileInputStream.java:66)
..

how can i supress this error from showing when i execute
./pythonscript.py and at the same time logging it to an errlog file??

thanks

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


List text files showing LFs and expanded tabs (was: Colorize expanded tabs)

2005-12-12 Thread qwweeeit
Hi all,
in a previous post I asked help for colorizing expanded tab.
I wanted to list text files showing in colors LFs and the expanded
tabs.
I hoped to use only bash but, being impossible, I reverted to Python.
I programmed a very short script .
Here it is (... and I ask comments or critics):

# for Linux users
# starting from a list of all the lines of a text files (lFileList)

nNP=9   # n. of Not Printables characters
for line in lFileList:
nTab= line.count('\t')
if nTab > 0:
 for i in range(nTab):
 nPosTab=line.find('\t')
 line=line.replace('\t',"\033[41m"+\
  (8-(nPosTab-(nNP*i))%8)*' '+"\033[0m",1)
print line.replace('\n',"\033[7m \033[0m\n"),
print

The Linux users can also use piping.
For example:
python lft.py lft.py|grep range

correctly displays:
  for i in range(nTab):
+ the mark of the LF (a small white rectangle)
 
Bye.

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


Re: Problem with Lexical Scope

2005-12-12 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> reducer does have no side effects so I suppose short-circuting it would
> be the best thing. I think the only thing about the last example is
> that it starts things off with a zero. I think that would boink it.

In that case, and assuming that fields contains at least one entry:

def collect(fields, reducer):
 def rule(record):
f = iter(fields)
prev = record[f.next()]
for field in f: 
if not reducer(prev, record[field]):
return False
prev = record[field]
return True
 return rule
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating referenceable objects from XML

2005-12-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> ElementTree ( http://www.xml.com/pub/a/2003/02/12/py-xml.html ) is a
> Python InfoSet rather than a Python data binding.  You access nodes
> using generic names related to the node type rather than the node name.
> Whether data bindings or Infosets are your preference is a matter of
> taste, but it's a useful distinction to make between the approaches.
> It looks as if Gerald Flanagan has constructed a little specialized
> binding tool on top of ElementTree, and that's one possible hybrid
> approach.

in my experience, it's hard to make a python/xml mapping that's well suited for 
all
possible use cases (many bindings suffer from issues with namespaces, collisions
between tags/attribute names and python names, etc), but it's usually trivial 
to write
a custom wrapper for a specific case.

for most normal use, manual infoset navigation is often the easiest way to pull 
out
data from the infoset (find, get, findtext, int, float, etc).

for certain cases, creating wrappers on demand can be quite efficient; e.g.

http://online.effbot.org/2003_07_01_archive.htm#element-tricks

and for highly regular cases, incremental parsing/conversion up front is often 
the
fastest and most efficient way to deal with data; e.g.

http://effbot.org/zone/element-iterparse.htm#plist

 



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


make a video from xwd output

2005-12-12 Thread Sinan Nalkaya
hi i want to write a program that makes a video of my desktop, i think that 
can be via return or output xwd functions in X11 lib then through to the mpeg  
video encoding codes, hmm is there an easier solution to this via python?
thanks for your attention.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie question

2005-12-12 Thread Steven D'Aprano
On Mon, 12 Dec 2005 12:12:46 +, Antoon Pardon wrote:

>> And maybe it isn't a Coordinate class at all, hmmm?
> 
> Indeed it isn't. It is usually a Point class.
> 
>> An ordinary, Cartesian, real-valued Coordinate is a pair of ordinates, an
>> X and Y ordinates. That's what it *is* -- a coordinate class without X and
>> Y ordinates isn't a coordinate class, regardless of how they are
>> implemented (via properties, named attributes, or a whole bucketful of
>> helper functions).
> 
> That is why a coordinate class is a bad idea. It mentions an
> implementation in what should be an abstract idea like a 2D point.
> 
> In that case if you find out that you are manipulating your objects
> in ways, for which polar coordinates are better, you can transparantly
> change the implementation.

That's a great idea Antoon, but you don't go far enough. Why limit
yourself to something as concrete as a pair of floats? What we actually
need is an even more abstract class, one which can hold an arbitrary
number of ordinates, not just two. And why limit ourselves to floats? What
if the user decides that he wants to specify ordinates as written English
numbers like the Morse Code for "thirty-seven point three four", coded in
base64?

For that matter, now that we have an arbitrary number of ordinates, why
limit yourself to list implementation? Perhaps a better implementation is
a tree structure, or an orchard, or some sort of mapping? Or some hybrid
of all three. 

And the methods, well, the methods. It is so limiting to be forced into
one specific API, with names like instance.move(), rotate(), reflect() and
so forth. What if I should change my mind, and decide what I really need
is a message-passing model instead? We better write some more code
isolating the methods from the user, making the class even more abstract
again, just in case we should ever choose to change those methods'
interface.

Heaven forbid that we should actually decide on a model for our class,
ever. Sure, we'll end up having to implement a Turing-complete programming
language as our class, but I think we'll all agree that that cost is a
small price to pay for something which is sufficiently abstract.



-- 
Steven

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


Re: OO in Python? ^^

2005-12-12 Thread bruno at modulix
Mike Meyer wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> 
>>> ^^ There is no functionality to check if a subclass correctly
>>>implements an inherited interface
>>
>>I don't know of any language that provide such a thing. At least for
>>my definition of "correctly".
> 
> 
> Well, since your definition of "correclty" is uknown, I won't use
> it. 

!-)

My own definition of 'correctly' in this context would be about ensuring
that the implementation respects a given semantic.

But honestly, this was a somewhat trollish assertion, and I'm afraid
forgot to add a smiley here.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal: Inline Import

2005-12-12 Thread bruno at modulix
Mike Meyer wrote:
> Shane Hathaway <[EMAIL PROTECTED]> writes:
> 
(snip)
> 
>>What's really got me down is the level of effort required to move code
>>between modules.  After I cut 100 lines from a 500 line module and
>>paste them to a different 500 line module, I have to examine every
>>import in both modules as well as examine the code I moved for missing
>>imports.
> 
> 
> Has it ever occured to you that if you're cutting and pasting 500 line
> blocks, you're doing something fundamentally wrong? One of the points
> of modules and OO is that you don't *have* to do things like
> that. Cut-n-paste means you wind up with two copies of the code to
> maintain, 

Mike, has it ever occured to you that this could be refactoring, not
copy_paste ?-)

(for the record, I too frequently *move* - not 'copy_paste' - big chunks
of code,  at least at the beginning of a project, or before a major
evolution)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: make a video from xwd output

2005-12-12 Thread Fredrik Lundh
Sinan Nalkaya wrote:

> hi i want to write a program that makes a video of my desktop, i think that
> can be via return or output xwd functions in X11 lib then through to the mpeg
> video encoding codes, hmm is there an easier solution to this via python?

http://www.unixuser.org/~euske/vnc2swf/

?

 



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


Re: make a video from xwd output

2005-12-12 Thread Sinan Nalkaya
On Monday 12 December 2005 03:34 pm, Fredrik Lundh wrote:
> Sinan Nalkaya wrote:
> > hi i want to write a program that makes a video of my desktop, i think
> > that can be via return or output xwd functions in X11 lib then through to
> > the mpeg video encoding codes, hmm is there an easier solution to this
> > via python?
>
> http://www.unixuser.org/~euske/vnc2swf/
>
> ?
>
> 

i didnt try that but it seems ,just makes swf to me.
thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic XML library with XPath support for Jython?

2005-12-12 Thread Alan Kennedy
[James]
> A couple of years ago there wasn't one and the recommendation was to
> simply use Java libs. Have things changed since?

AFAIK, things haven't changed.

Things you might be interested to know

1. There is a module in PyXML, called javadom, that layers python 
semantics on top of various Java DOM implementations.

2. I submitted a patch that extends that support to JAXP, although the 
patch has not yet been folded into the main jython repo. I think I 
really need to submit the patch to PyXML.

http://sourceforge.net/tracker/index.php?func=detail&aid=876821&group_id=12867&atid=312867

3. It should not be too complex to develop a binding for the excellent 
Jaxen "universal xpath engine", which could provide PyXML compatible 
xpath support under jython.

http://www.jaxen.org

> I see ElementTree promises one in the future but are there any out now?

Not yet, although I could be wrong.

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie question

2005-12-12 Thread Antoon Pardon
Op 2005-12-12, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> On Mon, 12 Dec 2005 12:12:46 +, Antoon Pardon wrote:
>
>>> And maybe it isn't a Coordinate class at all, hmmm?
>> 
>> Indeed it isn't. It is usually a Point class.
>> 
>>> An ordinary, Cartesian, real-valued Coordinate is a pair of ordinates, an
>>> X and Y ordinates. That's what it *is* -- a coordinate class without X and
>>> Y ordinates isn't a coordinate class, regardless of how they are
>>> implemented (via properties, named attributes, or a whole bucketful of
>>> helper functions).
>> 
>> That is why a coordinate class is a bad idea. It mentions an
>> implementation in what should be an abstract idea like a 2D point.
>> 
>> In that case if you find out that you are manipulating your objects
>> in ways, for which polar coordinates are better, you can transparantly
>> change the implementation.
>
> That's a great idea Antoon, but you don't go far enough. Why limit
> yourself to something as concrete as a pair of floats? What we actually
> need is an even more abstract class, one which can hold an arbitrary
> number of ordinates, not just two.

In point of fact, the class I have can do just that. 

> And why limit ourselves to floats? What
> if the user decides that he wants to specify ordinates as written English
> numbers like the Morse Code for "thirty-seven point three four", coded in
> base64?

How the user specifies his values and how they are internally stored
are two entirely different issues. The fact that the use specifies
his numbers in Morse Code or written out in words doesn't imply
they have to be stored in that form. Just as the user supplying his
points with x,y coordinates doesn't imply the implementation has
to work with carthesion coordinates.

> For that matter, now that we have an arbitrary number of ordinates, why
> limit yourself to list implementation? Perhaps a better implementation is
> a tree structure, or an orchard, or some sort of mapping? Or some hybrid
> of all three. 

Indeed different kind of applications work better with different
kind of implementations. That is the whole point, use the same
API for the same functionality even if the implementation is
different, so I can solve the same kind of problem with the same
code, independant on whether I have 2D point 3D points or maybe
sparse 10 000 000D points.

> And the methods, well, the methods. It is so limiting to be forced into
> one specific API, with names like instance.move(), rotate(), reflect() and
> so forth. What if I should change my mind, and decide what I really need
> is a message-passing model instead? We better write some more code
> isolating the methods from the user, making the class even more abstract
> again, just in case we should ever choose to change those methods'
> interface.
>
> Heaven forbid that we should actually decide on a model for our class,
> ever.

There is a difference between deciding on a model and exposing your
model. If you are working with certain kinds of objects, the solution
should more or less be independant of the model chosen to implement
the object. If you need to expose the model in order to solve particular
problems with your objects, I would think you either have chosen the
wrong kind of objects or a bad implementation of them to solve your
problem.

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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-12 Thread Rick Wotnaz
Antoon Pardon <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> Op 2005-12-11, Rick Wotnaz schreef <[EMAIL PROTECTED]>:
>>
>> Because you're accustomed to one set of conventions, you 
>> may find Python's set strange at first. Please try it, and 
>> don't fight it. See if your objections don't fade away. If 
>> you're like most Python newbies, you'll stop thinking about 
>> brackets before long, and if you're like a lot of us, 
>> you'll wonder what those funny squiggles mean when you are 
>> forced to revert to one of those more primitive languages.
> 
> I think the suggestion that those who have some problem
> with how python deals with compound statements - obligated
> indentation, no end markers - are newbees, is getting
> stale. I am not a newbee and I have problems with it.
> I had problems with it when I was a newbee, grew used
> to it and even liked it at some point and now again
> have problems with it.
> 
> Well problems is probably too strong, would prefer
> differently seems closer.
> 

You're right that I should not have assumed newbie status, but I 
most often see posts complaining about lack of braces from those 
newly exposed to Python's way of doing things. The post I responded 
to considered whitespace indention a "design defect". I would be 
surprised to hear an experienced Python programmer say that, but 
maybe I'm just naive.

I am not a fanatic about structuring via whitespace. From time to 
time, code arrives at this group with leading whitespace removed, 
which makes me think it might be nice to have bracketing, so the 
original logic could (maybe) be recreated. That's most of the 
downside, though, and an artificial problem at that. It has nothing 
to do with Python, but with hostile software along the way. The 
upside is clarity of code (and a little less typing, too), and that 
makes up for the occasional artificial problem.

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


making fractals in python

2005-12-12 Thread evil_daffid
hi,
Im reseaching fractals, and how to make them in python using recursion.
I've written a bit of code to make the   koch isalnd   but something isn't
right, I have the basic shape but there's something wrong with the
recursion i've used, could someone help me.

Here is the code im using:

import turtle
turtle.clear

def koch_line(line_length, smallest):
third = line_length/3
if (third <= smallest):
turtle.forward(line_length)
else:
koch_line(third,smallest)
turtle.right(90)
if(third<=smallest):
turtle.forward(line_length/2)
else:
koch_line(line_length/2, smallest)
turtle.right(90)
if (third <= smallest):
turtle.forward(third)
else:
koch_line(line_length/2, smallest)
turtle.left(90)
if (third <= smallest):
turtle.forward(third)
else:
koch_line(line_length,smallest)
if (third <= smallest):
turtle.forward(line_length)
else:
koch_line(third,smallest)
turtle.right(90)
if(third<=smallest):
turtle.forward(line_length/2)
else:
koch_line(line_length/2, smallest)
turtle.right(90)
if (third <= smallest):
turtle.forward(third)
else:
koch_line(line_length/2, smallest)
turtle.left(90)
if (third <= smallest):
turtle.forward(third)
else:
koch_line(line_length,smallest)
return

def koch(line_length, smallest):
koch_line(line_length, smallest)
turtle.left(90)
koch_line(line_length, smallest)
turtle.left(90)
koch_line(line_length, smallest)
return

koch(500,10)

Thank you for your help


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


Re: Using XML w/ Python...

2005-12-12 Thread uche . ogbuji
"""
>>> import amara
>>> print dir(amara)

['__builtins__', '__doc__', '__file__', '__name__', '__path__',
'__version__', 'binderytools', 'os', 'parse']
"""

So it's not able to load domtools.  What do you get trying

from amara import domtools
print domtools.py

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

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


Re: how to catch error with system()

2005-12-12 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> hi
> 
> i have a piece of python code extract that calls an external java
> program
> cmd = """java someclass someargs"""
> try:
>ret = os.WEXITSTATUS(os.system(cmd))
> except:
>print blah
> else:
>dosomething(ret)
> 
> the thing is, the java class "someclass" produces it's own errors when
> something goes wrong.
> something like
> java.io.FileNotFoundException: somefile (No such file or directory)
> at java.io.FileInputStream.open(Native Method)
> at java.io.FileInputStream.(FileInputStream.java:106)
> at java.io.FileInputStream.(FileInputStream.java:66)
> ..
> 
> how can i supress this error from showing when i execute
> ./pythonscript.py and at the same time logging it to an errlog file??

You probably want to catche the subprocesses stdout/stderr streams. To do
so, use the subprocess module (if you are on python2.4), or the
popen2-module. See the docs for how to use them.

-- 
Regards,

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


Re: Using XML w/ Python...

2005-12-12 Thread Rick Wotnaz
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> """
> Spoke too soon, i get this error when running amara in
> ActivePython 
> 
 import amara
 amara.parse("http://www.digg.com/rss/index.xml";)
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python23\Lib\site-packages\amara\__init__.py", line
>   50, in 
> parse
> if IsXml(source):
> NameError: global name 'IsXml' is not defined
> 
> So im guessing theres an error with one of the files...
> """
> 
> IsXml is imported conditionally, so this is an indicator that
> somethign about your module setup is still not agreeing with
> ActivePython.   What do you see as the output of:
> 
> python -c "import amara; print dir(amara)"
> 
> ?  I get:
> 
> ['InputSource', 'IsXml', 'Uri', 'Uuid', '__builtins__',
> '__doc__', '__file__', '__name__', '__path__', '__version__',
> 'bindery', 'binderytools', 'binderyxpath', 'create_document',
> 'dateutil_standins', 'domtools', 'os', 'parse', 'pushbind',
> 'pushdom', 'pyxml_standins', 'saxtools']
> 

Not wanting to hijack this thread, but it got me interested in 
installing amara. I downloaded Amara-allinone-1.0.win32-py2.4.exe 
and ran it. It professed that the installation directory was to be 
D:\Python24\Lib\site-packages\ ... but it placed FT and amara in D:
\Python24\Python24\Lib\site-packages . Possibly the installer is 
part of the problem here?


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


Help: how to run python applications as NT service?

2005-12-12 Thread zxo102
Hi there,
I have a python application (many python scripts) and I start the
application like this

python myServer.py start

in window. It is running in dos window. Now I would like to put it in
background as NT service. I got a example code: SmallestService.py from
chapter 18 of the book "Python Programming On Win32" by Mark Hammond
etc. The code is as follows and runs well as an NT service.

Since I don't have the book, anybody knows how to "insert" my "python
myServer.py start" into the sample code as follows.

Thanks a lot for your help.

ouyang

#
import win32serviceutil
import win32service
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "SmallestPythonService"
_svc_display_name_ = "The smallest possible Python Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop
process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# And set my event.
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
# We do nothing other than wait to be stopped!
win32event.WaitForSingleObject(self.hWaitStop,
win32event.INFINITE)

if __name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)

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


how fast can you pingpong pickled objects?

2005-12-12 Thread Bram Stolk
Hi there,

I'm transfering small pickled object over a socket.
The performance I see is lower than expected.

How fast should I be able to ping/pong small objects in python?

I use a threaded SocketServer, telnetlib and pickle to test this,
and I see that a 100 ping-pongs take 4 seconds or so, (over the
localhost network).

ping localhost gives me 0.06 msec, so the network
is fast enough.

My test code is here:

http://stolk.org/tmp/pingpong.py

Is there a limit in Python on how many times per second
a thread can be scheduled?

Thanks,

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


IsString

2005-12-12 Thread Tuvas
I need a function that will tell if a given variable is a character or
a number. Is there a way to do this? Thanks!

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


NoneType to unicode

2005-12-12 Thread John Morey
My program reads ID3 tags from MP3 files and enters them into a database.
I have been testing it on a variety of MP3s, including ones with
weird characters in the tags (such as norweigan black metal bands)
When this happens it throws the program as they are outside the ascii 
range, the program crashes as soon as I try to bind the tag to a string
using the str() function. 

I have tried using the encode() function to change the values to unicode
however I cannot do this because they are returned from the id3 
library as "NoneType" instances. which means I need to convert
to a string first (which i can't do because it crashes the application)

Any ideas?
cheers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IsString

2005-12-12 Thread Rick Wotnaz
"Tuvas" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> I need a function that will tell if a given variable is a
> character or a number. Is there a way to do this? Thanks!
> 

If you really need to, you can test for type:
>>> for x in ['3',3,3.1,3j]:
... print type(x)





>>> for x in ['3',3,3.1,3j]:
... if type(x) is str: print "it's a string"
... elif type(x) is int: print "it's an int"
... elif type(x) is float: print "it's a float"
... elif type(x) is complex: print "it's a complex number"

it's a string
it's an int
it's a float
it's a complex number

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


line deletion

2005-12-12 Thread ghaitma
I am a beginner, I have this line that write something on the
screen(Text(Point(4,15), "Question 4").draw(window). How do I delete it
later on in the program so that I can write another one.

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


Re: List text files showing LFs and expanded tabs (was: Colorize expanded tabs)

2005-12-12 Thread gene tani

qwweeeit wrote:
> Hi all,
> in a previous post I asked help for colorizing expanded tab.
> I wanted to list text files showing in colors LFs and the expanded
> tabs.
> I hoped to use only bash but, being impossible, I reverted to Python.
> I programmed a very short script .
> Here it is (... and I ask comments or critics):
>
> # for Linux users
> # starting from a list of all the lines of a text files (lFileList)
>
> nNP=9   # n. of Not Printables characters
> for line in lFileList:
> nTab= line.count('\t')
> if nTab > 0:
>  for i in range(nTab):
>  nPosTab=line.find('\t')
>  line=line.replace('\t',"\033[41m"+\
>   (8-(nPosTab-(nNP*i))%8)*' '+"\033[0m",1)
> print line.replace('\n',"\033[7m \033[0m\n"),
> print
>
> The Linux users can also use piping.
> For example:
> python lft.py lft.py|grep range
>
> correctly displays:
>   for i in range(nTab):
> + the mark of the LF (a small white rectangle)
>
> Bye.

?? Whatever editor you use for python should do this: (vim, komodo,
textmate)show and convert hard tabs to soft, show CR-LF, etc.

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


Re: NoneType to unicode

2005-12-12 Thread Alan Franzoni
John Morey on comp.lang.python said: 

> I have tried using the encode() function to change the values to unicode
> however I cannot do this because they are returned from the id3 
> library as "NoneType" instances. which means I need to convert
> to a string first (which i can't do because it crashes the application)

NoneType is just the type of None. It should mean that your ID3 library
returns 'None' when trying to read non-ascii ID3s. I think you should check
your ID3 library, not your main program.

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


Re: PHP = Perl Improved

2005-12-12 Thread Dave Hansen
On Sat, 10 Dec 2005 08:25:08 GMT in comp.lang.python, Tim Roberts
<[EMAIL PROTECTED]> wrote:

[...]
>
>The design of the PHP language is not too bad, and the standard library is
>extensive.  It is quite possible to write well-structured, class-based web
>programs with PHP.
>
>However, it seems that almost no one actually does so.  Virtually all of
>the vast PHP code samples on the web are crap.  Maybe the simplicity of the
>language encourages inexperienced programmers who write spaghetti code
>without a thought to the structure; I don't know the exact cause, but I
>have seen it more often than not.

This reminds me of a comment that John Levine (moderator of
comp.compilers) wrote in a post back in 1997: "It is my impression
that it's possible to write good programs in C++, but nobody does."

However, in the case of C++, I wouldn't blame "... the simplicity of
the language ..."

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using XML w/ Python...

2005-12-12 Thread uche . ogbuji
"""
Not wanting to hijack this thread, but it got me interested in
installing amara. I downloaded Amara-allinone-1.0.win32-py2.4.exe
and ran it. It professed that the installation directory was to be
D:\Python24\Lib\site-packages\ ... but it placed FT and amara in D:
\Python24\Python24\Lib\site-packages . Possibly the installer is
part of the problem here?
"""

That's really good to know.  Someone else builds the Windows installer
package for Amara (I'm a near Windows illiterate), but I definitely
want to help be sure the installer works properly.  In fact, your
message rings a bell that this specifically came up before:

http://lists.fourthought.com/pipermail/4suite/2005-November/007610.html

I'll have to ask some of the Windows gurus on the 4Suite list whether
they know why this might be.  Do you mind if I cc you on those
messages, so that you can perhaps try out any solutions we come up
with?

Thanks.

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

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


Re: making fractals in python

2005-12-12 Thread evil_daffid
Heres a link to the koch island:

http://mathworld.wolfram.com/LindenmayerSystem.html

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


PythonWin + console

2005-12-12 Thread g.franzkowiak
Hi everybody,

it was a long way, have a runing COM connection,
but wishing run it from the console.

The COM part is embedded in the example 'createwin.py' from pywin/Demo
but it operates only with "pythonwin /run 'test.py'".

Is it possible to use that as an python thread and hide the pythonwin
environment ?
I want use that test in my older python application.

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


Re: Help: how to run python applications as NT service?

2005-12-12 Thread gene tani

zxo102 wrote:
> Hi there,
> I have a python application (many python scripts) and I start the
> application like this
>
> python myServer.py start
>
> in window. It is running in dos window. Now I would like to put it in
> background as NT service. I got a example code: SmallestService.py from
> chapter 18 of the book "Python Programming On Win32" by Mark Hammond
> etc. The code is as follows and runs well as an NT service.
>
> Since I don't have the book, anybody knows how to "insert" my "python
> myServer.py start" into the sample code as follows.
>
> Thanks a lot for your help.
>
> ouyang
>
> #
> import win32serviceutil
> import win32service
> import win32event
>
> class SmallestPythonService(win32serviceutil.ServiceFramework):
> _svc_name_ = "SmallestPythonService"
> _svc_display_name_ = "The smallest possible Python Service"
> def __init__(self, args):
> win32serviceutil.ServiceFramework.__init__(self, args)
> # Create an event which we will use to wait on.
> # The "service stop" request will set this event.
> self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
>
> def SvcStop(self):
> # Before we do anything, tell the SCM we are starting the stop
> process.
> self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
> # And set my event.
> win32event.SetEvent(self.hWaitStop)
>
> def SvcDoRun(self):
> # We do nothing other than wait to be stopped!
> win32event.WaitForSingleObject(self.hWaitStop,
> win32event.INFINITE)
>
> if __name__=='__main__':
> win32serviceutil.HandleCommandLine(SmallestPythonService)

look at ASPN activestate (online cookbook) recipes linked in this
thread (sorry i don't do those qURL things)

http://groups.google.com/group/comp.lang.python/browse_frm/thread/39e482a3ea7f6041/8ac679d13cf95867?q=windows+service+activestate&rnum=1#8ac679d13cf95867

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


Re: Using XML w/ Python...

2005-12-12 Thread Rick Wotnaz
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> """
> Not wanting to hijack this thread, but it got me interested in
> installing amara. I downloaded
> Amara-allinone-1.0.win32-py2.4.exe and ran it. It professed that
> the installation directory was to be 
> D:\Python24\Lib\site-packages\ ... but it placed FT and amara in
> D: \Python24\Python24\Lib\site-packages . Possibly the installer
> is part of the problem here?
> """
> 
> That's really good to know.  Someone else builds the Windows
> installer package for Amara (I'm a near Windows illiterate), but
> I definitely want to help be sure the installer works properly. 
> In fact, your message rings a bell that this specifically came
> up before: 
> 
> http://lists.fourthought.com/pipermail/4suite/2005-November/00761
> 0.html 
> 
> I'll have to ask some of the Windows gurus on the 4Suite list
> whether they know why this might be.  Do you mind if I cc you on
> those messages, so that you can perhaps try out any solutions we
> come up with?
> 
> Thanks.
> 

I'd be delighted to run them. Bring 'em on! 

If this is useful information: the opening screen of the installer 
correctly shows D:\Python24\ as my Python directory, and correctly 
shows (on my computer): 
D:\Python24\Lib\site-packages\ as the Installation Directory. The 
file names as it installs are of the form 
"Python24\Lib\site-packages\...", which to me hints that it takes 
that generated name and appends it to the Python directory to 
produce the actual file path it then uses.

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


Re: PHP = Perl Improved

2005-12-12 Thread gene tani

Tim Roberts wrote:
> "Xah Lee" <[EMAIL PROTECTED]> wrote:
>
> >recently i got a project that involves the use of php. In 2 days, i
> >read almost the entirety of the php doc. Finding it a breeze because it
> >is roughly based on Perl, of which i have mastery.
> >
> >i felt a sensation of neatness, as if php = Perl Improved, for a
> >dedicated job of server-side scripting.
>
> The design of the PHP language is not too bad, and the standard library is
> extensive.  It is quite possible to write well-structured, class-based web
> programs with PHP.
>
> However, it seems that almost no one actually does so.  Virtually all of
> the vast PHP code samples on the web are crap.  Maybe the simplicity of the
> language encourages inexperienced programmers who write spaghetti code
> without a thought to the structure; I don't know the exact cause, but I
> have seen it more often than not.
> --
> - Tim Roberts, [EMAIL PROTECTED]
>   Providenza & Boekelheide, Inc.

agreed, once you explain MVC, it's pretty hard to argue against it.

Keeping from getting defaced is another matter.  About a year ago, this
page (or somethign very similar) was php.net's *homepage*, I almost
fell over when i saw it.  Moral of hte story, don't use shared server.

http://www.php.net/security-note.php

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


How does Scons compare to distutils?

2005-12-12 Thread [EMAIL PROTECTED]
How does Scons compare to distutils?  Should I ignore
it or move to it?

Chris

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


Re: Python is incredible!

2005-12-12 Thread Luis M. Gonzalez

You are not the first lisper who fell inlove with Python...
Check this out:
http://www.paulgraham.com/articles.html

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


Newbie - BigInt

2005-12-12 Thread Jim Steil




I am trying to call a SOAP web service with python and I having success
unless I need to pass a BigInteger parameter.  Since python is
dynamically typed it seems to be sending a regular int instead of
BigInteger and my web service doesn't like that.  Is there a way for me
to tell my variable that it should be a big integer instead of int?

    -Jim
-- 
Jim Steil

VP of Application Development
CustomCall Data Systems
(608) 274-3009 x286



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

Re: OO in Python? ^^

2005-12-12 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (Alex Martelli) wrote:

> Tom Anderson <[EMAIL PROTECTED]> wrote:
>...
> > Haskell is strongly and statically typed - very strongly and very 
> > statically!
> 
> Sure.
> 
> 
> > However, what it's not is manifestly typed - you don't have to put the
> > types in yourself; rather, the compiler works it out. For example, if i
> > wrote code like this (using python syntax):
> > 
> > def f(x):
> >   return 1 + x
> > 
> > The compiler would think "well, he takes some value x, and he adds it to 1
> > and 1 is an integer, and the only thing you can add to an integer is 
> > another integer, so x must be an integer; he returns whatever 1 + x works
> > out to, and 1 and x are both integers, and adding two integers makes an
> > integer, so the return type must be integer", and concludes that you meant
> 
> hmmm, not exactly -- Haskell's not QUITE as strongly/rigidly typed as
> this... you may have in mind CAML, which AFAIK in all of its variations
> (O'CAML being the best-known one) *does* constrain + so that "the only
> thing you can add to an integer is another integer".  In Haskell, + can
> sum any two instances of types which meet typeclass Num -- including at
> least floats, as well as integers (you can add more types to a typeclass
> by writing the required functions for them, too).  Therefore (after
> loading in ghci a file with
> f x = x + 1
> ), we can verify...:
> 
> *Main> :type f
> f :: (Num a) => a -> a
> 
> 
> A very minor point, but since the need to use +. and the resulting lack
> of polymorphism are part of what keeps me away from O'CAML and makes me
> stick to Haskell, I still wanted to make it;-).

But if you try
   f x = x + 1.0

it's
   f :: (Fractional a) => a -> a

I asserted something like this some time ago here, and was
set straight, I believe by a gentleman from Chalmers.  You're
right that addition is polymorphic, but that doesn't mean
that it can be performed on any two instances of Num.  I had
constructed a test something like that to check my thinking,
but it turns out that Haskell was able to interpret "1" as
Double, for example -- basically, 1's type is Num too.
If you type the constant (f x = x + (1 :: Int)), the function
type would be (f :: Int -> Int).  Basically, it seems (+) has
to resolve to a (single) instance of Num.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-12 Thread gene tani

Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, JohnBMudd
> wrote:
>
> > Python could take over the programming world except one of it's best
> > features (scope by indent) is a primary reason why it never will.  It's
> > not flexible enough.  A large percentage of programmers won't even try
> > the language.
>
> Their loss.  :-)
>
> > And nobody else sees the need for change?  Oh, except those who think
> > Tabs are evil and should no longer be allowed.
> >
> > How about (1) add some more flexibility for optional braces [...]
>
> Try this::
>
>   from __future__ import braces
>
> Ciao,
>   Marc 'BlackJack' Rintsch

My catalog of asymptotic threads  (i.e. once in a while somebody
*might* post something we haven't read before):

- why do tabs have syntax-significance
- why are there more python web app frameworks/ IDEs / GUI frameworks
than python keywords
- why don't you fix the official documentation?
- what's the best IDE / editor (actually, this discussion is still
worthwhile)

Jamie Zawinski would say: "there are python people, who, when
confronted with a problem, think "Aha, i'll post to c.l.python"  At
that point...

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


Re: Newbie - BigInt

2005-12-12 Thread Fredrik Lundh
Jim Steil wrote

> I am trying to call a SOAP web service with python and I having success
> unless I need to pass a BigInteger parameter.  Since python is
> dynamically typed it seems to be sending a regular int instead of
> BigInteger and my web service doesn't like that.  Is there a way for me
> to tell my variable that it should be a big integer instead of int?

it might help to know what SOAP library you're using.





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


simple question on optional parameters

2005-12-12 Thread scooterm
I am using a toolkit that has a SetFaveNumbers() method. the method
accepts any number
of comma-separated numbers.

the following are all valid examples:

FooToolkit.SetFaveNumbers(1,3,5)
FooToolkit.SetFaveNumbers(2,4,6,8,10)
FooToolkit.SetFaveNumbers(1)

I do not know how this method is implemented, but I would like to be
able
to call the method using a single variable:

MyFaveNumbers = []
MyFaveNumbers.append(2)
MyFaveNumbers.append(4)

FooToolkit.SetFaveNumbers(MyFaveNumbers)

how is this possible in python?

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


mxODBC argv sql query

2005-12-12 Thread BartlebyScrivener
This can't be the most elegant way to get a command line parameter into
an sql query. It works but I can't explain why. Is there another, more
correct way? Here sys.argv[1] is a topic like "laugher" or "technology"

import mx.ODBC.Windows as odbc
import sys

driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
Databases/Quotations2005'

conn = odbc.DriverConnect(driv)
c = conn.cursor()

c.execute ("SELECT Author, Topics.Topic1, Topic2, Quote FROM QUOTES7
WHERE Topics.Topic1 LIKE '%%%s%%'"  % sys.argv[1])

rows = c.fetchall()

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


Re: Python is incredible!

2005-12-12 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Tolga <[EMAIL PROTECTED]> wrote:
.
.
.
>Actually I loved Lisp and still don't want to throw it away beacuse of
>my interest of artificial intelligence, but using Python is not
>programming, it IS a fun! It is so friendly and soft and nice and
.
.
.
While there is indeed much to love about Lisp, please be aware
that meaningful AI work has already been done in Python (http://programmer-art.org/dan/python-ai.html >, for example).
-- 
http://mail.python.org/mailman/listinfo/python-list


namespace in Python?

2005-12-12 Thread Carl
What is the equivalent of a C++ (or C#) namespace in Python?

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


Re: Another newbie question

2005-12-12 Thread james . moughan

Mike Meyer wrote:
> [EMAIL PROTECTED] (Alex Martelli) writes:
> > Mike Meyer <[EMAIL PROTECTED]> wrote:
> >> > "In addition to the full set of methods which operate on the coordinate 
> >> > as
> >> > a whole, you can operate on the individual ordinates via instance.x and
> >> > instance.y which are floats."
> >> That's an API which makes changing the object more difficult. It may
> >> be the best API for the case at hand, but you should be aware of the
> >> downsides.
> > Since x and y are important abstractions of a "2-D coordinate", I
> > disagree that exposing them makes changing the object more difficult, as
> > long of course as I can, if and when needed, change them into properties
> > (or otherwise obtain similar effects -- before we had properties in
> > Python, __setattr__ was still quite usable in such cases, for example,
> > although properties are clearly simpler and more direct).
>
> Exposing them doesn't make making changes more difficult. Allowing
> them to be used to manipulate the object makes some changes more
> difficult. Properties makes the set of such changes smaller, but it
> doesn't make them vanish.
>
> Take our much-abused coordinate example, and assume you've exposed the
> x and y coordinates as attributes.
>
> Now we have a changing requirement - we want to get to make the polar
> coordinates available. To keep the API consistent, they should be
> another pair of attributes, r and theta. Thanks to Pythons nice
> properties, we can implement these with a pair of getters, and compute
> them on the fly.

But the API cannot be consistent.  :-)   If setting r is expensive
because it requires several trig calculations but setting x is cheap,
that's an inconsistency.  It would be a vital one for any application
where I'd be likely to use a point.  You certainly couldn't change the
internal representation of a point from cartesian to polar without
breaking my code.

Good example from the C++ strandard library; string only specifies the
'literal' interface.  The internal representation is left totally
undefined... and so you can only program to a specific implementation
of string.  (Which, of course, can and does change between different
versions of a compiler, let alone between compilers.)  The STL got
things right, by contrast.

Sometimes these issues don't matter much.  Other times they do.
Perhaps they matter more to me because if the Python version is not
sufficiently fast, then I have to recode the thing in C++. ;-)

Anyway, my point:  some types of things fundamentally cannot be cleanly
seperated into an implementation and an API.  Whether a point is 2D or
polar is one of these issues, IMO.

This is obviously not to diss the whole idea of encapsulation and
modularisation.  I've worked on horrible code and beautiful code, and I
know what a difference these things make.  However, you also cannot
program blindly by general rules.  The toughest code I've ever had to
modify would probably have passed quite a few OO-style guides; the
author was really trying to adhere to a 'philosophy', he just didn't
get it.

James M

>
> If x and y can't be manipulated individually, you're done. If they
> can, you have more work to do. If nothing else, you have to decide
> that you're going to provide an incomplete interface, in that users
> will be able to manipulate the object with some attributes but not
> others for no obvious good reason. To avoid that, you'll have to add
> code to run the coordinate transformations in reverse, which wouldn't
> otherwise be needed. Properties make this possible, which is a great
> thing.
>
>--
> Mike Meyer <[EMAIL PROTECTED]>
> http://www.mired.org/home/mwm/
> Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

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


Re: Python is incredible!

2005-12-12 Thread Tolga
Oh, Mr(s) Laird, you've indicated to a very important thing for me:

Let's suppose that I actually want to leave Lisp totally but what about
AI sources? Most of them are based on Lisp. Oh yes, yes, I know, one
may study AI with any language, even with BASIC, but nearly all
important AI books start with a short Lisp intro. They say that "you do
not have to use Lisp, you can use another language with this book".
Ohmigod, does somebody explain me how can this be possible? You're
trying to learn something you don't know, and you will try to read some
important examples written in a language you don't know. This is so
weird!

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


Re: simple question on optional parameters

2005-12-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I am using a toolkit that has a SetFaveNumbers() method. the method
> accepts any number of comma-separated numbers.

any number of arguments, that is.

> the following are all valid examples:
>
> FooToolkit.SetFaveNumbers(1,3,5)
> FooToolkit.SetFaveNumbers(2,4,6,8,10)
> FooToolkit.SetFaveNumbers(1)
>
> I do not know how this method is implemented, but I would like to be
> able to call the method using a single variable:
>
> MyFaveNumbers = []
> MyFaveNumbers.append(2)
> MyFaveNumbers.append(4)
>
> FooToolkit.SetFaveNumbers(MyFaveNumbers)

try:

FooToolkit.SetFaveNumbers(*MyFaveNumbers)





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


Re: simple question on optional parameters

2005-12-12 Thread D H
[EMAIL PROTECTED] wrote:
> I am using a toolkit that has a SetFaveNumbers() method. the method
> accepts any number
> of comma-separated numbers.
> 
> the following are all valid examples:
> 
> FooToolkit.SetFaveNumbers(1,3,5)
> FooToolkit.SetFaveNumbers(2,4,6,8,10)
> FooToolkit.SetFaveNumbers(1)
> 
> I do not know how this method is implemented, but I would like to be
> able
> to call the method using a single variable:
> 
> MyFaveNumbers = []
> MyFaveNumbers.append(2)
> MyFaveNumbers.append(4)
> 
> FooToolkit.SetFaveNumbers(MyFaveNumbers)

See if this works:
FooToolkit.SetFaveNumbers(*MyFaveNumbers)

The asterix unpacks a list or tuple into individual items.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespace in Python?

2005-12-12 Thread Fredrik Lundh
"Carl" <[EMAIL PROTECTED]> wrote:

> What is the equivalent of a C++ (or C#) namespace in Python?

modules and packages:

http://docs.python.org/tut/node8.html





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


Re: namespace in Python?

2005-12-12 Thread Heiko Wundram
Carl wrote:
> What is the equivalent of a C++ (or C#) namespace in Python?

Your best bet will be modules:

---

a.py


def test():
print "I am test() from a.py"

b.py


import a

a.test()

---

They are no direct match to C++-namespaces though, as the namespace doesn't
show up in the source but rather relies on the naming of the source
files...

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


Re: Newbie - BigInt

2005-12-12 Thread Jim Steil




SOAPpy

    -Jim

Jim Steil

VP of Application Development
CustomCall Data Systems
(608) 274-3009 x286



Fredrik Lundh wrote:

  Jim Steil wrote

  
  
I am trying to call a SOAP web service with python and I having success
unless I need to pass a BigInteger parameter.  Since python is
dynamically typed it seems to be sending a regular int instead of
BigInteger and my web service doesn't like that.  Is there a way for me
to tell my variable that it should be a big integer instead of int?

  
  
it might help to know what SOAP library you're using.





  



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

allow_none=True in SimpleXMLRPCServer

2005-12-12 Thread Daniel Crespo
Hello,

Does anyone know which methods do I have to override for allowing Nones
to be accepted and sended from SimpleXMLRPCServer to the client?

Thanks

Daniel

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


Re: making fractals in python

2005-12-12 Thread Ernst Noch
evil_daffid wrote:
> hi,
> Im reseaching fractals, and how to make them in python using recursion.
> I've written a bit of code to make the   koch isalnd   but something isn't
> right, I have the basic shape but there's something wrong with the
> recursion i've used, could someone help me.
> 
> Here is the code im using:
> 
[Code snipped]

Is this a homework assignment or something?

Anyway, this is a little bit more pythonic and flexible, though my 
python has gotten a little bit rusty. It uses L-Systems for state storage.
Recursion is only left in because you asked for it.
Iterate() should get more sophisticated for more complex string 
substitutions.

import turtle
turtle.clear

class fractal(object):

 def __init__(self, lstring, rule, line_length, angle, 
shrink_factor):
 self.lstring = lstring
 self.rule = rule
 self.line_length = line_length
 self.angle = angle
 self.shrink_factor=shrink_factor

 def draw(self):
 drawingdict = {'F': lambda: turtle.forward(self.line_length),
'-':lambda: turtle.right(self.angle),
'+':lambda: turtle.left(self.angle),}
 for rule in self.lstring:
 drawingdict[rule]()

 def iterate(self):
 self.lstring = self.lstring.replace(rule[0],rule[1])
 self.line_length=self.line_length/self.shrink_factor

def recurse(f,smallest):
 if f.line_length>=smallest:
 turtle.reset()
 f.iterate()
 f.draw()
 recurse(f,smallest)

if __name__=='__main__':
 start = 'F+F+F+F'
 rule = ('F','F+F-F-FF+F+F-F')
 f = fractal(start,rule,50,90,2)
 recurse(f,10)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Documentation suggestions

2005-12-12 Thread A.M. Kuchling
On Sat, 10 Dec 2005 11:45:12 +0100, 
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>> to make it better.  Maybe it could be "'', from ''
>> by ".  Then the text for your file would be "'The zlib module',
>> from '(the eff-bot guide to) The Standard Python Library' by Fredrik Lundh."
> 
> that should work.

Now implemented in SVN.

> the DC documentation is a bit convoluted, but if I understand things
> correctly, the dc:identifier field should, by default, contain an URI.

That's what I assumed.  You could theoretically supply something like
urn:isbn:1234567890, but then what are you linking to?  I implemented
your suggested check.

I've written Fred Drake about this, but haven't received a reply yet.
Fred is in the same area as me, so I'm hoping we can talk about
various doc things over coffee (example links being one of them).

--amk

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


Developing a network protocol with Python

2005-12-12 Thread Laszlo Zsolt Nagy

  Hello,

I would like to develop a new network protocol, where the server and the 
clients are Python programs.
I think to be effective, I need to use TCP_NODELAY, and manually 
buffered transfers.
I would like to create a general messaging object that has methods like

sendinteger
recvinteger
sendstring
recvstring

To be more secure, I think I can use this loads function to transfer 
more elaborate python stuctures:

def loads(s):
"""Loads an object from a string.
   
@param s: The string to load the object from.
@return: The object loaded from the string. This function will not 
unpickle globals and instances.
"""
f = cStringIO.StringIO(s)
p = cPickle.Unpickler(f)
p.find_global = None
return p.load()

Am I on the right way to develop a new protocol?
Are there any common mistakes that programmers do?
Is there a howto where I can read more about this?

Thanks

   Les


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


Re: How does Scons compare to distutils?

2005-12-12 Thread John J. Lee
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> How does Scons compare to distutils?  Should I ignore
> it or move to it?
[...]

Yes.

Seriously, what are you doing?

distutils seems pretty ubiquitous when building Python extensions,
since it has special knowledge of the Python with which it is run, and
makes some common tasks easy.  scons, OTOH, is a general
make-replacement.  scons is most useful for people writing projects
mostly in compiled languages.  I imagine scons has some support for
distutils.


John

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


Re: Help: how to run python applications as NT service?

2005-12-12 Thread Larry Bates
zxo102 wrote:
> Hi there,
> I have a python application (many python scripts) and I start the
> application like this
> 
> python myServer.py start
> 
> in window. It is running in dos window. Now I would like to put it in
> background as NT service. I got a example code: SmallestService.py from
> chapter 18 of the book "Python Programming On Win32" by Mark Hammond
> etc. The code is as follows and runs well as an NT service.
> 
> Since I don't have the book, anybody knows how to "insert" my "python
> myServer.py start" into the sample code as follows.
> 
> Thanks a lot for your help.
> 
> ouyang
> 
> #
> import win32serviceutil
> import win32service
> import win32event
> 
> class SmallestPythonService(win32serviceutil.ServiceFramework):
> _svc_name_ = "SmallestPythonService"
> _svc_display_name_ = "The smallest possible Python Service"
> def __init__(self, args):
> win32serviceutil.ServiceFramework.__init__(self, args)
> # Create an event which we will use to wait on.
> # The "service stop" request will set this event.
> self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
> 
> def SvcStop(self):
> # Before we do anything, tell the SCM we are starting the stop
> process.
> self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
> # And set my event.
> win32event.SetEvent(self.hWaitStop)
> 
> def SvcDoRun(self):
> # We do nothing other than wait to be stopped!
> win32event.WaitForSingleObject(self.hWaitStop,
> win32event.INFINITE)
> 
> if __name__=='__main__':
> win32serviceutil.HandleCommandLine(SmallestPythonService)
> 

Basically you insert your python program code inside the SvcDoRun
method of this service.  You will, of course, have to change it to
act like class method code instead of regular main program code.
You can then register it and start/stop it like any other service.

The other part you add is code about how often you want the service
to wake up and run the SvcDoRun method.  Normally you wouldn't
use win32event.INFINITE  but rather wait some number of milliseconds
before running a second time.  The example just waits for a stop
signal.


Here is a skeleton of a service that should get you started.  I
HIGHLY recommend spending the money to purchase the book
(Python Programming on WIN32).  There are more extensive examples
than the one you have that would help you a lot.

Hope this helps.
Larry Bates

import win32serviceutil
import win32service
import win32event
import win32evtlogutil


class Yourservice(win32serviceutil.ServiceFramework):
# Indent all code below 4 spaces
def SvcDoRun(self):
import servicemanager
#--
# Make entry in the event log that this service started
#--
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
  servicemanager.PYS_SERVICE_STARTED,
  (self._svc_name_, ''))

#-
# Set an amount of time to wait (in milliseconds) between runs
#-
self.timeout=6 (60 seconds)
while 1:
#---
# Wait for service stop signal, if I timeout, loop again
#---
rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
#
# Check to see if self.hWaitStop happened
#
if rc == win32event.WAIT_OBJECT_0:
#
# Stop signal encountered
#
break

else:
#
# Put your code here
#

#
# Only return from SvcDoRun when you wish to stop
#
return


def SvcStop(self):
#-
# Before we do anything, tell SCM we are starting the stop process.
#-
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
#-
# And set my event
#-
win32event.SetEvent(self.hWaitStop)
return
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie - BigInt

2005-12-12 Thread Jim Steil




Found my answer.

x = 1L

sets x to 1 and makes it a type of Long.  I tested with my web
service and it works.

    -Jim

Jim Steil

VP of Application Development
CustomCall Data Systems
(608) 274-3009 x286



Fredrik Lundh wrote:

  Jim Steil wrote

  
  
I am trying to call a SOAP web service with python and I having success
unless I need to pass a BigInteger parameter.  Since python is
dynamically typed it seems to be sending a regular int instead of
BigInteger and my web service doesn't like that.  Is there a way for me
to tell my variable that it should be a big integer instead of int?

  
  
it might help to know what SOAP library you're using.





  



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

Re: IsString

2005-12-12 Thread Peter Decker
On 12 Dec 2005 08:26:06 -0800, Tuvas <[EMAIL PROTECTED]> wrote:
> I need a function that will tell if a given variable is a character or
> a number. Is there a way to do this? Thanks!

Use isinstance().

e.g.:

x = 7
isinstance(x, int)
-> True
isinstance(x, basestring)
-> False
x = "Hello"
isinstance(x, int)
-> False
isinstance(x, basestring)
-> True

I always use the basestring class for comparison, unless I need to
know whether or not the string is unicode.

--

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mxODBC argv sql query

2005-12-12 Thread Steve Holden
BartlebyScrivener wrote:
> This can't be the most elegant way to get a command line parameter into
> an sql query. It works but I can't explain why. Is there another, more
> correct way? Here sys.argv[1] is a topic like "laugher" or "technology"
> 
> import mx.ODBC.Windows as odbc
> import sys
> 
> driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
> Databases/Quotations2005'
> 
> conn = odbc.DriverConnect(driv)
> c = conn.cursor()
> 
> c.execute ("SELECT Author, Topics.Topic1, Topic2, Quote FROM QUOTES7
> WHERE Topics.Topic1 LIKE '%%%s%%'"  % sys.argv[1])
> 
> rows = c.fetchall()
> 

Try

c.execute ("""SELECT Author, Topics.Topic1, Topic2, Quote FROM QUOTES7
   WHERE Topics.Topic1 LIKE ?""", ("%"+sys.argv[1],)

First, note that mx.ODBC uses paramstyle qmark bydefault. If you look in 
the DB API manual you'll see that the cursor execute() method can take a 
second argument which is a tuple of data values to replace the parameter 
marks in the statement.

The parameterised query is the best way to avoid the potential for "SQL 
injection" exploits against your program.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: IsString

2005-12-12 Thread Larry Bates
Tuvas wrote:
> I need a function that will tell if a given variable is a character or
> a number. Is there a way to do this? Thanks!
> 
You can test the type of the object as follows:
>>> a='abc'
>>> isinstance(a, str)
True
>>> isinstance(a, (list, tuple))
False
>>>

The old way was to use type(a), but I think isinstance is
the new "preferred" method.

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


Re: TypeError: no arguments expected

2005-12-12 Thread shawn a
thanks for all your input. Ive gotten it to work thanks!

--shawn

On 12/12/05, Steve Holden <[EMAIL PROTECTED]> wrote:
> Dennis Lee Bieber wrote:
> > On Sun, 11 Dec 2005 22:00:55 -0500, shawn a <[EMAIL PROTECTED]>
> > declaimed the following in comp.lang.python:
> >
> >
> >>I havet these 2 files in the same dir. This is code im writing to learn 
> >>pythong
> >>mkoneurl.py:
> >>#! /usr/bin/env python
> >>
> >>import make_ou_class
> >>
> >>run = make_ou_class.makeoneurl()
> >
> >
> >   Okay, you've just defined a "run" object that contains an instance
> > of "makeoneurl"... What do you expect it to do?
> >
> Let's get the terminology right: sloppy terminology leads to sloppy
> thinking. The statement binds the name "run" to a newly-created
> "make_one_url" instance. Remember, "run" isn't an object, it's a
> reference to an object like all Python names.
> >
> >>
> >>make_ou_class.py:
> >>
> >
> >   Well, first off... You need to /supply/ a placeholder for "self".
> > ALL methods of a class receive the instance as the first argument. So...
> >
> Again you need to be a little careful here, since we now have class
> methods and static methods to cloud the picture. So it would be more
> accurate to say that "instance methods are all automatically called with
> a reference to the instance as the first argument; it is conventional to
> use the name 'self' to refer to the instance".
> >
> [...]
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC www.holdenweb.com
> PyCon TX 2006  www.python.org/pycon/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does Scons compare to distutils?

2005-12-12 Thread Robert Kern
John J. Lee wrote:
> I imagine scons has some support for
> distutils.

Not really, no.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: Problem with Lexical Scope

2005-12-12 Thread Bengt Richter
On 12 Dec 2005 01:23:48 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

>Thanks for the example code. Definately provided a few different ways
>of doing the construction.
>
>Actually, the status variable was the only thing that mattered for the
>inner function.  The first code post had a bug b/c I was first just
>trying to use reduce. However, I realized that the boolean reducer
>ended up using the boolean result instead of the next field for
>subsequent operations.
>
>The effect I was going for was was a logical AND of all the returned
>values from reducer. However the inner function is supposed to use the
>same type algorithm as the built-in reduce function.
>
>reducer does have no side effects so I suppose short-circuting it would
>be the best thing. I think the only thing about the last example is
>that it starts things off with a zero. I think that would boink it.
>
>The way that this thing works is it's a general algorithm for boolean
>operations that are applied to fields in a dict.
>
>def lt(*fields):
>return collect(fields, lambda x, y: x < y)
>
>data = {
>  'birth_date' : 19740201,
>  'hire_date' : 19840721,
>  'fire_date' :   19850123
>}
>
>rule = lt('birth_date', 'hire_date')
>assert rule(data) == True
>
I suspect you are trying to win an obfuscation contest ;-)
It appears that in this case you want lt to have the same effect
as if it were written

 >>> def lt(*fields):
 ... def _(dct):
 ... return dct[fields[0]] < dct[fields[1]]
 ... return _
 ...
 >>> data = {
 ...   'birth_date' : 19740201,
 ...   'hire_date' : 19840721,
 ...   'fire_date' :   19850123
 ... }
 >>>
 >>> rule = lt('birth_date', 'hire_date')
 >>> rule
 
 >>> rule(data)
 True
 >>> assert rule(data)
 >>> assert rule(data) == True

But why do you need to "collect" with reduce and all that cryptic cruft?
I think we need a use case where you have other than two fields to operate on.
but in that case, what would reduce do? Something seems bogus with that.

I'm guessing you want to loop through a bunch of "records" that are extracted 
from
a database in the form of dicts, and you want to check them in various ways.
So you want to extract fields in given order and apply various checks, 
something like (untested)

for data in dbrecordsupply:
for fields, check, msg in record_supply_checklist:
assert check(*[data[field] for field in fields]), msg

where record_supply_checklist is something like (untested) (and eschewing 
lambdas for a change ;-)

def before(x, y): return xhttp://mail.python.org/mailman/listinfo/python-list


Re: Proposal: Inline Import

2005-12-12 Thread adam
When I'm feeling too lazy to do imports while moving large blocks of
code, I use this little hack. It lets me proceed with checking whether
the move does what I wanted and at the end I fix the imports and remove
the try/except wrapper. I think it would achieve your desired result
and not have an impact on the language itself.

try:
#your main code here
print string.upper("blah")
except NameError, error_value:
mod_name = error_value.args[0][error_value.args[0].find("'") +
1:error_value.args[0].rfind("'")]
try:
__import__(mod_name)
print "imported %s" % mod_name
except:
print "NameError: %s" % error_value.args[0]
pass

-adam

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


sql using characters like é and ã

2005-12-12 Thread tjerk
Hello, I am switching from VB to python.
I managed to crank my files into a sqlite
dbase, converting the original names to
unicode with s=unicode(s,"latin-1").
Everything is working fine, but when
I query the dbase with dbapi2 and want
to retrieve names this way:
'Select * from table where name like "José%"´
The ´José's don´t appear in my list.
Other names lets say "Maria%" works fine.
Also "João%" doesn´t work. 
Anybody knows a trick?

Herdsman in Brazil

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


Rpy: displaying multivariate data with pairs() and coplot()

2005-12-12 Thread malv
Did anybody manage to use pairs() or coplot() from python using the rpy
module?
In fact any information going a bit beyond Tim Churches' very useful
examples on plot() usage in rpy would be highly welcome.
Thx.
malv

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


  1   2   >