COM makepy util finds multiple versions of my COM object

2007-02-02 Thread bg_ie
Hi,

I have a problem where an earlier version of my Com object is being
used by makepy for early binding. In makepy I see -

MyCom (1.0)
MyCom (1.0)
MyCom (2.0)

I created version 2 of my Com object hoping that this would solve the
problem but makepy is still using an earlier version. I can solve the
problem by editing the registry, but this problem now exists on a
number of computers...

Any ideas as to how I might solve this one?

I'm using build 210 of pythonwin.

Thanks for your help,

Barry.

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


Re: A* search implementation in Python

2007-02-02 Thread Peter Otten
Steven D'Aprano wrote:

> On Thu, 01 Feb 2007 18:21:57 -0800, bearophileHUGS wrote:
> 
>> Reid Priedhorsky:
>>> I'm looking for an open-source Python implementation of A* search for
>>> use in a mapping application.
>> 
>> You can try this one:
>> http://aima.cs.berkeley.edu/python/search.html
> 
> To paraphrase a wise saying:
> 
> If you give a man a link, you satisfy his need for one day.
> But if you teach a man to search, you satisfy his need forever.
> 
> Given that Reid had problems formulating a good search (because * is an
> operator in Google) what did you do?

What he might have done:

http://www.google.com/codesearch?hl=de&lr=&q=lang%3Apython+A%5B*%5D+search&btnG=Suche

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


Re: Python, readline and OS X

2007-02-02 Thread Mark Asbach
Hi James, hi Ron,

> Where have you installed libreadline? Is LD_LIBRARY_PATH pointing to the
> directory libreadline.dylib? Did you install libreadline with fink? If
> so, try
> 
>setenv LD_LIBRARY_PATH /sw/lib

That would probably make no difference since on Mac OS X that variable
is called DYLD_LIBRARY_PATH (contrary to SysV Unices).

> Bash (OSX default) and similar shells use this silly 2 part syntax:
> 
>LD_LIBRARY_PATH=/sw/lib
>export LD_LIBRARY_PATH

It's just your way of using it that makes it a 2 part syntax:

export DYLD_LIBRARY_PATH=/sw/lib

does the trick. And by the way: the bash construct is far less error
prone regarding quoting when used in shell scripts. 

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


Re: win32com.client

2007-02-02 Thread GHUM
rzed,

> 1) In your browser, enter this URL:http://sourceforge.net/projects/pywin32/
>
[...]
> Try those steps, then try importing win32com again.

man, you are SO 2005. Could'nt you please make a screen cap video,
upload it to youtube and give a pointer to it on your blog?
*wink*

Harald


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


Re: win32com.client

2007-02-02 Thread GHUM
btw... the statement with "youtube" was a joke.

I really applaud rzed you for giving this detailed descriptions,
people like him make the spirit of c.l.p.: People get help here WAY
over what commercial support usually gets you.

Thanks for doing that, rzed!

best wishes,

HArald

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


Re: Sorting a list

2007-02-02 Thread Duncan Booth
Steven Bethard <[EMAIL PROTECTED]> wrote:

> You don't need to use sorted() -- sort() also takes the key= and 
> reverse= arguments::
> 
>  >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'),
>  ...  ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'),
>  ...  ('1996', 'aaa')]
>  >>> from operator import itemgetter
>  >>> lines.sort(key=itemgetter(0), reverse=True)
>  >>> lines
>  [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'),
>  ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]

I suspect you want another line in there to give the OP what they actually 
want: sort the list alphabetically first and then reverse sort on the year.

The important thing to note is that the reverse flag on the sort method 
doesn't reverse elements which compare equal. This makes it possible to 
sort on multiple keys comparatively easily.

>>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'),
  ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'),
  ('1996', 'aaa')]
>>> from operator import itemgetter
>>> lines.sort(key=itemgetter(1))
>>> lines.sort(key=itemgetter(0), reverse=True)
>>> lines
[('1997', 'aaa'), ('1997', 'bbb'), ('1996', 'aaa'), ('1996', 'ccc'), 
('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: LDAP/LDIF Parsing

2007-02-02 Thread Cruelemort
On Feb 1, 11:08 pm, "aspineux" <[EMAIL PROTECTED]> wrote:
> The tree hierarchy is defined by the DN of each object, the types of
> the object is specified by its objectClass.
> Just collect all items (or do it dynamically by tunning the scope and
> the base of your search request)
>
> On 1 fév, 18:22, "Cruelemort" <[EMAIL PROTECTED]> wrote:
>
>
>
> > All,
>
> > I am hoping someone would be able to help me with a problem. I have an
> > LDAP server running on a linux box, this LDAP server contains a
> > telephone list in various groupings, the ldif file of which is -
>
> > dn: dc=example,dc=com
> > objectClass: top
> > objectClass: dcObject
> > objectClass: organization
> > dc: example
> > o: Example Organisation
>
> > dn: ou=groupa,dc=example,dc=com
> > ou: groupa
> > objectClass: top
> > objectClass: organizationalUnit
> > description: Group A
>
> > dn: cn=johnsmith,ou=groupa,dc=example,dc=com
> > cn: johnsmith
> > objectClass: top
> > objectClass: person
> > sn: Smith
> > telephoneNumber: 112
>
> > dn: cn=davesteel,ou=groupa,dc=example,dc=com
> > cn: davesteel
> > objectClass: top
> > objectClass: person
> > sn: Steel
> > telephoneNumber: 113
>
> > dn: ou=groupb,dc=example,dc=com
> > ou: groupb
> > objectClass: top
> > objectClass: organizationalUnit
> > description: Group B
>
> > dn: cn=williamdavis,ou=groupb,dc=example,dc=com
> > cn: williamdavis
> > objectClass: top
> > objectClass: person
> > sn: Davis
> > telephoneNumber: 122
>
> > dn: cn=jamesjarvis,ou=groupb,dc=example,dc=com
> > cn: jamesjarvis
> > objectClass: top
> > objectClass: person
> > sn: Jarvis
> > telephoneNumber: 123
>
> > I am creating a python client program that will display the telephone
> > list in the same directory structure as is on the LDAP server (i.e. it
> > starts with buttons of all the groups, when you click on a group it
> > comes up with buttons of all the numbers or groups available, and you
> > can continually drill down).
>
> > I was wondering the best way to do this? I have installed and used the
> > python-ldap libraries and these allow me to access and search the
> > server, but the searches always return a horrible nesting of lists,
> > tuples and dictionaries, below is an example of returning just one
> > record -
>
> > ('dc=example,dc=com', {'objectClass': ['top', 'dcObject',
> > 'organization'], 'dc': ['example'], 'o': ['Example Organisation']})
>
> > Basically i think i need to parse the search results to create objects
> > and build the python buttons around this, but i was hoping someone
> > would be able to point me in the correct direction of how to do this?
> > Is there a parser available? (there is an ldif library available but
> > it is not obvious how this works, i cannot see much documentation, and
> > it seems to be deprecated...).
>
> > Many thanks.
>
> > Ian- Hide quoted text -
>
> - Show quoted text -

Thanks for the replies all - it was a higher level wrapper like Bruno
mentioned that i was looking for (with objects and attributes based on
each objectClass), but the code posted above will work fine.

Many thanks all.

Ian

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


Re: asyncore DoS vulnerability

2007-02-02 Thread William Heymann
On Thursday 01 February 2007, billie wrote:

> Here's the traceback:
>
> Traceback (most recent call last):
>   File "C:\Documents and Settings\root\Desktop\test.py", line 31, in ?
> asyncore.loop(timeout=1)
>   File "C:\Python24\lib\asyncore.py", line 192, in loop
> poll_fun(timeout, map)
>   File "C:\Python24\lib\asyncore.py", line 122, in poll
> r, w, e = select.select(r, w, e, timeout)
> ValueError: too many file descriptors in select()
>

I just tried this on 64bit kubuntu edgy and this is what I got


1019
1020
Exception in thread Thread-1021:
Traceback (most recent call last):
  File "threading.py", line 442, in __bootstrap
  File "threading.py", line 422, in run
  File "client.py", line 5, in client
  File "socket.py", line 148, in __init__
error: (24, 'Too many open files')

1021
Exception in thread Thread-1022:
Traceback (most recent call last):
  File "threading.py", line 442, in __bootstrap
  File "threading.py", line 422, in run
  File "client.py", line 5, in client
  File "socket.py", line 148, in __init__
error: (24, 'Too many open files')

Exception in thread Thread-1020:
Traceback (most recent call last):
  File "threading.py", line 442, in __bootstrap
  File "threading.py", line 422, in run
  File "client.py", line 12, in client
error: (104, 'Connection reset by peer')

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


Re: Python design project

2007-02-02 Thread Michael
[EMAIL PROTECTED] wrote:
..
> I'm a Dutch student, and graduating this year on my graphic design
> study. For my graduating study, I want to do some Python work and i'm
> lokking for a partner wich can help/ cooperate me in programming
> python.
> 
> The project
> In short: The project subject is type, and i want to create a self
> generating type.

At the risk of asking a stupid question, what do you mean by a self
generating type? (Indeed, what do you mean by "type" here?) 

Given the phrases "python" and "graphic design" in the same post I can think
of at least two definitions of "type" that are relevant, and not sure how
you'd view either as self-generating :-)

Curiously,


Michael.

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


Inconsistent list/pointer problem

2007-02-02 Thread Eduardo \"EdCrypt\" O. Padoan
> def myFunc(listA):
> listB = listA
> work on & modify listB
> return(listB)

def my_func(listA):
   listB = listA[:]
   #work on & modify listB
   return listB

Attribution makes the name t the left 'point' to the result of the
expression at the right.
In your myFunc the expersion at the right is the name listA, at it
willl eval to the list that this  references. So you will end with to
references.
In my my_func, the expression at the right is a slicing of the list,
from begin to end (listA[:]). Slicing returns a new list, in this
example, with the same items of the original list. So you end with two
lists, as you wanted.


--
EduardoOPadoan (eopadoan->altavix::com)
Bookmarks: http://del.icio.us/edcrypt
Blog: http://edcrypt.blogspot.com
Jabber: edcrypt at jabber dot org
ICQ: 161480283
GTalk: eduardo dot padoan at gmail dot com
MSN: eopadoan at altavix dot com


-- 
EduardoOPadoan (eopadoan->altavix::com)
Bookmarks: http://del.icio.us/edcrypt
Blog: http://edcrypt.blogspot.com
Jabber: edcrypt at jabber dot org
ICQ: 161480283
GTalk: eduardo dot padoan at gmail dot com
MSN: eopadoan at altavix dot com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent list/pointer problem

2007-02-02 Thread Bruno Desthuilliers
Eduardo "EdCrypt" O. Padoan a écrit :
>> def myFunc(listA):
>> listB = listA
>> work on & modify listB
>> return(listB)
> 
> def my_func(listA):
>   listB = listA[:]
>   #work on & modify listB
>   return listB


Won't do for the OP's needs - he wants to modify the objects contained 
in listB without impacting the ones in listA (or at least that's what I 
understand).

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

Writing "pythonish" code

2007-02-02 Thread Mizipzor
Hi, this is my first mail to the list (and any list for that matter)
so any pointers on errors from my part would be appreciated. Im more
used to forums.

To start off, Ive read some python documents and done some small apps
so I think I can say I know it semi-well, and I know c++ very well.
But I want learn python even better, since I know that a company I aim
to be employed by make heavy use of python, knowing python myself
would give me an extra edge.

The problem isnt in pythons syntax, its in the architecture/design,
the concept of writing "pythonish code" if you like. One thing is that
in c++ im used to have private members in classes and no member is
altered except through the public functions of the class. In python
everything is, as far as I know, public. Im confused by this, should I
still have members in the python class that I simply dont edit
directly and let the class do its internal stuff? Or should I see the
python classes like c++ structs with functions?

I guess the ultimate is somewhere in between but I would like a nudge
or two to get there.

Now, the thing that bothers me the most. When I write python modules I
write one class per file, and the file and the class has a common
name. Maybe this is due to c++ habits. The problem is when I import
the module, make an instance of its class and store it in a variable:

foo.py
=

class foo:
def bar(self):
print "bar"

=

main.py
=

import foo

localFoo = foo.foo()
localFoo.bar()

=

To me, the main.py code above looks very ugly. So, assuming Im never
gonna have more than one instance of the foo class, can I write
something like this:

foo.py
=

def bar(self):
print "bar"

=

main.py
=

import foo

foo.bar()

=

Thats much more cleaner if you ask me, and kinda a good way to make
sure that you dont have more than one "instance" of the foo class
(which no longer is a class at all). But is it "pythonish"?

Gonna stop now, this mail got a little longer than i first thought.
Any input will be greatly appreciated. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


re: Inconsistent list/pointer problem

2007-02-02 Thread Eduardo \"EdCrypt\" O. Padoan
> Won't do for the OP's needs - he wants to modify the objects contained
> in listB without impacting the ones in listA (or at least that's what I
> understand).


Sorry. That is true - the items referenced on the [:] copy are the same as
in the original. Rereading what the OP msg, I think we agree.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: coping directories

2007-02-02 Thread Gigs_
Gabriel Genellina wrote:
> En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ <[EMAIL PROTECTED]> escribió:
> 
>> class CVisitor(FileVisitor):
>>  def __init__(self, fromdir, todir):
>>  self.fromdirLen = len(fromdir) + 1# here is my problem
>>  self.todir = todir
>>  FileVisitor.__init__(self, fromdir)
>>  def visitdir(self, dirpath):
>>  topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
>>  os.mkdir(topath)
>>  def visitfile(self, filepath):
>>  topath = os.path.join(self.todir, filepath[self.fromdirLen:])
>>  cpfile(filepath, topath)#copy contents from filepath to
>> topath[/code]
>>
>>
>> When I copy contents from C:\IronPython to C:\temp
>> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this
>> self.fromdirLen = len(fromdir) + 1
>> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen
>> = len(fromdir) i get contents copied to C:\ (actually to parent dir)
> 
> Instead of actually doing os.mkdir and cpfile, use a print statement to 
> output the involved variables, and try with and without +1. You'll see 
> yourself what happens.
> 
> --Gabriel Genellina
> 
but when I change
self.fromdirLen = len(fromdir) + 1 to self.fromdirLen = len(fromdir) i 
get contents copied to C:\ (actually to parent dir) instead to C:\temp
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing "pythonish" code

2007-02-02 Thread skyofdreams

"Mizipzor" <[EMAIL PROTECTED]> 
??:[EMAIL PROTECTED]
> Hi, this is my first mail to the list (and any list for that matter)
> so any pointers on errors from my part would be appreciated. Im more
> used to forums.
>
> To start off, Ive read some python documents and done some small apps
> so I think I can say I know it semi-well, and I know c++ very well.
> But I want learn python even better, since I know that a company I aim
> to be employed by make heavy use of python, knowing python myself
> would give me an extra edge.
>
> The problem isnt in pythons syntax, its in the architecture/design,
> the concept of writing "pythonish code" if you like. One thing is that
> in c++ im used to have private members in classes and no member is
> altered except through the public functions of the class. In python
> everything is, as far as I know, public. Im confused by this, should I
> still have members in the python class that I simply dont edit
> directly and let the class do its internal stuff? Or should I see the
> python classes like c++ structs with functions?
>
> I guess the ultimate is somewhere in between but I would like a nudge
> or two to get there.
>

as far as i know,  the class attributes haven't  privilege identifier.
I think If in C++ i need  friend relationship between 2 classes, then in 
python, i'll access the attribute directly.
in other cases, i treat  it as class,  suspose it's private attribute , just 
like classes in C++.


>
> To me, the main.py code above looks very ugly. So, assuming Im never
> gonna have more than one instance of the foo class, can I write
> something like this:
>
> foo.py
> =
>
> def bar(self):
>print "bar"
>
> =

main.py

from foo import foo
foo().bar()

try this, it's ok,  "from foo import foo"  the first  "foo" is module-name, 
the latter foo is class name.
the formal package import tutortial link is 
http://docs.python.org/tut/node8.html#SECTION00840

> Thats much more cleaner if you ask me, and kinda a good way to make
> sure that you dont have more than one "instance" of the foo class
> (which no longer is a class at all). But is it "pythonish"?
>
> Gonna stop now, this mail got a little longer than i first thought.
> Any input will be greatly appreciated. :)

HTH
-skyofdreams 


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


Interpreter window

2007-02-02 Thread Nils Overas Bergen
I have created a Python application in Windows XP which uses
WxWidgets. When I start the application from the Python interpreter I
get one empty interpreter window in addition to the application
window. Is there a way to close the interpreter window without closing
the application? Or, can I start the interpreter and the application
script without starting the interpreter window?

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


simple SOAP method doesn't work,

2007-02-02 Thread Grzegorz Smith
Hi All. I 'm learning ZSI to use SOAP and I desperately need help. I'm
working on example from tutorial -> (examples/server/send_response/
simple/wsdl/).
Here are my wsdl files -> http://pastebin.com/873488.
I made wsdl2py wsdl2py --complexType --file=binding.wsdl and get
Example_services.py and Example_Services_types.py.
Here is the Example_services.py -> http://pastebin.com/873492
and Example_Services_types.py -> http://pastebin.com/873494
Now I use cgi script for getting request/ sending response.
Script is runned by apache2.0.
It looks like this:
#!c:\opt\python24\python
from Example_services import EchoResponse
def echo(message):
response = EchoResponse()
response._Message = message
return response

from ZSI import dispatch
dispatch.AsCGI()

Now i write 2 scripts to test my Soap webservices. First is write just
like in guide.html
from Example_services import *
loc = ExampleServiceLocator()
port = loc.getExample()
req = EchoRequest()
req._Message='test'

resp =  port.echo(req)
print resp

and I get:
Traceback (most recent call last):
  File "test.py", line 9, in ?
resp =  port.echo(req)
  File "I:\Prace\PRYWATNE\test\Example_services.py", line 41, in echo
response = self.binding.Receive(typecode)
  File "I:\Prace\PRYWATNE\test\client.py", line 497, in Receive

  File "I:\Prace\PRYWATNE\test\client.py", line 397, in ReceiveSOAP

  File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI
\parse.py", line 59, in __init__
  File "c:\opt\python24\lib\site-packages\PyXML-0.8.4-py2.4-win32.egg
\_xmlplus\dom\ext\reader\__init__.py", line 60, in
fromString
return self.fromStream(stream, ownerDoc)
  File "c:\opt\python24\lib\site-packages\PyXML-0.8.4-py2.4-win32.egg
\_xmlplus\dom\ext\reader\PyExpat.py", line 65, in f
romStream
success = self.parser.ParseFile(stream)
xml.parsers.expat.ExpatError: unclosed token: line 12, column 152

Second looks like this:
import sys
from ZSI.client import Binding
b = Binding(url='http://127.0.0.1/cgi-bin/cgi.py',
tracefile=sys.stdout)
print b.echo('test')
and i get:
_ Fri Feb 02 13:05:06 2007 REQUEST:
http://schemas.xmlsoap.org/soap/
encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org
/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/";
xmlns:xsd="http://www.w3.org/2001/XMLSchema"; xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"; SOAP-
ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/";>test
_ Fri Feb 02 13:05:07 2007 RESPONSE:
200
OK
---
Date: Fri, 02 Feb 2007 12:05:06 GMT
Server: Apache/2.0.59 (Win32) DAV/2 PHP/5.1.6 mod_python/3.2.10 Python/
2.4.3 SVN/1.4.2
Content-Length: 453
Content-Type: text/xml; charset="utf-8"

http://schemas.xmlsoap.org/soap/
encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org
/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/";
xmlns:xsd="http://www.w3.org/2001/XMLSchema"; xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance";>test
Traceback (most recent call last):
  File "testSoap.py", line 12, in ?
zPalca()
  File "testSoap.py", line 7, in zPalca
print b.echo('test')
  File "I:\Prace\PRYWATNE\test\client.py", line 42, in __call__

  File "I:\Prace\PRYWATNE\test\client.py", line 171, in RPC

  File "I:\Prace\PRYWATNE\test\client.py", line 502, in Receive

  File "I:\Prace\PRYWATNE\test\client.py", line 436, in Receive

  File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI
\parse.py", line 323, in Parse
  File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI
\TC.py", line 573, in parse
  File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI
\TC.py", line 542, in parse_into_dict_or_list
  File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI
\TC.py", line 572, in parse
ZSI.EvaluateException: Any cannot parse untyped element
[Element trace: /SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:echoResponse/
Message]

Can anyone tell me what I'm doing wrong?
I read guide and think do everything in right way, but it's not
working
Thanks for any help I really ned this

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


How do I print out in the standard output coloured lines

2007-02-02 Thread cniharral
Hi,

  I'm interested in printing out coloured lines of my application and
I don't know what to use. Can anybody give me an idea??

Regards.

  Carlos Niharra López

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


compound statement from C "?:"

2007-02-02 Thread Holger
Hi

I have not been able to figure out how to do compound statement from C
- "?:"

But something similar must exist...?!

I would like to do the equivalent if python of the C line:
printf("I saw %d car%s\n", n, n != 1 ? "s" : "")

Please help

/Holger

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


Re: division by 7 efficiently ???

2007-02-02 Thread Bart Ogryczak
On Feb 1, 3:42 am, [EMAIL PROTECTED] wrote:
> How to divide a number by 7 efficiently without using - or / operator.
> We can use the bit operators. I was thinking about bit shift operator
> but I don't know the correct answer.

It´s quiet simple. x ==  8*(x/8) + x%8, so x == 7*(x/8) + (x/8 + x%8)
x/8 == x>>3, x%8 == x&7
And there you have it, function rounds upwards for numbers not
divisible by 7. Gotta change int(x>0) to int(x>3) to round normally,
or int(x>6) to round downwards.

def d7(x):
if(x>>3 == 0): return int(x>0)
return (x>>3)+d7((x>>3)+(x&7))

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


Re: Writing "pythonish" code

2007-02-02 Thread Ben Finney
Mizipzor <[EMAIL PROTECTED]> writes:

> The problem isnt in pythons syntax, its in the architecture/design,
> the concept of writing "pythonish code" if you like.

The nomenclature around here for that concept is "Pythonic".

> One thing is that in c++ im used to have private members in classes
> and no member is altered except through the public functions of the
> class. In python everything is, as far as I know, public.

Python has no strict prohibition on accessing any attribute of a
class. The convention is to name attributes with a leading underscore
if you don't think they should be accessed from outside the
class.

This allows users of your class (i.e. people writing code that uses
that class) to know what the public interface is -- i.e. all the
attributes that aren't named with a leading underscore -- without
preventing access to the other attributes if that makes for better
code. Since you can't ever know all the possible uses of a class when
you write it, this flexibility is a good thing.

> Im confused by this, should I still have members in the python class
> that I simply dont edit directly and let the class do its internal
> stuff?

Who is "I" in the above question? You should write your classes on the
assumption that you don't know who will be making use of them, and
consider your code to be a means of communication with the later users
(programmers) of your code.

> Or should I see the python classes like c++ structs with functions?

I don't see what benefit this would have; Python classes are classes.

> Now, the thing that bothers me the most. When I write python modules
> I write one class per file, and the file and the class has a common
> name.

To move toward more Pythonic code, you should treat a module as a
logically-coherent collection of functionality. It can contain any
number of classes or other objects. Divide your code into modules by
functionality, not dogmatically by one-class-per-module.

> foo.py
> =
>
> class foo:
> def bar(self):
> print "bar"
>
> =
>
> main.py
> =
>
> import foo
>
> localFoo = foo.foo()
> localFoo.bar()
>
> =
>
> To me, the main.py code above looks very ugly.

Can you articulate what looks ugly? Python makes strong use of
namespaces, so the above looks fine to me: it's clear where everything
is coming from. The only confusion comes from the fact that the module
"foo" and the class "foo" have the same name, which as discussed
doesn't need to be the case unless it actually makes sense.

> So, assuming Im never gonna have more than one instance of the foo
> class

This is a separate assumption, and doesn't necessarily follow from
what you've said above.

> can I write something like this:
>
> foo.py
> =
>
> def bar(self):
> print "bar"
>
> =
>
> main.py
> =
>
> import foo
>
> foo.bar()
>
> =
>
> Thats much more cleaner if you ask me, and kinda a good way to make
> sure that you dont have more than one "instance" of the foo class
> (which no longer is a class at all). But is it "pythonish"?

Very. This is Python's response to the "Singleton" pattern that some
other languages require: put attributes directly at a module level,
import that module wherever you need those attributes, and you're
guaranteed a single shared instance of the module. A good example is a
module containing a set of attributes defining the configuration for
the application.

-- 
 \   "I was sleeping the other night, alone, thanks to the |
  `\exterminator."  -- Emo Philips |
_o__)  |
Ben Finney

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


Re: Interpreter window

2007-02-02 Thread skyofdreams

"Nils Overas Bergen" <[EMAIL PROTECTED]> 
[EMAIL PROTECTED]
>I have created a Python application in Windows XP which uses
> WxWidgets. When I start the application from the Python interpreter I
> get one empty interpreter window in addition to the application
> window. Is there a way to close the interpreter window without closing
> the application? Or, can I start the interpreter and the application
> script without starting the interpreter window?
>

do you mean  console window?
you can try pythonw.exe instead of python.exe

-sods 


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


Re: Python does not play well with others

2007-02-02 Thread Paul Boddie
On 2 Feb, 03:46, Paul Rubin  wrote:
>
> I'd say the functionality that John wants is the same that pretty much
> everyone wants, and it's much easier to get for other languages than
> for Python.

If the hosting provider doesn't want to install MySQLdb then it may
not be a technical issue - perhaps they just can't be bothered to
install it, possibly because there's no demand or benefit to the
bottom line in doing so. That said, I think that a large part of the
community does no-one any favours by "fashionably" requiring the most
cutting edge software, insisting on Python 2.5 in some cases, in order
for their stuff to work. Then again, getting stuff to work across
several versions (and combinations of several versions of several
packages) is an issue of release engineering, and it's no coincidence
that companies have made good business out of this kind of thing.

Perhaps Python needs a "backports" project where newer software is
backported to older Python releases. Alternatively, given the
increasing prominence of virtual server hosting, people might be
advised to consider one of those hosting plans: the benefits of being
able to install almost anything, often with modern operating system
distributions whose packages are updated, surely outweigh the
administrative demands and price differences in at least some
situations.

Paul

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


Re: File system API

2007-02-02 Thread Eduardo \"EdCrypt\" O. Padoan
On 2/2/07, Tal Einat <[EMAIL PROTECTED]> wrote:
> > I think that there aready exists a proposal for an Abstract FS Layer
> > for Python somewere.
>
> I haven't been able to find any mention of it. Maybe you could point me in
> the right direction?
>
> - Tal
>
http://wiki.python.org/moin/CodingProjectIdeas/FileSystemVirtualization

Another related reference is the recently announced UniPath module:
http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html

-- 
EduardoOPadoan (eopadoan->altavix::com)
Bookmarks: http://del.icio.us/edcrypt
Blog: http://edcrypt.blogspot.com
Jabber: edcrypt at jabber dot org
ICQ: 161480283
GTalk: eduardo dot padoan at gmail dot com
MSN: eopadoan at altavix dot com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> Hi,
> 
>   I'm interested in printing out coloured lines of my
>   application and 
> I don't know what to use. Can anybody give me an idea??
> 

You could speed up the process if you explain what your application 
is and what you mean by colored lines. Does your application emit 
output to a plotter, an ink-jet printer, or a color laser printer? Is 
it a drawing program? An editor in which you want lines colored to 
highlight context? It might be useful to know what system you are 
running as well. Just a little detail here.

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


Re: Interpreter window

2007-02-02 Thread Nils Overas Bergen
On 2 Feb, 13:07, "skyofdreams" <[EMAIL PROTECTED]> wrote:
> "Nils Overas Bergen" <[EMAIL PROTECTED]>
> [EMAIL PROTECTED]
>
> >I have created a Python application in Windows XP which uses
> > WxWidgets. When I start the application from the Python interpreter I
> > get one empty interpreter window in addition to the application
> > window. Is there a way to close the interpreter window without closing
> > the application? Or, can I start the interpreter and the application
> > script without starting the interpreter window?
>
> do you mean  console window?
> you can try pythonw.exe instead of python.exe
>
> -sods

Thanks! Now my application starts without the console window.

Nils

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


Re: Writing "pythonish" code

2007-02-02 Thread James Stroud
Mizipzor wrote:
> Hi, this is my first mail to the list (and any list for that matter)
> so any pointers on errors from my part would be appreciated. Im more
> used to forums.
> 
> To start off, Ive read some python documents and done some small apps
> so I think I can say I know it semi-well, and I know c++ very well.
> But I want learn python even better, since I know that a company I aim
> to be employed by make heavy use of python, knowing python myself
> would give me an extra edge.
> 
> The problem isnt in pythons syntax, its in the architecture/design,
> the concept of writing "pythonish code" if you like. One thing is that
> in c++ im used to have private members in classes and no member is
> altered except through the public functions of the class. In python
> everything is, as far as I know, public. Im confused by this, should I
> still have members in the python class that I simply dont edit
> directly and let the class do its internal stuff? Or should I see the
> python classes like c++ structs with functions?
> 
> I guess the ultimate is somewhere in between but I would like a nudge
> or two to get there.
> 
> Now, the thing that bothers me the most. When I write python modules I
> write one class per file, and the file and the class has a common
> name. Maybe this is due to c++ habits. The problem is when I import
> the module, make an instance of its class and store it in a variable:
> 
> foo.py
> =
> 
> class foo:
>def bar(self):
>print "bar"
> 
> =
> 
> main.py
> =
> 
> import foo
> 
> localFoo = foo.foo()
> localFoo.bar()
> 
> =
> 
> To me, the main.py code above looks very ugly. So, assuming Im never
> gonna have more than one instance of the foo class, can I write
> something like this:
> 
> foo.py
> =
> 
> def bar(self):
>print "bar"
> 
> =
> 
> main.py
> =
> 
> import foo
> 
> foo.bar()
> 
> =
> 
> Thats much more cleaner if you ask me, and kinda a good way to make
> sure that you dont have more than one "instance" of the foo class
> (which no longer is a class at all). But is it "pythonish"?
> 
> Gonna stop now, this mail got a little longer than i first thought.
> Any input will be greatly appreciated. :)

The "import foo ... foo.bar()" way is preferred. Your instincts are correct.

If you want to write pythonic style, here are some references in roughly 
the order I would read them after the tutorial--this is not a ranking 
but more ordered for study:

1. google and read the "python style guide"
2. "How to Think like a Computer Scientist" (google it)
3. Read this email list and take notes--these people know
4. David Mertz's "Text Processing in Python" -- a classic (google it)
5. John Grayson's "Python and Tkinter Programming" (Manning)
6. "Programming Python" by Mark Lutz (O'Reilly)

I'm sure the cookbook (Ed. Alex Martelli) should be in there, but I 
haven't read it extensively so I don't know where it fits. Probably #7.

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


Re: Python does not play well with others

2007-02-02 Thread Paul Boddie
On 2 Feb, 04:56, Ben Finney <[EMAIL PROTECTED]>
wrote:
>
> A bug report should be sent to the bug tracker for the software
> against which you're reporting a bug. Only at that point does it
> become something on which you can comment about attitude toward bug
> reports, because before that point the bug report doesn't exist in a
> useful form.

I think it's also worth considering various social factors when filing
bug reports. Whilst a report sent directly to the developers of a
particular module might ultimately be the way to get bugs fixed
"permanently", it is also worth investigating whether there are any
other parties affected by those bugs, whether bugs have been filed in
other places (eg. in a Linux distribution's bug tracker), and whether
there are communities who have an interest in fixing the bugs in a
more timely fashion.

I see this kind of thing every now and again with projects like KDE.
Often, in a distribution, the version of KDE won't be the absolute
latest from kde.org, and the level of interest amongst the original
developers to fix bugs in older releases is somewhat restrained.
Consequently, I would look to distributions to fix problems with their
KDE packages, especially since many of them appear to perform surgery
on KDE, often making the resulting software almost unmaintainable by
the original developers. Of course, if the bugs are genuine things
which are present "upstream" (ie. in the original software) then I'd
expect that any fixes ultimately make their way back to the original
developers, although various projects (including KDE) seem
uninterested even in merging ready-made fixes to older releases unless
it involves a major security flaw.

Paul

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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread cniharral
On Feb 2, 1:16 pm, rzed <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote innews:[EMAIL PROTECTED]:
>
> > Hi,
>
> >   I'm interested in printing out coloured lines of my
> >   application and
> > I don't know what to use. Can anybody give me an idea??
>
> You could speed up the process if you explain what your application
> is and what you mean by colored lines. Does your application emit
> output to a plotter, an ink-jet printer, or a color laser printer? Is
> it a drawing program? An editor in which you want lines colored to
> highlight context? It might be useful to know what system you are
> running as well. Just a little detail here.
>
> --
> rzed

Well, yes, it's a program that prints out lines to the standard output
with a print command, and I want to print them coloured. For example:

print "Hello World!!"

I want it in red colour.

That's all.

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


re: compound statement from C "?:"

2007-02-02 Thread Eduardo \"EdCrypt\" O. Padoan
http://effbot.org/pyfaq/is-there-an-equivalent-of-c-s-ternary-operator.htm

-- 
EduardoOPadoan (eopadoan->altavix::com)
Bookmarks: http://del.icio.us/edcrypt
Blog: http://edcrypt.blogspot.com
Jabber: edcrypt at jabber dot org
ICQ: 161480283
GTalk: eduardo dot padoan at gmail dot com
MSN: eopadoan at altavix dot com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> On Feb 2, 1:16 pm, rzed <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote
>> innews:[EMAIL PROTECTED]: 
>>
>> > Hi,
>>
>> >   I'm interested in printing out coloured lines of my
>> >   application and
>> > I don't know what to use. Can anybody give me an idea??
>>
>> You could speed up the process if you explain what your
>> application is and what you mean by colored lines. Does your
>> application emit output to a plotter, an ink-jet printer, or a
>> color laser printer? Is it a drawing program? An editor in
>> which you want lines colored to highlight context? It might be
>> useful to know what system you are running as well. Just a
>> little detail here. 
>>
>> --
>> rzed
> 
> Well, yes, it's a program that prints out lines to the standard
> output with a print command, and I want to print them coloured.
> For example: 
> 
> print "Hello World!!"
> 
> I want it in red colour.
> 
> That's all.
> 
> 

If you're on Linux, you could use the curses module. There may be 
a precompiled Windows version compatible with your Python version, 
or maybe not, but the Windows source is available, and you may be 
able to get it to work with your Python with some effort. Linux 
distros include curses, I think. For Windows curses, take a look 
at . You will understand why 
the phrase "Windows curses" is used, I expect. 

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


Why does this not work?

2007-02-02 Thread alain
I tried the following:

myobj=object()
myobj.newattr=5

results in:


Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'object' object has no attribute 'newattr'

Any idea?


Alain

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


Re: LDAP/LDIF Parsing

2007-02-02 Thread Hallvard B Furuseth
Bruno Desthuilliers writes:
> class LdapObject(object):
>(...)
>def __getattr__(self, name):
>  try:
>data = self._record[name]
>  except KeyError:
>raise AttributeError(
>  "object %s has no attribute %s" % (self, name)
> )

Note that LDAP attribute descriptions may be invalid Python
attribute names.  E.g.
{...
 'title;lang-en': ['The Boss']
 'title;lang-no': ['Sjefen']}
So you'd have to call getattr() explicitly to get at all the attributes
this way.

>  else:
># all LDAP attribs are multivalued by default,
># even when the schema says they are monovalued
>if len(data) == 1:
>   return data[0]
>else:
>   return data[:]

IMHO, this just complicates the client code since the client needs to
inserts checks of isinstance(return value, list) all over the place.
Better to have a separate method which extracts just the first value of
an attribute, if you want that.

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


Re: Why does this not work?

2007-02-02 Thread Bart Van Loon
It was 2 Feb 2007 04:41:48 -0800, when alain wrote:
> I tried the following:
>
> myobj=object()
> myobj.newattr=5
>
> results in:
>
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: 'object' object has no attribute 'newattr'
>
> Any idea?

I think it's because... object has no attribute 'newattr'

what else is there left to say?

try:

myobj=object()
print dir(myobj)

does that contain 'myattr'?

-- 
groetjes,
BBBart

   "To make a bad day worse, spend it wishing for the impossible." -Calvin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does this not work?

2007-02-02 Thread alain
On Feb 2, 1:57 pm, Bart Van Loon <[EMAIL PROTECTED]> wrote:
> It was 2 Feb 2007 04:41:48 -0800, when alain wrote:
>
> > I tried the following:
>
> > myobj=object()
> > myobj.newattr=5
>
> > results in:
>
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > AttributeError: 'object' object has no attribute 'newattr'
>
> > Any idea?
>
> I think it's because... object has no attribute 'newattr'
>
> what else is there left to say?
>
> try:
>
> myobj=object()
> print dir(myobj)
>
> does that contain 'myattr'?
>
> --
> groetjes,
> BBBart
>
>"To make a bad day worse, spend it wishing for the impossible." -Calvin


What about this:
class Object(object):pass
myobj=Object()
myobj.newattr=5

and it works !!!
Python allows the dynamic creation of attributes for an instance of an
object.

Alain


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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread cniharral
On Feb 2, 1:38 pm, rzed <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote innews:[EMAIL PROTECTED]:
>
>
>
> > On Feb 2, 1:16 pm, rzed <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] wrote
> >> innews:[EMAIL PROTECTED]:
>
> >> > Hi,
>
> >> >   I'm interested in printing out coloured lines of my
> >> >   application and
> >> > I don't know what to use. Can anybody give me an idea??
>
> >> You could speed up the process if you explain what your
> >> application is and what you mean by colored lines. Does your
> >> application emit output to a plotter, an ink-jet printer, or a
> >> color laser printer? Is it a drawing program? An editor in
> >> which you want lines colored to highlight context? It might be
> >> useful to know what system you are running as well. Just a
> >> little detail here.
>
> >> --
> >> rzed
>
> > Well, yes, it's a program that prints out lines to the standard
> > output with a print command, and I want to print them coloured.
> > For example:
>
> > print "Hello World!!"
>
> > I want it in red colour.
>
> > That's all.
>
> If you're on Linux, you could use the curses module. There may be
> a precompiled Windows version compatible with your Python version,
> or maybe not, but the Windows source is available, and you may be
> able to get it to work with your Python with some effort. Linux
> distros include curses, I think. For Windows curses, take a look
> at . You will understand why
> the phrase "Windows curses" is used, I expect.
>
> --
> rzed

Yes, I'm on a Linux box. I've tried with the curses module, but I
don't how I could fetch the current use of curses of my shell. I don't
know if I'm talking about something impossible. I've made some tests
with the curses module and works fine, but I need to capture the
current window and change the attributes of texts.

Carlos Niharra López

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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread Bart Van Loon
It was 2 Feb 2007 04:27:06 -0800, when [EMAIL PROTECTED] wrote:

> print "Hello World!!"
>
> I want it in red colour.
>
> That's all.

Use colour escape codes:

print "\033[1;31mHello World\033[0m"

That's all. :-)

-- 
groetjes,
BBBart

   Golly, I'd hate to have a kid like me!
  -- Calvin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing "pythonish" code

2007-02-02 Thread Toby A Inkster
Mizipzor wrote:

> One thing is that in c++ im used to have private members in classes and
> no member is altered except through the public functions of the class.

By convention, class members starting with a single underscore are
considered private. 

This is much the same as the convention that on UNIX, files that start with
a dot are considered hidden -- there is nothing actually *preventing* a
programme from showing you these files in a directory listing, but by
convention it won't, unless you explicitly ask to see them.

Class members starting with a double underscore are "mangled" which makes
it more difficult for other code (even subclasses!) to access the member.
Difficult though -- not impossible.

-- 
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: LDAP/LDIF Parsing

2007-02-02 Thread Bruno Desthuilliers
Hallvard B Furuseth a écrit :
> Bruno Desthuilliers writes:
>> class LdapObject(object):
>>(...)
>>def __getattr__(self, name):
>>  try:
>>data = self._record[name]
>>  except KeyError:
>>raise AttributeError(
>>  "object %s has no attribute %s" % (self, name)
>> )
> 
> Note that LDAP attribute descriptions may be invalid Python
> attribute names.  E.g.
> {...
>  'title;lang-en': ['The Boss']
>  'title;lang-no': ['Sjefen']}
> So you'd have to call getattr() explicitly to get at all the attributes
> this way.

Yeps, true. Another solution would be to add a __getitem__ method 
pointing to the same implementation, ie:

 __getitem__ = __getattr__

>>  else:
>># all LDAP attribs are multivalued by default,
>># even when the schema says they are monovalued
>>if len(data) == 1:
>>   return data[0]
>>else:
>>   return data[:]
> 
> IMHO, this just complicates the client code since the client needs to
> inserts checks of isinstance(return value, list) all over the place.
> Better to have a separate method which extracts just the first value of
> an attribute, if you want that.

Most of the times, in a situation such as the one described by the OP, 
one knows by advance if a given LDAP attribute will be used as 
monovalued or multivalued. Well, this is at least my own experience...

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


Re: mysqldb duplicate entry error handling

2007-02-02 Thread baur79
thanks John
this solves my problem
 except MySQLdb.IntegrityError, message:

thanks everybody again

Baurzhan Zhakashev
Kazakhstan / Shymkent city

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


Re: asyncore DoS vulnerability

2007-02-02 Thread aspineux
Did you take a look for "too many file descriptors in select()" on
google.

On 1 fév, 20:18, "billie" <[EMAIL PROTECTED]> wrote:
> Hi all. I've just terminated a server application using asyncore /
> asynchat frameworks.
> I wrote a test script that performs a lot of connections to the server
> app and I discovered that asyncore (or better, select()) can manage
> only a limited number of file descriptors (aka simultaneous
> connections).

I thing this is the system that limit the number of open sockets or
select() list

> When this number is reached select() raises an error but asyncore
> doesn't handle this exception (a crash occurs).

This is not a CRASH, It looks an exception with a "Traceback", this is
the normal way python report problems, nothing wrong with that.
You can handle it with a try: except:

> If you want to try this I pasted two scripts below: a server and a
> client.
> On my Windows XP system server.py the crash occurs when 512
> simultaneous connections are reached.

512 is probably a fixed limit into XP, win2k3 or win2k server will
accept more.
Maybe It's possible to increase this value somewhere in the registry.
If not this is how microsoft justify the difference between server and
workstation products :-)

> Here's the traceback:
>
> Traceback (most recent call last):
>   File "C:\Documents and Settings\root\Desktop\test.py", line 31, in ?
> asyncore.loop(timeout=1)
>   File "C:\Python24\lib\asyncore.py", line 192, in loop
> poll_fun(timeout, map)
>   File "C:\Python24\lib\asyncore.py", line 122, in poll
> r, w, e = select.select(r, w, e, timeout)
> ValueError: too many file descriptors in select()
>
> Why does this exception isn't handled inside asyncore.py?

To do what ? To raise a custom asyncore error ?
You can can probably run over this limit by starting multiple of your
server process (not thread, process) .

>
> 
> # server.py
> import asyncore, socket
>
> class server(asyncore.dispatcher):
> """The base class for the backend."""
>
> def __init__(self):
> asyncore.dispatcher.__init__(self)
> self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
> self.bind(('', 8080))
> self.listen(5)
>
> def handle_accept(self):
> sock_obj, addr = self.accept()
> handler(sock_obj)
>
> class handler(asyncore.dispatcher):
>
> def __init__(self, sock_obj):
> asyncore.dispatcher.__init__(self, sock=sock_obj)
>
> def handle_write(self):
> pass
>
> def handle_read(self):
> pass
>
> server()
> asyncore.loop(timeout=1)
>
> -
>
> # client.py
> import socket, threading, os
>
> def client():
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> try:
> s.connect(("127.0.0.1", 8080))
> except:
> print x
> os._exit(0)
> while 1:
> s.recv(1024)
>
> x = 0
> while 1:
> x +=1
> threading.Thread(target=client).start()
> print x


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


Re: coping directories

2007-02-02 Thread Gigs_
Gabriel Genellina wrote:
> En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ <[EMAIL PROTECTED]> escribió:
> 
>> class CVisitor(FileVisitor):
>>  def __init__(self, fromdir, todir):
>>  self.fromdirLen = len(fromdir) + 1# here is my problem
>>  self.todir = todir
>>  FileVisitor.__init__(self, fromdir)
>>  def visitdir(self, dirpath):
>>  topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
>>  os.mkdir(topath)
>>  def visitfile(self, filepath):
>>  topath = os.path.join(self.todir, filepath[self.fromdirLen:])
>>  cpfile(filepath, topath)#copy contents from filepath to
>> topath[/code]
>>
>>
>> When I copy contents from C:\IronPython to C:\temp
>> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this
>> self.fromdirLen = len(fromdir) + 1
>> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen
>> = len(fromdir) i get contents copied to C:\ (actually to parent dir)
> 
> Instead of actually doing os.mkdir and cpfile, use a print statement to 
> output the involved variables, and try with and without +1. You'll see 
> yourself what happens.
> 
> --Gabriel Genellina
> 
well I have tried with print but can't figure out
I got this when I have removed + 1
 >>> C = CpallVisitor('C:\\New', 'c:\\temp')
 >>> C.run(startdir='C:\\New')
c:\temp\
filepath: C:\New\AUTOEXEC.BAT Topath: \AUTOEXEC.BAT
filepath: C:\New\boot.ini Topath: \boot.ini
filepath: C:\New\CONFIG.SYS Topath: \CONFIG.SYS

but needs to be this
 >>> C = CpallVisitor('C:\\New', 'c:\\temp')
 >>> C.run(startdir='C:\\New')
c:\temp\
filepath: C:\New\AUTOEXEC.BAT Topath: c:\temp\AUTOEXEC.BAT
filepath: C:\New\boot.ini Topath: c:\temp\boot.ini
filepath: C:\New\CONFIG.SYS Topath: c:\temp\CONFIG.SYS


In python shell I got same thing, no matter fromdirLen is
len(fromdir) + 1 or len(fromdir)

 >>> fromdir = 'C:\\New'
 >>> fromdirLen = len(fromdir)
 >>> todir = 'C:\\temp'
 >>> topath = os.path.join(todir, fromdir[fromdirLen:])
 >>> topath
'C:\\temp\\'
 >>> fromdirLen = len(fromdir)+1
 >>> topath = os.path.join(todir, fromdir[fromdirLen:])
 >>> topath
'C:\\temp\\'
 >>> fromdir[fromdirLen:]
''
 >>> fromdirLen = len(fromdir)
 >>> fromdir[fromdirLen:]
''
 >>> fromdir
'C:\\New'


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


About PyCamp - a Regional Python Unconference

2007-02-02 Thread Jeff Rush
A week or so ago, the Dallas and Houston Python User Groups met online in a
chat room, to discuss the possibility of a regional Python conference.  There
was interest on all sides.  Some of the Dallas members had recently attended
their second BarCamp (http://barcamp.org), defined as an ad-hoc gathering born
from the desire for people to share and learn in an open environment.

 From this interaction as well as the realization, after the Dallas group
hosted PyCon in 2006 and will again in 2007, that a conference is a *lot* of
work, we decided to try the idea of running an "unconference".

An unconference (http://en.wikipedia.org/wiki/Unconference) is a conference
where the content of the sessions is driven and created by the participants,
generally day-by-day during the course of the event, rather than by a single
organizer, or small group of organizers, in advance.

And tossing around some names, we decided upon "PyCamp".  There is much to be
discussed re dates, location and how it will operate, so I set up the website:

   http://pycamp.python.org/

and a Mailman instance for mailing lists at:

   http://pycamp.python.org/lists/

The rough idea is to hold a Texas-wide unconference, perhaps sometimes in
August and near Austin.  There was also the idea of holding a rotating
unconference that moves between Dallas, Austin and Houston, say twice a year.
  To minimize the impact on participant (not attendee - this is an
unconference after all where you are expected to get involved) schedules, it
was suggested we hold it over a weekend.  We'd meet for dinner/drinks on a
Friday evening, hold our talks at some hotel on Saturday and early Sunday, and
then travel home Sunday evening.

You'll notice that I keep saying "maybe", "suggested" and other weasel words
above.  This is because I'm not the conference chair (thankfully) and we're
not imposing the schedule/rules.  Ralph Green of Dallas has volunteered to
wrangle the project and website, and is one of those who has attended a
BarCamp.  We need the creative energy and participation by members of all
Python User Groups in Texas and invite you to join the Texas PyCamp mailing
list (see above URL).

Oh, and we didn't want to be the only ones having fun, so the PyCamp URL, wiki
and mailing lists are available to other states or regions than Texas.
Hopefully we can start a movement toward regional PyCamp Unconferences
everywhere.  If you're unfortunate enough to not live in Texas, drop me an
email and I'll set you up your own regional section of the PyCamp site.

Jump in and let's talk.  And with PyCon rapidly approaching, we'd like to meet
face-to-face with kindred spirits there.  I'll make sure it gets on the
conference schedule.

Jeff Rush
Python Advocacy Coordinator
Dallas-Ft. Worth Pythoneers Coordinator
PyCon 2007 Co-Chair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does this not work?

2007-02-02 Thread Laurent Pointal
alain a écrit :
> On Feb 2, 1:57 pm, Bart Van Loon <[EMAIL PROTECTED]> wrote:
>> It was 2 Feb 2007 04:41:48 -0800, when alain wrote:
>>
>>> I tried the following:
>>> myobj=object()
>>> myobj.newattr=5
>>> results in:
>>> Traceback (most recent call last):
>>>   File "", line 1, in ?
>>> AttributeError: 'object' object has no attribute 'newattr'
>>> Any idea?
>> I think it's because... object has no attribute 'newattr'
>>
>> what else is there left to say?
>>
>> try:
>>
>> myobj=object()
>> print dir(myobj)
>>
>> does that contain 'myattr'?
>>
>> --
>> groetjes,
>> BBBart
>>
>>"To make a bad day worse, spend it wishing for the impossible." -Calvin
> 
> 
> What about this:
> class Object(object):pass
> myobj=Object()
> myobj.newattr=5
> 
> and it works !!!
> Python allows the dynamic creation of attributes for an instance of an
> object.


See previous discussion in this group "Re: Why don't have an object()
instance a __dict__ attribute by default?" (2007-01-30)

http://groups.google.fr/group/comp.lang.python/browse_thread/thread/a7e952d01b2eea68/961dec95bc20877e?lnk=st&q=&rnum=1#961dec95bc20877e

A+

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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread cniharral
On Feb 2, 2:08 pm, Bart Van Loon <[EMAIL PROTECTED]> wrote:
> It was 2 Feb 2007 04:27:06 -0800, when [EMAIL PROTECTED] wrote:
>
> > print "Hello World!!"
>
> > I want it in red colour.
>
> > That's all.
>
> Use colour escape codes:
>
> print "\033[1;31mHello World\033[0m"
>
> That's all. :-)
>
> --
> groetjes,
> BBBart
>
>Golly, I'd hate to have a kid like me!
>   -- Calvin


Well, this is fine. It's what I was looking for. I have done something
similar with a system command execution (echo) but it was not really
smart, but this fit my needs.

Thanks a lot.

Regards.

Carlos Niharra López

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


newbie/ merging lists of lists with items in common

2007-02-02 Thread ardief
Hi everyone
Here is my problem:
I have a list that looks like this -
[['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
'4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]

and I would like to end up with something like this, i.e. with the
only one list per letter:

[['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
['e', ['11', '5', '16', '7']]]

I have the feeling it's trivial, and I've scoured the group archives -
sets might be a possibility, but I'm not sure how to operate on a list
of lists with sets.

This function also gives me what I want, more or less, but I don't
know how to make it run until it's covered all the possibilities, if
that makes sense...

def sigh(list):
for a in list:
i = list.index(a)
if a != list[-1]:##if a is not the last one, i.e. there is a
next one
n = alist[i+1]
if a[0] == n[0]:
a.append(n[1:])
del alist[i+1]

Sorry about the lengthy message and thanks for your suggestions - I'm
trying to learn...

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


Re: LDAP/LDIF Parsing

2007-02-02 Thread Michael Ströder
Cruelemort wrote:
> I was wondering the best way to do this? I have installed and used the
> python-ldap libraries and these allow me to access and search the
> server, but the searches always return a horrible nesting of lists,
> tuples and dictionaries, below is an example of returning just one
> record -
> 
> ('dc=example,dc=com', {'objectClass': ['top', 'dcObject',
> 'organization'], 'dc': ['example'], 'o': ['Example Organisation']})

It's just modeled after the X.500 data model. A DN and the entry. The
entry consists of attributes which consists of attribute type and a set
of attribute values.

You could write your own wrapper class around ldap.ldapobject.LDAPObject
and overrule method search_s().

> (there is an ldif library available but
> it is not obvious how this works, i cannot see much documentation, and
> it seems to be deprecated...).

Module ldif is not deprecated. It's actively maintained by me like the
rest of python-ldap. It parses LDIF and returns the same data structure
as above. You don't need it for LDAP access anyway. Only for reading
LDIF files.

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: division by 7 efficiently ???

2007-02-02 Thread Neil Cerutti
On 2007-02-01, Michael Yanowitz <[EMAIL PROTECTED]> wrote:
>   I think it is off by 1 in small numbers, off by a little more with large
> numbers:
 def div7 (N):
> ...return (N>>3) + ((N-7*(N>>3))>>3)
> ...
 div7 (70)
> 9
 div7 (77)
> 10
 div7 (700)
> 98
 div7 (7)
> 0
 div7 (10)
> 1
 div7 (14)
> 1
 div7 (21)
> 2
 div7 (700)
> 98
 div7 (7000)
> 984
>

Heh, heh. That's reminding of the "fabulous" O(n) Dropsort
algorithm I saw linked from Effbot's blog.

-- 
Neil Cerutti
I'm tired of hearing about money, money, money, money, money. I just want to
play the game, drink Pepsi, wear Reebok. --Shaquille O'Neal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread Neil Cerutti
On 2007-02-02, rzed <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote in
> news:[EMAIL PROTECTED]: 
>
>> On Feb 2, 1:16 pm, rzed <[EMAIL PROTECTED]> wrote:
>>> [EMAIL PROTECTED] wrote
>>> innews:[EMAIL PROTECTED]: 
>>>
>>> > Hi,
>>>
>>> >   I'm interested in printing out coloured lines of my
>>> >   application and
>>> > I don't know what to use. Can anybody give me an idea??
>>>
>>> You could speed up the process if you explain what your
>>> application is and what you mean by colored lines. Does your
>>> application emit output to a plotter, an ink-jet printer, or a
>>> color laser printer? Is it a drawing program? An editor in
>>> which you want lines colored to highlight context? It might be
>>> useful to know what system you are running as well. Just a
>>> little detail here. 
>>>
>>> --
>>> rzed
>> 
>> Well, yes, it's a program that prints out lines to the standard
>> output with a print command, and I want to print them coloured.
>> For example: 
>> 
>> print "Hello World!!"
>> 
>> I want it in red colour.
>> 
>> That's all.
>
> If you're on Linux, you could use the curses module. There may
> be a precompiled Windows version compatible with your Python
> version, or maybe not, but the Windows source is available, and
> you may be able to get it to work with your Python with some
> effort. Linux distros include curses, I think. For Windows
> curses, take a look at .
> You will understand why the phrase "Windows curses" is used, I
> expect. 

On Windows, there's pdcurses for DOS or ncurses for the Cygwin
platform, but I don't know how to get either to work with Python.

Far simpler to get working in Windows is Fredrik Lundh's Console.

  http://www.effbot.org/downloads/#console

If you're using Windowd 98 or earlier there are versions of a
Python readline library that provide cursor addressing and color
using the ANSI excape sequences.

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


Re: need help on a data structure problem

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Ben Finney <[EMAIL PROTECTED]> wrote:
> "Dongsheng Ruan" <[EMAIL PROTECTED]> writes:
>
>> Not quite related with Python. But my Data Structure course is
>> experiemented on python and there is no data structure group, So I
>> have to post here:
>
> Better, you should discuss it in your class, with your teacher.

Also: comp.algorithms is the usual Usenet place for discussion of
algorithms and data structures.

However most of the talk there is pretty high-falutin'.

-- 
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading the tilde operator?

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Ben Finney <[EMAIL PROTECTED]> wrote:
> James Stroud <[EMAIL PROTECTED]> writes:
>> Ben Finney wrote:
>> > The Python runtime parser is designed to parse Python, not
>> > some arbitrary language that someone chooses to implement in
>> > Python.
>>
>> You haven't addressed why the limitation isn't arbitrary.
>
> Good thing I wasn't trying to do that, then. I was pointing out
> the source of the limitation.
>
> The Python syntax parser must follow the rules of the Python
> language. If you accept that premise, it follows that the '~'
> operator is unary only. If you *don't* accept that premise, I
> have no help to offer.

There's been only one (or two?) languages in history that
attempted to provide programmers with the ability to implement
new infix operators, including defining precedence level and
associativity (I can't think of the name right now).

C++, for example, works the same way as Python here. You can
override most of the operators, but you cannot change their
arity, associativity, or precedence level.

-- 
Neil Cerutti
Let us join David and Lisa in the celebration of their wedding and bring their
happiness to a conclusion. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Miki
Hello,
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> and I would like to end up with something like this, i.e. with the
> only one list per letter:
>
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]
I'd use a dictionary to store value for a given key:
>>> def aggregate(lst):
items = {} # key -> values
for key, value in lst:
values = items.get(key)
if values:
if type(values) == list:
values.append(value)
else:
items[key] = [values, value]
else:
items[key] = value
return [list(pair) for pair in items.items()]

>>> aggregate(lst)
[['a', ['13', '3']], ['c', ['12', '15', '4']], ['b', '6'], ['e',
['11', '5', '16', '7']], ['d', '2']]
>>>

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread Miki
Hello Carlos,

>   I'm interested in printing out coloured lines of my application and
> I don't know what to use. Can anybody give me an idea??
I use the following script:
#!/usr/bin/env python
'''Print message using ANSI terminal codes'''

__author__ = "Miki Tebeka <[EMAIL PROTECTED]>"
# $Id: ansiprint 1229 2005-05-16 05:50:22Z mikit $

# =
# Copyright (c) Miki Tebeka <[EMAIL PROTECTED]>
# This file is under the GNU Public License (GPL), see
# http://www.gnu.org/copyleft/gpl.html for more details
# =

from sys import stdout, stderr

# Format
bright = 1
dim = 2
underline = 4
blink = 5
reverse = 7
hidden = 8

# Forground
black = 30
red = 31
green = 32
yellow = 33
blue = 34
magenta = 35
cyan = 36
white = 37

# Background
on_black = 40
on_red = 41
on_green = 42
on_yellow = 43
on_blue = 44
on_magenta = 45
on_cyan = 46
on_white = 47

def ansiformat(msg, *args):
'''Format msg according to args.

See http://www.termsys.demon.co.uk/vtansi.htm for more details/
'''
return "\033[%sm%s\033[0m" % (";".join(["%s" % f for f in args]),
msg)

def ansiprint(msg, *args, **kw):
'''Print formatted message.

Should work on ANSI compatible terminal.
'''

if kw.get("stderr", 0):
outfo = stderr
else:
outfo = stdout

outfo.write(ansiformat(msg, *args))
outfo.flush()

if __name__ == "__main__":
from sys import argv, exit
from os.path import basename

h = {
"bright" : bright,
"dim" : dim,
"underline" : underline,
"blink" : blink,
"reverse" : reverse,
"hidden" : hidden,
"black" : black,
"red" : red,
"green" : green,
"yellow" : yellow,
"blue" : blue,
"magenta" : magenta,
"cyan" : cyan,
"white" : white,
"on_black" : on_black,
"on_red" : on_red,
"on_green" : on_green,
"on_yellow" : on_yellow,
"on_blue" : on_blue,
"on_magenta" : on_magenta,
"on_cyan" : on_cyan,
"on_white" : on_white
}

eg = "e.g. ansiprint hello red on_green underline -> %s" % \
ansiformat("hello", red, on_green, underline)

# Check command line
if len(argv) < 2:
print >> stderr, "usage: %s message [format ...]" %
basename(argv[0])
print >> stderr, eg
exit(1)
for i in argv[2:]:
if i not in h:
ansiprint("%s: Unknown format\n" % i, red, bright,
stderr=True)
print >> stderr, "Formats can be:",
msg = ", ".join([ansiformat(f, h[f]) for f in h.keys()])
print msg
print >> stderr, eg
exit(1)

# Print
ansiprint(argv[1], *[h[i] for i in argv[2:]])
print

# vim: ft=python

Hope you find it useful.
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Larry Bates
ardief wrote:
> Hi everyone
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
> 
> and I would like to end up with something like this, i.e. with the
> only one list per letter:
> 
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]
> 
> I have the feeling it's trivial, and I've scoured the group archives -
> sets might be a possibility, but I'm not sure how to operate on a list
> of lists with sets.
> 
> This function also gives me what I want, more or less, but I don't
> know how to make it run until it's covered all the possibilities, if
> that makes sense...
> 
> def sigh(list):
>   for a in list:
>   i = list.index(a)
>   if a != list[-1]:##if a is not the last one, i.e. there is a
> next one
>   n = alist[i+1]
>   if a[0] == n[0]:
>   a.append(n[1:])
>   del alist[i+1]
> 
> Sorry about the lengthy message and thanks for your suggestions - I'm
> trying to learn...
> 
One solution:

l=[['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c','4'],
['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
d={}
for k, v in l:
if d.has_key(k): d[k].append(v)
else: d[k]=[v]
print "d=", d

l=[x for x in d.items()]
print l


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


Re: LDAP/LDIF Parsing

2007-02-02 Thread Hallvard B Furuseth
Bruno Desthuilliers writes:
>Hallvard B Furuseth a écrit :
>>>  else:
>>># all LDAP attribs are multivalued by default,
>>># even when the schema says they are monovalued
>>>if len(data) == 1:
>>>   return data[0]
>>>else:
>>>   return data[:]
>> IMHO, this just complicates the client code since the client needs to
>> inserts checks of isinstance(return value, list) all over the place.
>> Better to have a separate method which extracts just the first value of
>> an attribute, if you want that.
>
> Most of the times, in a situation such as the one described by the OP,
> one knows by advance if a given LDAP attribute will be used as
> monovalued or multivalued. Well, this is at least my own experience...

But if the attribute is multivalued, you don't know if it will contain
just one value or not.  If you expect telephoneNumber to be multivalued,
but receive just one value '123',
  for value in foo.telephoneNumber: print value
will print
1
2
3

BTW, Cruelemort, remember that attribute names are case-insensitive.  If
you ask the server to for attribute "cn", it might still return "CN".

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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread Geoffrey Clements
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On Feb 2, 1:38 pm, rzed <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote 
> innews:[EMAIL PROTECTED]:
>
>
>
> > On Feb 2, 1:16 pm, rzed <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] wrote
> >> innews:[EMAIL PROTECTED]:
>
> >> > Hi,
>
> >> >   I'm interested in printing out coloured lines of my
> >> >   application and
> >> > I don't know what to use. Can anybody give me an idea??
>

[snip]

>
> If you're on Linux, you could use the curses module. There may be
> a precompiled Windows version compatible with your Python version,
> or maybe not, but the Windows source is available, and you may be
> able to get it to work with your Python with some effort. Linux
> distros include curses, I think. For Windows curses, take a look
> at . You will understand why
> the phrase "Windows curses" is used, I expect.
>
> --
> rzed
>
> Yes, I'm on a Linux box. I've tried with the curses module, but I
> don't how I could fetch the current use of curses of my shell. I don't
> know if I'm talking about something impossible. I've made some tests
> with the curses module and works fine, but I need to capture the
> current window and change the attributes of texts.

You may find the following useful, it's from Gentoo's portage:
http://sources.gentoo.org/viewcvs.py/portage/main/trunk/pym/portage/output.py?rev=5780&view=markup

-- 
Geoff 


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


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Paddy
On Feb 2, 1:55 pm, "ardief" <[EMAIL PROTECTED]> wrote:
> Hi everyone
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> and I would like to end up with something like this, i.e. with the
> only one list per letter:
>
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]
>
> I have the feeling it's trivial, and I've scoured the group archives -
> sets might be a possibility, but I'm not sure how to operate on a list
> of lists with sets.
>
> This function also gives me what I want, more or less, but I don't
> know how to make it run until it's covered all the possibilities, if
> that makes sense...
>
> def sigh(list):
> for a in list:
> i = list.index(a)
> if a != list[-1]:##if a is not the last one, i.e. there 
> is a
> next one
> n = alist[i+1]
> if a[0] == n[0]:
> a.append(n[1:])
> del alist[i+1]
>
> Sorry about the lengthy message and thanks for your suggestions - I'm
> trying to learn...

: python
Python 2.5 (r25:51908, Nov 28 2006, 16:10:01)
[GCC 3.4.3 (TWW)] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from pprint import pprint as pp
>>> from collections import defaultdict
>>> data = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], 
>>> ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>>> d = defaultdict(list)
>>> _ = [d[x0].append(x1) for x0,x1 in data]
>>> pp(d)
defaultdict(, {'a': ['13', '3'], 'c': ['12', '15', '4'],
'b': ['6'], 'e': ['11', '5', '16', '7'], 'd': ['2']})
>>> pp(sorted(d.items()))
[('a', ['13', '3']),
 ('b', ['6']),
 ('c', ['12', '15', '4']),
 ('d', ['2']),
 ('e', ['11', '5', '16', '7'])]
>>>

- Paddy

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


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Neil Cerutti
On 2007-02-02, ardief <[EMAIL PROTECTED]> wrote:
> Hi everyone
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> and I would like to end up with something like this, i.e. with
> the only one list per letter:
>
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]
>
> I have the feeling it's trivial, and I've scoured the group
> archives - sets might be a possibility, but I'm not sure how to
> operate on a list of lists with sets.

This is a job for... duhn-duhn-DH! Captain CHAOS!

Er... I mean itertools.groupby.

I took the liberty of not assuming the alist was sorted already.
This could be a one-liner if you wanted to be evil.

def bundle_alist(seq):
""" Bundle together some alist tails. 

>>> seq = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], 
['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>>> bundle_alist(seq)
[['a', ['13', '3']], ['b', ['6']], ['c', ['12', '15', '4']], ['d', ['2']], 
['e', ['11', '5', '16', '7']]]

"""
from itertools import groupby
def key_func(t):
return t[0]
groups = groupby(sorted(seq, key=key_func), key_func)
seq = []
for item in groups:
seq.append([item[0], [a[1] for a in item[1]]])
return seq


-- 
Neil Cerutti
Music gets more chromatic and heavy towards the end of the century. One of the
popular questions of the day was, "Why?" --Music Lit Essay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Laurent Pointal
ardief a écrit :
> Hi everyone
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
> 
> and I would like to end up with something like this, i.e. with the
> only one list per letter:
> 
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]
> 
> I have the feeling it's trivial, and I've scoured the group archives -
> sets might be a possibility, but I'm not sure how to operate on a list
> of lists with sets.
> 
> This function also gives me what I want, more or less, but I don't
> know how to make it run until it's covered all the possibilities, if
> that makes sense...
> 
> def sigh(list):
>   for a in list:
>   i = list.index(a)
>   if a != list[-1]:##if a is not the last one, i.e. there is a
> next one
>   n = alist[i+1]
>   if a[0] == n[0]:
>   a.append(n[1:])
>   del alist[i+1]
> 
> Sorry about the lengthy message and thanks for your suggestions - I'm
> trying to learn...
> 

You may take a look to the groupby iterator in the standard itertools
module.

http://docs.python.org/lib/itertools-functions.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Paddy
On Feb 2, 2:39 pm, "Paddy" <[EMAIL PROTECTED]> wrote:
> On Feb 2, 1:55 pm, "ardief" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi everyone
> > Here is my problem:
> > I have a list that looks like this -
> > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> > and I would like to end up with something like this, i.e. with the
> > only one list per letter:
>
> > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> > ['e', ['11', '5', '16', '7']]]
>
> > I have the feeling it's trivial, and I've scoured the group archives -
> > sets might be a possibility, but I'm not sure how to operate on a list
> > of lists with sets.
>
> > This function also gives me what I want, more or less, but I don't
> > know how to make it run until it's covered all the possibilities, if
> > that makes sense...
>
> > def sigh(list):
> > for a in list:
> > i = list.index(a)
> > if a != list[-1]:##if a is not the last one, i.e. there 
> > is a
> > next one
> > n = alist[i+1]
> > if a[0] == n[0]:
> > a.append(n[1:])
> > del alist[i+1]
>
> > Sorry about the lengthy message and thanks for your suggestions - I'm
> > trying to learn...
>
> : python
> Python 2.5 (r25:51908, Nov 28 2006, 16:10:01)
> [GCC 3.4.3 (TWW)] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> from pprint import pprint as pp
> >>> from collections import defaultdict
> >>> data = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], 
> >>> ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
> >>> d = defaultdict(list)
> >>> _ = [d[x0].append(x1) for x0,x1 in data]
> >>> pp(d)
>
> defaultdict(, {'a': ['13', '3'], 'c': ['12', '15', '4'],
> 'b': ['6'], 'e': ['11', '5', '16', '7'], 'd': ['2']})>>> pp(sorted(d.items()))
>
> [('a', ['13', '3']),
>  ('b', ['6']),
>  ('c', ['12', '15', '4']),
>  ('d', ['2']),
>  ('e', ['11', '5', '16', '7'])]
>
>
>
> - Paddy


Use defaultdict(set) and d[x0].add(x1) if you also want to remove
duplicates.

- Paddy.

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


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Bart Ogryczak
On Feb 2, 2:55 pm, "ardief" <[EMAIL PROTECTED]> wrote:
> Hi everyone
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> and I would like to end up with something like this, i.e. with the
> only one list per letter:
>
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]

your_list = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c',
'15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'],
['e', '7']]
d = {}
for k,v in your_list: d.setdefault(k,[]).append(v)
result = [list(x) for x in d.items()] # if you really need it as list
of lists
# if list of tuples is ok, then it´d be just:
# result = d.items()
result.sort() # if you need this list sorted by keys


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


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Laurent Pointal
Neil Cerutti a écrit :
> On 2007-02-02, ardief <[EMAIL PROTECTED]> wrote:


> This is a job for... duhn-duhn-DH! Captain CHAOS!
> 
> Er... I mean itertools.groupby.
> 

> def key_func(t):
> return t[0]

Not needed: --> from operator import itemgetter

See in the example:
http://docs.python.org/lib/itertools-example.html

So much stuff in libraries, so few we know. Thanks to doc writers,
Usenet contributors & Google search engines.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Bart Ogryczak
On Feb 2, 3:19 pm, Larry Bates <[EMAIL PROTECTED]> wrote:

> l=[x for x in d.items()]

d.items() is not an iterator, you don´t need this. This code is
equivalent to l = d.items().



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


Re: Writing "pythonish" code

2007-02-02 Thread Istvan Albert
On Feb 2, 6:20 am, Mizipzor <[EMAIL PROTECTED]> wrote:


> Now, the thing that bothers me the most. When I write python modules I
> write one class per file, and the file and the class has a common
> name. Maybe this is due to c++ habits.

Python modules typically contain multiple classes and module level
functions as well. That way having to deal with redundant names such
as  foo.foo comes up less often.

Also it is a good habit to make capitalize class names, that way
writing:

from foo import Foo, bar

makes it clear that one is a class the other a function.

i.

PS: here is my personal pet peeve ...  say it out loud ... I love the
functionality it offers and saved me a lot of work, yet I have to make
his conscious effort to keep these  names:  package, module, class
apart.

from elementtree.ElementTree import ElementTree

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


Re: Germany issues warrants for 13 American CIA agents

2007-02-02 Thread Boris Borcic
Vance P. Frickey wrote:

> I understand that Mengele's old boss is still alive and well 
> in Deutschland

What else do you understand ?

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


Re: compound statement from C "?:"

2007-02-02 Thread Jussi Salmela
Holger kirjoitti:
>
> I would like to do the equivalent if python of the C line:
> printf("I saw %d car%s\n", n, n != 1 ? "s" : "")
> 
> Please help
> 
> /Holger
> 

In this particular case you don't need the ternary operator:

print "I saw %d car%s\n" % (n, ("", "s")[n != 1])


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


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Laurent Pointal <[EMAIL PROTECTED]> wrote:
> Neil Cerutti a écrit :
>> On 2007-02-02, ardief <[EMAIL PROTECTED]> wrote:
>
>
>> This is a job for... duhn-duhn-DH! Captain CHAOS!
>> 
>> Er... I mean itertools.groupby.
>> 
>
>> def key_func(t):
>> return t[0]
>
> Not needed: --> from operator import itemgetter

I agree. But I used it anyway, to make it easier to see that the
sort and the groupby must be and are using the same key function.

In this case I admit it's a not a huge readability win, but I was
also following the "Do Not Repeat Yourself Rule", which makes the
key function easier to refactor.

> See in the example:
> http://docs.python.org/lib/itertools-example.html
>
> So much stuff in libraries, so few we know. Thanks to doc
> writers, Usenet contributors & Google search engines.

Yup.

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


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread ardief
On Feb 2, 1:55 pm, "ardief" <[EMAIL PROTECTED]> wrote:
> Hi everyone
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> and I would like to end up with something like this, i.e. with the
> only one list per letter:
>
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]


thanks to everyone for the help, and the speed of it! It's really
useful and I will spend some time working on understanding the code
you posted. I'd be so lost without this group...

r

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


Re: Tkinter Scrolling

2007-02-02 Thread Eric Brunel
On Thu, 01 Feb 2007 20:26:08 +0100, D <[EMAIL PROTECTED]> wrote:
> Bob Greschke wrote:
>> The typical way to do it is to make a scrolling canvas and
>> pack the buttons and other stuff into an empty Frame() and then pack
>> the frame on to the canvas, which I haven't had to do yet.
>>
>> Bob
> Thanks, Bob - have you seen any examples of the latter approach (using
> a canvas and frame)?  Sounds rather confusing, but it definitely seems
> like the approach I need to take.  Thanks again.

Here you are:

---
 from Tkinter import *

## Main window
root = Tk()
## Grid sizing behavior in window
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
## Canvas
cnv = Canvas(root)
cnv.grid(row=0, column=0, sticky='nswe')
## Scrollbars for canvas
hScroll = Scrollbar(root, orient=HORIZONTAL, command=cnv.xview)
hScroll.grid(row=1, column=0, sticky='we')
vScroll = Scrollbar(root, orient=VERTICAL, command=cnv.yview)
vScroll.grid(row=0, column=1, sticky='ns')
cnv.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll.set)
## Frame in canvas
frm = Frame(cnv)
## This puts the frame in the canvas's scrollable zone
cnv.create_window(0, 0, window=frm, anchor='nw')
## Frame contents
for i in range(20):
   b = Button(frm, text='Button n#%s' % i, width=40)
   b.pack(side=TOP, padx=2, pady=2)
## Update display to get correct dimensions
frm.update_idletasks()
## Configure size of canvas's scrollable zone
cnv.configure(scrollregion=(0, 0, frm.winfo_width(), frm.winfo_height()))
## Go!
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: Writing "pythonish" code

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Toby A Inkster <[EMAIL PROTECTED]> wrote:
> Mizipzor wrote:
>> One thing is that in c++ im used to have private members in
>> classes and no member is altered except through the public
>> functions of the class.
>
> By convention, class members starting with a single underscore
> are considered private. 

An important consideration is that this convention is simply a
lower level of enforcement than C++ provides. Private members in
C++ are accessible if you use pointers.

> Class members starting with a double underscore are "mangled"
> which makes it more difficult for other code (even subclasses!)
> to access the member. Difficult though -- not impossible.

I think it's best to never use such names in new code. Python's
mangling is troubled, since it uses unqualified names in the
mangle, resulting in ambiguity.

-- 
Neil Cerutti
Ushers will eat latecomers. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: division by 7 efficiently ???

2007-02-02 Thread Jesse Chounard
On 31 Jan 2007 19:13:14 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Its not an homework. I appeared for EA sports interview last month. I
> was asked this question and I got it wrong. I have already fidlled
> around with the answer but I don't know the correct reasoning behind
> it.

I think this works:

>>> def div7 (N):
... return ((N * 9362) >> 16) + 1
...
>>> div7(7)
1
>>> div7(14)
2
>>> div7(700)
100
>>> div7(7)
1

The coolest part about that (whether it works or not) is that it's my
first Python program.  I wrote it in C first and had to figure out how
to convert it.  :)

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


Re: division by 7 efficiently ???

2007-02-02 Thread John Machin
On Feb 2, 11:03 pm, "Bart Ogryczak" <[EMAIL PROTECTED]> wrote:
> On Feb 1, 3:42 am, [EMAIL PROTECTED] wrote:
>
> > How to divide a number by 7 efficiently without using - or / operator.
> > We can use the bit operators. I was thinking about bit shift operator
> > but I don't know the correct answer.
>
> It´s quiet simple. x ==  8*(x/8) + x%8, so x == 7*(x/8) + (x/8 + x%8)
> x/8 == x>>3, x%8 == x&7
> And there you have it, function rounds upwards for numbers not
> divisible by 7. Gotta change int(x>0) to int(x>3) to round normally,
> or int(x>6) to round downwards.
>
> def d7(x):
> if(x>>3 == 0): return int(x>0)
> return (x>>3)+d7((x>>3)+(x&7))

I doubt that a recursive function call (even a tail-recursive one)
comes near what the OP and his interrogators mean by "efficiently".

Nicko has already given the answer for the case where a 31-bit non-
negative dividend is required. Here are some examples of the technique
for cases where smaller numbers are found e.g. in date arithmetic.

def div7a(N):
assert 0 <= N <= 684
r = (N << 3) + N
r = (r << 3) + N
r = (r << 2) + N
r >>= 11
return r

def div7b(N):
assert 0 <= N <= 13109
r = (N << 3) + N
r = (r << 3) + N
r = (r << 3) + N
r = (r << 3) + N
r = (r << 1) + N
r >>= 16
return r

What's going on there? Well, using the first example, (2 ** 11) // 7
and rounded to the higher integer is 293.  So 293 / 2048 is an
approximation to 1 / 7. Dividing by 2048 is a doddle. The shift-left-
add stuff is doing the multiplication by 293, unrolled loop, one cycle
per line when implemented as a SHLnADD instruction from the HP PA-RISC
architecture.  Unsigned division otherwise would take 32 DS (divide
step) instructions.

FWIW, gcc emits code for the Intel IA32 architecture that gloriously
"misuses" the LEAL instruction to get the same reg1 = (reg2 << n) +
reg3 effect.

Any relevance to this newsgroup? Yes, there's a lot of pre-computation
involved there. Python is an excellent language for debugging such
stuff and generating include files for a production code.

Cheers,
John

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


Re: asyncore DoS vulnerability

2007-02-02 Thread billie
> This is not a CRASH, It looks an exception with a "Traceback", this is
> the normal way python report problems, nothing wrong with that.
> You can handle it with a try: except:

I think that such a thing should be handled by asyncore itself.

> 512 is probably a fixed limit into XP, win2k3 or win2k server will
> accept more.
> Maybe It's possible to increase this value somewhere in the registry.
> If not this is how microsoft justify the difference between server and
> workstation products :-)

Yeah, maybe...

>> Why does this exception isn't handled inside asyncore.py?
> To do what ? To raise a custom asyncore error ?

asyncore aims to be a framework, right?
I think that when select() limit is reached asyncore should just drop
other connections. That's all.

> You can can probably run over this limit by starting multiple of your
> server process (not thread, process).

Hope you're joking...
Why should I have to run multiple processes / threads to avoid such a
problem?
And what if my system / inteprepter does not support multiple
processes / threads?

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


Re: division by 7 efficiently ???

2007-02-02 Thread John Machin
On Feb 3, 2:31 am, "Jesse Chounard" <[EMAIL PROTECTED]> wrote:
> On 31 Jan 2007 19:13:14 -0800, [EMAIL PROTECTED]
>
> <[EMAIL PROTECTED]> wrote:
> > Its not an homework. I appeared for EA sports interview last month. I
> > was asked this question and I got it wrong. I have already fidlled
> > around with the answer but I don't know the correct reasoning behind
> > it.
>
> I think this works:

You think wrongly. Inspection reveals that it is obviously incorrect
for N == 0. Trivial testing reveals that it is wrong for about 6 out
of every 7 cases.

>
> >>> def div7 (N):
>
> ... return ((N * 9362) >> 16) + 1
> ...>>> div7(7)
> 1
> >>> div7(14)
> 2
> >>> div7(700)
> 100
> >>> div7(7)
>
> 1
>
> The coolest part about that (whether it works or not) is that it's my
> first Python program.  I wrote it in C first and had to figure out how
> to convert it.  :)

Try testing algorithms with a pencil on the back of an envelope first.

The uncoolest part about that is that your test data is horribly
deficient:

>>> for N in xrange(0, 23):
... a = ((N * 9362) >> 16) + 1
... e = N // 7
... print N, a, e, a == e
...
0 1 0 False
1 1 0 False
2 1 0 False
3 1 0 False
4 1 0 False
5 1 0 False
6 1 0 False
7 1 1 True
8 2 1 False
9 2 1 False
10 2 1 False
11 2 1 False
12 2 1 False
13 2 1 False
14 2 2 True
15 3 2 False
16 3 2 False
17 3 2 False
18 3 2 False
19 3 2 False
20 3 2 False
21 3 3 True
22 4 3 False

HTH,
John

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


Re: asyncore DoS vulnerability

2007-02-02 Thread Chris Mellon
On 2 Feb 2007 07:32:14 -0800, billie <[EMAIL PROTECTED]> wrote:
> > This is not a CRASH, It looks an exception with a "Traceback", this is
> > the normal way python report problems, nothing wrong with that.
> > You can handle it with a try: except:
>
> I think that such a thing should be handled by asyncore itself.
>

Handled by doing what, exactly?

> > 512 is probably a fixed limit into XP, win2k3 or win2k server will
> > accept more.
> > Maybe It's possible to increase this value somewhere in the registry.
> > If not this is how microsoft justify the difference between server and
> > workstation products :-)
>
> Yeah, maybe...
>
> >> Why does this exception isn't handled inside asyncore.py?
> > To do what ? To raise a custom asyncore error ?
>
> asyncore aims to be a framework, right?
> I think that when select() limit is reached asyncore should just drop
> other connections. That's all.

Silently rejecting connections in a way that is invisible to the
application is clearly the wrong thing to do.

>
> > You can can probably run over this limit by starting multiple of your
> > server process (not thread, process).
>
> Hope you're joking...
> Why should I have to run multiple processes / threads to avoid such a
> problem?

Thats like asking why you should have to move your fingers to type or
why you should have to eat food in order to not starve. Windows is
placing a limit of 512 descriptors per process. Call Microsoft if you
want to go over that.

Or, you can volunteer to write a win32 port of asyncore that uses
native winsock functions instead of the BSD compatibility functions.

> And what if my system / inteprepter does not support multiple
> processes / threads?
>

What if it doesn't support sockets? This is a platform limitation, not
an arbitrary Python one. Nothing Python is going to do is going to
convince Windows to select() on more than 512 file descriptors per
process.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: coping directories

2007-02-02 Thread Jussi Salmela
Gigs_ kirjoitti:
> hi people
> 
> I have problem with this example, not actually the problem, but
> [code]
> class FileVisitor(object):
> def __init__(self, data=None):
> self.context = data
> def run(self, startdir=os.curdir):
> os.path.walk(startdir, self.visitor, None)
> def visitor(self, data, dirname, filesindir):
> self.visitdir(dirname)
> for fname in filesindir:
> fpath = os.path.join(dirname, fname)
> if not os.path.isdir(fpath):
> self.visitfile(fpath)
> def visitdir(self, dirpath):# override or extend this 
> method
> print dirpath, '...'
> def visitfile(self, filepath):  # override or extend this 
> method
> print self.fcount, '=>', filepath
> #
> class CVisitor(FileVisitor):
> def __init__(self, fromdir, todir):
> self.fromdirLen = len(fromdir) + 1# here is my problem
> self.todir = todir
> FileVisitor.__init__(self, fromdir)
> def visitdir(self, dirpath):
> topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
> os.mkdir(topath)
> def visitfile(self, filepath):
> topath = os.path.join(self.todir, filepath[self.fromdirLen:])
> cpfile(filepath, topath)#copy contents from filepath to 
> topath[/code]
> 
> 
> When I copy contents from C:\IronPython to C:\temp
> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this 
> self.fromdirLen = len(fromdir) + 1
> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen 
> = len(fromdir) i get contents copied to C:\ (actually to parent dir)
> 
> Can anyone explain me that?
> 
> Thanks!!!
>  :o

Why do you want to change a working program anyway? :)

The result of your change is that os.path.join does the join 
differently. Before the change the join is, for example:
os.path.join(r'c:\temp', r'AUTOEXEC.BAT')
with a result:
c:\temp\AUTOEXEC.BAT

After your change the join is:
os.path.join(r'c:\temp', r'\AUTOEXEC.BAT')
with a result:
\AUTOEXEC.BAT

This is described in the doc:

  join( path1[, path2[, ...]])

Join one or more path components intelligently. If any component is an 
absolute path, all previous components (on Windows, including the 
previous drive letter, if there was one) are thrown away, and joining 
continues.

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


from __future__ import absolute_import ?

2007-02-02 Thread Ron Adam

from __future__ import absolute_import

Is there a way to check if this is working?  I get the same results with or 
without it.

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17)
[MSC v.1310 32 bit (Intel)] on win 32


_Ron

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


Re: coping directories

2007-02-02 Thread Gigs_
Jussi Salmela wrote:
> Gigs_ kirjoitti:
>> hi people
>>
>> I have problem with this example, not actually the problem, but
>> [code]
>> class FileVisitor(object):
>> def __init__(self, data=None):
>> self.context = data
>> def run(self, startdir=os.curdir):
>> os.path.walk(startdir, self.visitor, None)
>> def visitor(self, data, dirname, filesindir):
>> self.visitdir(dirname)
>> for fname in filesindir:
>> fpath = os.path.join(dirname, fname)
>> if not os.path.isdir(fpath):
>> self.visitfile(fpath)
>> def visitdir(self, dirpath):# override or extend this 
>> method
>> print dirpath, '...'
>> def visitfile(self, filepath):  # override or extend this 
>> method
>> print self.fcount, '=>', filepath
>> #
>> class CVisitor(FileVisitor):
>> def __init__(self, fromdir, todir):
>> self.fromdirLen = len(fromdir) + 1# here is my problem
>> self.todir = todir
>> FileVisitor.__init__(self, fromdir)
>> def visitdir(self, dirpath):
>> topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
>> os.mkdir(topath)
>> def visitfile(self, filepath):
>> topath = os.path.join(self.todir, filepath[self.fromdirLen:])
>> cpfile(filepath, topath)#copy contents from filepath to 
>> topath[/code]
>>
>>
>> When I copy contents from C:\IronPython to C:\temp
>> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this 
>> self.fromdirLen = len(fromdir) + 1
>> but when I change self.fromdirLen = len(fromdir) + 1 to 
>> self.fromdirLen = len(fromdir) i get contents copied to C:\ (actually 
>> to parent dir)
>>
>> Can anyone explain me that?
>>
>> Thanks!!!
>>  :o
> 
> Why do you want to change a working program anyway? :)
> 
> The result of your change is that os.path.join does the join 
> differently. Before the change the join is, for example:
> os.path.join(r'c:\temp', r'AUTOEXEC.BAT')
> with a result:
> c:\temp\AUTOEXEC.BAT
> 
> After your change the join is:
> os.path.join(r'c:\temp', r'\AUTOEXEC.BAT')
> with a result:
> \AUTOEXEC.BAT
> 
> This is described in the doc:
> 
>  join( path1[, path2[, ...]])
> 
> Join one or more path components intelligently. If any component is an 
> absolute path, all previous components (on Windows, including the 
> previous drive letter, if there was one) are thrown away, and joining 
> continues.
> 
> HTH,
> Jussi

thats what i need to know
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stlib name clash when using python as ASP language

2007-02-02 Thread Gabriel Genellina
"Joost" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> When using ASP the iis/inetsrv path is placed as the first item in
> sys.path. Consequently importing httplib2 will cause the following
> error:
>
> ImportError: dynamic module does not define init function (initgzip)
>
> The following per page hack *fixes* the problem most of the time:
> import sys
> sys.path[0] = "c:/python24/lib"
>
> Strangely, even with this code loaded in every page the import error
> sporadically occurs. What would be the preferred way to solve this
> name clash?

You *assume* that [0] is the IIS path, but perhaps some other imported 
module changed sys.path too, and now it's not the first one anymore.
If you know exactly the path, try sys.path.remove(iis_path).

-- 
Gabriel Genellina 


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


Re: division by 7 efficiently ???

2007-02-02 Thread Bart Ogryczak
On Feb 1, 2:00 pm, "Nicko" <[EMAIL PROTECTED]> wrote:

> precision and the answer that they were looking for was:
> a = (b * 045L) >> 32
> Note that the constant there is in octal.

045L? Shouldn´t it be  044?
Or more generally,
const = (1<>bitPrecision


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


Re: Sorting a list

2007-02-02 Thread John Salerno
Bruno Desthuilliers wrote:
> John Salerno a écrit :
> (snip)
> 
>> Oh I didn't sort then reverse, I just replaced sort with reverse. 
>> Maybe that's why!
> 
> Hmmm... Probably, yes...
> 
> !-)

lol, this is what a couple months away from python does to me!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: coping directories

2007-02-02 Thread Gabriel Genellina
"Gigs_" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]
Gabriel Genellina wrote:
> En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ <[EMAIL PROTECTED]> escribió:
>
>> class CVisitor(FileVisitor):
>>  def __init__(self, fromdir, todir):
>>  self.fromdirLen = len(fromdir) + 1# here is my problem
>>  self.todir = todir
>>  FileVisitor.__init__(self, fromdir)
>>  def visitdir(self, dirpath):
>>  topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
>>  os.mkdir(topath)
>>  def visitfile(self, filepath):
>>  topath = os.path.join(self.todir, filepath[self.fromdirLen:])
>>  cpfile(filepath, topath)#copy contents from filepath to
>> topath[/code]
>>
>>
>> When I copy contents from C:\IronPython to C:\temp
>> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this
>> self.fromdirLen = len(fromdir) + 1
>> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen
>> = len(fromdir) i get contents copied to C:\ (actually to parent dir)
>
> Instead of actually doing os.mkdir and cpfile, use a print statement to
> output the involved variables, and try with and without +1. You'll see
> yourself what happens.
>
> well I have tried with print but can't figure out
> I got this when I have removed + 1
>  >>> C = CpallVisitor('C:\\New', 'c:\\temp')
>  >>> C.run(startdir='C:\\New')
> c:\temp\
> filepath: C:\New\AUTOEXEC.BAT Topath: \AUTOEXEC.BAT
> filepath: C:\New\boot.ini Topath: \boot.ini
> filepath: C:\New\CONFIG.SYS Topath: \CONFIG.SYS

So it's clear that you need the +1 for the program to work properly, ok?

> In python shell I got same thing, no matter fromdirLen is
> len(fromdir) + 1 or len(fromdir)
>  >>> fromdir = 'C:\\New'
>  >>> fromdirLen = len(fromdir)
>  >>> todir = 'C:\\temp'
>  >>> topath = os.path.join(todir, fromdir[fromdirLen:])
>  >>> topath
> 'C:\\temp\\'

This is *not* what your program does; the original code above has another 
variable, filepath.

> Please help

I assume that you're doing this as some kind of learning exercise - else 
there are other simpler ways. And you want to know why do you need that +1. 
Because it's clear that using +1 is the right answer, ok? You'll have to 
understand it yourself. Try running the program step by step. Hints:
- compare os.path.join("c:\\temp", "AUTOEXEC.BAT") with 
os.path.join("c:\\temp", "\\AUTOEXEC.BAT") with os.path.join("c:\\temp\\", 
"AUTOEXEC.BAT") with os.path.join("c:\\temp\\", "\\AUTOEXEC.BAT") - remember 
that len("\\") == 1
- compare c:\temp c:\temp\AUTOEXEC.BAT and see where the filename part 
begins and what your program is doing with this.

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


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


Re: asyncore DoS vulnerability

2007-02-02 Thread skip

billie> asyncore aims to be a framework, right?  I think that when
billie> select() limit is reached asyncore should just drop other
billie> connections. That's all.

You're asking asyncore to make a policy decision on behalf the controlling
application.  It has no idea what that application wants to do when the open
file limit is reached.  Maybe it should close the oldest connection instead
of refusing all new ones.  Maybe it should adjust the rate at which it
accepts new connections.  asyncore doesn't know.

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


Re: Interpreter window

2007-02-02 Thread Gabriel Genellina
"Nils Overas Bergen" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> On 2 Feb, 13:07, "skyofdreams" <[EMAIL PROTECTED]> wrote:
>> "Nils Overas Bergen" <[EMAIL PROTECTED]>
>> [EMAIL PROTECTED]
>>
>> >I have created a Python application in Windows XP which uses
>> > WxWidgets. When I start the application from the Python interpreter I
>> > get one empty interpreter window in addition to the application
>> > window. Is there a way to close the interpreter window without closing
>> > the application? Or, can I start the interpreter and the application
>> > script without starting the interpreter window?
>>
>> do you mean  console window?
>> you can try pythonw.exe instead of python.exe
>
> Thanks! Now my application starts without the console window.

And, if you rename the .py to .pyw, it will open with pythonw.exe by 
default.

-- 
Gabriel Genellina 


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


Re: division by 7 efficiently ???

2007-02-02 Thread Nicko
On Feb 2, 4:21 pm, "Bart Ogryczak" <[EMAIL PROTECTED]> wrote:
> On Feb 1, 2:00 pm, "Nicko" <[EMAIL PROTECTED]> wrote:
>
> > precision and the answer that they were looking for was:
> > a = (b * 045L) >> 32
> > Note that the constant there is in octal.
>
> 045L? Shouldn´t it be  044?
> Or more generally,
> const = (1< a = (b * const)>>bitPrecision

It's to do with rounding. What you actually need is
ceiling((1

Re: asyncore DoS vulnerability

2007-02-02 Thread Jean-Paul Calderone
On Fri, 2 Feb 2007 10:39:57 -0600, [EMAIL PROTECTED] wrote:
>
>billie> asyncore aims to be a framework, right?  I think that when
>billie> select() limit is reached asyncore should just drop other
>billie> connections. That's all.
>
>You're asking asyncore to make a policy decision on behalf the controlling
>application.  It has no idea what that application wants to do when the open
>file limit is reached.  Maybe it should close the oldest connection instead
>of refusing all new ones.  Maybe it should adjust the rate at which it
>accepts new connections.  asyncore doesn't know.

It could ask the application.  On the other hand, maybe asyncore remains in
a perfectly consistent state even after it raises this exception, and it is
already "asking" by letting this exception propagate up: if the application
is free to start the loop again after this happens, then it seems everything
is just fine; if some state becomes inconsistent, though, then asyncore should
probably do something more (assuming asyncore applications are supposed to be
able to be resistent to this kind of DoS).

Still, this basically means every asyncore-based server can be shut down more
or less at the whim of the public internet.  Doesn't that problem merit some
attention (maybe it doesn't, I don't know - that's why I'm asking)?

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


OSS and ALSA

2007-02-02 Thread Silver Rock

Hi all,



I've seen that python comes by default with a module for communication
with OSS.

I've looked for a ALSA module too (pyalsa) but it seems to handle only
limited operations.

Is it recommended that one programm using oss becouse of Alsa's OSS
compatibility?

thanks,
claire

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

Re: from __future__ import absolute_import ?

2007-02-02 Thread Peter Otten
Ron Adam wrote:

> 
> from __future__ import absolute_import
> 
> Is there a way to check if this is working?  I get the same results with
> or without it.
> 
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17)
> [MSC v.1310 32 bit (Intel)] on win 32

If there are two modules 'foo', one at the toplevel and the other inside a
package 'bar', 

from __future__ import absolute_import
import foo

will import the toplevel module whereas 

import foo

will import bar.foo. A messy demonstration:

$ ls bar
absolute.py  foo.py  __init__.py  relative.py
$ cat bar/absolute.py
from __future__ import absolute_import
import foo
$ cat bar/relative.py
import foo
$ cat foo.py
print "toplevel"
$ cat bar/foo.py
print "in bar"
$ python2.5 -c 'import bar.absolute'
toplevel
$ python2.5 -c 'import bar.relative'
in bar


Another example is here:

http://mail.python.org/pipermail/python-list/2007-January/422889.html

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


Re: Spring Python 0.2.0 is released

2007-02-02 Thread Jonathan Curran
Greg,
You have managed to peak my interest. I'll be dabbling with this in the 
next 
few hours. This looks very promising, keep up the good work.

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


Re: division by 7 efficiently ???

2007-02-02 Thread Nicko
On Feb 1, 8:25 pm, "Krypto" <[EMAIL PROTECTED]> wrote:
> The correct answer as told to me by a person is
>
> (N>>3) + ((N-7*(N>>3))>>3)
>
> The above term always gives division by 7

No it doesn't.  The above term tends towards N * (9/64), with some
significant rounding errors.  9/64 is a fairly poor (6 bit)
approximation of 1/7 but the principle is the same as the solution I
proposed above.

Nicko

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


Re: from __future__ import absolute_import ?

2007-02-02 Thread Peter Otten
Peter Otten wrote:

> If there are two modules 'foo', one at the toplevel and the other inside a
> package 'bar',
> 
> from __future__ import absolute_import
> import foo
> 
> will import the toplevel module whereas
> 
> import foo
> 
> will import bar.foo. 

... provided these imports are performed from modules within 'bar'.

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


Re: compound statement from C "?:"

2007-02-02 Thread bearophileHUGS
Jussi Salmela:
> In this particular case you don't need the ternary operator:
> print "I saw %d car%s\n" % (n, ("", "s")[n != 1])

The last newline is probably unnecessary. This seems be a bit more
readable:
print "I saw", n, "car" + ("", "s")[n != 1]

With Python 2.5 this looks better:
print "I saw", n, "car" + ("" if n == 1 else "s")

Or the vesion I like better:
print "I saw", n, ("car" if n == 1 else "cars")

Those () aren't necessary, but they help improve readability, and
avoid problems with operator precedence too. That if has a quite low
precedence.

Bye,
bearophile

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


Build Python 2.5 wit VC6.0 ?

2007-02-02 Thread Alexander Eisenhuth
Hi everybody,

does somebody have experience in building with VC6.0. On my first try there 
where missing C-Modules. Is that true. VC6.0 is not supported?


Thanks a lot.

Regards
Alexander

PC: What Python version supports VC6.0?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing "pythonish" code

2007-02-02 Thread bearophileHUGS
Mizipzor:
> To me, the main.py code above looks very ugly.

With time, and looking at other people code, you will learn what
pythonic means, in the meantime you can remember that into your Python
code if you find something that makes you write too much code, or you
see something "ugly", then that's probably the wrong way to write it.
The language is designed in a way that often the simpler and shorter
things are the right ones. There are exceptions to that rule (like
avoiding to use import *, using xrange instead of range, etc), but
it's a stating point.

Bye and welcome here,
bearophile

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


Timeout for M2Crypto working - patch

2007-02-02 Thread John Nagle

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


[Q] result of os.times() is different with 'time' command

2007-02-02 Thread kwatch
Hi,

I have a question about os.times().
os.times() returns a tuple containing user time and system time,
but it is not matched to the result of 'time' command.
For example, os.times() reports that user time is 39.85 sec,
but 'time' command reports that user time is 28.55sec.
(machine: Python2.5, MacOS X 10.4 Tiger, MacBook 1.83GHz intel core
duo)

  file: ostimetest.py
  
  import os

  ## benchmark function
  def f(x):
  if x <= 1:
  return 1
  else:
  return f(x-1) + f(x-2)

  ## do benchmark
  n = 35
  t1 = os.times() # start time
  v = f(n)# end time
  print "n=%d, v=%d" % (n, v)
  t2 = os.times()

  ## print result
  utime = t2[0] - t1[0]   # user time
  stime = t2[1] - t1[1]   # system time
  print "utime=%s, stime=%s" % (utime, stime)
  

  Result:
  
  $ python -V
  Python 2.5
  $ time python ostimetest.py
  n=35, v=14930352
  utime=39.85, stime=0.2167
  real0m28.554suser0m23.938ssys 0m0.177s
  

This shows that os.times() reports that user time is 39.85sec,
but time command shows that user time is 23.938sec.
Why os.times() reports wrong result? Do I have any mistake?

--
kwatch

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


Checking default arguments

2007-02-02 Thread Igor V. Rafienko

Hi,


I was wondering whether it was possible to find out which parameter
value is being used: the default argument or the user-supplied one.
That is:  

def foo(x, y="bar"):
# how to figure out whether the value of y is 
# the default argument, or user-supplied?

foo(1, "bar") => user-supplied
foo(1)=> default

{}.pop seems to be able to make this dictinction.

I've checked the inspect module, but nothing obvious jumped at me. Any
hints?

Thanks,





ivr
-- 
"...but it's HDTV -- it's got a better resolution than the real world."
   -- Fry, "When aliens attack"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ubunu - Linux - Unicode - encoding

2007-02-02 Thread Franz Steinh�usler
On Fri, 2 Feb 2007 00:12:45 +0100, Alan Franzoni
<[EMAIL PROTECTED]> wrote:

>Il Thu, 01 Feb 2007 20:57:53 +0100, Franz Steinhäusler ha scritto:
>
>> If I copy files with german umlauts (äöü and strong 's' ß), these
>> filenames are not copied properly, and that characters are replaces
>> by little square symbols.
>
>Yes... I, myself, am italian, and I found no problem in using accented
>letter (òèàìù). Since you say there's a problem as well in Nautilus and
>other Ubuntu software, I suppose there's something wrong with your linux
>setup, not with Python.
>
>Or, at least: you should try solving that problem first, then check what
>happens with python.
>
>Try appending this options in your fstab as hda1 mount options:
>
>iocharset=iso8859-15
>
>unmount & remount and check what does happen.


Thank you again, I will give it a try!
-- 
Franz Steinhaeusler
-- 
http://mail.python.org/mailman/listinfo/python-list


Sybase module 0.38pre2 released

2007-02-02 Thread Sébastien Sablé
WHAT IS IT:

The Sybase module provides a Python interface to the Sybase relational
database system.  It supports all of the Python Database API, version
2.0 with extensions.


The module is available here:

http://downloads.sourceforge.net/python-sybase/python-sybase-0.38pre2.tar.gz

The module home page is here:

http://python-sybase.sourceforge.net/


CHANGES SINCE 0.38pre1:

* Add structured error information to Sybase.DatabaseError thanks to
patch provided by Gregory Bond (close tracker 1631902)

* Resurrected Sybase.Bulkcopy functionality thanks to patch provided
by Gregory Bond (close tracker 1632916)

* Corrected AttributeError when locking is off (close tracker 1637942
reported by Jim Nusbaum)

* Corrected incorrect type mx.DateTime.DateTime returned by
Sybase.Date() in "mx" datetime mode. This type is not supported by
DataBuf.

* Corrected crash on a BLK object when debug is enabled (close tracker
1630941 reported by Gregory Bond)

* rowcount is now propagated to Cursor (corrects tracker 1621003)

* Added support for python datetime type in DataBuf and as parameter
of Cursor.execute()

* Corrected Date, Time and Timestamp functions when using mx.DateTime
or native python datetime types

* Corrected DATETIME as cursor.description still returns native Sybase
datetime types

* Corrected blk_describe always returns (status, None) thanks to patch
by Phil Porter

* Patch to handle CS_LONG type based on patch by Paul Rensing


MAJOR CHANGES SINCE 0.37:

* This release works with python 2.5

* It also works with sybase 15

* It works with 64bits clients

* It can be configured to return native python datetime objects

* The bug "This routine cannot be called because another command
structure has results pending." which appears in various cases has
been corrected

* It includes a unitary test suite based on the dbapi2.0 compliance
test suite
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python does not play well with others

2007-02-02 Thread Paul Rubin
"Paul Boddie" <[EMAIL PROTECTED]> writes:
> If the hosting provider doesn't want to install MySQLdb then it may
> not be a technical issue - perhaps they just can't be bothered to
> install it, possibly because there's no demand or benefit to the
> bottom line in doing so.

Why should the hosting provider need to devote attention to something
like that?  MySQLdb or something like it should be included with
Python, not added separately by the hosting provider.  Python is
really making more demands on hosting providers than comparable
languages do.  PHP hosting providers don't have to install a separate
PHP to MySQL interface gizmo as far as I know.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >