Re: XMLRPC Solution Code

2006-07-18 Thread Frank Millman

Steve Holden wrote:
> dylpkls91 wrote:
> >
> > The hard part now is getting the server code to run as a Windows
> > service- argh!!!
> > I can get it installed and started using modified code from:
> > http://www.schooltool.org/products/schooltool-calendar/documentation/how-to/running-as-a-windows-service/schooltool-service.py/view
> >
> > but for some reason when the server is a service the client refuses to
> > connect properly!
> > Grrr... anybody know why?
> >
> Because there are specific requirements for Windows services, that your
> program isn't comlpying with.
>
>
> I'm afraid you'll need to Google for "python windows service" or
> similar: in essence the main thing the service has to do (besides serve)
> is ensure a continuous flow of messages through the system. It's ugly,
> but people have done it before.
>

I use something called 'srvany' -
   http://support.microsoft.com/kb/q137890/

I have a socket server program, written in pure Python, which I need to
run as a service. 'srvany' enables me to do this without using any of
the Win32 extensions or other complications.

I have not run it in a heavy-duty environment so I don't know if there
are any problems with it. I have it set up on my Windows 2003 Server,
and after a restart, my server program is automatically started as a
service and any client can connect straight away.

Frank Millman

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


Re: range() is not the best way to check range?

2006-07-18 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, tac-tics
wrote:

> Grant Edwards wrote:
>> for pete's sake use the comparison operator like god intended.
>>
>> if 0 <= i <= 1:
> 
> I'm assuming you used Python's compound comparison as opposed to the
> C-style of and'ing two comparisons together to emphasize the fact it is
> god's chosen way of doing this ;-)

Pete doesn't like to be called god in public.  ;-)

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


Re: Coding style

2006-07-18 Thread Peter Otten
Carl Banks wrote:

> 
> Peter Otten wrote:
>> Carl Banks wrote:
>>
>> > def process_values(lst):
>> > if not lst:
>> > return
>> > do_expensive_initialization_step()
>> > for item in lst:
>> > do_something_with(item)
>> > do_expensive_finalization_step()
>>
>> > What if you called the function like this:
>> >
>> > process_values(x.strip() for x in values_lst)
>> >
>> > Oops, now we've just gone through an expensive initialization and
>> > finalization for nothing (since values_lst was empty).  Maybe some
>> > subtle bugs introduced.  If we're lucky, the finalization step will
>> > throw an exception.
>>
>> The good news is that the above has a 99 percent chance that it just
>> works with iterators/generators -- even though the writer may not have
>> been aware of them/they didn't exist when the code was written...
> 
> There's a litmus test I like to use when justifying something with
> percentages: I imagine that I'm presenting it to my boss, and ask
> myself if I still expect to have a job the next day. :-)

That 99 percent chance is not meant to exempt you from actually verifying
that it works. Docstrings can do wonders here

def process_values(lst):
   "Foos all bars in a list"

vs

def process_values(lst):
   "Foos all bars in an iterable"
 
If in doubt, pass a list (-comprehension) as there are other ways of quiet
failure (the function may loop twice over its argument).

> Yes, I agree with you, it most cases I expect merely unnecessary work.
> (Which is not the best news; the best news would be an exception right
> away.)  That's why I think this is only a "pretty good" reason to use
> "if len(lst)>0", not a slam dunk.

If process_values() were /aware/ of iterators it would probably be written

def process_values(items):
first_pass = True
for item in items:
if first_pass:
   do_expensive_initialization_step()
   first_pass = False 
do_something_with(item)
if not first_pass:
do_expensive_finalization_step()

or just with an additional

items = list(items)

as its first statement.

Peter


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


Re: function v. method

2006-07-18 Thread Leif K-Brooks
danielx wrote:
> This is still a little bit of magic, which gets me thinking again about
> the stuff I self-censored. Since the dot syntax does something special
> and unexpected in my case, why not use some more dot-magic to implement
> privates? Privates don't have to be entirely absent from Klass.__dict__
> (which would make Python not introspective); they can just be invisible
> when using the dot-syntax.

You can do this now, kind of:

 >>> class Foo(object):
...  x = property()
...  def doStuffWithX(self):
...   self.__dict__['x'] = 123
...   print self.__dict__['x']
...
 >>> bar = Foo()
 >>> bar.doStuffWithX()
123
 >>> bar.x
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: unreadable attribute

If you're proposing that self.x and bar.x should give different results, 
then that's quite a bit more magic than property() and methods use. They 
both use the descriptor API; for more information on that, read 
.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XMLRPC Solution Code

2006-07-18 Thread Laszlo Nagy

> I'm afraid you'll need to Google for "python windows service" or 
> similar: in essence the main thing the service has to do (besides serve) 
> is ensure a continuous flow of messages through the system. It's ugly, 
> but people have done it before.
>   
Also don't forget to "Allow the service interact with the desktop" - 
otherwise you will not be able to start GUI applications from the service.

   Laszlo

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


Re: Augument assignment versus regular assignment

2006-07-18 Thread Antoon Pardon
On 2006-07-17, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
>> Antoon Pardon <[EMAIL PROTECTED]> (AP) wrote:
>
>>AP> On 2006-07-14, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
>
 Just read what it says. `It is only evaluated once' is quite clear I would
 say.
>
>>AP> If it is so clear, why don't you explain it? 
>
> I have done that in another thread.

Before I respond I would like you to be more specific
about where you gave that explanation. The subject
of the thread would be fine or a message-id perhaps.

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


Re: function v. method

2006-07-18 Thread Duncan Booth
danielx wrote:

 Foo.func = dan# <-- Appearantly, something magical happens here, 
because...
 Foo.func
>
 f = Foo.func
 f is dan   # <-- things begins to look suprising here.
> False
 ismethod(f)
> True
> 
> Imagine my surprise. Why would Python do this?
> 

Nothing magical happens at the point you said. The assignment is just an 
assignment and you saw that the function was stored unchanged when you 
looked in the class's dictionary.

The magic happens when you access a member of a class or an instance. If 
the value is a descriptor then its __get__ method is called. Roughly 
speaking, Foo.func is equivalent to:

>>> Foo.__dict__['func'].__get__(None, Foo)


Python does this so that it can support other descriptor types such as 
property, classmethod, staticmethod.

You can see this happening if you define your own descriptor:

>>> class MyDesc(object):
def __get__(self, *args):
print "__get__ called", args
return None


>>> d = MyDesc()
>>> Foo.oops = d
>>> Foo.oops
__get__ called (None, )

http://docs.python.org/ref/descriptor-invocation.html has a description of 
this. Although it claims "Note that descriptors are only invoked for new 
style objects or classes (ones that subclass object() or type())." the 
descriptor mechanism is partially implemented for old style classes. 
Several aspects of descriptors don't work properly though in old-style 
classes which is one reason why you should always use new-style classes.

> Privates don't have to be entirely absent from Klass.__dict__
> (which would make Python not introspective); they can just be invisible
> when using the dot-syntax.

You could implement that using a data descriptor, but if you are going to 
prevent access to your private variables using the dot operator, then your 
code is going to look pretty silly with a lot of references to 
self.__dict__['theprivate'] which doesn't gain anything in readability over 
self.__theprivate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client.Dispatch - understanding error messages

2006-07-18 Thread Duncan Booth
 wrote:

 False
> False
 blah = win32com.client.Dispatch('MSXML2.XMLHTTP')
 blah.open("POST", "12.5.81.49/crg_cbsil_vtest_52/crg.aspx", False)

Does using an absolute URL for the url parameter help any? You've specified 
a relative URL (i.e. the folder 12.5.81.49 under the current location).

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


Re: Google Earth contact? (OT, sort of...)

2006-07-18 Thread Duncan Booth
Bell, Kevin wrote:

> Sorry if this is an off topic shot in the dark, but...
> 
> Does anyone know a contact for anyone that works for Google Earth?  I
> wanted to shoot 'em an email about a possible enhancement, but they're
> smart enough to not leave contact info ANYWHERE on their websites.
> 
How about posting to http://groups.google.co.uk/group/google-earth ?


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


Re: unicode html

2006-07-18 Thread Duncan Booth
 wrote:

> As an example I would like to do this kind of conversion:
> \uc3B4 => ô
> for all available html entities.

>>> u"\u3cB4".encode('ascii','xmlcharrefreplace')
'㲴'

Don't bother using named entities. If you encode your unicode as ascii  
replacing all non-ascii characters with the xml entity reference then your 
pages will display fine whatever encoding is specified in the HTTP headers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to know if socket is still connected

2006-07-18 Thread Laszlo Nagy
[EMAIL PROTECTED] írta:
> ok, yeah, thats in my book.
> thanks, and no, it isn't enabled.
> thanks again for everything
> -sk
>   
Another hint: use select.select() on the socket before reading. It will 
tell you if recv() will block or not. This way you can implement your 
own async timeout and do something else in your program while waiting 
for the connection to be available.

Best,

   Laszlo

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


Re: range() is not the best way to check range?

2006-07-18 Thread Nick Craig-Wood
Grant Edwards <[EMAIL PROTECTED]> wrote:
>  Creating and then searching a 10,000 element list to see if a
>  number is between two other numbers is insane.

>  Using xrange as somebody else suggested is also insane.

Aye to both

>  If you want to know if a number is between two other numders,
>  for pete's sake use the comparison operator like god intended.
> 
>  if 0 <= i <= 1:

Sets are pretty fast too, and have the advantage of flexibility in
that you can put any numbers in you like

$ python2.4 -m timeit -s 's=range(0,1); i=5000' 'i in s'
1000 loops, best of 3: 228 usec per loop

$ python2.4 -m timeit -s 's=set(range(0,1)); i=5000' 'i in s'
100 loops, best of 3: 0.312 usec per loop

$ python2.4 -m timeit -s 'i=5000' '0 <= i < 1'
100 loops, best of 3: 0.289 usec per loop

The below prints

range) That took 21.512 seconds: result 10001.0
set) That took 0.023 seconds: result 10001.0
comparison) That took 0.024 seconds: result 10001.0



import time

start = time.time()
a = 1.0
for i in range(0, 3):
if i in range(0, 1):
a += 1
dt = time.time() - start
print "range) That took %.3f seconds: result %s" % (dt, a)

start = time.time()
a = 1.0
mine = set(range(0, 1))
for i in range(0, 3):
if i in mine:
a += 1
dt = time.time() - start
print "set) That took %.3f seconds: result %s" % (dt, a)

start = time.time()
a = 1.0
mine = set(range(0, 1))
for i in range(0, 3):
if 0 <= i < 1:
a += 1
dt = time.time() - start
print "comparison) That took %.3f seconds: result %s" % (dt, a)

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


Re: function v. method

2006-07-18 Thread Bruno Desthuilliers
danielx wrote:
> At first I was going to post the following:
> 
> 
> 
(snip)
> 
> 
> 
> but then I tried this:
> 
> 
res = Foo.__dict__['func']
res is dan
> 
> True
> 
> And it all started to make sense. The surprising thing turned out to be
> not so surprising: When the expression Foo.func gets evaluated, we get
> a method which is just a wrapper around dan. Therefore, f is not dan!
> This is still a little bit of magic,

FWIW, the function class implements the descriptor protocol... Here's
the "magic".

> which gets me thinking again about
> the stuff I self-censored. Since the dot syntax does something special
> and unexpected in my case,

"unexpected" ? Did you ever wondered how the instance or class was
passed as first arg when doing method calls ?

> why not use some more dot-magic to implement
> privates?

What for ? What makes you think we need language-inforced access
restriction ?

(snip)

> BTW, I am aware of Python's name mangling feature.

Name mangling is mainly here to protect from accidental overridding. The
 convention for implementation attributes is single-leading-underscore.


-- 
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


Python Developer required for 6 Months Contract - South West UK

2006-07-18 Thread Rakesh Thakrar
My client based in the South West - UK is looking for a Python Developer to join an existing project team for a 6-month contract. Suitable candidates will have commercial experience programming with Python and knowledge of Software Design Architecture. 
Ideally you will have knowledge any one of the following; QT, GTK, KDE or similar toolkits/technologies .  Please do not hesitate to call me for further information.-- Regards
Rakesh 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
tac-tics wrote:
>>Or even just:
>>
>>lst = []
>>
>>;-)
> 
> 
> Indeed.
> 
> I'd say the second one. 

And you'd be plain wrong.

> Empty lists are not false.

In a bolean context, empty containers (lists, tuples, dicts, sets etc),
empty strings, integer 0, float 0.0 and None are all false. This is part
of the language specs.

-- 
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: Accessors in Python (getters and setters)

2006-07-18 Thread mystilleef

Bruno Desthuilliers wrote:
> mystilleef wrote:
> Please don't top-post
> > On State and Behavior:
> >
> > To understand objects in terms of state and behavior you need to
> > absolve yourself from implementation details of languages
> > and think at an abstract level.
>
>
>
> > Take a button object, for example. It has state and behavior. Possible
> > states may include, is_active, is_focused, is_mapped, etc. Behavior is
> > what the button does when it responds to events, (e.g when you click on
> > it, or drag it, or position a pointer over it.) If you've done any form
> > of event based programming (GUI/Games/Simulation), this method of
> > thinking becomes natural.
> >
> > As you can see, when I'm designing a button object, I don't care what
> > Python does with is_active. I don't care how it accesses. I don't care
> > what is_active means to Python. I don't care about Python's __get__
> > /__set__ special/latent functions or implementation details. is_active
> > to me and every other developer is a state of the button object. And at
> > that level that's all that matters. Python can tell me it's just ones
> > and zeros for all I care.
> >
> > In very well designed systems, the state of an object should only be
> > changed by the object.
>
> ... as a response to a message.
>
> > For example, a third party randomly changing
> > is_active, (which Python lets you do freely and easily)
>
> Unless you make it a read-only property.
>

So you see the purpose of accessors then?

> > from False to
> > True may crash your GUI.
>
> > And I'm not making this up. Things like this
> > do really happen depending on the whackyness of your toolkit. So
> > sometimes, it is my duty to protect the state of an object. Especially
> > if its state cannot afford to be corrupted rendering the system
> > unstable. And situations like this are found a plenty in event based
> > programming. Which is programming objects based almost entirely on
> > state and behavior. As you can see this has nothing to do with Python
> > vs Java's vs X's implementation of accessors and how using them sucks,
> > or how they aren't Pythonic. Some domains just require this stuff.
>
> Properties *are* 'accessors'.
>

I never said they weren't.

> > One of the requirements for designing robust object systems is ensuring
> > the state of objects aren't easily contaminated.
>
> "contaminated" ???
>

Make an object's state unreliable. See above example.

> > That "state" is the
> > objects data (read: stuff the object needs to do something "reliably").
>
> Makes no sens to me.
>

is_active is an object's data, with regards to our example.

> > And this is why many overzealous OO languages do "force" you to use
> > accessors. It's not because they hate you or aren't aware of the
> > convenience of having direct access to an object's attributes. It's
> > just because these languages convenience/robustness ratios are
> > different.
> >
> > Thinking in terms of callable vs non-callable is not helpful for me,
> > because it isn't high level enough.
>
> Allo, Huston ?
>
> > Thinking in terms of state and
> > behavior is, because it works regardless of programming language or
> > implementations. This is the reason I like working with Python. I
> > wanted a language that didn't bore me with it semantics and allowed me
> > to focus on design. Let me reiterate, I'm not obsessing over language
> > semantics, I just need practical, not religious, solutions for my
> > problem domain.
>
> Using properties instead of explicit getters/setters is pragmatism, not
> religion. Using the default get/set mechanism when there's no specific
> reason to do otherwise is pragmatism too. And understanding the object
> model and idioms of the language you're using is IMHO the very pragmatic
> thing to do...
>

Again, the object model of the language is irrelevant. The only
relevant model is my application's model, which should work regardless
of the language I use.

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


Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
tac-tics wrote:
> dwelch91 wrote:
> 
>>tac-tics wrote:
>>
>>>I'd say the second one. Empty lists are not false. They are empty. Long
>>>live dedicated boolean data types.
>>>
>>
>>Uh, no, empty lists are False in a boolean context:
>>
>>http://docs.python.org/lib/truth.html
>>
>>-Don
> 
> 
> Perhaps I should have specified it like this:
> 
> 
empty_list = []
empty_list is not False
> 
> True

Physical identity is not structural equality.


> I'm well aware that both of these snippets does the same thing. I'm
> just spouting my opinion that lists and integers are not tests, and in
> an ideal world (Java??? X-) 

You naughty troll

> if statements support only boolean types.

if statements supports only boolean *expressions*. An expression is
boolean if it's result can be coerced to a boolean value, ie fed to the
bool type's constructor. So your example is wrong wrt/ if statements -
it should read:

empty_list = []
bool(empty_list) is False
=> True


-- 
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: Coding style

2006-07-18 Thread Bruno Desthuilliers
dwelch91 wrote:
> PTY wrote:
> 
>> Which is better?
>>
>> lst = [1,2,3,4,5]
>>
>> while lst:
>>   lst.pop()
>>
>> OR
>>
>> while len(lst) > 0:
>>   lst.pop()
>>
> 
> I think the first one is better, but if all you are doing is removing
> all the items in the list, this is definitely better:
> 
> lst = []

Not if there are other names bound to the same list. You are only
rebinding this name, which does *not* empty the list object. The correct
solution here is

del lst[:]

which will remove all content from the list object,



-- 
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


Python : Event-Driven Paradigm

2006-07-18 Thread Kusanagi



Hi All, 
 
    I have been looking through 
wikipedia at the Event-Driven Page http://en.wikipedia.org/wiki/Event-driven_programming
and I noticed that it mentions that TCL has event 
driven programming built in. I also looked over the Python 3000 proposals and I 
did not notice any mention of future versions of python that are going to be 
changed to include this awesome feature. 
 
    I currently use the Twisted 
framework in various ways and I was just curious to know if the event-driven 
paradigm is going to be implemented without 
the use of 3rd party frameworks. i.e. Twisted. in the future. 

 
    If this question has already 
been asked and answered then please accept my apology. 
 
 
    - Steven. 
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Accessors in Python (getters and setters)

2006-07-18 Thread mystilleef

Bruno Desthuilliers wrote:
> mystilleef wrote:
> > Gerhard Fiedler wrote:
> >
> >>On 2006-07-15 06:55:14, mystilleef wrote:
> >>
> >>
> >>>In very well designed systems, the state of an object should only be
> >>>changed by the object.
> >>
> >>IMO that's not quite true. Ultimately, the state always gets changed by
> >>something else (user interaction, physical events); very few objects are
> >>completely self-contained in their behavior.
> >>
> > Then in those cases the system becomes a victim of high coupling.
>
> Time to burn your book and face reality. ObjA sends message Msg1 to
> ObjB. Part of the associated behaviour is that in responce to Msg1, objB
> changes it's own state. Practical result : ObjB's state has been changed
> by ObjA. Practical question : how do you hope to avoid this "hi
> coupling" (lol), apart from making all your objects totally autistic ?
>

Are you serious? Well, you design an object that serves as a mediator.
All objects can then only interact with themselves and the mediator
only. Via signals, objects learn to automatically adjust their states
and respond to events. This is just one of several methods you can
dramatically reduce coupling. I'm sure glad I didn't burn my book.

> >>In most systems (and you possibly have written some of them) are objects
> >>whose state gets changed by other objects -- possibly through the
> >>intermediation of setter methods that do nothing else but set the state.
> >>There's no conceptual difference between directly setting the state or
> >>calling a setter function that does nothing else but directly setting the
> >>state -- except for one unnecessary level of indirection in the latter.
> >>
> >
> >
> > It depends. If certain conditions need to be met before changing the
> > state of an object, then arbitrarily changing it can be dangerous.
>
> Does this imply a 'method call' *syntax* ?

That's language dependent.

>Given the existence of
> "computed attributes" (ie: support for 'attribute access' *syntax* with
> hidden accessors) and the possibility to redefine implementation (from
> default attribute r/w access to computed/controlled) without touching
> the interface, why advocate the *systematic* use of computed attributes
> when it's just duplicating the default behaviour ?
>

I'm not advocating anything. I'm just stating the use case for
accessors and the wisdom behind them. My qualm with implicit accessors
remains the name issue.

>
> >
> >>>For example, a third party randomly changing is_active, (which Python
> >>>lets you do freely and easily) from False to True may crash your GUI.
> >>>And I'm not making this up. Things like this do really happen depending
> >>>on the whackyness of your toolkit.
> >>
> >>That's quite true, but a setter that does nothing but change is_active
> >>doesn't prevent this. If there is logic necessary to prevent state changes
> >>in certain situations, this should be implemented. But whether you then
> >>call this a part of the "behavior" (looking at the implementation as being
> >>a setter method) or a part of the "state" (looking at the implementation as
> >>being an added feature of the attribute) doesn't really make an objective
> >>difference.
> >>
> >
> >
> > Of course using setters for the sake of just using them is pointless.
>
> Indeed.
>
> > The reason to use them is if pre-conditions or post-conditions need to
> > be met. Or to control access to an objects states.
>
> Then why advocate *systematic* use of them ?
>
> (snip)

I never advocated anything. On the contrary, I asked a query?

> >
> > State - behavior is not something I made up, so it isn't subjective.
>
> The words (and the concept they describe) are not. Interpretation of
> what is state and what is behaviour is subjective.
>
> > It
> > is a common term used in OO literature. In fact, the only reason I used
> > it is because I thought is was common knowledge.
>
> It is.
>
> > And behaviors are not
> > just necessarily getters/setters, they are methods of objects.
>
> Behaviour is how a given object reacts to a given message. *Nothing* in
> this implies the notions of attributes or methods. Attributes and
> methods are implementation details of the concepts of state and
> behaviour, and - while this is a common implementation of OO concepts -
>   the choice to use non-callable attributes as representing the state
> and callable ones as representing behaviour is totally
> implementation-dependant.
>

I agree. And I already told you I think in terms of state and behavior
and not language dependent semantics.

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


Re: Google Earth contact? (OT, sort of...)

2006-07-18 Thread Daniel Fischer
Bell, Kevin!

> Does anyone know a contact for anyone that works for Google Earth?  I
> wanted to shoot 'em an email about a possible enhancement, but they're
> smart enough to not leave contact info ANYWHERE on their websites.

They do have a form for sales inquiry, though. 

Of course, when I sent them a request on behalf of the company I work for,
I ever only received an automated reply, so don't expect too much.


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


tkinter wm_delete_window

2006-07-18 Thread yvesd
hello i want to intercept tkinter python system events like
wm_delete_window
and if possible for any window, but the newest code I've produced give
me
an error :

Traceback (most recent call last):
  File "C:\Documents and Settings\yvesd\Bureau\protowin.py", line 36,
in ?
b1 = Tkinter.Button (win1)
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1933, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1856, in __init__
BaseWidget._setup(self, master, cnf)
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1834, in _setup
self.tk = master.tk
AttributeError: MyDlg instance has no attribute 'tk'

thanks a lot for the help answer.

here is my code :

import Tkinter
from Tkinter import *

class MyDlg(Toplevel):


def ma_fonction():
print "my function is finished."


def __init__(arg1, arg2):
arg1.protocol("WM_DELETE_WINDOW", arg1.ma_fonction)

root = Tkinter.Tk ()
#win1 = Tkinter.Toplevel (root)
win1 = MyDlg(root)
b1 = Tkinter.Button (win1)
b1.config (text="hello")

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


Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
PTY wrote:
> Bob Greschke wrote:
> 
>><[EMAIL PROTECTED]> wrote in message
>>news:[EMAIL PROTECTED]
>>
>>>PTY wrote:
>>>
Which is better?

lst = [1,2,3,4,5]

while lst:
  lst.pop()

OR

while len(lst) > 0:
  lst.pop()
>>>
>>>A dozen posts, but nobody has posted the right
>>>answer yet, so I will :-)
>>>
>>>It doesn't matter -- use whichever you prefer (*)
>>>This is an angels on the head of a pin issue.
>>>
>>>(*) -- If your code is part of an existing body of
>>>code that uses one or the other style consistently,
>>>then you should do the same.
>>>
>>
>>I'd go even one step further.  Turn it into English (or your favorite
>>non-computer language):
>>
>>1. While list, pop.
>>
>>2. While the length of the list is greater than 0, pop.
>>
>>Which one makes more sense?  Guess which one I like.  CPU cycles be damned.
>>:)
>>
>>Bob
> 
> 
> 
> It looks like there are two crowds, terse and verbose.  

Nope, there are two crowds: those who RTFM, and those who don't.

> I thought terse
> is perl style and verbose is python style.

s/terse/cryptic/
s/verbose/readable/

Python is much more readable than Java because it's *less* verbose than
Java.

>  BTW, lst = [] was not what
> I was interested in :-) 

Nor is it the correct functional equivalent of your code snippet.

> I was asking whether it was better style to
> use len() or not.

The idiomatic solution is clearly derivable from Python's language
documentation : in a boolean context, empty lists (etc...) eval to
False. FWIW, it's also more generic (you could have an object supporting
pop() but not __len__()), less error-prone, and can allow optimisations
(a container may know that it is empty without computing it's length).


-- 
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: range() is not the best way to check range?

2006-07-18 Thread Paul Boddie
John Machin wrote:
> On 18/07/2006 12:41 PM, [EMAIL PROTECTED] wrote:
> > it seems that range() can be really slow:

[...]

> Some things to try:
> 1a. Read what the manual has to say about the range() function ... what
> does it produce?

Indeed. Still, the addition of a __contains__ method to range (and
xrange) would permit acceptable performance for the code given. Perhaps
this is a convenience worth considering for future Python releases.

Paul

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


Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
Carl Banks wrote:
> Patrick Maupin wrote:
> 
>>PTY wrote:
>>
>>
>>>It looks like there are two crowds, terse and verbose.  I thought terse
>>>is perl style and verbose is python style.  BTW, lst = [] was not what
>>>I was interested in :-)  I was asking whether it was better style to
>>>use len() or not.
>>
>>It's not canonical Python to use len() in this case.  From PEP 8:
>>
>>- For sequences, (strings, lists, tuples), use the fact that empty
>>  sequences are false.
>>
>>  Yes: if not seq:
>>   if seq:
>>
>>  No: if len(seq)
>>  if not len(seq)
>>
>>The whole reason that a sequence supports testing is exactly for this
>>scenario.  This is not an afterthought -- it's a fundamental design
>>decision of the language.
> 
> 
> That might have made sense when Python and string, list, tuple were the
> only sequence types around.
> 
> Nowadays, Python has all kinds of spiffy types like numpy arrays,
> interators, generators,
> etc., for which "empty sequence is false" just
> doesn't make sense.  

Iterators and generators are *not* sequences types. wrt/ non-builtin
container types, I suggest you re-read section 3.3.1 of the language
references:

"""
__nonzero__(self)
Called to implement truth value testing, and the built-in operation
bool(); should return False or True, or their integer equivalents 0 or
1. When this method is not defined, __len__() is called, if it is
defined (see below). If a class defines neither __len__() nor
__nonzero__(), all its instances are considered true.
"""
http://docs.python.org/ref/customization.html


> If Python had been designed with these types in
> mind, I'm not sure "empty list is false" would have been part of the
> language, let alone recommend practice.

FWIW, this magic method already existed in 1.5.2 :
http://www.python.org/doc/1.5.2p2/ref/customization.html


-- 
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


How to use ParseTuple with unknown number of args?

2006-07-18 Thread ondekoza
Hi,

I am embedding python in a large application, written in C. To allow
access to
the internals of the app, I embedded python as recommended by the
`extending and embedding'-document on python.org. Most functions that
are now callable from python have fixed number of args and are easy
to parse with ParseTuple.

Now I want to be able to add a function to add array data and I cannot
figure out
how this is done.

The resulting python script should look like this.

import embedded_module as em
em.mysimplecall(5)
em.anothersimplecall(4.5)
d=[1,2,3,4,5]
em.arraycall(d)
d.append(99)
em.arraycall(d)

The C-program should be able to retrieve the array, regardless of its
length.
I suspect it must be done using "O" or "O!", but I cannot find any
examples.

Yours
Stefan Schroeder (Ondekoza)

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


Re: Augument assignment versus regular assignment

2006-07-18 Thread Antoon Pardon
On 2006-07-17, Paul Boddie <[EMAIL PROTECTED]> wrote:
> Antoon Pardon wrote:
>>
>> What the language reference should have said IMO is that in case x
>> is an attribute reference, index or slicing, the primary expression
>> will be evaluated only once, as will be the index or slice in the
>> two latter cases.
>
> I think the difficulty here for the author of this particular section
> of the reference is in describing the mechanisms at work whilst keeping
> the description at a conceptual level which can be directly connected
> to the source text in a program.

Sure! However the author of the augmented assignment reference uses
a concept that seems not be a pythonic concept: a target evaluation.
Call it an lvalue, a lefthand evaluation if you prefer, but in
the assignment reference it is never mentioned. Each time the
word evaluation is used, it is the evaluation of an expression, never
a target. Sure sometimes such a expression is part of a target, but
the evaluation never reaches a point where the result is the evaluation
of a target: So why doesn't the autor of the augmented assignment reference
limit himself to the same concepts used in the assignment reference?

Now maybe I'm just not bright enough, so maybe you can explain what
something like col['t'] is evaluated to in a statement like:

  col['t'] = exp

> However, apart from providing a vague
> intuition about how augmented assignment must work, the description
> doesn't answer all questions effectively, particularly in cases where
> the actual assignments are not simple local/global name binding
> operations.
>
> One way to consider augmented assignment is as a statement formulated
> in the following way:
>
> setvalue(namespace, name, op(getvalue(namespace, name), expr))
>
> Consider an augmented assignment on a local name:
>
> a += b
>
> This could be phrased as follows:
>
> setname(locals, "a", add(getname(locals, "a"), b))
>
> Or really:
>
> setname(locals, "a", add(getname(locals, "a"), getname(locals, "b")))
>
> Consider an augmented assignment on an attribute:
>
> a.b += c
>
> This could also be phrased similarly:
>
> setattr(a, "b", add(getattr(a, "b"), c))
>
> And consider an augmented assignment on an item:
>
> a[b] += c
>
> This too is phrased similarly:
>
> setitem(a, b, add(getitem(a, b), c))
>
> So, as long as you're willing to accept that the setvalue class of
> operations (setname, setattr, setitem) aren't really evaluating the
> target of the assignment - strictly, the thing being replaced in the
> assignment - then only the getvalue class of operations (getname,
> getattr, getitem) are causing the evaluation of the target. And since
> setname is just a normal name binding assignment which we know doesn't
> cause the target to be evaluated, we can assume that the other
> operations in that class behave similarly.

Well maybe I'm missing your point entirely but would you be so friendly,
as to rephrase the following statements too:

  a = a + b
  a.b = a.b + c
  a[b] = a[b] + c

Because as far as I can see the rephrasing of these statements will
result in exactly the same results as their augmented assignment
counter parts. So following your logic above, we would have to
come to the conclusion that the "targets" of these statements are
evaluated once too. This while the language reference suggests
they are evaluated twice.

IMO the language reference sugest that the stament:

  a[i] += [b]

is more effective than:

  a[i] = a[i] + [b]

IMO it suggests that the augmented assignment version is
just as effective as:

  a[i].append(b)

Because, i hope, we agree that a[i] is evaluated only
once here!

So we have here three statements all which result
in a similar result one in which the
number of evaluations of a[i] is under dispute,

one in which the number of evaluations is suggested
to be two

one in which the number of evaluations is one.

Yet the work done in the augmented version of this
example is almost the same as in the normal assignment,
the difference is negligible IMO and both version
differ about the same with the append version which
will have to do about half what the other versions had to
do, depending on how expensive the __xetitem__ methods
are.


> Now, one aspect of evaluation has been skipped in the above
> explanation: what if we have a "complicated" expression on the left
> hand side? Consider this:
>
> a.f().x += y
>
> We could naively write this as follows:
>
> setattr(a.f(), "x", add(getattr(a.f(), "x"), y))
>
> However, it looks like we are evaluating at least part of the left hand
> side twice. Thus, we need to be a bit clearer about what really
> happens:
>
> namespace = a.f()
> setattr(namespace, "x", add(getattr(namespace, "x"), y))
>
> In order to avoid double evaluation, we first obtain the target
> namespace (or itemspace, I suppose). Then, we perform the operations as
> stated above.

Yes, and what you are doing here is eliminating the double evaluation
of the primary. In a statement like a.f().x = ... 

Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Bob Greschke wrote:
> 
> 
>>I'd go even one step further.  Turn it into English (or your favorite
>>non-computer language):
>>
>>1. While list, pop.
>>
>>2. While the length of the list is greater than 0, pop.
>>
>>Which one makes more sense?  Guess which one I like.  CPU cycles be
>>damned.
>>:)
> 
> 
> One of my rules is, always program like the language actually has a Boolean
> type, even if it doesn't.

Python has a boolean type.

> That means, never assume that arbitrary values
> can be interpreted as true or false,

There's nothing to assume, and nothing arbitrary in it. It's all clearly
defined in whole letters in the language references.

> always put in an explicit comparison
> if necessary so it's obvious the expression is a Boolean.

The fact that the expression is used in the context of a if statement is
clearly enough to denote a boolean expression. Explicitly testing
against a boolean is uselessly redundant - and doesn't change anything,
since it's always a boolean expression. FWIW, getting rid of theses
"explicit" redundant tests was one of the first things I learned about
programming.


-- 
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: Augument assignment versus regular assignment

2006-07-18 Thread Antoon Pardon
On 2006-07-17, Terry Reedy <[EMAIL PROTECTED]> wrote:
>  "Antoon Pardon" <[EMAIL PROTECTED]> wrote in message
>  news:[EMAIL PROTECTED]
>> On 2006-07-15, Terry Reedy <[EMAIL PROTECTED]> wrote:
>>> The problem with understanding augmented assignment is that  it directs 
>>> the
>>> compiler and interpreter to do one or maybe two mostly invisible
>>> optimizations.  To me, the effective meaning of 'evalutating once versus
>>> twice' is most easily seen in the byte code generated by what is, 
>>> remember,
>>> the reference implementation.  What it does is what the
>>> less-than-super-clear doc means.
>>
>> But what does one do, if the question is raised whether or not the
>> code generated actually behaves as described by the language reference?
>
> One can just as well ask whether or not the docs actually describe the 
> behavior of the interpreter ;-).  In this case, not as well as one might 
> like.  Or, whether docs (and reasonable interpretation thereof) and 
> implementation match, which I claim they do it this case.

Well this dispute seems to boil down what is and what is not
involved in evaluating a target, and I have come to doubt that
target evaluation is even a meaningfull concept in python, so
maybe in order that I can understand how you come to that claim,
can you explain what a target evaluates to? So in a statement like

  col['t'] = exp

What is the evaluation of col['t']?

>> Shouldn't the language reference be clear enough to be understandable
>> without the help of byte code generated by the reference implementation?
>
> Normally, code experiments, such as you attempted, should be enough.  But, 
> as I said, trying to document mostly invisibly behavior is more difficult. 
> Based on looking at the byte code, I would put it this way: the difference 
> between assignment with duplicated source and target expressions and 
> augmented assigment with the same expression is that the interpreter 
> eliminates as much duplicate calculation as possible.  But precisely what 
> that mean seems a bit interpreter dependent to me.
>
> Should we expect a reference writen in (ambiguous) natural language to be 
> unambiguously clear?  I think not; that is why formal grammers and 
> notations were invented.  I learned Python with the doc in one window and 
> the interactive interpreter in another.

But there seems to be no formal system used for explaning the behaviour.
So I think one should take extra care in the language reference to
write in a way that is as clear as possible. IMO there is room for
improvement in the augmented assignment part. That is why I proposed
that the language reference would state that the primary of the
target would be evaluated only once, along with the index/key or slice.
Such wording avoids the notion of a target evaluation, which seems
trouble some and explains what kind of optimisations can be expected.

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


Re: How to use ParseTuple with unknown number of args?

2006-07-18 Thread ondekoza
With some more research on comp.lang.python I found that this topic has
been discussed earlier to some extend.

One recommendation was to use numpy. This would introduce an additional
dependency which I try to avoid.

The earlier posts generally highlight some specific feature of calling
with arrays. Can someone point me to a piece of software, where sth.
like this is actually used?

Stefan S. (Ondekoza)

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


Python linker

2006-07-18 Thread byteschreck
I love python - I use it as a utility language to complement my C#
programming every day. However, the reason I do not use it as my
primary language is - surprise, surprise - not its lack of static type
checking, but the size of standalone executes  (which embed the python
runtime).

Would it be possible to link only the used functions into your
resulting executable? After all, a typical application might only use
20% of everything that is in the Python .dlls.

The same applies to wxPython - it would be great if you could only link
in what you need. Would it be possible to write such linkers at all
(maybe based on GCC)?

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


Re: tkinter wm_delete_window

2006-07-18 Thread Eric Brunel
On Tue, 18 Jul 2006 11:16:04 +0200, yvesd <[EMAIL PROTECTED]> wrote:
> hello i want to intercept tkinter python system events like
> wm_delete_window
> and if possible for any window, but the newest code I've produced give
> me
> an error :
> Traceback (most recent call last):
>   File "C:\Documents and Settings\yvesd\Bureau\protowin.py", line 36,
> in ?
> b1 = Tkinter.Button (win1)
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1933, in __init__
> Widget.__init__(self, master, 'button', cnf, kw)
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1856, in __init__
> BaseWidget._setup(self, master, cnf)
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1834, in _setup
> self.tk = master.tk
> AttributeError: MyDlg instance has no attribute 'tk'
> thanks a lot for the help answer.
> here is my code :
> import Tkinter
> from Tkinter import *

Do not import the same module twice: either use "import Tkinter" and  
prefix everything in it with 'Tkinter.', or use "from Tkinter import *"  
and don't specify any prefix. You're mixing both here.

> class MyDlg(Toplevel):
>   def ma_fonction():

You must specify 'self' as first parameter here. Or put 'ma_fonction'  
outside the class.

>   print "my function is finished."
>   def __init__(arg1, arg2):
>   arg1.protocol("WM_DELETE_WINDOW", arg1.ma_fonction)

Please don't use anything else than 'self' as the name for methods' first  
parameter. It will confuse everyone who knows Python. And your mistake is  
here: the constructor for the super-class (Toplevel) is not called  
automatically by the sub-class constructor; so you have to do it yourself.  
So just rewrite these two lines as:

def __init__(self):
   Toplevel.__init__(self)
   self.protocol("WM_DELETE_WINDOW", self.ma_fonction)

and everything should work fine. BTW, I've removed the parameter arg2 that  
you didn't use at all.

> root = Tkinter.Tk ()
> #win1 = Tkinter.Toplevel (root)
> win1 = MyDlg(root)

Replace that with:

win1 = MyDlg()

> b1 = Tkinter.Button (win1)
> b1.config (text="hello")

An additional small note: you can write the last two lines as a single one:

b1 = Tkinter.Button(win1, text='hello')

And you also must call:
- b1.pack, b1.grid or b1.place to put your button somewhere in your window.
- root.mainloop() in the end or your window will never appear.

If you want to do Tkinter the OO way, you may also create the button in  
the dialog's constructor.

So here would be my version of your program:

--
 from Tkinter import *

class MyDlg(Toplevel):
   def __init__(self):
 Toplevel.__init__(self)
 b1 = Button(self, text='hello')
 b1.pack()
 self.protocol("WM_DELETE_WINDOW", self.ma_fonction)
   def ma_fonction(self):
 print "my function is finished."

root = Tk()
win1 = MyDlg()
root.mainloop()
--

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Augument assignment versus regular assignment

2006-07-18 Thread Paul Boddie
Antoon Pardon wrote:
>
> Now maybe I'm just not bright enough, so maybe you can explain what
> something like col['t'] is evaluated to in a statement like:
>
>   col['t'] = exp

In the notation given earlier, let us say that it would be this:

namespace = col
setitem(namespace, "t", exp)

Note that in my notation I use the term namespace to apply to actual
namespaces (locals, globals, classes, objects) as well as what I call
"itemspaces" (things which store items). In the above, we still obtain
the namespace first, but we don't attempt to fetch the item previously
stored at item "t" (if any was present).

[...]

> Well maybe I'm missing your point entirely but would you be so friendly,
> as to rephrase the following statements too:
>
>   a = a + b

This is where it gets interesting, even though it should not appear to
do so. We might consider writing this as follows:

setname(ns_target, "a", add(getname(ns_source, "a"), b))

Here, I've skipped over how b is obtained, but it'd be something like
getname(locals, "b") or getname(globals, "b"). Since recent versions of
Python perform some special tricks to disallow assignments involving
mixed namespaces (considering a is global and that the above code is in
a function), we probably can assume the same namespace is at work. But
really, the most pertinent question relates to the evaluation of the
namespaces themselves: a simple name binding operation involves the
local or global namespaces which can be obtained without side-effects.
Thus, the simple assignment above is mostly equivalent to the augmented
assignment...

a += b

...since ns_target == ns_source and their evaluation can be considered
free of side-effects. In other words, we can rewrite it thus:

assert ns_target == ns_source
namespace = ns_target
setname(namespace, "a", add(getname(namespace, "a"), b))

>   a.b = a.b + c

We could consider writing this:

setattr(a, "b", add(getattr(a, "b"), c))

Once again, I've skipped over how c is obtained, since it isn't central
to the assignment. As above, it appears that the namespace is the same
on both sides of the assignment (given Python's assignment rules),
although by using an opaque identifier the above example doesn't really
permit us to illustrate this. We could expand the identifier a to
investigate further:

setattr(getname(ns_target, "a"), "b", add(getattr(getname(ns_source,
"a"), "b"), c))

Which according to the above reduces to this:

setattr(getname(namespace, "a"), "b", add(getattr(getname(namespace,
"a"), "b"), c))

And to this:

ns_a = getname(namespace, "a")
setattr(ns_a, "b", add(getattr(ns_a, "b"), c))

Which shows that the augmented assignment is probably equivalent. See
below for a better example.

>   a[b] = a[b] + c

And again, we could consider writing this:

setitem(a, b, add(getitem(a, b), c))

Once again, I've skipped over how b and c are obtained. Consider this
as an exercise! ;-) And as noted above, the example doesn't really
permit us to illustrate this point - you could expand the terms and
produce something that suggests that this simple case is equivalent to
an augmented assignment.

> Because as far as I can see the rephrasing of these statements will
> result in exactly the same results as their augmented assignment
> counter parts. So following your logic above, we would have to
> come to the conclusion that the "targets" of these statements are
> evaluated once too. This while the language reference suggests
> they are evaluated twice.

Quoting from the reference: "In the augmented version, x is only
evaluated once." Let us look in depth at some of the unillustrated
issues from above.

> IMO the language reference sugest that the stament:
>
>   a[i] += [b]

Here, we can be sure that the same namespace is involved:

namespace = a
setitem(namespace, i, add(getitem(namespace, i), [b]))

> is more effective than:
>
>   a[i] = a[i] + [b]

Whilst I, knowing that a appears twice and believing that a always
produces the same result, might write the same as above, let us
consider a more complicated expression instead of a (where the function
f returns a list):

f()[i] = f()[i] + [b]

Here, since we can make no guarantees that f() evaluates to the same
thing every time it is called, we must evaluate it twice to honour the
intent of the statement:

setitem(f(), i, add(getitem(f(), i), [b]

To see this clearly...

f1 = f()
f2 = f()
setitem(f1, i, add(getitem(f2, i), [b])

Meanwhile, in the case of the augmented assignment...

f()[i] += [b]

...the author has more or less stated that he/she wants f() to be
evaluated only once - anything else would be surprising:

namespace = f()
setitem(namespace, i, add(getitem(namespace, i), b))

> IMO it suggests that the augmented assignment version is
> just as effective as:
>
>   a[i].append(b)
>
> Because, i hope, we agree that a[i] is evaluated only
> once here!

The rule is that if the namespace (what you call the primary, I think)
is mentioned once, it is evaluated only once.

[...]

> Yes, a

Re: What is a type error?

2006-07-18 Thread Joachim Durchholz
Marshall schrieb:
> Chris Smith wrote:
>> Joachim Durchholz <[EMAIL PROTECTED]> wrote:
>> I *think* I understand Marshall here.  When you are saying "assignment",
>> you mean assignment to values of attributes within tuples of the cell.
>> When Marshall is saying "assignment", he seems to mean assigning a
>> completely new *table* value to a relation; i.e., wiping out the entire
>> contents of the relation and replacing it with a whole new set of
>> tuples.  Your assignment is indeed less powerful than DML, whereas
>> Marshall's assignment is more powerful than DML.
> 
> Exactly.

Ah well. I never meant that kind of assignment.

Besides, all the aliasing possibilities already happen at the field 
level, so it never occurred to me that whole-table assignment might 
enter into the picture.

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


Re: range() is not the best way to check range?

2006-07-18 Thread Andy Dingley

[EMAIL PROTECTED] wrote:

> it seems that range() can be really slow:

> if i in range (0, 1):

RTFM on range()

You're completely mis-using it here, using it with an if ... in ...
test. The purpose of range() in Python is as loop control, not
comparisons!  It's not a SQL BETWEEN statement.

Although you _can_ do this (you've done it!) you've also found that
it's slow. Many people would argue that even using range() for loop
control is unusably slow.

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


Re: New SourceForge project: Diet Python!!!

2006-07-18 Thread skip

>> Diet Python is a flavor of Python with allegro, multiarray, umath,
>> calldll, npstruct and curses builtin, all else nonessential to
>> language ripped out. Total size < 3MB, 1% of PSF Python. Diet Python
>> helps keep clients thin :)

Just an FYI, but Python 2.5 comes with ctypes, not calldll.  Might be worth
switching to remain compatible at that level.

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


Getting and Setting Cookies

2006-07-18 Thread Vlad Dogaru
Hello,

I am trying to use cookies and Python to create a simple login example.
But I am very disoriented at the existence of two cookie libraries,
namely Cookie and cookielib. I have seen examples of setting cookies
(although I am still not sure about timestamps and cookie lifespan),
but no reference to getting the currently set cookies. For instance, I
want to see if there is any 'user' value, to check whether the user has
logged in. Please, enlighten me.

Thanks in advance,
Vlad

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


Re: How to use ParseTuple with unknown number of args?

2006-07-18 Thread Daniel Dittmar
ondekoza wrote:
> The earlier posts generally highlight some specific feature of calling
> with arrays. Can someone point me to a piece of software, where sth.
> like this is actually used?

Python source/Objects/stringobject.c string_join would be an example if 
you only allow a list or tuple.

Python/bltinmodule.c min_max demonstrates how to allow either a sequence 
or a variable number of arguments.

Modules/itertools.c has probably lots of examples on how to work with 
iterators at the C API level.

Daniel

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


Re: range() is not the best way to check range?

2006-07-18 Thread Leif K-Brooks
Grant Edwards wrote:
> Using xrange as somebody else suggested is also insane.

Sorry about that, I somehow got the misguided notion that xrange defines 
its own __contains__, so that it would be about the same speed as using 
comparison operators directly. I figured the OP might have a better 
reason for wanting to use range() than his post mentioned -- perhaps the 
range to check was being passed from a function, and it would be easier 
to pass an object than a tuple of lower and upper bound -- but since 
xrange does looping for a membership test, my suggestion was indeed insane.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Track keyboard and mouse usage

2006-07-18 Thread skip

Dennis> Problem: X-Window supports remote displays; you'd need a means
Dennis> of specifying which display to track (unless you've opened a GUI
Dennis> application and that application is asking for positions ...

Watch does this via server mode (sort of).  You run watch on both your local
and remote machines.  The remote machine forwards information about mouse
movement to the local machine.

Dennis> I don't think anyone has ported raw X-protocol access to Python.

There is a (defunct) Xlib wrapper for Python.  Nowadays you could probably
redo just the parts you need pretty easily with ctypes.

Dennis> * If working raw xt/DECWindows wasn't bad enough... Add GKS
Dennis> (is that still around?) on top of it -- I had a DECWindows UI
Dennis> whose [... many magical reminiscences elided ;-) ...]

I believe OpenGL pretty much killed the market for stuff like GKS.  X
servers have enough features and video boards have enough performance that
for all but the most demanding graphics applications there's no desired to
write bits using something other than OpenGL and no need to expose the raw
framebuffer at the application program level.

Skip

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


Re: What is a type error?

2006-07-18 Thread Joachim Durchholz
Marshall schrieb:
> No. The variable is the table, not the records.

In your examples, yes.

 > Relations are not arrays.

They are, in all ways that matter for aliasing:
They are a collection of mutable data, accessible via selector values.

> Records are not lvalues.

Agreed, but they have identity. An lvalue is an identity that you can 
track in software; record identity is untrackable in standard SQL, but 
it's real enough to create aliasing problems.

> I would propose that variables have identity, and values do not.

What's a "variable", by that definition?
It can't be "something that has a name in a program", since that would 
exclude variables on the heap.
Another definition would be "something that may have a different value 
if I look at it sometime later", but then that would include SQL records 
as well. Besides, the temporal aspect is problematic, since it's unclear 
whether the "it" some time later is still the same as the "it" before 
(if you have a copying garbage collector, you'd have to somehow 
establish identity over time, and we're full circle back at defining 
identity).

Personally, I say "two things are identical / have the same identity", 
if they are (a) equal and (b) stay equal after changing just one of 
them. That's a nice local definition, and captures exactly those cases 
where aliasing is relevant in the first place (it's actually that 
"changing here also changes there" aspect that makes aliasing so dangerous).
It also covers SQL records. Well, they do have aliasing problems, or 
problems that are similar enough to them, so I'd say this is a 
surprising but actually interesting and useful result of having that 
definition.

> In part this is via the supplied definition of identity, in which, when
> you change one thing, if something else changes as well, they
> share identity. Since one cannot change values, they necessarily
> lack identity.

I agree that immutable values don't have identity (or, rather, that 
identity isn't an interesting concept for them since it's already 
subsumed under equality).

>> It's certainly not storage location:
>> if you DELETE a record and then INSERT it with the same values, it may
>> be allocated somewhere entirely else, and our intuition would say it's
>> not "the same" (i.e. not identical).
> 
> Well, it would depend on how our intuition had been primed. If it
> was via implementation techniques in low level languages, we
> might reach a different conclusion than if our intuition was primed
> via logical models and relation theory.

Sure.

However, since I'm interested in practical consequences for programming, 
I'm looking for definitions that allow me to capture those effects that 
create bugs.
In the case of identity, I'd say that's aliasing.

>> Since intuition gives me ambivalent results here, I'll go back to my
>> semiformal definition (and take the opportunity to make it a bit more
>> precise):
>> Two path expressions (lvalues, ...) are aliases if and only if the
>> referred-to values compare equal, and if they stay equal after applying
>> any operation to the referred-to value through either of the path
>> expressions.
> 
> Alas, this leaves me confused. I don't see how a path expression
> (in this case, SELECT ... WHERE) can be an l-value. You cannot
> apply imperative operations to the result.

It's not SELECT...WHERE..., it's WHERE... that's an lvalue.
And you can indeed use it with UPDATE, so yes it's an lvalue by my book. 
(A given WHERE clause may become invalid or refer to a different record 
after some updates, so it's not the kind of lvalue that you have in a C 
program.)

 > (Also I think the use
> of equality here is too narrow; it is only necessary to show that
> two things both change, not that they change in the same way.)

Sorry for using misleading terminology.
An "alias" is when two names refer to an identical object (both in real 
life and IMHO in programming), and that's what I wrote.
"Aliasing" is the kind of problems that you describe.

> I was under the impression you agred that "i+2" was not
> a "path expression".

Yes, but [i+2] is one.

In the same vein, "name = 'John'" is an expression, "WHERE name = 
'John'" is a path expression.

 > If our hypothetical language lacks record
> identity, then I would say that any query is simply an expression
> that returns a value, as in "i+2."

As long as the data is immutable, yes.
The question is how equality behaves under mutation.

>> On the other hand, variable addresses as tangible identities don't hold
>> much water anyway.
>> Imagine data that's written out to disk at program end, and read back
>> in. Further imagine that while the data is read into main memory,
>> there's a mechanism that redirects all further reads and writes to the
>> file into the read-in copy in memory, i.e. whenever any program changes
>> the data, all other programs see the change, too.
>> Alternatively, think about software agents that move from machine to
>> machine, carrying their data

Dictionary question

2006-07-18 Thread Brian Elmegaard
Hi 

I have written the following which works, but I would like to write it
less clumsy. I have a dictionary in which I loop through the keys for
a dynamic programming algorithm. If a key is present I test if its
value is better than the current, if it is not present I just create
it. Would it be possible to write it more compact?

###3
c=1
s=8
x=2

l=list()
l.append(dict())
l[0][5]=0

l.append(dict())

for a, e in l[-2].iteritems():
if a+chttp://www.et.web.mek.dtu.dk/Staff/be/be.html
Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about what lamda does

2006-07-18 Thread nephish
ok, i think i get it.
pretty cool.
thanks
-sk


Dan Bishop wrote:
> [EMAIL PROTECTED] wrote:
> > Hey there,
> > i have been learning python for the past few months, but i can seem to
> > get what exactly a lamda is for.
>
> It defines a function.
>
> f = lambda x, y: expression
>
> is equivalent to
>
> def f(x, y):
>return expression
>
> Note that lambda is an expression while def is a statement.
>
> > What would i use a lamda for that i
> > could not or would not use a def for ? Is there a notable difference ?
> > I only ask because i see it in code samples on the internet and in
> > books.
>
> Lambdas are typically used as parameters to functions that take
> functions as arguments, like property() and reduce().  You never *need*
> to use one, but sometimes it's convenient.

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


wanting

2006-07-18 Thread arsl89
hy gys i m wanting python programming language.
plz snd me the backup of python




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


Re: Capturing instant messages

2006-07-18 Thread Nick Vatamaniuc
Ed,

It depends on what IM protocol the company is using. If there is more
than one, your job might end up being quite complicated. You indicated
port 5190 in your post, does it mean that the company is using only AOL
IM? In general it seems like you would have to:

1) Capture the traffic
2) Decode the IM protocol
3) Record the captured text

1) As far as capturing the traffic, I would use a specific tool like
tcpick ( a cousin of tcpdump but actually dumps the data to console not
just the headers and recreates the tcp streams -- good stuff!).  Again
if you know the exact port number and the exact protocol this might be
very easy because you will set up your capturing program to capture
traffic from only 1 port. Let's assume that for now. Here is my quick
and dirty attempt. First install tcpick http://tcpick.sourceforge.net/
if you don't have it, then become root and open a Python prompt. (Use
ipython... because my mom says it's better ;).
In [1]:from subprocess import * #don't do this in your final script
always use 'import subprocess'
In [2]:cmd='/usr/sbin/tcpick -i eth0 -bR tcp port 80' #use your IM port
here instead of 80
#-bR means reconstruct TCP stream and dump data in raw mode to console
(good for ASCII stuff).
In [3]:p=Popen(cmd, shell=True, bufsize=0, stdout=PIPE, stderr=PIPE)
#start a subprocess w/ NO_WAIT
In [4]:p.pid #check the process pid, can use this to issue a 'kill'
command later...
Out[4]:7100
In [5]:p.poll()
In [6]:#Acutally it is None, which means process is not finished
In [7]:#Read some lines one by one from output
In [8]:p.stdout.readline() #Might block here, if so start a browser and
load a page
Out[8]:'Starting tcpick 0.2.1 at 2006-XX-XX XX:XX EDT\n'
In [9]:#
In [10]:#Print some lines from the output, one by one:
In [11]:p.stdout.readline()
Out[11]:'Timeout for connections is 600\n' #first line, tcpick prompt
stuff
In [12]:p.stdout.readline()
Out[12]:'tcpick: listening on eth0\n'
In [13]:p.stdout.readline()
Out[13]:'setting filter: "tcp"\n'
In [14]:p.stdout.readline()
Out[14]:'1  SYN-SENT   192.168.0.106:53498 >
64.233.167.104:www\n'
In [15]:p.stdout.readline()
Out[15]:'1  SYN-RECEIVED   192.168.0.106:53498 >
64.233.167.104:www\n'
In [16]:p.stdout.readline()
Out[16]:'1  ESTABLISHED192.168.0.106:53498 >
64.233.167.104:www\n'
In [17]:p.stdout.readline() #the good stuff should start right here
Out[17]:'GET /search?hl=en&q=42&btnG=Google+Search HTTP/1.1\r\n'
In [18]:p.stdout.readline()
Out[18]:'Host: www.google.com\r\n'
In [19]:p.stdout.readline()
Out[19]:'User-Agent: blah blah...\r\n'
In [20]:p.stdout.read() #try a read() -- will block, press Ctrl-C
exceptions.KeyboardInterrupt
In [21]:p.poll()
Out[21]:0  #process is finished, return errcode = 0
In [22]:p.stderr.read()
Out[22]:'' #no error messages
In [23]:p.stdout.read()
Out[23]:'\n257 packets captured\n7 tcp sessions detected\n'
In [24]: #those were the last stats before tcpick was terminated.

Well anyway, your readline()'s will block on process IO when no data
supplied from tcpick. Might have to start a thread in Python to manage
the thread that spawns the capture process. But in the end the
readlines will get you the raw data from the network (in this case it
was just one way from my ip to Google, of course you will need it both
ways).

2) The decoding will depend on your protocol, if you have more than one
IM protocol then the capture idea from above won't work too well, you
will have to capture all the traffic then decode each stream, for each
side, for each protocol.

3) Recording or replay is easy. Save to files or dump to a MySQL table
indexed by user id,  timestamp, IP etc. Because of buffering issues you
will probably not get a very accurate real-time monitoring system with
this setup.

Hope this helps,
Nick Vatamaniuc






Ed Leafe wrote:
> I've been approached by a local business that has been advised that
> they need to start capturing and archiving their instant messaging in
> order to comply with Sarbanes-Oxley. The company is largely PC, but
> has a significant number of Macs running OS X, too.
>
>   Googling around quickly turns up IM Grabber for the PC, which would
> seem to be just what they need. But there is no equivalent to be
> found for OS X. So if anyone knows of any such product, please let me
> know and there will be no need for the rest of this post.
>
>   But assuming that there is no such product, would it be possible to
> create something in Python, using the socket or a similar module?
> They have a number of servers that provide NAT for each group of
> machines; I was thinking that something on those servers could
> capture all traffic on port 5190 and write it to disk. Is this
> reasonable, or am I being too simplistic in my approach?
> 
> -- Ed Leafe
> -- http://leafe.com
> -- http://dabodev.com

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


Re: question about what lamda does

2006-07-18 Thread Nick Vatamaniuc
Use it anywhere a quick definition of a function is needed that can be
written as an expression. For example when a callback function is
needed you could say:
def callback(x,y):
  return x*y
some_function(when_done_call_this=callback)
But with lambda you could just write
some_function(when_done_call_this=lambda x,y:x*y)
Note: because it is an _expression_ you cannot do stuff like 'if..else'
inside of lambda.

-Nick V.

[EMAIL PROTECTED] wrote:
> Hey there,
> i have been learning python for the past few months, but i can seem to
> get what exactly a lamda is for. What would i use a lamda for that i
> could not or would not use a def for ? Is there a notable difference ?
> I only ask because i see it in code samples on the internet and in
> books.
> 
> thanks for any clarity
> 
> sk

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


Re: wanting

2006-07-18 Thread Paul Rubin
"arsl89" <[EMAIL PROTECTED]> writes:
> hy gys i m wanting python programming language.
> plz snd me the backup of python

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


Re: Dictionary question

2006-07-18 Thread Brian Elmegaard
Brian Elmegaard <[EMAIL PROTECTED]> writes:

At least it was clumsy to post a wrong example.
This shows what = find clumsy.

c=1
x=2

l=list()
l.append(dict())
l[0][5]=0

l.append(dict())

for a, e in l[-2].iteritems():
# Can this be written better?
if a+c in l[-1]:
if l[-1][a+c] Hi 
>
> I have written the following which works, but I would like to write it
> less clumsy. I have a dictionary in which I loop through the keys for
> a dynamic programming algorithm. If a key is present I test if its
> value is better than the current, if it is not present I just create
> it. Would it be possible to write it more compact?
>
> ###3
> c=1
> s=8
> x=2
>
> l=list()
> l.append(dict())
> l[0][5]=0
>
> l.append(dict())
>
> for a, e in l[-2].iteritems():
> if a+c if a+c in l[-1]: #
> if l[-1][a+c] l[-1][a+c]=x+e #
> else: #
> l[-1][a+c]=x+e #
> print l
> #
>
> tia,
> -- 
> Brian (remove the sport for mail)
> http://www.et.web.mek.dtu.dk/Staff/be/be.html
> Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client.Dispatch - understanding error messages

2006-07-18 Thread mirandacascade
Duncan Booth wrote:
> wrote:
>
> Does using an absolute URL for the url parameter help any? You've specified
> a relative URL (i.e. the folder 12.5.81.49 under the current location).

I don't know the answer to that question.  I know that when I'm on the
same workstation and I copy/paste the string that is the url parameter
into my browser and press Enter, that a reply appears within the
browser, and that reply has content that suggests that the browser app
was able to 'talk' to an application on the other end.  The error
message being received in reply to the open method make me think that
the open method wasn't able to talk to any app on the other end.  I'm
not sure what can be inferred from that observation other than the url
parameter appears to be valid when it is used in a browser application.

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


Re: Coding style

2006-07-18 Thread Carl Banks

Bruno Desthuilliers wrote:
> Carl Banks wrote:
> > Patrick Maupin wrote:
> >
> >>PTY wrote:
> >>
> >>
> >>>It looks like there are two crowds, terse and verbose.  I thought terse
> >>>is perl style and verbose is python style.  BTW, lst = [] was not what
> >>>I was interested in :-)  I was asking whether it was better style to
> >>>use len() or not.
> >>
> >>It's not canonical Python to use len() in this case.  From PEP 8:
> >>
> >>- For sequences, (strings, lists, tuples), use the fact that empty
> >>  sequences are false.
> >>
> >>  Yes: if not seq:
> >>   if seq:
> >>
> >>  No: if len(seq)
> >>  if not len(seq)
> >>
> >>The whole reason that a sequence supports testing is exactly for this
> >>scenario.  This is not an afterthought -- it's a fundamental design
> >>decision of the language.
> >
> >
> > That might have made sense when Python and string, list, tuple were the
> > only sequence types around.
> >
> > Nowadays, Python has all kinds of spiffy types like numpy arrays,
> > interators, generators,
> > etc., for which "empty sequence is false" just
> > doesn't make sense.
>
> Iterators and generators are *not* sequences types. wrt/ non-builtin
> container types, I suggest you re-read section 3.3.1 of the language
> references:

I'm aware of the semantics, thank you, and that they're as advertised
in the docs.  It doesn't matter whether you call it a sequence or not.
Iterables, lists, arrays, and whatever else have overlapping uses, but
bool(obj) behaves differently for different types, making it unsuitable
for writing generic functions that might use some other types that
aren't vanilla list, tuple, and string.

All I'm saying is, knowing there's lots of roughly-list-like types that
don't consider "empty" to be  "false", and that there's not reasonable
way to get consistent behavior as to what the boolean value of such
types is, it's possible that these types wouldn't even have a boolean
value and any tests for emptiness would have to be explicit.

But who knows?  Maybe this is just one case where brevity trumps
everything else.


Carl BAnks

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


Re: range() is not the best way to check range?

2006-07-18 Thread John Machin
On 18/07/2006 7:22 PM, Paul Boddie wrote:
> John Machin wrote:
>> On 18/07/2006 12:41 PM, [EMAIL PROTECTED] wrote:
>>> it seems that range() can be really slow:
> 
> [...]
> 
>> Some things to try:
>> 1a. Read what the manual has to say about the range() function ... what
>> does it produce?
> 
> Indeed. Still, the addition of a __contains__ method to range (and
> xrange) would permit acceptable performance for the code given. Perhaps
> this is a convenience worth considering for future Python releases.
> 

range() and xrange() are functions. You are suggesting that 2 
*functions* should acquire a __contains__ method each? I trust not.

Perhaps you meant that the acquisitors should be the objects that those 
functions return.

range() returns a list. Lists already have a __contains__ method. It's 
been getting a fair old exercising in the last few hours, but here we go 
again:

 >python -mtimeit -s"x=range(3)" "x.__contains__(4)"
1000 loops, best of 3: 1.09 msec per loop

 >python -mtimeit -s"x=range(3)" "4 in x"
1000 loops, best of 3: 1.09 msec per loop

 >python -mtimeit -s"x=range(3)" "x.__contains__(1)"
100 loops, best of 3: 0.434 usec per loop

 >python -mtimeit -s"x=range(3)" "1 in x"
100 loops, best of 3: 0.137 usec per loop

A __contains__ method for xrange objects? The case of x in xrange(lo, 
hi) is met by lo <= x < hi. IMHO, anyone who wants x in xrange(lo, hi, 
step) should be encouraged to do the necessary algebra themselves; I 
wouldn't suggest that any core dev time be wasted on implementing such 
folderol.

In any case, isn't the *whole* xrange gizmoid on GvR's I-wish-I-hadn't list?

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


Re: Dictionary question

2006-07-18 Thread Nick Vatamaniuc
Brian,
You can try the  setdefault method of the dictionary.
For a dictionary D the setdefault work like this:
D.setdefault(k, defvalue). If k not in D then D[k] is set to defvalue
and defvalue is returned.
For example:
In [1]:  d={}
In [2]:  d.setdefault(1,5)
Out[2]:5
In [3]:  d
Out[3]:{1: 5}
In your case you could do something like:

if l[-1].setdefault(a+c, x+e) Brian Elmegaard <[EMAIL PROTECTED]> writes:
>
> At least it was clumsy to post a wrong example.
> This shows what = find clumsy.
>
> c=1
> x=2
>
> l=list()
> l.append(dict())
> l[0][5]=0
>
> l.append(dict())
>
> for a, e in l[-2].iteritems():
> # Can this be written better?
> if a+c in l[-1]:
> if l[-1][a+c] l[-1][a+c]=x+e
> else:
> l[-1][a+c]=x+e
> #
>
> print l
>
>
> > Hi
> >
> > I have written the following which works, but I would like to write it
> > less clumsy. I have a dictionary in which I loop through the keys for
> > a dynamic programming algorithm. If a key is present I test if its
> > value is better than the current, if it is not present I just create
> > it. Would it be possible to write it more compact?
> >
> > ###3
> > c=1
> > s=8
> > x=2
> >
> > l=list()
> > l.append(dict())
> > l[0][5]=0
> >
> > l.append(dict())
> >
> > for a, e in l[-2].iteritems():
> > if a+c > if a+c in l[-1]: #
> > if l[-1][a+c] > l[-1][a+c]=x+e #
> > else: #
> > l[-1][a+c]=x+e #
> > print l
> > #
> >
> > tia,
> > --
> > Brian (remove the sport for mail)
> > http://www.et.web.mek.dtu.dk/Staff/be/be.html
> > Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk
>
> --
> Brian (remove the sport for mail)
> http://www.et.web.mek.dtu.dk/Staff/be/be.html
> Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk

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


Re: win32com.client.Dispatch - understanding error messages

2006-07-18 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> Duncan Booth wrote:
>> wrote:
>>
>> Does using an absolute URL for the url parameter help any? You've
>> specified a relative URL (i.e. the folder 12.5.81.49 under the
>> current location). 
> 
> I don't know the answer to that question.  I know that when I'm on the
> same workstation and I copy/paste the string that is the url parameter
> into my browser and press Enter, that a reply appears within the
> browser, and that reply has content that suggests that the browser app
> was able to 'talk' to an application on the other end.  The error
> message being received in reply to the open method make me think that
> the open method wasn't able to talk to any app on the other end.  I'm
> not sure what can be inferred from that observation other than the url
> parameter appears to be valid when it is used in a browser
> application. 
> 
Are you really sure that the browser isn't making guesses about what you 
meant and correcting the error for you? Does what remains in the address 
bar when the page is retrieved really match *exactly* what you copied and 
pasted?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive function returning a list

2006-07-18 Thread Boris Borcic
> Do you have any ideas?

you could use a recursive generator, like

def genAllChildren(self) :
 for child in self.children :
 yield child
 for childchild in child.genAllChildren() :
 yield childchild
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary question

2006-07-18 Thread Justin Azoff
Brian Elmegaard wrote:
> for a, e in l[-2].iteritems():
> # Can this be written better?
> if a+c in l[-1]:
> if l[-1][a+c] l[-1][a+c]=x+e
> else:
> l[-1][a+c]=x+e
> #

I'd start with something like

for a, e in l[-2].iteritems():
keytotal  = a+c
valtotal  = x+e
last  = l[-1]
if keytotal in last:
if last[keytotal] < valtotal:
last[keytotal] = valtotal
else:
last[keytotal] = valtotal

Could probably simplify that even more by using min(), but I don't know
what kind of data you are expecting
last[keytotal] = min(last.get(keytotal), valtotal)
comes close to working - it would if you were doing max.


-- 
- Justin

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


Re: range() is not the best way to check range?

2006-07-18 Thread Paul Boddie
John Machin wrote:
>
> range() and xrange() are functions. You are suggesting that 2
> *functions* should acquire a __contains__ method each? I trust not.

Well, range is a function in the current implementation, although its
usage is similar to that one would get if it were a class, particularly
a subclass of list or one providing a list-style interface. With such a
class, you could provide a __contains__ method which could answer the
question of what the range contains based on the semantics guaranteed
by a range (in contrast to a normal list).

> Perhaps you meant that the acquisitors should be the objects that those
> functions return.

The whole point was to avoid expanding the range into a list.

[...]

> A __contains__ method for xrange objects? The case of x in xrange(lo,
> hi) is met by lo <= x < hi. IMHO, anyone who wants x in xrange(lo, hi,
> step) should be encouraged to do the necessary algebra themselves; I
> wouldn't suggest that any core dev time be wasted on implementing such
> folderol.

Sure, you could always implement your own class to behave like an
existing range and to implement the efficient semantics proposed above.

> In any case, isn't the *whole* xrange gizmoid on GvR's I-wish-I-hadn't list?

Yes, he wants range to return an iterator, just like xrange more or
less does now. Given that xrange objects support __getitem__, unlike a
lot of other iterators (and, of course, generators), adding
__contains__ wouldn't be much of a hardship. Certainly, compared to
other notational conveniences bounced around on the various development
lists, this one would probably provide an order of magnitude
improvement on the usual bang per buck development ratio.

Paul

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


Re: Capturing instant messages

2006-07-18 Thread Ed Leafe
On Jul 18, 2006, at 7:36 AM, Nick Vatamaniuc wrote:

> It depends on what IM protocol the company is using. If there is more
> than one, your job might end up being quite complicated. You indicated
> port 5190 in your post, does it mean that the company is using only  
> AOL
> IM?

Yes, they've told me that the users routinely use AIM to contact  
clients and each other. I don't believe that their firewalls permit  
other IM protocols.

> 1) As far as capturing the traffic, I would use a specific tool like
> tcpick ( a cousin of tcpdump but actually dumps the data to console  
> not
> just the headers and recreates the tcp streams -- good stuff!).  Again
> if you know the exact port number and the exact protocol this might be
> very easy because you will set up your capturing program to capture
> traffic from only 1 port.

Thanks; I'll have to play around with tcpick today.

> 2) The decoding will depend on your protocol, if you have more than  
> one
> IM protocol then the capture idea from above won't work too well, you
> will have to capture all the traffic then decode each stream, for each
> side, for each protocol.

I guess I'll have to start googling for AIM decoding information.

> 3) Recording or replay is easy. Save to files or dump to a MySQL table
> indexed by user id,  timestamp, IP etc. Because of buffering issues  
> you
> will probably not get a very accurate real-time monitoring system with
> this setup.

They aren't interested in real-time monitoring; their main concern  
is Sarb-ox compliance.

Thanks for your help!

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com



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


Re: Dictionary question

2006-07-18 Thread John Machin
On 18/07/2006 9:51 PM, Brian Elmegaard wrote:
> Brian Elmegaard <[EMAIL PROTECTED]> writes:
> 
> At least it was clumsy to post a wrong example.
> This shows what = find clumsy.
> 
> c=1
> x=2
> 
> l=list()
> l.append(dict())
> l[0][5]=0
> 
> l.append(dict())
> 
> for a, e in l[-2].iteritems():
> # Can this be written better?

Definitely.
1. Use meaningful names. Especially don't use 'L'.lower() as it's too 
easily confused with the digit '1'.
2. Put spaces around operators -- in general, RTFStyleGuide 
http://www.python.org/dev/peps/pep-0008
3. When you find yourself typing the same expression 4 times, it's time 
to give it a name of its own (or to throw away a usage or two).


> if a+c in l[-1]:
> if l[-1][a+c] l[-1][a+c]=x+e
> else:
> l[-1][a+c]=x+e

Here's a start. Only you know what *really* meaningful names you should 
be using.

mykey = a + c
newvalue = x + e
lastdict = dictlist[-1]
if mykey not in lastdict or lastdict[mykey] < newvalue:
 lastdict[mykey] = newvalue

4. Add some comments about what you are trying to achieve. What is the 
point of keeping the two dicts in a list??? Can't you give them names, 
like rawdatadict and maxdict?

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


Re: Python on RedHat AS 2.1?

2006-07-18 Thread Bill Scherer
Jeremy Winters wrote:

> All the stuff I've found personally are security patches for python 
> 1.5.2... which seems to be baked into the OS.
>
> I don't choose to use this OS... it is mandated by our IT dept.  I 
> have no complaints other than this...
>
> Is there nobody in pythonland who has installed python 2.2 or higher 
> on this OS?
>
> Anybody?

Sure. Python2.4 builds just fine on RHEL2.1:

# uname -r
2.4.9-e.65enterprise
# cat /etc/redhat-release
Red Hat Linux Advanced Server release 2.1AS (Pensacola)
# python2.4
Python 2.4.2 (#1, Nov  3 2005, 08:53:49)
[GCC 2.96 2731 (Red Hat Linux 7.2 2.96-129.7.2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>>


The system installed python1.5 is prefixed to /usr. By default, 
./configure for python will prefix to /usr/local. You should (assuming 
you have the proper development tools installed) be able to just 
./configure; make; make install (assuming you have the proper 
permissions). They can coexist just fine.

- Bill

>
> Jeremy
>
>
>
> From: Fredrik Lundh <[EMAIL PROTECTED]>
> To: python-list@python.org
> Date: Sat, 15 Jul 2006 10:20:21 +0200
> Subject: Re: Python on RedHat AS 2.1?
>
> Jeremy Winters wrote:
>
> > Installable package?
> >
> > Any ideas?
>
> is RedHat no longer providing pre-built packages for their
> distributions ?
>
>
>
>
> 
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great 
> rates starting at 1¢/min. 
> 

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


Re: wanting

2006-07-18 Thread Tim Chase
> "arsl89" <[EMAIL PROTECTED]> writes:
>> hy gys i m wanting python programming language.
>> plz snd me the backup of python
> 
> Me too. 

LOL.  U r0x0rz!  cheCk ot tHiz sekret w4rez s1te!!

http://www.python.org/download/

yul find ur "backup" of python hear.  iF ur 133t nuf, u can 
axcessorz all teh bakup at

svn co http://svn.python.org/projects/python/trunk python-svn

all ur bakupzors are belong 2 us

-tkc
[ouch...my head hurtzors now...]




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


Re: range() is not the best way to check range?

2006-07-18 Thread Stefan Behnel
Andy Dingley wrote:
> The purpose of range() in Python is as loop control,

No, the purpose of range() is to create a list, as the docs state.

http://docs.python.org/lib/built-in-funcs.html

"""
range(...) - This is a versatile function to create lists containing
arithmetic progressions.
"""

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


Re: Python linker

2006-07-18 Thread Sion Arrowsmith
 <[EMAIL PROTECTED]> wrote:
>I love python - I use it as a utility language to complement my C#
>programming every day. However, the reason I do not use it as my
>primary language is - surprise, surprise - not its lack of static type
>checking, but the size of standalone executes  (which embed the python
>runtime).

Er, what? How are you generating your standalone executables? What
size is "acceptable"? python24.dll is only 1.8M -- surely on any
non-embedded platform these days 1.8M isn't worth bothering about.
And since you mention wx (all of another 4.8M) I'd guess we're
talking about desktop applications. Who's going to notice if your
executable is a couple of M slimmer?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

mkdir

2006-07-18 Thread westymatt
I have been looking around for a while, but I haven't seen many
examples of os.mkdir()
Anybody have any experience with it, is a since deprecated function?

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


Re: mkdir

2006-07-18 Thread Simon Brunning
On 18 Jul 2006 05:45:48 -0700, westymatt <[EMAIL PROTECTED]> wrote:
> I have been looking around for a while, but I haven't seen many
> examples of os.mkdir()
> Anybody have any experience with it, is a since deprecated function?

Example here -  - but it really
couldn't be simpler. There's not much to demonstrate.

If it's deprecated, it's the first I've heard of it.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python linker

2006-07-18 Thread Irmen de Jong
[EMAIL PROTECTED] wrote:
> I love python - I use it as a utility language to complement my C#
> programming every day. However, the reason I do not use it as my
> primary language is - surprise, surprise - not its lack of static type
> checking, but the size of standalone executes  (which embed the python
> runtime).

Why not just install Python itself,
so that all of your python programs are only a few Kb each.
Because they all use the single shared installation.

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


Re: wanting

2006-07-18 Thread Bruno Desthuilliers
arsl89 wrote:
> hy gys i m wanting python programming language.
> plz snd me the backup of python
> 
Welcome to my bozo-list.

-- 
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: mkdir

2006-07-18 Thread westymatt
thanks a ton

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


Re: Dictionary question

2006-07-18 Thread Brian Elmegaard
John Machin <[EMAIL PROTECTED]> writes:

> 2. Put spaces around operators -- in general, RTFStyleGuide
>http://www.python.org/dev/peps/pep-0008

I din't know it. Thanks.

> Only you know what *really* meaningful names you should be using.

I have better names in my running code.

> mykey = a + c
> newvalue = x + e
> lastdict = dictlist[-1]
> if mykey not in lastdict or lastdict[mykey] < newvalue:
>  lastdict[mykey] = newvalue

Better, thanks.

> 4. Add some comments about what you are trying to achieve. What is the
>point of keeping the two dicts in a list??? Can't you give them
>names, like rawdatadict and maxdict?

It's a dynamic programming problem, so this will contain as many dicts
as hours in the year.

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary question

2006-07-18 Thread Brian Elmegaard
"Justin  Azoff" <[EMAIL PROTECTED]> writes:

> last[keytotal] = min(last.get(keytotal), valtotal)
> comes close to working - it would if you were doing max.

Thanks, I think this would help.

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary question

2006-07-18 Thread Brian Elmegaard
"Nick Vatamaniuc" <[EMAIL PROTECTED]> writes:

> if l[-1].setdefault(a+c, x+e) l[-1][a+c]=x+e

Thanks for the answer. I will try it.

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Has anyone used davlib by Greg Stein?

2006-07-18 Thread Joel Hedlund
Hi!

I want to PUT files to a authenticated https WebDAV server from within a python 
script. Therefore I put "python dav" into google, and the davlib module by Greg 
Stein (and Guido?) came up. It seems to be soild but has very little docs. Has 
anyone worked with this? Is it any good? Where can I find some good docs for 
it? 

Thanks for your time! 

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


Re: wanting

2006-07-18 Thread Steve Holden
Bruno Desthuilliers wrote:
> arsl89 wrote:
> 
>>hy gys i m wanting python programming language.
>>plz snd me the backup of python
>>
> 
> Welcome to my bozo-list.
> 
Note how the OP even abbreviates "arsehole" to "arsl" :-)

regards
  Steve

(to the original poster: sorry about all this humour at your expense. 
Just go to www.python.org, click on the "downloads" link, and download 
and run an appropriate installer. Probably the Windoze one).
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


array alice of [:-0] ??

2006-07-18 Thread guthrie
Beginner question! :-)

x=[1,2,3,4]
for i in range(len(x)):
print x[:-i]

 >>> []
 >>> [1,2,3]
 >>> [1,2]
 >>> [1]

1) The x[:-0] result seems inconsistent to me;
 I get the idea that -0=0, so it is taken as x[:0] -> []
2) how then should one do this basic left-recursive subsetting (easily).

Thanks.


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array alice of [:-0] ??

2006-07-18 Thread Boris Borcic
guthrie wrote:
> Beginner question! :-)
> 
> x=[1,2,3,4]
> for i in range(len(x)):
>print x[:-i]
> 
>  >>> []
>  >>> [1,2,3]
>  >>> [1,2]
>  >>> [1]
> 
> 1) The x[:-0] result seems inconsistent to me;
> I get the idea that -0=0, so it is taken as x[:0] -> []

that's what you get.

> 2) how then should one do this basic left-recursive subsetting (easily).

I am not sure what you mean, but replacing x[:-i] by x[:len(x)-i] you will get 
continuous behavior at i==0.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array alice of [:-0] ??

2006-07-18 Thread John Machin
On 18/07/2006 11:17 PM, guthrie wrote:
> Beginner question! :-)
> 
> x=[1,2,3,4]
> for i in range(len(x)):
>print x[:-i]
> 
>  >>> []
>  >>> [1,2,3]
>  >>> [1,2]
>  >>> [1]
> 
> 1) The x[:-0] result seems inconsistent to me;
> I get the idea that -0=0, so it is taken as x[:0] -> []
> 2) how then should one do this basic left-recursive subsetting (easily).
> 
>

|>> for i in range(len(x), -1, -1):
... print x[:i]
...
[1, 2, 3, 4]
[1, 2, 3]
[1, 2]
[1]
[]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array alice of [:-0] ??

2006-07-18 Thread Antoon Pardon
On 2006-07-18, guthrie <[EMAIL PROTECTED]> wrote:
> Beginner question! :-)
>
> x=[1,2,3,4]
> for i in range(len(x)):
> print x[:-i]
>
> >>> []
> >>> [1,2,3]
> >>> [1,2]
> >>> [1]
>
> 1) The x[:-0] result seems inconsistent to me;
>  I get the idea that -0=0, so it is taken as x[:0] -> []

That is correct. Negative indexes are a handy shorthand, but
they can give unexpected/strange results in a number of cases.

> 2) how then should one do this basic left-recursive subsetting (easily).

  x=[1,2,3,4]
  lng = len(x)
  for i in range(lng):
  print x[:lng-i]

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


Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
Carl Banks wrote:
> Bruno Desthuilliers wrote:
> 
>>Carl Banks wrote:
>>
>>>Patrick Maupin wrote:
>>>
>>>
PTY wrote:



>It looks like there are two crowds, terse and verbose.  I thought terse
>is perl style and verbose is python style.  BTW, lst = [] was not what
>I was interested in :-)  I was asking whether it was better style to
>use len() or not.

It's not canonical Python to use len() in this case.  From PEP 8:

- For sequences, (strings, lists, tuples), use the fact that empty
 sequences are false.

 Yes: if not seq:
  if seq:

 No: if len(seq)
 if not len(seq)

The whole reason that a sequence supports testing is exactly for this
scenario.  This is not an afterthought -- it's a fundamental design
decision of the language.
>>>
>>>
>>>That might have made sense when Python and string, list, tuple were the
>>>only sequence types around.
>>>
>>>Nowadays, Python has all kinds of spiffy types like numpy arrays,
>>>interators, generators,
>>>etc., for which "empty sequence is false" just
>>>doesn't make sense.
>>
>>Iterators and generators are *not* sequences types. wrt/ non-builtin
>>container types, I suggest you re-read section 3.3.1 of the language
>>references:
> 
> 
> I'm aware of the semantics, thank you, and that they're as advertised
> in the docs.  It doesn't matter whether you call it a sequence or not.

Your opinion - not mine. Sequences are iterable, but not all iterables
are sequences.

> Iterables, lists, arrays, and whatever else have overlapping uses, but
> bool(obj) behaves differently for different types,

bool(obj) will mainly look for __len__(), then for __nonzero__(), then
return True. You can only call len(obj) on objects implementing
__len__(), so relying on (implicit) 'bool(obj)' is clearly more generic
than 'len(obj) > 0'.  Also, since bool(obj) will try to call
obj.__len__(), explicitely calling len(obj) doesn't make any difference.

> making it unsuitable
> for writing generic functions that might use some other types that
> aren't vanilla list, tuple, and string.

Using an explicit test against the length of an iterator or generator
*won't* work anyway, since iterators and generators are unsized. And
that's one of the reasons why the difference between sequences and
iterables does matter.

And if you want your own sequence types to be well-behaved sequence
types, just take time to implement the needed protocol(s), including
__len__().

For short: either your function expects an iterable or it expects a
sequence. If it expects an iterable, treat it as an iterable wether it
happens to be a sequence or not. If it expects a sequence, it obviously
won't work with a non-sequence.

> All I'm saying is, knowing there's lots of roughly-list-like

"roughly-list-like" ?

> types that
> don't consider "empty" to be  "false",

This means they are unsized (ie don't implement __len__).

> and that there's not reasonable
> way to get consistent behavior as to what the boolean value of such
> types is, 

I don't know what "types" you are talkink about, but seems like either
they're not designed to be treated as sequences or they are badly
implemented. In the first case, you're not using them correctly. In the
second case, send a bug report to the authors.

> it's possible that these types wouldn't even have a boolean
> value and any tests for emptiness would have to be explicit.

Yes ? How ? Calling len() on them ?-)
(hint: reread how len() and bool() works wrt/ __len__())



-- 
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: Recursive function returning a list

2006-07-18 Thread Bruno Desthuilliers
Boris Borcic wrote:
>> Do you have any ideas?
> 
> 
> you could use a recursive generator, like
> 
> def genAllChildren(self) :
> for child in self.children :
> yield child
> for childchild in child.genAllChildren() :
> yield childchild


Or how to *not* address the real problem...

Boris, using a generator may be a pretty good idea, but *not* as a way
to solve a problem that happens to be a FAQ !-)

-- 
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: Python linker

2006-07-18 Thread tac-tics

[EMAIL PROTECTED] wrote:
> I love python - I use it as a utility language to complement my C#
> programming every day. However, the reason I do not use it as my
> primary language is - surprise, surprise - not its lack of static type
> checking, but the size of standalone executes  (which embed the python
> runtime).
>
> Would it be possible to link only the used functions into your
> resulting executable? After all, a typical application might only use
> 20% of everything that is in the Python .dlls.
>
> The same applies to wxPython - it would be great if you could only link
> in what you need. Would it be possible to write such linkers at all
> (maybe based on GCC)?

For your distribution, just move your DLLs to the appropriate system
folder. That's what DLLs do. You throw them in system32, forget they
were there in the first place, and the Linker Troll does the rest for
you.

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


Re: wanting

2006-07-18 Thread Bruno Desthuilliers
Steve Holden wrote:
> Bruno Desthuilliers wrote:
> 
>> arsl89 wrote:
>>
>>> hy gys i m wanting python programming language.
>>> plz snd me the backup of python
>>>
>>
>> Welcome to my bozo-list.
>>
> Note how the OP even abbreviates "arsehole" to "arsl" :-)
> 
> regards
>  Steve
> 
> (to the original poster: sorry about all this humour at your expense.
> Just go to www.python.org, click on the "downloads" link, and download
> and run an appropriate installer. Probably the Windoze one).

But before, take a few minutes to educate yourself and read this:
http://catb.org/esr/faqs/smart-questions.html

with particular attention to this section:
http://catb.org/esr/faqs/smart-questions.html#writewell


-- 
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: wanting

2006-07-18 Thread placid

Steve Holden wrote:
> Bruno Desthuilliers wrote:
> > arsl89 wrote:
> >
> >>hy gys i m wanting python programming language.
> >>plz snd me the backup of python

this is one of my aims in life, to bloody understand this 1337 speak!


--Cheers

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


Howto Determine mimetype without the file name extension?

2006-07-18 Thread Phoe6
Hi all,
 I had a filesystem crash and when I retrieved the data back
the files had random names without extension. I decided to write a
script to determine the file extension and create a newfile with
extension.
---
method 1:
# File extension utility.

import os
import mimetypes
import shutil

def main():

for root,dirs,files in os.walk(r'C:\Senthil\test'):
for each in files:
fname = os.path.join(root,each)
print fname
mtype,entype = mimetypes.guess_type(fname)
fext = mimetypes.guess_extension(mtype)
if fext is not None:
try:
newname = fname + fext
print newname
shutil.copyfile(fname,newname)
except (IOError,os.error), why:
print "Can't copy %s to %s: %s" %
(fname,newname,str(why))


if __name__ == "__main__":
main()


The problem I faced with this script is. if the filename did not have
any extension, the mimetypes.guess_type(filename) failed!!!
How do I get around this problem.

As it was a linux box, I tried using file command to get the work done.

Method 2:

import os
import shutil
import re

def detext(filename):
cin,cout,cerr = os.popen3('file ' + filename)
fileoutput = cout.read()
rtf = re.compile('Rich Text Format data')
#   doc = re.compile('Microsoft Office Document')
pdf = re.compile('PDF')

if rtf.search(fileoutput) is not None:
shutil.copyfile(filename,filename + '.rtf')
if doc.search(fileoutput) is not None:
shutil.copyfile(filename,filename + '.doc')

if pdf.search(fileoutput) is not None:
shutil.copyfile(filename,filename + '.pdf')

def main():
for root,dirs,files in os.walk(os.getcwd()):
for each in files:
fname = os.path.join(root,each)
detext(fname)

if __name__ == '__main__':
main()


but the problem with using file was it recognized both .xls (MS Excel)
and .doc ( MS Doc) as Microsoft Word Document only. I need to separate
the .xls and .doc files, I dont know if file will be helpful here.

--
If the first approach of mimetypes works, it would be great!
Has anyone faced this problem? How did you solve it?

thanks,
Senthil

http://phoe6.livejournal.com

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


ScientificPython - LeastSquareFit diverges

2006-07-18 Thread Harold Fellermann
Dear all,

I am trying to fit a powerlaw to a small dataset using
Scientific.Functions.LeastSquares fit.
Unfortunately, the algorithm seems to diverge and throws an
OverflowException.
Here is how I try it:
>>> from Scientific.Functions.LeastSquares import leastSquaresFit
>>>
>>> data = [
... (2.5, 589.0, 0.10001),
... (7.5, 442.0, 0.10001),
... (12.5, 96.0, 0.10001),
... (17.5, 36.0, 0.10001),
... (22.5, 16.0, 0.10001),
... (27.5, 7.0, 0.10001),
... (32.5, 6.0, 0.10001),
... (37.5, 3.0, 0.10001),
... (42.5, 3.0, 0.10001),
... (47.5, 1.0, 0.10001),
... (52.5, 3.0, 0.10001),
... (57.5, 1.0, 0.10001),
... (67.5, 1.0, 0.10001),
... (77.5, 2.0, 0.10001),
... (82.5, 1.0, 0.10001),
... (87.5, 2.0, 0.10001)
... ]
>>>
>>> def powerlaw((a,b),x) :
... return a*x**b
...
>>> params,chisq = leastSquaresFit(powerlaw,(10,-3),data)
Traceback (most recent call last):
  File "", line 1, in ?
  File
"/usr/lib/python2.4/site-packages/Scientific/Functions/LeastSquares.py",
line 72, in leastSquaresFit
next_chi_sq, next_alpha = _chiSquare(model, next_p, data)
  File
"/usr/lib/python2.4/site-packages/Scientific/Functions/LeastSquares.py",
line 22, in _chiSquare
f = model(parameters, point[0])
  File "", line 2, in powerlaw
  File
"/usr/lib/python2.4/site-packages/Scientific/Functions/FirstDerivatives.py",
line 182, in __rpow__
return pow(other, self)
  File
"/usr/lib/python2.4/site-packages/Scientific/Functions/FirstDerivatives.py",
line 171, in __pow__
raise OverflowError, "Numerical result of pow(%s,%s) out of range."
% (self.value,other.value-1)
OverflowError: Numerical result of pow(2.5,8376.79243687) out of range.
>>>


I added some debugging output in
/usr/lib/python-2.4/site-packages/Scientifc/Functions/LeastSquares.py
in the function _chiSquare that prints the fit parameters during the
Levenberg-Marquardt iteration.
The procedure seems do diverge after the first step:

((10, [1]), (-3, [0, 1]))
[(-67402.311817579117, [1]), (8377.7924368716158, [0, 1])]

Note that I could easily fit the above data using gnuplots internal
fitting procedure. Any idea what is going wrong here? Is it a known
problem? Are there any work arounds or other packages?

Any help is appreciated!

- harold -

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


Re: Accessors in Python (getters and setters)

2006-07-18 Thread Bruno Desthuilliers
mystilleef wrote:
> Bruno Desthuilliers wrote:
> 
>>mystilleef wrote:
>>
>>>Gerhard Fiedler wrote:
>>>
>>>
On 2006-07-15 06:55:14, mystilleef wrote:



>In very well designed systems, the state of an object should only be
>changed by the object.

IMO that's not quite true. Ultimately, the state always gets changed by
something else (user interaction, physical events); very few objects are
completely self-contained in their behavior.

>>>
>>>Then in those cases the system becomes a victim of high coupling.
>>
>>Time to burn your book and face reality. ObjA sends message Msg1 to
>>ObjB. Part of the associated behaviour is that in responce to Msg1, objB
>>changes it's own state. Practical result : ObjB's state has been changed
>>by ObjA. Practical question : how do you hope to avoid this "hi
>>coupling" (lol), apart from making all your objects totally autistic ?
>>
> 
> 
> Are you serious?

Deadly serious. But I'm afraid you're still missing the point.

> Well, you design an object that serves as a mediator.
> All objects can then only interact with themselves and the mediator
> only. Via signals, objects learn to automatically adjust their states
> and respond to events.

signal -> message -> method call -> change state.

Spell it how you like, add as many indirection levels you want, it still
boils down to the fact that *something* triggers the state change.

> This is just one of several methods you can
> dramatically reduce coupling.

It's just one of several methods that dramatically increases complexity,
without changing anything to the fact that in the end, *practically*,
some object ObjA changes its state as a response to a message sent by ObjB.

> I'm sure glad I didn't burn my book.

No comment.

> 
In most systems (and you possibly have written some of them) are objects
whose state gets changed by other objects -- possibly through the
intermediation of setter methods that do nothing else but set the state.
There's no conceptual difference between directly setting the state or
calling a setter function that does nothing else but directly setting the
state -- except for one unnecessary level of indirection in the latter.

>>>
>>>
>>>It depends. If certain conditions need to be met before changing the
>>>state of an object, then arbitrarily changing it can be dangerous.
>>
>>Does this imply a 'method call' *syntax* ?
> 
> 
> That's language dependent.
> 
> 
>>Given the existence of
>>"computed attributes" (ie: support for 'attribute access' *syntax* with
>>hidden accessors) and the possibility to redefine implementation (from
>>default attribute r/w access to computed/controlled) without touching
>>the interface, why advocate the *systematic* use of computed attributes
>>when it's just duplicating the default behaviour ?
>>
> 
> 
> I'm not advocating anything.

cf below on this.

> I'm just stating the use case for
> accessors and the wisdom behind them. My qualm with implicit accessors
> remains the name issue.

The "name issue" is *your* problem. And AFAICT, it's a "problem" because
you refuse to free your mind from a "what's in the book" mindset.

> 
>For example, a third party randomly changing is_active, (which Python
>lets you do freely and easily) from False to True may crash your GUI.
>And I'm not making this up. Things like this do really happen depending
>on the whackyness of your toolkit.

That's quite true, but a setter that does nothing but change is_active
doesn't prevent this. If there is logic necessary to prevent state changes
in certain situations, this should be implemented. But whether you then
call this a part of the "behavior" (looking at the implementation as being
a setter method) or a part of the "state" (looking at the implementation as
being an added feature of the attribute) doesn't really make an objective
difference.

>>>
>>>
>>>Of course using setters for the sake of just using them is pointless.
>>
>>Indeed.
>>
>>
>>>The reason to use them is if pre-conditions or post-conditions need to
>>>be met. Or to control access to an objects states.
>>
>>Then why advocate *systematic* use of them ?
>>
>>(snip)
> 
> I never advocated anything. 

You advocated
"""
1). Make all attributes of a class private/protected .
2). If a "non-callable" attribute is going to be used outside a class,
think about making it a property and name the property well, because
you never know...
"""

> 
>>>State - behavior is not something I made up, so it isn't subjective.
>>
>>The words (and the concept they describe) are not. Interpretation of
>>what is state and what is behaviour is subjective.
>>
>>
>>>It
>>>is a common term used in OO literature. In fact, the only reason I used
>>>it is because I thought is was common knowledge.
>>
>>It is.
>>
>>
>>>And behaviors are not
>>>just necessarily getters/setters, they are methods of objects.
>>
>>Behaviour is how a given object rea

Re: execute a shell script from a python script

2006-07-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Simon Forman <[EMAIL PROTECTED]> wrote:
>spec wrote:
>> Thanks, actually there are no args, is there something even simpler?
>>
>> Thanks
>> Frank
>
>you could try os.system()
>
>>From the docs:
>
>system(command)
.
[more detail]
.
.
I'm concerned the follow-ups in this thread have been too subtle.
Here is what you need to know:  use system().  A model such as

  import os
  os.system("my_script")

fulfills exactly the requirements the original poster described.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wanting

2006-07-18 Thread Patrick Bothe
placid wrote:
> this is one of my aims in life, to bloody understand this 1337 speak!
100k h3r3, 8|2o:
http://www.1337.net/

Regards,
 Patrick

Ps:
The translator might come in handy.

-- 
2 does not equal 3. Even for large values of 2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-18 Thread Carl Banks

Bruno Desthuilliers wrote:
> Carl Banks wrote:
> > Iterables, lists, arrays, and whatever else have overlapping uses, but
> > bool(obj) behaves differently for different types,
>
> bool(obj) will mainly look for __len__(), then for __nonzero__(), then
> return True. You can only call len(obj) on objects implementing
> __len__(), so relying on (implicit) 'bool(obj)' is clearly more generic
> than 'len(obj) > 0'.  Also, since bool(obj) will try to call
> obj.__len__(), explicitely calling len(obj) doesn't make any difference.

I'm well aware of Python's semantics, and it's irrelvant to my
argument.  What low level operations it does do not concern me.  I'm
concerned about what equats to "truth".  For generators and such, it's
"always".  For lists, it's "empty".  For numpy arrays, there is no
truth value.

For the purpose of writing generic functions, this is inconsistent.
And, IMO, it's possible that the language would have been designed
differently (by not letting them have any truth value) if they'd been
around in the beginning.


> And if you want your own sequence types to be well-behaved sequence
> types, just take time to implement the needed protocol(s), including
> __len__().

You know very well that not all iterables can know their length ahead
of time.


> For short: either your function expects an iterable or it expects a
> sequence. If it expects an iterable, treat it as an iterable wether it
> happens to be a sequence or not.

1. This is fine in a perfect world where all code clearly conforms to
expectation.  Problem is, a lot doesn't.  I think it's quite easy to
accidentally check something intended as an iterable for emptiness.
And, as I've explained in other posts, this can lead to subtle bugs.
Whereas if you check for emptiness using len, it throws an exception
right away, no bugs.  It's safer to use len.  (Safest of all is not to
check for emptiness at all.)

2. This logic doesn't work for numpy arrays.  In a lot of cases, a
function expecting a list works perfectly fine if you pass it a numpy
arrray.  But, if you were to write such a function with "if lst"
instead of "if len(lst)>0", it's guaranteed to fail.  The function is
more generic with the len test.


> > it's possible that these types wouldn't even have a boolean
> > value and any tests for emptiness would have to be explicit.
>
> Yes ? How ? Calling len() on them ?-)
> (hint: reread how len() and bool() works wrt/ __len__())

Yes.  If the language had been designed such that a list had no
nb_nonzero slot, you'd have to check for emptiness with len.  Perhaps
you're missing some of the nuances of English verb tenses (don't feel
too bad, it's hard).  I'm not arguing "what is", I'm arguing what
"could have been if circumstances were different".  If the language
were designed differently, then the rules would be different.


Carl Banks

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


Using Visual Slick Edit for Python

2006-07-18 Thread Brian Buderman
Anyone know if there is a way to make slickedit tag the built in modules 
such as os and sys so that code completion and the like work?
-- 
http://mail.python.org/mailman/listinfo/python-list


rounding of a decimal object

2006-07-18 Thread Yuan HOng

How can I round a decimal object to desired decimal position? It seems
you have to use some unintuitive expression like:

Decimal('7.325').quantize(Decimal('.01'))

why not simply use Decimal('7.325').round(2) or just round(Decimal('7.325'), 2)?

--
Hong Yuan

大管家网上建材超市
装修装潢建材一站式购物
http://www.homemaster.cn
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Accessors in Python (getters and setters)

2006-07-18 Thread Bruno Desthuilliers
mystilleef wrote:
> Bruno Desthuilliers wrote:
> 
>>mystilleef wrote:
>>Please don't top-post
>>
>>>On State and Behavior:
>>>
>>>To understand objects in terms of state and behavior you need to
>>>absolve yourself from implementation details of languages
>>>and think at an abstract level.
>>
>>
>>
>>>Take a button object, for example. It has state and behavior. Possible
>>>states may include, is_active, is_focused, is_mapped, etc. Behavior is
>>>what the button does when it responds to events, (e.g when you click on
>>>it, or drag it, or position a pointer over it.) If you've done any form
>>>of event based programming (GUI/Games/Simulation), this method of
>>>thinking becomes natural.
>>>
>>>As you can see, when I'm designing a button object, I don't care what
>>>Python does with is_active. I don't care how it accesses. I don't care
>>>what is_active means to Python. I don't care about Python's __get__
>>>/__set__ special/latent functions or implementation details. is_active
>>>to me and every other developer is a state of the button object. And at
>>>that level that's all that matters. Python can tell me it's just ones
>>>and zeros for all I care.
>>>
>>>In very well designed systems, the state of an object should only be
>>>changed by the object.
>>
>>... as a response to a message.
>>
>>
>>>For example, a third party randomly changing
>>>is_active, (which Python lets you do freely and easily)
>>
>>Unless you make it a read-only property.
>>
>  
> So you see the purpose of accessors then?

*where* did I say *anything* that could *possibly* be taken as me not
seeing the point of computed attributes ?

What I'm saying here is that it's totally useless to duplicate default
behaviour.

> 
>>>from False to
>>>True may crash your GUI.
>>
>>>And I'm not making this up. Things like this
>>>do really happen depending on the whackyness of your toolkit. So
>>>sometimes, it is my duty to protect the state of an object. Especially
>>>if its state cannot afford to be corrupted rendering the system
>>>unstable. And situations like this are found a plenty in event based
>>>programming. Which is programming objects based almost entirely on
>>>state and behavior. As you can see this has nothing to do with Python
>>>vs Java's vs X's implementation of accessors and how using them sucks,
>>>or how they aren't Pythonic. Some domains just require this stuff.
>>
>>Properties *are* 'accessors'.
>>
> 
> I never said they weren't.

Fine.

Now : in a language with support for computed attributes, direct
attribute access is the default r/w accessors.

> 
>>>One of the requirements for designing robust object systems is ensuring
>>>the state of objects aren't easily contaminated.
>>
>>"contaminated" ???
>> 
> Make an object's state unreliable. See above example.

That's the word you choose that I find really strange.

> 
>>>That "state" is the
>>>objects data (read: stuff the object needs to do something "reliably").
>>
>>Makes no sens to me.
>>
> 
> is_active is an object's data, 

class Obj(object):
  # 
  @apply
  def is_active():
def fget(self):
  return (self.something and self.computeThis()) \
  or self.otherCondition()
def fset(self, val):
  raise ReadOnlyError()
def fdel(self):
  raise UndeletableError()
return **locals()

According to *your* sayings, Obj.is_active is "behaviour"...

>>>And this is why many overzealous OO languages do "force" you to use
>>>accessors.

The only languages I know that "force" you to use accessors are
Smalltalk and Ruby (and Ruby offers some syntactic sugar for 'default' -
ie r/w - accessors).

> It's not because they hate you or aren't aware of the
>>>convenience of having direct access to an object's attributes. It's
>>>just because these languages convenience/robustness ratios are
>>>different.

I'm afraid it has very few to do with "robustness".

>>>Thinking in terms of callable vs non-callable is not helpful for me,
>>>because it isn't high level enough.
>>
>>Allo, Huston ?
>>
>>
>>>Thinking in terms of state and
>>>behavior is, because it works regardless of programming language or
>>>implementations. This is the reason I like working with Python. I
>>>wanted a language that didn't bore me with it semantics and allowed me
>>>to focus on design. Let me reiterate, I'm not obsessing over language
>>>semantics, I just need practical, not religious, solutions for my
>>>problem domain.
>>
>>Using properties instead of explicit getters/setters is pragmatism, not
>>religion. Using the default get/set mechanism when there's no specific
>>reason to do otherwise is pragmatism too. And understanding the object
>>model and idioms of the language you're using is IMHO the very pragmatic
>>thing to do...
>> 
> 
> Again, the object model of the language is irrelevant. 

Allo, Huston ?

> The only
> relevant model is my application's model, which should work regardless
> of the language I use.

What to say...



-- 
bruno desthuilliers
python -c "print '@'.join([

Re: embedding executable code in a regular expression in Python

2006-07-18 Thread Anthra Norell
Hi, see below ...

- Original Message -
From: "Paul McGuire" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: 
Sent: Monday, July 17, 2006 10:09 AM
Subject: Re: embedding executable code in a regular expression in Python


> Avi Kak wrote:
> > Folks,
> >
> > Does regular expression processing in Python allow for executable
> > code to be embedded inside a regular expression?
> >
> > For example, in Perl the following two statements
> >
> > $regex = qr/hello(?{print "saw hello\n"})mello(?{print "saw
> > mello\n"})/;
> > "jellohellomello"  =~  /$regex/;
> >
> > will produce the output
> >
> >   saw hello
> >   saw mello
> >
>
> Not nearly so terse, but perhaps easier to follow, here is a pyparsing
> version.  Pyparsing parse actions are intended to do just what you ask.
>  Parse actions may be defined to take no arguments, just one argument
> (which will be passed the list of matching token strings), 2 arguments
> (the match location and the matching tokens), or 3 arguments (the
> original source string, the match location, and the tokens).  Parse
> actions are very good for transforming input text into modified output
> form, such as the "background-color" to "backgroundColor" transform -
> the BoaConstructor team used pyparsing to implement a version upgrade
> that transformed user source to a new version of wx (involving a
> variety of suh changes).
>
> Here is your jello/mello program, with two variations of parse actions.
>
> -- Paul
>
> from pyparsing import *
>
> instr = "jellorelohellomellofellowbellowmello"
> searchTerm = oneOf( ["jello","mello"] )
>
> # simple parse action, just echoes matched text
> def echoMatchedText(tokens):
> print "saw", tokens[0]
>
> searchTerm.setParseAction( echoMatchedText )
> searchTerm.searchString(instr)
>
> # modified parse action, prints location too
> def echoMatchedText(loc,tokens):
> print "saw", tokens[0], "at locn", loc
>
> searchTerm.setParseAction( echoMatchedText )
> searchTerm.searchString(instr)
>
> Prints out:
> saw jello
> saw mello
> saw mello
> saw jello at locn 0
> saw mello at locn 14
> saw mello at locn 31
>
> --
> http://mail.python.org/mailman/listinfo/python-list

One fine example of a pyparse solution!

On my part I had a second thought on the SE solution I proposed. It was
needlessly complicated. Let me try again:

>>> sentence = 'On each occurrence of the word "square" in this text the
variable n will be squared. When it says "double" it will be doubled. At the
end print n % 11.'
>>> def square_n (): global n; n *= n
>>> def double_n (): global n; n += n
>>> def n_mod_11 (): global n; return n % 11
>>> se_definitions = """
...  "square=print 'Calling square_n () - ',; square_n (); print 'n is now
%d' % n \n"   # A piece of code for 'square'
 ... "double=print 'Calling double_n () - ',; double_n (); print 'n is now
%d' % n \n"   # Another piece of code for 'double'
 ... ".=\nprint 'n %% 11 is: %d' % n_mod_11 ()\n"   # Another piece of code
for the final dot
... """
>>> from SE import *
>>> Stream_Editor = SE (definitions)
>>> n = 9; exec (Stream_Editor (sentence))
Calling square_n () -  n is now 81
Calling square_n () -  n is now 6561
n % 11 is: 5
Calling double_n () -  n is now 13122
Calling double_n () -  n is now 26244
n % 11 is: 9
n % 11 is: 9

Suppose we now realize that the quoted words "square" and "double" should
not trigger the respective function and neither should the ending dot of
each sentence, except the last one. We fix the defintions in seconds, adding
the exceptions as deletions. The order is immaterial. Targets may be regular
expressions. (The last one is.)

se_definitions = """ # Deletes everything except the defined
substitutions
...  "square=print 'Calling square_n () - ',; square_n (); print 'n is now
%d' % n \n"   # A piece of code for 'square'
... "double=print 'Calling double_n () - ',; double_n (); print 'n is now
%d' % n \n"   # Another piece of code for 'double'
... ".=\nprint 'n %% 11 is: %d' % n_mod_11 ()\n"   # Another piece of code
for the final dot
... \""square"=" \""double"="  # Deletes the quoted words
... "~\.\s~="  # Deletes dots followed by white space.
... """
>>> n = 9; exec (SE (se_definitions)(sentence))
Calling square_n () -  n is now 81
Calling double_n () -  n is now 162
n % 11 is: 8

Note 1: SE is no match for pyparse on many accounts. Conversely SE has its
own strengths in the realm of its specialty, in particular ease and speed of
use, versatility and modularity.
  Most any problem can be solved in a variety of different ways. Finding
good approaches is one of the appeals of programming.

Note 2: The SE solution rests entirely on Python's 'exec' functionality and
so here we have another testimony to Python's excellence.

Note 3: I shall include the example in the manual. I hadn't thought of it.
My thanks to the OP for the inspiration. Perhaps he might want to explain
his purpose. I don't quite see the solution's problem.

Frederic


-- 
http://mail.python.org/mailman/li

Re: question about what lamda does

2006-07-18 Thread nephish
so a lamda needs to stay at one expression, and use more than one lamda
for more expressions ?

i think i get it.

sk

Nick Vatamaniuc wrote:
> Use it anywhere a quick definition of a function is needed that can be
> written as an expression. For example when a callback function is
> needed you could say:
> def callback(x,y):
>   return x*y
> some_function(when_done_call_this=callback)
> But with lambda you could just write
> some_function(when_done_call_this=lambda x,y:x*y)
> Note: because it is an _expression_ you cannot do stuff like 'if..else'
> inside of lambda.
>
> -Nick V.
>
> [EMAIL PROTECTED] wrote:
> > Hey there,
> > i have been learning python for the past few months, but i can seem to
> > get what exactly a lamda is for. What would i use a lamda for that i
> > could not or would not use a def for ? Is there a notable difference ?
> > I only ask because i see it in code samples on the internet and in
> > books.
> > 
> > thanks for any clarity
> > 
> > sk

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


Re: Howto Determine mimetype without the file name extension?

2006-07-18 Thread Justin Azoff
Phoe6 wrote:
> Hi all,
>  I had a filesystem crash and when I retrieved the data back
> the files had random names without extension. I decided to write a
> script to determine the file extension and create a newfile with
> extension.
[...]
> but the problem with using file was it recognized both .xls (MS Excel)
> and .doc ( MS Doc) as Microsoft Word Document only. I need to separate
> the .xls and .doc files, I dont know if file will be helpful here.

You may want to try the gnome.vfs module:

info = gnome.vfs.get_file_info(filename,
gnome.vfs.FILE_INFO_GET_MIME_TYPE)
info.mime_type #mime type

If all of your documents are .xls and .doc, you could also use one of
the cli tools that converts .doc to txt like catdoc.  These tools will
fail on an .xls document, so if you run it and check for output.  .doc
files would output a lot, .xls files would output an error or nothing.
The gnome.vfs module is probably your best bet though :-)

Additionally, I would re-organize your program a bit. something like:

import os
import re
import subprocess

types = (
('rtf', 'Rich Text Format data'),
('doc', 'Microsoft Office Document'),
('pdf', 'PDF'),
('txt', 'ASCII English text'),
)

def get_magic(filename):
pipe=subprocess.Popen(['file',filename],stdout=subprocess.PIPE)
output = pipe.stdout.read()
pipe.wait()
return output

def detext(filename):
fileoutput = get_magic(filename)
for ext, pattern in types:
if pattern in fileoutput:
return ext


def allfiles(path):
for root,dirs,files in os.walk(os.getcwd()):
for each in files:
fname = os.path.join(root,each)
yield fname

def fixnames(path):
for fname in allfiles(path):
extension = detext(fname)
print fname, extension #

def main():
path = os.getcwd()
fixnames(path)

if __name__ == '__main__':
main()

Short functions that just do one thing are always best.

To change that to use gnome.vfs, just change the types list to be a
dictionary like
types = {
 'application/msword': 'doc',
 'application/vnd.ms-powerpoint': 'ppt',
}

and then

def get_mime(filename):
info = gnome.vfs.get_file_info(filename,
gnome.vfs.FILE_INFO_GET_MIME_TYPE)
return info.mime_type

def detext(filename):
mime_type = get_mime(filename)
return types.get(mime_type)

-- 
- Justin

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


Re: Python linker

2006-07-18 Thread byteschreck
I develop shareware applications that need to be extremely slim (less
than 1 MB is preferable).

Delphi applications easily meet this requirement and I can expect end
users to download the .NET framework (if they don't already have it!).

However, I cannot expect users to download 3.5 MB.

For corporate clients, size does not matter the least, but for end
users, anything that is a couple of megs seems "bloated".

> For your distribution, just move your DLLs to the appropriate system
> folder. That's what DLLs do. You throw them in system32, forget they
> were there in the first place, and the Linker Troll does the rest for
> you.

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


Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
Carl Banks wrote:
> Bruno Desthuilliers wrote:
> 
>>Carl Banks wrote:
>>
>>>Iterables, lists, arrays, and whatever else have overlapping uses, but
>>>bool(obj) behaves differently for different types,
>>
>>bool(obj) will mainly look for __len__(), then for __nonzero__(), then
>>return True. You can only call len(obj) on objects implementing
>>__len__(), so relying on (implicit) 'bool(obj)' is clearly more generic
>>than 'len(obj) > 0'.  Also, since bool(obj) will try to call
>>obj.__len__(), explicitely calling len(obj) doesn't make any difference.
> 
> 
> I'm well aware of Python's semantics, and it's irrelvant to my
> argument.  What low level operations it does do not concern me.  I'm
> concerned about what equats to "truth".  For generators and such, it's
> "always". 

"generators and such" are not sequences.

> For lists, it's "empty".  For numpy arrays, there is no
> truth value.

Then treat numpy arrays as iterables (which they are), not as sequences.

> For the purpose of writing generic functions, this is inconsistent.

Not if you choose to design your function to work on iterables (which
means you don't use len() at all to test for emptiness).

> And, IMO, it's possible that the language would have been designed
> differently (by not letting them have any truth value) if they'd been
> around in the beginning.
> 
> 
> 
>>And if you want your own sequence types to be well-behaved sequence
>>types, just take time to implement the needed protocol(s), including
>>__len__().
> 
> 
> You know very well that not all iterables can know their length ahead
> of time.

Yes, but I was talking about *sequences*, not iterables.

> 
>>For short: either your function expects an iterable or it expects a
>>sequence. If it expects an iterable, treat it as an iterable wether it
>>happens to be a sequence or not.
> 
> 
> 1. This is fine in a perfect world where all code clearly conforms to
> expectation.  Problem is, a lot doesn't.  I think it's quite easy to
> accidentally check something intended as an iterable for emptiness.

Testing a random iterable for emptiness can not be done by testing it's
length.

> And, as I've explained in other posts, this can lead to subtle bugs.

If you clearly documents what your function expects (ie sequence or
iterable), then I don't see any subtleties involved...

> Whereas if you check for emptiness using len, it throws an exception
> right away, no bugs.  It's safer to use len.

It's safer to decide which protocol is expected, ie iterable or
sequence, and then write the code according to this expectation.

>  (Safest of all is not to
> check for emptiness at all.)

Unless you clearly expect a sequence and have to branch according to
it's state (ie empty/not empty).

> 2. This logic doesn't work for numpy arrays.  In a lot of cases, a
> function expecting a list works perfectly fine if you pass it a numpy
> arrray.  But, if you were to write such a function with "if lst"
> instead of "if len(lst)>0", it's guaranteed to fail.  The function is
> more generic with the len test.

If the function is to work with non-sequence types, write it so it can
work with non-sequence types.

>>>it's possible that these types wouldn't even have a boolean
>>>value and any tests for emptiness would have to be explicit.
>>
>>Yes ? How ? Calling len() on them ?-)
>>(hint: reread how len() and bool() works wrt/ __len__())
> 
> 
> Yes.  If the language had been designed such that a list had no
> nb_nonzero slot,

>>> [].__nonzero__
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'list' object has no attribute '__nonzero__'


> you'd have to check for emptiness with len.

bool(obj) *do* the test on __len__() if __nonzero__() is not implemented.

>  Perhaps
> you're missing some of the nuances of English verb tenses (don't feel
> too bad, it's hard).  I'm not arguing "what is", I'm arguing what
> "could have been if circumstances were different".  If the language
> were designed differently, then the rules would be different.

Totally true - and totally irrelevant IMHO.

-- 
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: range() is not the best way to check range?

2006-07-18 Thread Dan Bishop
Paul Boddie wrote:

> Yes, he wants range to return an iterator, just like xrange more or
> less does now. Given that xrange objects support __getitem__, unlike a
> lot of other iterators (and, of course, generators), adding
> __contains__ wouldn't be much of a hardship. Certainly, compared to
> other notational conveniences bounced around on the various development
> lists, this one would probably provide an order of magnitude
> improvement on the usual bang per buck development ratio.

xrange already has __contains__.  The problem is, it's implemented by a
highly-inefficient sequential search.  Why not modify it to merely
check the bounds and (value - start) % step == 0?

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 17)

2006-07-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Cameron Laird <[EMAIL PROTECTED]> wrote:
.
.
.
>John Machin illustrates the rudiments of embedding:
>   
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/3189b10b83a6d64a/
.
.
.
Oops; that should have been

  
http://groups.google.com/group/comp.lang.python/browse_thread/thread/a9fb3bed00a26678/

My apologies to those I've led astray.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python linker

2006-07-18 Thread Simon Brunning
On 18 Jul 2006 08:01:22 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> I develop shareware applications that need to be extremely slim (less
> than 1 MB is preferable).
>
> Delphi applications easily meet this requirement and I can expect end
> users to download the .NET framework (if they don't already have it!).

So, they'll download and install the .NET framework at 23 MB, but they
won't download and install Python at 9 and half?

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array slice of [:-0] ??

2006-07-18 Thread guthrie
Thanks all!!
-

guthrie wrote:

> Beginner question! :-)
> 
> x=[1,2,3,4]
> for i in range(len(x)):
>print x[:-i]
> 
>  >>> []
>  >>> [1,2,3]
>  >>> [1,2]
>  >>> [1]
> 
> 1) The x[:-0] result seems inconsistent to me;
> I get the idea that -0=0, so it is taken as x[:0] -> []
> 2) how then should one do this basic left-recursive subsetting (easily).
> 
> Thanks.
> 


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode html

2006-07-18 Thread Duncan Booth
Sybren Stuvel wrote:

> Duncan Booth enlightened us with:
>> Don't bother using named entities. If you encode your unicode as
>> ascii  replacing all non-ascii characters with the xml entity
>> reference then your pages will display fine whatever encoding is
>> specified in the HTTP headers.
> 
> Which means OP can't use Unicode/UTF-8 entity references, since that's
> not specified in the HTTP header.
> 
That doesn't matter, character references are not affected by the network 
encoding.

>From http://www.w3.org/TR/html4/charset.html#h-5.3.1

> 5.3.1 Numeric character references
> 
> Numeric character references specify the code position of a character
> in the document character set. 

The character references use the *document character set*, which is 
independant of the character encoding used for network transmission. This 
is defined for HTML as ISO10646, and (section 5.1) "The character set 
defined in [ISO10646] is character-by-character equivalent to Unicode 
([UNICODE])".
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >