ANN: Release 1.9.1 of SimPy (Simulation in Python) package

2008-03-18 Thread kgmuller
We announce the availability of SimPy version 1.9.1. This is an important
bug-fix release of SimPy 1.9 which any user of SimPy 1.9 should download.

SimPy 1.9.1 can be downloaded from
http://sourceforge.net/project/showfiles.php?group_id=62366 .

The SimPy homepage is at http://SimPy.SourceForge.Net .

What is SimPy?
==
SimPy (= Simulation in Python) is an object-oriented, process-based
discrete-event simulation language completely implemented in Python. It is
released under the GNU Lesser GPL (LGPL). SimPy provides the modeler with
components of a simulation model including processes, for active components
like customers, messages, and vehicles, and resources, for passive
components that form limited capacity congestion points like servers,
checkout counters, and tunnels. It also provides monitor variables to aid in
gathering statistics. Random variates are provided by the standard Python
random module.

Many users claim that SimPy is one of the cleanest, easiest to use discrete
event simulation packages! SimPy is in use at many universities, research
institutes and in industry.

SimPy comes with data collection capabilities, GUI and plotting packages. It
can be easily interfaced to other packages, such as plotting, statistics, or
database systems.

SimPy is platform-independent and runs on all systems on which Python 2.3 or
later is available.

Acknowledgements


The bugs were identified and reported by members of the SimPy user
community. Thanks for this! Collaboration works!

==
Release notes for SimPy 1.9.1
==
  
Repairs

SimPy 1.9.1 cures two bugs:

(1) Excessive memory requirements of large or long-running scripts. This
performance problem was caused by circular references between Process and
event notice instances.

(2) Runtime errors for pre-empts of processes holding multiple Resource
objects.

Additions


In addition to all the other, extensive documentation, SimPy 1.9.1 provides
a short manual which only addresses the basic facilities of SimPy. You could
consider this as SimPy light. This manual is aimed at introducing SimPy to
beginners.


(end of Release Notes)

Enjoy!

Klaus Müller Tony Vignaux

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Colorado Python training in May

2008-03-18 Thread lutz
Python author and trainer Mark Lutz will be teaching another
3-day Python class at a conference center in Longmont, Colorado,
on May 14-16, 2008.

This is a public training session open to individual enrollments, 
and covers the same topics as the 3-day onsite sessions that Mark
teaches, with hands-on lab work.

For more information on this session, please visit its web page:

http://home.earthlink.net/~python-training/longmont-public-classes.htm

For additional background on the class itself, see our home page:

http://home.earthlink.net/~python-training

Thanks for your interest.
--Mark Lutz at Python Training Services

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: writing to a binary file without intervening spaces

2008-03-18 Thread Larry
On Mar 18, 1:32 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:
 Larry [EMAIL PROTECTED] writes:
  It seems to me that Python always add intervening spaces between data
  elements when writing to a file

 It's just the print statement that does that.

I doubt that. I tried one small file, I opened it using the
application I mentioned, the display said like data, NaN, data, NaN...

I even went further to opening the file using notepad, and did a
search-and-replace for space characters. The result was what I
desired: data,data,data...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cost of Queue.put

2008-03-18 Thread Gabriel Genellina
On 18 mar, 01:13, James [EMAIL PROTECTED] wrote:

 Basically, what I need is a multi-process safe persistent quick queue.
 The arrangement I had was a simple XML-RPC service running on the web
 server which the various web server threads POST the relevant search
 engine updates to. These updates were added to a persistent queue
 built on top of Queue.Queue and cPickle, and there was a separate
 thread in the XML-RPC server actually adding the updates to the search
 engine.

 However, the CPU consumption of the XML-RPC server seems to grow
 pretty much linearly with the length of the persistent queue. Isn't
 Queue.put O(1)?

Maybe, but pickle.dumps is very likely O(n) and dominates. Why don't
you use a database? Just insert and delete records with each get and
put.

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


Re: ctypes in python failed to honor c_int

2008-03-18 Thread Jerry Fleming
Gabriel Genellina wrote:
 On 17 mar, 23:57, Jerry Fleming [EMAIL PROTECTED] wrote:
 
 I have a binary file written with c structures. Each record contains a
 null-terminated string followed by two 4-bytes integers. I wrote a small
 segment of python code to parse this file in this way:
 [coe]
 #!/usr/bin/python

 from ctypes import *

 class Entry(Structure):
 _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32)

 idx = open('x.idx', 'rb')
 str = idx.read(1000)
 obj = Entry(str)
 print obj.w
 print obj.s
 print obj.l
 [/code]
 where the field w is the string, and s and l are the integers. Problem
 is that, I can only get the strings, not the integers. Well, I did got
 integers, but they are all zeros. What should I do to get the real numbers?
 
 So the string has a variable length? For Hello you have
 'h','e','l','l','o', a zero byte, followed by the two integers? This
 is somewhat unusual for a C struct (in fact you can't declare it in
 C). Perhaps the string is actually a char[n] array with a declared
 maximum size?

Yes, it has a variable length. The C version of the structure is 
something like this:
[code]
struct entry {
 char *str,
 int start,
 int length
}
[/code]
And adding repr() would print something like this:
[code]
'(as) mad as a 
[EMAIL PROTECTED];\x00\x00\x00`.GIF\x00\x00\x00'
(as) mad as a hatter
0
0
[/code]
where the first line is the result of repr(). We can find that, after 
the null-terminated string '(as) mad as a hatter', there are two 
integers, 0 and 31 (0x1f). But python treat 31 as zero.

 
 Try printing repr(a_few_read_bytes) or a_few_read_bytes.encode(hex)
 to see the actual file contents.
 
 --
 Gabriel Genellina
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2.unquote() vs unicode

2008-03-18 Thread Gabriel Genellina
On 18 mar, 02:20, Maciej Bliziński [EMAIL PROTECTED] wrote:
 I've been hit by a urllib2.unquote() issue. Consider the following
 unit test:

 import unittest
 import urllib2

 class UnquoteUnitTest(unittest.TestCase):

    def setUp(self):
        self.utxt = u'%C4%99'
        self.stxt = '%C4%99'

    def testEq(self):
        self.assertEqual(
                self.utxt,
                self.stxt)

    def testStrEq(self):
        self.assertEqual(
                str(self.utxt),
                str(self.stxt))

    def testUnicodeEq(self):
        self.assertEqual(
                unicode(self.utxt),
                unicode(self.stxt))

    def testUnquote(self):
        self.assertEqual(
                urllib2.unquote(self.utxt),
                urllib2.unquote(self.stxt))

    def testUnquoteStr(self):
        self.assertEqual(
                urllib2.unquote(str(self.utxt)),
                urllib2.unquote(str(self.stxt)))

    def testUnquoteUnicode(self):
        self.assertEqual(
                urllib2.unquote(unicode(self.utxt)),
                urllib2.unquote(unicode(self.stxt)))

 if __name__ == '__main__':
    unittest.main()

 The three testEq*() tests positively confirm that the two are equal,
 they are the same, they are also the same if cast both to str or
 unicode. Tests with unquote() called with utxt and stxt cast into str
 or unicode are also successful. However...

 ...E..
 ==
 ERROR: testUnquote (__main__.UnquoteUnitTest)
 --
 Traceback (most recent call last):
  File unquote.py, line 28, in testUnquote
    urllib2.unquote(self.stxt))
  File /usr/lib/python2.4/unittest.py, line 332, in failUnlessEqual
    if not first == second:
 UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position
 0: ordinal not in range(128)

 --
 Ran 6 tests in 0.001s

 FAILED (errors=1)

 Why does this test fail while others are successful? Any ideas?

Both utxt and stxt consist exclusively of ASCII characters, so the
default ASCII encoding works fine.
When both are converted to unicode, or both are converted to string,
and then unquoted, the resulting objects are again both unicode or
both strings, and compare without problem (even if they can't be
represented in ASCII at this stage).
In testUnquote, after unquoting, you have non ASCII chars, both
string and unicode, and it fails to convert both to the same type to
compare them.

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


Re: About reading Python code

2008-03-18 Thread hellt
On 18 мар, 03:57, sturlamolden [EMAIL PROTECTED] wrote:
 On 17 Mar, 04:54, WaterWalk [EMAIL PROTECTED] wrote:

  So I'm curious how to read code effectively. I agree that python code
  is clear, but when it becomes long, reading it can still be a hard
  work.

 First, I recommend that you write readable code! Don't use Python as
 if you're entering the obfuscated C contest.

 Two particularly important points:

 * If you find yourself thinking this module is too long, that's
 probably what it is. Half a page of code per module is fine. Two pages
 of code per module can be too much.

 * Comments are always helpful to the reader.

 Second, I recommend getting a good IDE. E.g. pick one of:

 * Microsoft Visual Studio (commercial)
 * Eclipse with PyDev and CDT (free)
 * SPE (free)
 * ActiveState Komodo IDE (commercial)

under Microsoft Visual Studio do you mean IronPython instance?
-- 
http://mail.python.org/mailman/listinfo/python-list

Multiple Submits in HTML Forms - Cherrypy

2008-03-18 Thread Maurice LING
Hi,

Assuming that I have this code for Cherrypy 3

class Welcome:
 def index(self):
 return 
form action=btn_handler method=POST
input value=Add name=AddBtn type=submit
input value=Edit name=EditBtn type=submit
/form
 index.exposed = True

How should I write btn_handler so that it will perform different 
actions when different button is pressed?

Thanks in advance

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


Re: ctypes in python failed to honor c_int

2008-03-18 Thread Gabriel Genellina
On 18 mar, 04:12, Jerry Fleming [EMAIL PROTECTED] wrote:
 Gabriel Genellina wrote:
  On 17 mar, 23:57, Jerry Fleming [EMAIL PROTECTED] wrote:

  I have a binary file written with c structures. Each record contains a
  null-terminated string followed by two 4-bytes integers. I wrote a small
  segment of python code to parse this file in this way:
  [coe]
  #!/usr/bin/python

  from ctypes import *

  class Entry(Structure):
          _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32)

  idx = open('x.idx', 'rb')
  str = idx.read(1000)
  obj = Entry(str)
  print obj.w
  print obj.s
  print obj.l
  [/code]
  where the field w is the string, and s and l are the integers. Problem
  is that, I can only get the strings, not the integers. Well, I did got
  integers, but they are all zeros. What should I do to get the real numbers?

  So the string has a variable length? For Hello you have
  'h','e','l','l','o', a zero byte, followed by the two integers? This
  is somewhat unusual for a C struct (in fact you can't declare it in
  C). Perhaps the string is actually a char[n] array with a declared
  maximum size?

 Yes, it has a variable length. The C version of the structure is
 something like this:
 [code]
 struct entry {
      char *str,
      int start,
      int length}

 [/code]

But this doesn't match the file contents. There are no pointers in the
file.

 And adding repr() would print something like this:
 [code]
 '(as) mad as a
 [EMAIL PROTECTED];\x00\x00\x00`.GIF\­x00\x00\x00'
 (as) mad as a hatter
 0
 0
 [/code]
 where the first line is the result of repr(). We can find that, after
 the null-terminated string '(as) mad as a hatter', there are two
 integers, 0 and 31 (0x1f). But python treat 31 as zero.

Ah, but it doesn't treat 31 as zero. Entry(str) is the same as
Entry(w=str), that is, you are initializing the w attribute alone,
leaving the other two integers as 0.
I don't know how to use ctypes to read the structure (nor if it is
possible at all), I would read it normally with Python code and build
the struct afterwards (in case it is used to call any C code).

w, data = data.split('\x00', 1)
s, l = struct.unpack(ll, data[:8])
data= data[8:]

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


Re: Multiple Submits in HTML Forms - Cherrypy

2008-03-18 Thread Carsten Haese
On Tue, 2008-03-18 at 07:14 +, Maurice LING wrote:
 Hi,
 
 Assuming that I have this code for Cherrypy 3
 
 class Welcome:
  def index(self):
  return 
   form action=btn_handler method=POST
   input value=Add name=AddBtn type=submit
   input value=Edit name=EditBtn type=submit
   /form
  index.exposed = True
 
 How should I write btn_handler so that it will perform different 
 actions when different button is pressed?

Something like this would do it:

 def btn_handler(self, AddBtn=None, EditBtn=None):
 if AddBtn:
 return You pressed Add!
 if EditBtn:
 return You pressed Edit!

Alternatively you could use a kwargs dictionary and test it for the
presence of the AddBtn or EditBtn keys.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


please click here

2008-03-18 Thread [EMAIL PROTECTED]
 please click here


http://profile_myprofile.blogspot.com

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


Re: Why doesn't xmlrpclib.dumps just dump an empty value instead of nil/?

2008-03-18 Thread Marc 'BlackJack' Rintsch
On Mon, 17 Mar 2008 17:41:23 +0100, martin f krafft wrote:

 also sprach martin f krafft [EMAIL PROTECTED] [2008.03.16.1421 +0100]:
 Why doesn't it just yield
 
   'params\nparam\nvalue//param\n/params\n'
 
 Or even just
 
   'params\nparam/\n/params\n'
 
 There's a difference between those two. The first one has an empty
 string value ('') while the second one pretty clearly says that
 there is a parameter but has no value.
 
 Why nil/?

Because there is a difference between no value and the NULL value!?

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


Extending C++ with Python scripting: twin objects or proxy objects?

2008-03-18 Thread jdetaeye

Hi,

I would like to use Python as a scripting language for a C++ framework
I am working on.

The most common approach for this seems to be a twin objects: the
python and the C++ object have the same lifespan and are always linked
to each other.
My initial thinking was to use a proxy approach instead: the python
object is only a temporary proxy object with a pointer to the real C++
object. The C++ object would live much longer than the proxy.

Is the proxy approach a valid alternative?  I can't imagine it hasn't
been done before...
I am interested in hearing your experiences with it...

Currently I see the following + and -:
+ Easier for the C++ code (ie less changes, less coupling, no gc-
issues)
- Extending the framework through subclasses in Python is much harder
Anything else?

Regards,

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


Re: writing to a binary file without intervening spaces

2008-03-18 Thread Paul Rubin
Larry [EMAIL PROTECTED] writes:
 I even went further to opening the file using notepad, and did a
 search-and-replace for space characters. The result was what I
 desired: data,data,data...

In Windows, you also have to make sure to open binary files in binary
mode.
-- 
http://mail.python.org/mailman/listinfo/python-list


http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom

2008-03-18 Thread Gabriel Rossetti
Hello,

I am reading core python python programming and it talks about using the 
idiom
described on 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 .

I'm using python 2.5.1 and if I try :

class MyClass(object):
def __init__(self):
self._foo = foo
self._bar = bar

@property
def foo():
doc = property foo's doc string
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
def fdel(self):
del self._foo
return locals()  # credit: David Niergarth

@property
def bar():
doc = bar is readonly
def fget(self):
return self._bar
return locals()

like suggested in the book (the decorator usage) I get this :

a=MyClass()
a.foo
   Traceback (most recent call last):
 File stdin, line 1, in module
   TypeError: foo() takes no arguments (1 given)

but if I write it just like on the web page (without the decorator, using x = 
property(**x()) instead) it works :

a = MyClass()
a.foo
   'foo'

does anyone have an idea as of why this is happening?

Thanks,
Gabriel




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


Re: Multiple Submits in HTML Forms - Cherrypy

2008-03-18 Thread Maurice LING
Carsten Haese wrote:
 On Tue, 2008-03-18 at 07:14 +, Maurice LING wrote:
 Hi,

 Assuming that I have this code for Cherrypy 3

 class Welcome:
  def index(self):
  return 
  form action=btn_handler method=POST
  input value=Add name=AddBtn type=submit
  input value=Edit name=EditBtn type=submit
  /form
  index.exposed = True

 How should I write btn_handler so that it will perform different 
 actions when different button is pressed?
 
 Something like this would do it:
 
  def btn_handler(self, AddBtn=None, EditBtn=None):
  if AddBtn:
  return You pressed Add!
  if EditBtn:
  return You pressed Edit!
 
 Alternatively you could use a kwargs dictionary and test it for the
 presence of the AddBtn or EditBtn keys.
 

Thank you Carsten
maurice
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom

2008-03-18 Thread Carsten Haese
On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote:
 Hello,
 
 I am reading core python python programming and it talks about using the 
 idiom
 described on 
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 .
 
 I'm using python 2.5.1 and if I try :
 
 class MyClass(object):
 def __init__(self):
 self._foo = foo
 self._bar = bar
 
 @property
 def foo():
 doc = property foo's doc string
 def fget(self):
 return self._foo
 def fset(self, value):
 self._foo = value
 def fdel(self):
 del self._foo
 return locals()  # credit: David Niergarth
 
 @property
 def bar():
 doc = bar is readonly
 def fget(self):
 return self._bar
 return locals()
 
 like suggested in the book (the decorator usage) I get this :
 
 a=MyClass()
 a.foo
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: foo() takes no arguments (1 given)
 
 but if I write it just like on the web page (without the decorator, using x 
 = property(**x()) instead) it works :
 
 a = MyClass()
 a.foo
'foo'
 
 does anyone have an idea as of why this is happening?

You're mixing two completely different approaches of building a
property. If that code is actually in the book like that, that's a typo
that you should mention to the author.

The @property decorator can only be used to turn a single getter
function into a read-only attribute, because this:

   @property
   def foo(...):
  ...

is the same as this:

   def foo(...):
  ...
   foo = property(foo)

and calling property() with one argument builds a property that has just
a getter function that is the single argument you're giving it.

The recipe you're referring to uses a magical function that returns a
dictionary of getter function, setter function, deleter function, and
docstring, with suitable key names so that the dictionary can be passed
as a keyword argument dictionary into the property() constructor.
However, that requires the magical foo=property(**foo()) invocation, not
the regular decorator invocation foo=property(foo).

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Regarding coding style

2008-03-18 Thread Marc 'BlackJack' Rintsch
On Mon, 17 Mar 2008 12:51:14 -0700, [EMAIL PROTECTED] wrote:

 On Mar 17, 12:15 pm, rockingred [EMAIL PROTECTED] wrote:
 On Mar 10, 11:30 am, [EMAIL PROTECTED] [EMAIL PROTECTED]

 Unfortunately, no free VC system existed for the language in which I
 was programming
 
 Explain?  VC isn't language-specific.

It is.  It depends usually on the fact that there are individual files. 
Preferably text files if you want automagic merging of different changes. 
Now think of languages that are tightly coupled with their IDE storing
only binary tokenized files instead of plain text or even one big binary
file that contains all sources and resources of the project.

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


Decode email subjects into unicode

2008-03-18 Thread Laszlo Nagy
Hi All,

'm in trouble with decoding email subjects.  Here are some examples:

 =?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?=
 [Fwd: re:Flags Of The World, Us States, And Military]
 =?ISO-8859-2?Q?=E9rdekes?=
 =?UTF-8?B?aGliw6Fr?=


I know that =?UTF-8?B means UTF-8 + base64 encoding, but I wonder if 
there is a standard method in the email package to decode these 
subjects? I do not want to re-invent the weel.

Thanks,

   Laszlo

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


Re: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom

2008-03-18 Thread Gabriel Rossetti
Carsten Haese wrote:
 On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote:
   
 Hello,

 I am reading core python python programming and it talks about using the 
 idiom
 described on 
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 .

 I'm using python 2.5.1 and if I try :

 class MyClass(object):
 def __init__(self):
 self._foo = foo
 self._bar = bar

 @property
 def foo():
 doc = property foo's doc string
 def fget(self):
 return self._foo
 def fset(self, value):
 self._foo = value
 def fdel(self):
 del self._foo
 return locals()  # credit: David Niergarth

 @property
 def bar():
 doc = bar is readonly
 def fget(self):
 return self._bar
 return locals()

 like suggested in the book (the decorator usage) I get this :

 a=MyClass()
 a.foo
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: foo() takes no arguments (1 given)

 but if I write it just like on the web page (without the decorator, using x 
 = property(**x()) instead) it works :

 a = MyClass()
 a.foo
'foo'

 does anyone have an idea as of why this is happening?
 

 You're mixing two completely different approaches of building a
 property. If that code is actually in the book like that, that's a typo
 that you should mention to the author.

 The @property decorator can only be used to turn a single getter
 function into a read-only attribute, because this:

@property
def foo(...):
   ...

 is the same as this:

def foo(...):
   ...
foo = property(foo)

 and calling property() with one argument builds a property that has just
 a getter function that is the single argument you're giving it.

 The recipe you're referring to uses a magical function that returns a
 dictionary of getter function, setter function, deleter function, and
 docstring, with suitable key names so that the dictionary can be passed
 as a keyword argument dictionary into the property() constructor.
 However, that requires the magical foo=property(**foo()) invocation, not
 the regular decorator invocation foo=property(foo).

 HTH,

   
Ah, ok, I'll send him an email then, thanks for the explanation!

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


finding items that occur more than once in a list

2008-03-18 Thread Simon Forman
Is there a more efficient way to do this?

def f(L):
'''Return a set of the items that occur more than once in L.'''
L = list(L)
for item in set(L):
L.remove(item)
return set(L)


| f([0, 0, 1, 1, 2, 2, 3])
set([0, 1, 2])



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


Re: Immutable and Mutable Types

2008-03-18 Thread Duncan Booth
Stargaming [EMAIL PROTECTED] wrote:

 On Mon, 17 Mar 2008 16:03:19 +, Duncan Booth wrote:
 
 For the answer I actually want each asterisk substitutes for exactly one
 character.
 
 Played around a bit and found that one:
 
 Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20)
 [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2
 Type help, copyright, credits or license for more information.
 a = 1
 b = 1//1
 if a is b: print('yes!')
 ...
 b
 1
 type(b)
type 'int'

I've had a look to see why this happens: long division (and in Python 3 all 
integers are longs) allocates a new long to hold the result of the division 
so it will never use one of the preallocated 'small int' values.

That makes sense so far as it goes, but I'm slightly suprised if it isn't 
worth an extra check somewhere for numerator fitting in a machine int and 
shortcutting the long division.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comunicate processes with python

2008-03-18 Thread Adrián Bravo Navarro
Hi,

Does the absence of answers mean that the unique way to let the console
invoke daemon functions is trough dbus or sockets? I wonder if python
provides any other mechanism to get this.

Thanks
Adrian

2008/3/17, Adrián Bravo Navarro [EMAIL PROTECTED]:

 Hi,

 let me introduce ourselves first. We are a smallish group of students
 working on a open source snapshot/backup system (www.hdlorean.com or
 http://launchpad.net/hdlorean). We are using python for almost all of the
 code and for all of us this is the first python project we develop. At this
 point I must say that we are really happy with python, as it is a fast
 learning and easy language.

 Now I've just bored most of you, I would like to make a question to the
 list. Let me portray the scenario:

 We have a daemon (hdloreand) running. We also have a console so you can
 send commands to the daemon and retrieve some info. At this moment, that
 console is connecting to the daemon via Dbus. We would like to avoid this,
 because it will solve some collateral problemas as well as will guarantee
 that the comunication will work when no X server and no dbus session is
 running.

 Is there any simple way to achieve this goal? We've been thinking of
 sockets but Im not conviced at all with that.

 Thanks
 Adrian

 PS: Im sorry for my english.

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

Re: Convert binary file

2008-03-18 Thread Tim Golden
Diez B. Roggisch wrote:
 Vamp4L schrieb:
 Hello,
   Specifically, I'm trying to convert the Internet Explorer history
 file (index.dat) into a readable format.  Anyone done something
 similar or know of any functions that may help with such a task?  I'm
 not sure exactly what kind of file the index.dat is, it is some kind
 of binary file.  I have tried some of the binascii functions (http://
 docs.python.org/lib/module-binascii.html) without any luck.
  Thanks
 
 You have to have a definition of the format or reverse engineer it. If 
 you have done that, you can use the module struct.
 
 But there is no generic way to infer how a binary format is built.

Well, there is some info here:

   http://answers.google.com/answers/threadview?id=115849

on the subject. But, honestly, doing any kind of direct messing
with opaque file formats (Microsoft's or anyone else's) is pretty
much asking for trouble.

Without my ever having tried this, it looks as though
a combination of comtypes and IID_IUrlhistoryStg2 [2] might
work. If I get the time later I'll try to knock sthg
together. (Unless someone else pops in first!)

TJG

[1] http://pypi.python.org/pypi/comtypes
[2] http://support.microsoft.com/kb/897169
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decode email subjects into unicode

2008-03-18 Thread Laszlo Nagy
Sorry, meanwhile i found that email.Headers.decode_header can be used 
to convert the subject into unicode:

 def decode_header(self,headervalue):
 val,encoding = decode_header(headervalue)[0]
 if encoding:
 return val.decode(encoding)
 else:
 return val

However, there are malformed emails and I have to put them into the 
database. What should I do with this:


Return-Path: [EMAIL PROTECTED]
X-Original-To: [EMAIL PROTECTED]
Delivered-To: [EMAIL PROTECTED]
Received: from 195.228.74.135 (unknown [122.46.173.89])
by shopzeus.com (Postfix) with SMTP id F1C071DD438;
Tue, 18 Mar 2008 05:43:27 -0400 (EDT)
Date: Tue, 18 Mar 2008 12:43:45 +0200
Message-ID: [EMAIL PROTECTED]
From: Euro Dice Casino [EMAIL PROTECTED]
To: [EMAIL PROTECTED]
Subject: With 2’500 Euro of Welcome Bonus you can’t miss the chance!
MIME-Version: 1.0
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: 7bit



There is no encoding given in the subject but it contains 0x92. When I 
try to insert this into the database, I get:

ProgrammingError: invalid byte sequence for encoding UTF8: 0x92

All right, this probably was a spam email and I should simply discard 
it. Probably the spammer used this special character in order to prevent 
mail filters detecting can't and 2500. But I guess there will be 
other important (ham) emails with bad encodings. How should I handle this?

Thanks,

Laszlo

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

detect current timezone set by kde

2008-03-18 Thread Pradnyesh Sawant
Hello,
can someone please tell me how can I programatically detect the timezone
information that has been set through kde?

basically, I have a small pyqt4 app which shows the current time. however
it shows me my system time (dunno where that is stored; basically it shows
me time in IST). however, I'm right now in hk and would like the app to
show me time in my current timezone (hong kong). Any guidelines how may I
go about doing this?

thanks a lot in advance :-)
-- 
warm regards,
Pradnyesh Sawant
--
Believing everybody is dangerous; believing no one is dangerous...
--Abraham Lincoln


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Program source implemented in non-text storage (was: Regarding coding style)

2008-03-18 Thread Ben Finney
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] writes:

 [A general VCS] depends usually on the fact that there are
 individual files. Preferably text files if you want automagic
 merging of different changes.

Yes.

 Now think of languages that are tightly coupled with their IDE
 storing only binary tokenized files instead of plain text or even
 one big binary file that contains all sources and resources of the
 project.

Those issues have nothing to do with the language, and everything to
do with the language implementation.

Moreover, a brain-dead monstrosity as you describe would result in far
greater problems than merely the lack of decent version control
support. I think it's safe to leave such implementations to rot,
rather than stretching tools to acommodate them.

-- 
 \  “That's all very good in practice, but how does it work in |
  `\ *theory*?” —anonymous |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: finding items that occur more than once in a list

2008-03-18 Thread Chris
On Mar 18, 11:57 am, Simon Forman [EMAIL PROTECTED] wrote:
 Is there a more efficient way to do this?

 def f(L):
     '''Return a set of the items that occur more than once in L.'''
     L = list(L)
     for item in set(L):
         L.remove(item)
     return set(L)

 | f([0, 0, 1, 1, 2, 2, 3])
 set([0, 1, 2])

def f(L):
D = dict()
for item in L:
if item in D:
D[item] += 1
else:
D[item] = 1
return [i for i,j in D.items() if j  1]

That would be my way to do it, would need to test it via several
thousand iterations to see which one is most efficient though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom

2008-03-18 Thread Gabriel Rossetti
Carsten Haese wrote:
 On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote:
   
 Hello,

 I am reading core python python programming and it talks about using the 
 idiom
 described on 
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 .

 I'm using python 2.5.1 and if I try :

 class MyClass(object):
 def __init__(self):
 self._foo = foo
 self._bar = bar

 @property
 def foo():
 doc = property foo's doc string
 def fget(self):
 return self._foo
 def fset(self, value):
 self._foo = value
 def fdel(self):
 del self._foo
 return locals()  # credit: David Niergarth

 @property
 def bar():
 doc = bar is readonly
 def fget(self):
 return self._bar
 return locals()

 like suggested in the book (the decorator usage) I get this :

 a=MyClass()
 a.foo
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: foo() takes no arguments (1 given)

 but if I write it just like on the web page (without the decorator, using x 
 = property(**x()) instead) it works :

 a = MyClass()
 a.foo
'foo'

 does anyone have an idea as of why this is happening?
 

 You're mixing two completely different approaches of building a
 property. If that code is actually in the book like that, that's a typo
 that you should mention to the author.

 The @property decorator can only be used to turn a single getter
 function into a read-only attribute, because this:

@property
def foo(...):
   ...

 is the same as this:

def foo(...):
   ...
foo = property(foo)

 and calling property() with one argument builds a property that has just
 a getter function that is the single argument you're giving it.

 The recipe you're referring to uses a magical function that returns a
 dictionary of getter function, setter function, deleter function, and
 docstring, with suitable key names so that the dictionary can be passed
 as a keyword argument dictionary into the property() constructor.
 However, that requires the magical foo=property(**foo()) invocation, not
 the regular decorator invocation foo=property(foo).

 HTH,

   
I was able to get it t work with the decorator by doing this :

def MyProperty(fcn):
return property(**fcn())

and using it like this :

class MyClass(object):
   def __init__(self):
   self._foo = foo
   self._bar = bar

   @MyProperty
   def foo():
   doc = property foo's doc string
   def fget(self):
   return self._foo
   def fset(self, value):
   self._foo = value
   def fdel(self):
   del self._foo
   return locals()  # credit: David Niergarth

   @MyProperty
   def bar():
   doc = bar is readonly
   def fget(self):
   return self._bar
   return locals()   

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


Re: stdout custom

2008-03-18 Thread castironpi
On Mar 17, 8:16 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
 On 17 mar, 19:43, [EMAIL PROTECTED] wrote:

  Can I allocate a second console window, so I can place certain output
  to that directly, and leave the original streams alone?  I tried some
  things in subprocess (Py 3a3 /WinXP) but they failed.  I don't know if
  it's supposed to be possible though, so I didn't press very hard or
  keep the code.  If it is, I can go repro where it went south.  Is it?

 Have you tried using the creationflags argument to subprocess.Popen?
 Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation
 for CreateProcess 
 athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx
 (Note that a process can be attached at most to one console)

 If your goal is to output some debug information, try using
 OutputDebugString + the DebugView utility fromwww.sysinternals.com

One console per process is fine, but I tried using 'cmd.exe',
'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32)
as separate processes.  The sign is the console window splashes up and
vanishes right away.

 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdout= subprocess.P
IPE, creationflags= subprocess.CREATE_NEW_CONSOLE )
 p.poll()
0
 p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe', stdout= subprocess.PI
PE, creationflags= subprocess.CREATE_NEW_CONSOLE )
 p.poll()
0
 p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe /K', stdout= subprocess
.PIPE, creationflags= subprocess.CREATE_NEW_CONSOLE )
 p.poll()
0
 f= open( 'temp.txt', 'a' )
 p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe /K', stdout= f, creatio
nflags= subprocess.CREATE_NEW_CONSOLE )
 p.poll()
0

Couple other symptoms.

 f.write( b'abc' )
'f.write' is not recognized as an internal or external command,
operable program or batch file.


f.write( b'abc' )
Traceback (most recent call last):
  File stdin, line 1, in module
  File C:\Programs\Python\lib\io.py, line 1240, in write
s.__class__.__name__)
TypeError: can't write bytes to text stream

f.write( 'abc' )
3


 ^Z



 ^Z
^Z



5000
09871234


 f.write('2'*2000)
2000
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 f= os.fdopen( q[0], 'a' )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 f.read()
Traceback (most recent call last):
  File stdin, line 1, in module
  File C:\Programs\Python\lib\io.py, line 1378, in read
res += decoder.decode(self.buffer.read(), True)
  File C:\Programs\Python\lib\io.py, line 564, in read
self._unsupported(read)
  File C:\Programs\Python\lib\io.py, line 240, in _unsupported
(self.__class__.__name__, name))
io.UnsupportedOperation: BufferedWriter.read() not supported
 f.read(1)
Traceback (most recent call last):
  File stdin, line 1, in module
  File C:\Programs\Python\lib\io.py, line 1384, in read
readahead, pending = self._read_chunk()
  File C:\Programs\Python\lib\io.py, line 1277, in _read_chunk
readahead = self.buffer.read1(self._CHUNK_SIZE)
AttributeError: 'BufferedWriter' object has no attribute 'read1'
 f.write()
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: write() takes exactly 2 positional arguments (1 given)
 f.write('2')
1
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags= 16 )
 p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl
ags=0 )






-

Writing my own process is an option.  I did not try sysinternals yet.
-- 
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2008-03-18 Thread Tom Stambaugh
Duncan Booth [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 I've also just spent a while getting simplejson 1.7.4 to install on a 
 (non-
 windows) system without a C compiler.

 The trick is to unzip the tar file and then before you try to install it
 delete everything in simplejson.egg-info. Then 'setup.py install' will run
 to completion and while it warns about 'speedups are not enabled.' it
 doesn't take it as fatal error.

 Without this step it preserves the reference to native_libs.txt in
 SOURCES.txt even though the native_libs.txt file itself gets deleted.


I had no trouble getting it to install without the speedups -- but the 
primary reason I upgraded was to take advantage of the speedups!



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


RE: Decode email subjects into unicode

2008-03-18 Thread Ryan Ginstrom
 On Behalf Of Laszlo Nagy
  =?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?=
  [Fwd: re:Flags Of The World, Us States, And Military] 
  =?ISO-8859-2?Q?=E9rdekes?= =?UTF-8?B?aGliw6Fr?=

Try this code:

from email.header import decode_header

def getheader(header_text, default=ascii):
Decode the specified header

headers = decode_header(header_text)
header_sections = [unicode(text, charset or default)
   for text, charset in headers]
return u.join(header_sections)

I get the following output for your strings:

Быстровыполнимо и малозатратно
érdekeshibák

Regards,
Ryan Ginstrom

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

Get actual call signature?

2008-03-18 Thread Jarek Zgoda
Say, I have a function defined as:

def fun(arg_one, arg_two='x', arg_three=None):
pass

Is there any way to get actual arguments that will be effectively used
when I call this function in various ways, like:

fun(5) = [5, 'x', None]
fun(5, arg_three=['a', 'b']) = [5, 'x', ['a', 'b']]
fun(5, 'something') = [5, 'something', None]

(et caetera, using all possible mixes of positional, keyword and default
arguments)

I'd like to wrap function definition with a decorator that intercepts
not only passed arguments, but also defaults that will be actually used
in execution.

If this sounds not feasible (or is simply impossible), I'll happily
throw this idea and look for another one. ;)

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

We read Knuth so you don't have to. (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anomaly in time.clock()

2008-03-18 Thread Godzilla
Thanks Roel. If there is a way to pass in the PRESERVE_PRECISION
constant in the python time.clock library, that would be great. But
I'm afraid it's not possible. I think I will change away from using
time.clock() from now on... seems too edgy to me.

Thank you for sharing your experience with me nonetheless.

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


Re: detect current timezone set by kde

2008-03-18 Thread Gerald Klix
I suggest to change /etc/timezone by invoking sudo tzselect.

HTH,
Gerald

Pradnyesh Sawant schrieb:
 Hello,
 can someone please tell me how can I programatically detect the timezone
 information that has been set through kde?
 
 basically, I have a small pyqt4 app which shows the current time. however
 it shows me my system time (dunno where that is stored; basically it shows
 me time in IST). however, I'm right now in hk and would like the app to
 show me time in my current timezone (hong kong). Any guidelines how may I
 go about doing this?
 
 thanks a lot in advance :-)
 

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


Re: win32: emulating select() on pipes

2008-03-18 Thread Bryan Olson
gangesmaster wrote:
 i'm trying to figure out if a pipe on win32 has data for me to read.
[...]

 does anyone know of a better way to tell if data is available on a
 pipe?
 something that blocks until data is available or the timeout is
 elapsed,

In Win32 WaitForMultipleObjects and WaitForMultipleObjectsEx do
that, for up to 64 objects. In the Hammond Win32 extension
package, they're exported by win32event.

If 64 pipes in one call isn't enough, there are completion ports.
CreateIoCompletionPort is in win32file.

A third way in Win32 is WriteFileEx and a completion routine,
but it looks like the extension module doesn't support it.

I have not used the functions from the Hammond package, and
I notice the doc strings are None. You can probably figure
the wrappers out by reading the Microsoft documentation and
trying stuff. And of then there's the source.

If you put together a simple working example, I hope you'll
post it.


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


Re: finding items that occur more than once in a list

2008-03-18 Thread Paul Rubin
Simon Forman [EMAIL PROTECTED] writes:
 Is there a more efficient way to do this?

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-18 Thread Bryan Olson
Simon Forman wrote:
 Is there a more efficient way to do this?
 
 def f(L):
 '''Return a set of the items that occur more than once in L.'''
 L = list(L)
 for item in set(L):
 L.remove(item)
 return set(L)

That's neat, but quadratic time because list.remove() requires
a linear search. We can make an efficient variant by using
remove on a set rather than a list:

 def multiples(lst):
 singles = set(lst)
 mults = set()
 for x in lst:
 if x in singles:
 singles.remove(x)
 else:
 mults.add(x)
 return mults

Though probably better is:

 def multiples(lst):
 seen = set()
 mults = set()
 for x in lst:
 if x in seen:
 mults.add(x)
 else:
 seen.add(x)
 return mults


I've typically used dicts for such things, as in:

 def multiples(lst):
 h = {}
 for x in lst:
 h[x] = h.get(x, 0) + 1
 return set([x for x in h if h[x]  1])


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


Re: Python 3 and PEP238 division

2008-03-18 Thread Ninereeds
On Mar 17, 7:26 pm, Terry Reedy [EMAIL PROTECTED] wrote:
 Ninereeds [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]
 | Is the PEP238 change to division going into Python 3 as planned?

 IDLE 3.0a3 1/2

 0.5

 | I realise that the new integer division semantics have been available
 | in from __future__ for quite a few years now, but a warning might be
 | appropriate now that Python 3 is in alpha.

 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion
 program

The tools can work out the *intent* of any particular division
operator? Can work out whether the result should be integer or float,
independent of any particular set of arguments? Seems unlikely.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-18 Thread Ninereeds

Just to throw in one more alternative, if you sort your list, you only
need to test adjacent items for equality rather than needing a search
for each unique item found. You should get O(n log n) rather than
O(n^2), since the performance bottleneck is now the sorting rather
than the searching for duplicates. Also, since the sort method is
built into the list, sorting performance should be very good.

The dictionary version Chris suggests (and the essentially equivalent
set-based approach) is doing essentially the same thing in a way, but
using hashing rather than ordering to organise the list and spot
duplicates. This is *not* O(n) due to the rate of collisions
increasing as the hash table fills. If collisions are handled by
building a linked list for each hash table entry, the performance
overall is still O(n^2) since (for large amounts of data) there is
still a linear search on each collision. If collisions are handled by
building binary trees, the performance is back to O(n log n). That is,
for large enough datasets, the performance of hash tables is basically
the performance of the collision handling data structure (ignoring
scaling constants).

I suspect Python handles collisions using linked lists, since using
trees would require that all dictionary keys support ordered
comparisons. Using a dictionary or set to eliminate duplicates
therefore gives O(n^2) performance.

That said, hash tables have very good scaling constants to their
performance, so the dictionary technique will be a very good performer
in general. And if the lists are reasonably small the performance will
often seem like O(n) in practice.

The sort-then-filter approach should still be competitive, but of
course it requires that the contents of the list can be ordered
consistently. An inappropriate hash function can similarly cause
problems for the dictionary approach, causing that theoretical O(n^2)
performance to become apparent very quickly. This is probably one
reason why the cookbook recipe recommends an O(n^2) searching-based
approach.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 and PEP238 division

2008-03-18 Thread Marc 'BlackJack' Rintsch
On Tue, 18 Mar 2008 04:47:49 -0700, Ninereeds wrote:

 On Mar 17, 7:26 pm, Terry Reedy [EMAIL PROTECTED] wrote:
 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion
 program
 
 The tools can work out the *intent* of any particular division
 operator? Can work out whether the result should be integer or float,
 independent of any particular set of arguments? Seems unlikely.

The interpreter can at least print out warnings when a normal division
operator is called with two `int`\s at runtime.

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


automatically doing some cleaning-up by the process when the systems shuts down

2008-03-18 Thread bharath venkatesh
hi ..
  my programs runs as daemon and it does some logging .. when system
shuts down .. which may be done manually . i  want my process  do some
cleaning up automatically such as writing in to the log file when  the
process terminats   before the system shuts down
 thanks
-- 
http://mail.python.org/mailman/listinfo/python-list

Merging a patch/diff generated by difflib?

2008-03-18 Thread erikcw
Hi,

I'm trying to create an undo/redo feature for a webapp I'm working on
(django based).  I'd like to have an undo/redo function.

My first thought was to use the difflib to generate a diff to serve as
the backup, and then if someone wants to undo their operation, the
diff could just be merged/patched with the current text.

However, I've not be able to find a patch library.  Are there any
libraries that will handle merging the diff back into the text?

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


Re: how to create instances of classes without calling the constructor?

2008-03-18 Thread Steven D'Aprano
On Tue, 18 Mar 2008 01:08:45 +0100, Dominik Jain wrote:

 Hi!
 
 Does anyone know how an instance of a (new-style) class can be created
 without having to call the constructor (and providing the arguments it
 requires)? With old-style classes, this was possible using new.instance.
 Surely there must be a simple way to do this with new-style classes, too
 -- or else how does pickle manage?

I don't think you can create an instance without calling __new__. (At 
least not without all sorts of metaclass tricks.) Creating the instance 
is what __new__ does.

But you can create a new instance without calling the initialiser 
__init__. Here's a variation on a recipe from Alex Martelli:


class Spam(object):
def __init__(self, *args):
print spam spam spam spam
self.args = args


def empty_instance(cls):
class Empty(cls):
def __init__(self): pass
x = Empty()
x.__class__ = cls
return x



 # Create a Spam instance the regular way
... a = Spam(args)
spam spam spam spam
 # And a Spam instance the unusual way
... b = empty_instance(Spam)
 a.args
('args',)
 b.args
Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'Spam' object has no attribute 'args'



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


Re: Can't get bsddb working on Solaris 8

2008-03-18 Thread partofthething
I fixed it! I had omitted the cascade of exceptions, but the previous
one to the one shown is:

File /usr/local/lib/python2.5/dbhash.py, line 5, in module
import bsddb

So I just went into dbhash.py and changed line 5 to import bsddb3 as
bsddb. Then everything started working as planned. Excellent! But
definitely a hack.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdout custom

2008-03-18 Thread Tim Golden
[EMAIL PROTECTED] wrote:
 Can I allocate a second console window, so I can place certain output
 to that directly, and leave the original streams alone?  

I've rather lost track of what you're trying to do, but I would
second Gabriel's suggestion of the standard Windows method of
debug output: using OutputDebugString. There's an example here:

http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugString.html

and it shouldn't be too hard to wrap it in a file-like
object for stderr-substitution use, say.

Obviously there are 1,001 other ways of doing IPC but since this
one's ready-made you might as well use it. You can distinguish
between different processes' outputs by virtue of the PID which
is the first item on the mmap.

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


Re: Pycon disappointment

2008-03-18 Thread John DeRosa
On Mon, 17 Mar 2008 14:36:29 -0500, J. Clifford Dyer
[EMAIL PROTECTED] wrote:

Note to speakers:  do not say

   x, y = tee(foo)

say

   from itertools import tee
   x, y = tee(foo)

or better (for pedagogical purposes)

   import itertools
   x, y = itertools.tee(foo)


I was scratching my head over tee() also, in the session where I heard
it.  Were you in the iterators II session also?  I've used itertools
a bit, but never tee(), and so when I thumbed through my copy of PER I
thought, ahh, I've skimmed over but never registered the importance of
that little bugger before...  That was one of the more interesting
sessions to me.

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


Re: About reading Python code

2008-03-18 Thread sturlamolden
On 18 Mar, 08:00, hellt [EMAIL PROTECTED] wrote:

 under Microsoft Visual Studio do you mean IronPython instance?

AFAIK, with the latest VS 2008 you can develop for CPython and
IronPython.

http://blogs.msdn.com/haibo_luo/archive/2007/10/16/5482940.aspx



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


Re: Interesting math problem

2008-03-18 Thread sturlamolden
On 18 Mar, 00:58, Jeff Schwab [EMAIL PROTECTED] wrote:

 def make_slope(distance, parts):
  if parts == 0:
  return []

  q, r = divmod(distance, parts)

  if r and parts % r:
  q += 1

  return [q] + make_slope(distance - q, parts - 1)

Beautiful. If Python could optimize tail recursion, it would even run
fast.




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


Problems building zlib module on RHEL

2008-03-18 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
I can't seem to get the zlib module to build on an RHEL box.

I did the following:
1) Download zlib 1.2.3
2) configure;make;make install
3) Download python 2.5.2
4) configure;make;make install
5)  import zlib = ImportError: No module named zlib

In the make install step for python, I notice there are the following
errors:

building 'zlib' extension
gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/
Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
lib.linux-x86_64-2.5/zlib.so
/usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32
against `a local symbol' can not be used when making a shared object;
recompile with -fPIC
/usr/local/lib/libz.a: could not read symbols: Bad value
collect2: ld returned 1 exit status

Does anyone have any hints on how to get around this?

system info:
kernel : 2.6.9-67.0.1.ELsmp
gcc : 3.4.6

Thanks,

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


Re: PyCon video editing

2008-03-18 Thread amk
On Mar 17, 10:00 pm, dundeemt [EMAIL PROTECTED] wrote:
 Anyone know who is in charge of this?  I'd like to help out if I
 could.

I am, but haven't set anything up yet, such as a mailing list or a
host for the video.
I'll update the wiki page http://wiki.python.org/moin/PyConRecordingBof
with news/further developments (you can create a wiki account and
follow the envelope icon at the upper right
to be notified of changes via e-mail).

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


Re: finding items that occur more than once in a list

2008-03-18 Thread Hrvoje Niksic
Ninereeds [EMAIL PROTECTED] writes:

 The dictionary version Chris suggests (and the essentially
 equivalent set-based approach) is doing essentially the same thing
 in a way, but using hashing rather than ordering to organise the
 list and spot duplicates. This is *not* O(n) due to the rate of
 collisions increasing as the hash table fills. If collisions are
 handled by building a linked list for each hash table entry, the
 performance overall is still O(n^2)

This doesn't apply to Python, which implements dict storage as an
open-addressed table and automatically (and exponentially) grows the
table when the number of entries approaches 2/3 of the table size.
Assuming a good hash function, filling the dict should yield amortized
constant time for individual additions.

 I suspect Python handles collisions using linked lists,

Why suspect, it's trivial to check.  dictobject.c says:

The basic lookup function used by all operations.
This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Open addressing is preferred over chaining since the link overhead for
chaining would be substantial (100% with typical malloc overhead).
-- 
http://mail.python.org/mailman/listinfo/python-list


Need to force SpamBayes to run.

2008-03-18 Thread Andoni
Hi all,

I realise this is not the SpamBayes list but you could grow old
waiting for that so trying here.

We are using SpamBayes to filter messages coming in to a mailbox. It
misses some messages with errors like what's below. When this happens
we can go in and click Filter Messages and it runs no problem.

What I would like to be able to do is to have an hourly batch-job that
runs that same process for me. I don't see anything in the file system
that would allow me to run a command-line call that executes Filter
Messages.

Can anybody help?
Thanks in advance,
Andoni OConchubhair.


pythoncom error: Python error invoking COM method.

Traceback (most recent call last):
  File win32com\server\policy.pyc, line 283, in _Invoke_
  File win32com\server\policy.pyc, line 288, in _invoke_
  File win32com\server\policy.pyc, line 647, in _invokeex_
  File win32com\server\policy.pyc, line 581, in _invokeex_
  File addin.pyc, line 390, in OnItemAdd
  File msgstore.pyc, line 365, in GetMessage
msgstore.NotFoundException: NotFoundException: Exception 0x8004010f
(MAPI_E_NOT_FOUND): OLE error 0x8004010f
pythoncom error: Python error invoking COM method.

Traceback (most recent call last):
  File win32com\server\policy.pyc, line 283, in _Invoke_
  File win32com\server\policy.pyc, line 288, in _invoke_
  File win32com\server\policy.pyc, line 647, in _invokeex_
  File win32com\server\policy.pyc, line 581, in _invokeex_
  File addin.pyc, line 390, in OnItemAdd
  File msgstore.pyc, line 365, in GetMessage
msgstore.NotFoundException: NotFoundException: Exception 0x8004010f
(MAPI_E_NOT_FOUND): OLE error 0x8004010f
pythoncom error: Python error invoking COM method.

Traceback (most recent call last):
  File win32com\server\policy.pyc, line 283, in _Invoke_
  File win32com\server\policy.pyc, line 288, in _invoke_
  File win32com\server\policy.pyc, line 647, in _invokeex_
  File win32com\server\policy.pyc, line 581, in _invokeex_
  File addin.pyc, line 390, in OnItemAdd
  File msgstore.pyc, line 365, in GetMessage
msgstore.NotFoundException: NotFoundException: Exception 0x8004010f
(MAPI_E_NOT_FOUND): OLE error 0x8004010f
pythoncom error: Python error invoking COM method.

Traceback (most recent call last):
  File win32com\server\policy.pyc, line 283, in _Invoke_
  File win32com\server\policy.pyc, line 288, in _invoke_
  File win32com\server\policy.pyc, line 647, in _invokeex_
  File win32com\server\policy.pyc, line 581, in _invokeex_
  File addin.pyc, line 390, in OnItemAdd
  File msgstore.pyc, line 365, in GetMessage
msgstore.NotFoundException: NotFoundException: Exception 0x8004010f
(MAPI_E_NOT_FOUND): OLE error 0x8004010f
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-18 Thread Ninereeds

Hrvoje Niksic wrote:

 This doesn't apply to Python, which implements dict storage as an
 open-addressed table and automatically (and exponentially) grows the
 table when the number of entries approaches 2/3 of the table size.
 Assuming a good hash function, filling the dict should yield amortized
 constant time for individual additions.

OK. I obviously need to look up open-addressed tables. I thought this
was just, in effect, implicit linked listing - ie it still needs a
linear search to handle collisions, it just avoids the need for
explicitly stored link fields. Perhaps I'm mistaken.

As for the growth pattern, each time you grow the table you have to
redistribute all the items previously inserted to new locations.
Resizes would get rarer as more items are added due to the exponential
growth, but every table resize would take longer too since there are
more items to move. Inserting n items still intuitively looks like
O(n^2) to me.

That said, it does remind me of that old exponential realloc trick for
array resizing. Same thing, I suppose, since a hash table is basically
an array. Maybe my math intuition is just wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interesting math problem

2008-03-18 Thread Marc Christiansen
sturlamolden [EMAIL PROTECTED] wrote:
 On 18 Mar, 00:58, Jeff Schwab [EMAIL PROTECTED] wrote:
 
 def make_slope(distance, parts):
  if parts == 0:
  return []

  q, r = divmod(distance, parts)

  if r and parts % r:
  q += 1

  return [q] + make_slope(distance - q, parts - 1)
 
 Beautiful. If Python could optimize tail recursion, it would even run
 fast.

This was my first thought, too. But tailcall optimisation wouldn't help
here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets
executed after the recursion. 

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


Need Help Starting Out

2008-03-18 Thread jmDesktop
Hi, I would like to start using Python, but am unsure where to begin.
I know how to look up a tutorial and learn the language, but not what
all technologies to use.  I saw references to plain Python, Django,
and other things.

I want to use it for web building with database access.  What do I use
for that?  Does it matter what I use on the client side (mootools, or
whatever)?

My rational for using Python is because I am hoping it will allow me
to better understand other python programs in other areas, not just
web.  I have used other languages for web apps for several years.
Truth is that I always wanted to learn Python and have heard it was a
good thing to know.

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


lock access to serial port

2008-03-18 Thread [EMAIL PROTECTED]
hello group,

how to get ttyS0 serial port for exclusive access? I have a python
script that uses this device with AT commands. I need that two
instances can call simultaneosuly this python script but only one of
them gets the device. I tried fcntl.flock, it was just ignored, put
writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not
know what are appropriate arguments), googled half a day for various
phrases, error messages etcwithout success.

please help,

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


Re: Problems building zlib module on RHEL

2008-03-18 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Mar 18, 8:42 am, mhearne808[insert-at-sign-here]gmail[insert-dot-
here]com [EMAIL PROTECTED] wrote:
 I can't seem to get the zlib module to build on an RHEL box.

 I did the following:
 1) Download zlib 1.2.3
 2) configure;make;make install
 3) Download python 2.5.2
 4) configure;make;make install
 5)  import zlib = ImportError: No module named zlib

 In the make install step for python, I notice there are the following
 errors:

 building 'zlib' extension
 gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/
 Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
 lib.linux-x86_64-2.5/zlib.so
 /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32
 against `a local symbol' can not be used when making a shared object;
 recompile with -fPIC
 /usr/local/lib/libz.a: could not read symbols: Bad value
 collect2: ld returned 1 exit status

 Does anyone have any hints on how to get around this?

 system info:
 kernel : 2.6.9-67.0.1.ELsmp
 gcc : 3.4.6

 Thanks,

 Mike

I figured it out, although it wasn't obvious... You have to compile
zlib as a shared library by running configure -s.
-- 
http://mail.python.org/mailman/listinfo/python-list


globals() using For Loop against Generator

2008-03-18 Thread cokofreedom
if __name__ == '__main__':

print Globals (For Loop):
try:
for i in globals():
print \t%s % i
except RuntimeError:
print Only some globals() printed\n
else:
print All globals() printed\n

print Globals (Generator):
try:
print \n.join(\t%s % i for i in globals())
except RuntimeError:
print Only some globals() printed\n
else:
print All globals() printed\n


 Globals (For Loop):
 __builtins__
 Only some globals() printed

 Globals (Generator):
 __builtins__
 __name__
 __file__
 i
 __doc__
 All globals() printed


Why is it with a generator I get everything out but with a for loop I
don't? I know that globals is not read-only but I would of expected
the same behaviour from both...

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


Re: Decode email subjects into unicode

2008-03-18 Thread Jeffrey Froman
Laszlo Nagy wrote:

 I know that =?UTF-8?B means UTF-8 + base64 encoding, but I wonder if
 there is a standard method in the email package to decode these
 subjects?

The standard library function email.Header.decode_header will parse these
headers into an encoded bytestring paired with the appropriate encoding
specification, if any. For example:

 raw_headers = [
... '=?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?=',
... '[Fwd: re:Flags Of The World, Us States, And Military]',
... '=?ISO-8859-2?Q?=E9rdekes?=',
... '=?UTF-8?B?aGliw6Fr?=',
... ]
 from email.Header import decode_header
 for raw_header in raw_headers:
... for header, encoding in decode_header(raw_header):
... if encoding is None:
... print header.decode()
... else:
... print header.decode(encoding)
...
Быстровыполнимо и малозатратно
[Fwd: re:Flags Of The World, Us States, And Military]
érdekes
hibák


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

Re: Need Help Starting Out

2008-03-18 Thread rodmc

 Hi, I would like to start using Python, but am unsure where to begin.
 I know how to look up a tutorial and learn the language, but not what
 all technologies to use.  I saw references to plain Python, Django,
 and other things.

Hi,

For database stuff you can plug directly into either MySQL or SQLite.
For MySQL you need to install a third party library which you can get
from:

http://sourceforge.net/projects/mysql-python

I think SQLite support is now included in Python 2.5, all you need to
do is type import sqlite3, and away it goes. You will of course need
to install SQLite, just search for it online. I found SQlite more than
sufficient for any single user non-web based apps. On the client side
you can use these library and if you like build a free standing app to
run everything.

For GUI toolkits you can do worse than download and install wxPython,
which again is free (www.wxpython.org). If you want to dabble in games
programming there is also PyGame.

If you want to build free standing applications you can use Py2Exe
(Windows) and Py2App (Mac), just Google them and they will appear. You
may at times find Python a little slow, and you can even get round
that problem in Windows and Intel based Macs by using Psyco (again
just Google). It can speed up your code by quite a large margin.

Hope these help you get started...

Rod


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


Re: Interesting math problem

2008-03-18 Thread Jeff Schwab
Marc Christiansen wrote:
 sturlamolden [EMAIL PROTECTED] wrote:
 On 18 Mar, 00:58, Jeff Schwab [EMAIL PROTECTED] wrote:

 def make_slope(distance, parts):
  if parts == 0:
  return []

  q, r = divmod(distance, parts)

  if r and parts % r:
  q += 1

  return [q] + make_slope(distance - q, parts - 1)
 Beautiful. If Python could optimize tail recursion, it would even run
 fast.
 
 This was my first thought, too. But tailcall optimisation wouldn't help
 here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets
 executed after the recursion. 


def make_slope(distance, parts, L=()):
 if parts == 0:
 return L

 q, r = divmod(distance, parts)

 if r and parts % r:
 q += 1

 return make_slope(distance - q, parts - 1, (q,) + L)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Help Starting Out

2008-03-18 Thread D'Arcy J.M. Cain
On Tue, 18 Mar 2008 09:27:46 -0700 (PDT)
rodmc [EMAIL PROTECTED] wrote:
 
  Hi, I would like to start using Python, but am unsure where to begin.
  I know how to look up a tutorial and learn the language, but not what
  all technologies to use.  I saw references to plain Python, Django,
  and other things.
 
 Hi,
 
 For database stuff you can plug directly into either MySQL or SQLite.

Or PostgreSQL.

 For MySQL you need to install a third party library which you can get
 from:
 
 http://sourceforge.net/projects/mysql-python

And there are many interfaces for PostgreSQL including PyGreSQL which
I maintain at http://PyGreSQL.org/

 Hope these help you get started...

And don't forget the tutorial on the Python web site.

-- 
D'Arcy J.M. Cain [EMAIL PROTECTED] |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast 2D Raster Rendering with GUI

2008-03-18 Thread Miki
Hello Dave,

 Hi All. I've been formulating in my head a simple image editor. I
 actually started prototyping is some time ago in Java, but am liking
 Python more and more. My editor will be nowhere near the level of Gimp/
 Photoshop, but I do need fast pixel level control and display. For
 instance, that means no automatic anti-aliasing and that I will be
 implementing my own line drawing algorithms.

 I've got the high level architectual aspects of my program down, but
 am stuck on what graphics API to use. I want a canvas area of
 adjustable size which users can draw on with as little lag as
 possible. The canvas area will be composed of layers (i.e. I require
 an alpha channel) and I need to be able to zoom in and out of it (zoom
 levels will be at fixed intervals, so this can be simulated if need
 be.)

 I started looking at PyGame but realize that I need to integrate a GUI
 into the whole thing (or integrate the image  into the GUI rather) and
 I didn't see a straightforward way to do that. Of course, I don't even
 know if PyGame is the right API for the job anyways :P

 Any thoughts or ideas that could help me get started? Thanks!
Apart from PIL, some other options are:
1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object
you can draw on
2. A bit of an overkill, but you can use PyOpenGL
3. ImageMagick bindings? (http://www.imagemagick.org/script/api.php)

HTH,
--
Miki [EMAIL PROTECTED]
http://pythonwise.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Help Starting Out

2008-03-18 Thread Michael Mabin
Pylons is a Ruby on Rails-like web framework that allows you build dynamic
web applications with a database backend.  Here is a link to the Pylons web
site:

http://pylonshq.com/



On Tue, Mar 18, 2008 at 11:10 AM, jmDesktop [EMAIL PROTECTED] wrote:

 Hi, I would like to start using Python, but am unsure where to begin.
 I know how to look up a tutorial and learn the language, but not what
 all technologies to use.  I saw references to plain Python, Django,
 and other things.

 I want to use it for web building with database access.  What do I use
 for that?  Does it matter what I use on the client side (mootools, or
 whatever)?

 My rational for using Python is because I am hoping it will allow me
 to better understand other python programs in other areas, not just
 web.  I have used other languages for web apps for several years.
 Truth is that I always wanted to learn Python and have heard it was a
 good thing to know.

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




-- 
| _ | * | _ |
| _ | _ | * |
| * | * | * |
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Strange problem with structs Linux vs. Mac

2008-03-18 Thread Martin Blume
Marc 'BlackJack' Rintsch schrieb 
 
  I don't think this qualifies as a bug, but I am astonished
  that the struct module does not tell you whether you are
  big endian, you have to find out yourself with
 struct.unpack('@I', s)[0]==struct.unpack(I, s)[0]
 
 Maybe a little more compact and readable:
 
 In [92]: sys.byteorder
 Out[92]: 'little'
 
Yes, indeed it is more compact and readable.
Thanks.
Martin


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


Re: Comunicate processes with python

2008-03-18 Thread Joshua Kugler
Adrián Bravo Navarro wrote:
 Is there any simple way to achieve this goal? We've been thinking of
 sockets but Im not conviced at all with that.

If you want to communicate between processes on the same host, yes, you can
use DBus or a couple of the options here:
http://docs.python.org/lib/ipc.html

If you want to communicate between hosts, then sockets is probably going to
be your only options, although there are libraries that abstract some of
that for you to make it easier to manage.  You might want to take a look at
Pyro. http://pyro.sourceforge.net/

j

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


Re: finding items that occur more than once in a list

2008-03-18 Thread Raymond Hettinger
On Mar 18, 2:57 am, Simon Forman [EMAIL PROTECTED] wrote:
 Is there a more efficient way to do this?

 def f(L):
 '''Return a set of the items that occur more than once in L.'''
 L = list(L)
 for item in set(L):
 L.remove(item)
 return set(L)

 | f([0, 0, 1, 1, 2, 2, 3])
 set([0, 1, 2])


def f(L):
seen = set()
dups = set()
for e in L:
if e in seen:
dups.add(e)
else:
seen.add(e)
return dups



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


Re: globals() using For Loop against Generator

2008-03-18 Thread Mel
[EMAIL PROTECTED] wrote:
 if __name__ == '__main__':
 
 print Globals (For Loop):
 try:
 for i in globals():
 print \t%s % i
 except RuntimeError:
 print Only some globals() printed\n
 else:
 print All globals() printed\n
 
 print Globals (Generator):
 try:
 print \n.join(\t%s % i for i in globals())
 except RuntimeError:
 print Only some globals() printed\n
 else:
 print All globals() printed\n
 
 Globals (For Loop):
__builtins__
 Only some globals() printed

 Globals (Generator):
__builtins__
__name__
__file__
i
__doc__
 All globals() printed

 
 Why is it with a generator I get everything out but with a for loop I
 don't? I know that globals is not read-only but I would of expected
 the same behaviour from both...

Run the for loop in the interpreter, without catching exceptions.  You get

__builtins__
Traceback (most recent call last):
   File stdin, line 1, in module
RuntimeError: dictionary changed size during iteration


Then `print globals()` shows that i has been added to the global 
namespace.  If you run the for loop a second time, after i exists, the 
loop runs fine.

Apparently, generator comprehensions have been optimized so that they 
don't expose their working variables.  The generator comprehension 
won't add i to the global namespace, so all is well.

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


Re: Pycon disappointment

2008-03-18 Thread perrygreenfield
Amen on the diamond keynotes and lightning talks. The lightning talks
were a great disappointment. Sponsor talks (or any such talks pitched
at selling or recruiting) should go in their own, clearly labeled
group so those of us who don't care about them can avoid them.

If there must diamond 'keynotes' put them at the end of a session or
in a separate track so we can easily avoid them if we wish. But
personally, I don't think keynotes should be for sale at all in any
form.

One problem I faced was that there were sessions that had few talks I
was interested in and other that had several at the same time where I
couldn't attend all that I was interested. It's likely that there is
no good solution to this, but perhaps one could try a new scheme for
scheduling talks by posting the talk list early and letting
registrants select the top n talks they want to see and running some
sort of scheduling optimizer that tries to satisfy most of these
desires (I have no idea if anything like this exists anywhere).

And if you do decide to change how you handle sponsorship don't be
afraid to say publicly how things are going to be different next time.
There could well be many who won't go next time (like me) unless they
have some reasons to believe that things will be different.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast 2D Raster Rendering with GUI

2008-03-18 Thread sturlamolden
On 18 Mar, 17:48, Miki [EMAIL PROTECTED] wrote:

 Apart from PIL, some other options are:
 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object
 you can draw on

Yes, but at least on Windows you will get a GDI canvas. GDI is slow.


 2. A bit of an overkill, but you can use PyOpenGL

OpenGL gives you a fast 'bitblit' for drawing bitmaps to the fram
buffer (much faster than GDI). Here is some C code that does that (8-
bit color depth). Translating to Python is trivial. I prefer not to
use PyOpenGL as it has some unwanted overhead. It is better to use
ctypes.


void bitblt(void *frame, int w, int h)
{
glViewport(0,0,w,h);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLfloat)w, 0.0, (GLfloat)h);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRasterPos2i(0,0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glDrawPixels(w, h, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, (GLvoid *)frame);
glFlush();
}




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


Re: Comunicate processes with python

2008-03-18 Thread Adrián Bravo Navarro
That was what we were thinking of, so if there is not some kind of easy
python magic we will probably use some sockets.

Thanks!!

2008/3/18, Joshua Kugler [EMAIL PROTECTED]:

 Adrián Bravo Navarro wrote:
  Is there any simple way to achieve this goal? We've been thinking of
  sockets but Im not conviced at all with that.


 If you want to communicate between processes on the same host, yes, you
 can
 use DBus or a couple of the options here:
 http://docs.python.org/lib/ipc.html

 If you want to communicate between hosts, then sockets is probably going
 to
 be your only options, although there are libraries that abstract some of
 that for you to make it easier to manage.  You might want to take a look
 at
 Pyro. http://pyro.sourceforge.net/

 j


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

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

Re: Fast 2D Raster Rendering with GUI

2008-03-18 Thread Chris Mellon
On Tue, Mar 18, 2008 at 12:30 PM, sturlamolden [EMAIL PROTECTED] wrote:
 On 18 Mar, 17:48, Miki [EMAIL PROTECTED] wrote:

   Apart from PIL, some other options are:
   1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object
   you can draw on

  Yes, but at least on Windows you will get a GDI canvas. GDI is slow.

Of all the major platforms, GDI is probably the fastest for basic
pixel-level interaction with the screen. I have no idea why you think
it's slow.




   2. A bit of an overkill, but you can use PyOpenGL

  OpenGL gives you a fast 'bitblit' for drawing bitmaps to the fram
  buffer (much faster than GDI). Here is some C code that does that (8-
  bit color depth). Translating to Python is trivial. I prefer not to
  use PyOpenGL as it has some unwanted overhead. It is better to use
  ctypes.


  void bitblt(void *frame, int w, int h)
  {
 glViewport(0,0,w,h);
 glClearColor(0.0, 0.0, 0.0, 0.0);
 glClear(GL_COLOR_BUFFER_BIT);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 gluOrtho2D(0.0, (GLfloat)w, 0.0, (GLfloat)h);
 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();
 glRasterPos2i(0,0);
 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 glDrawPixels(w, h, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, (GLvoid *)frame);
 glFlush();


 }


OpenGL is totally unsuitable if the goal is to implement your own
pixel-level raster drawing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Merging a patch/diff generated by difflib?

2008-03-18 Thread Raymond Hettinger
On Mar 18, 6:08 am, erikcw [EMAIL PROTECTED] wrote:
 Hi,

 I'm trying to create an undo/redo feature for a webapp I'm working on
 (django based).  I'd like to have an undo/redo function.

 My first thought was to use the difflib to generate a diff to serve as
 the backup, and then if someone wants to undo their operation, the
 diff could just be merged/patched with the current text.

 However, I've not be able to find a patch library.  Are there any
 libraries that will handle merging the diff back into the text?

The difflib module has a restore() function.


Raymond

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


Re: Pycon disappointment

2008-03-18 Thread Mike Orr
On Mar 16, 6:10 am, Bruce Eckel [EMAIL PROTECTED] wrote:
vendors:
 But it gets worse. The lightning talks, traditionally the best, newest
 and edgiest part of the conference, were also sold like commercial air
 time.

We introduced sponsor lighting talks last year.  This year it got out
of hand because there were twice as many sponsors.  By the time the
Lightning Talk coordinators realized this, the sponsors had already
been promised a priority talk so we couldn't back out of it.  So it
was a lack of foresight, not some commercial plot.

Next year we (the Lightning Talk coordinators) have recommended either
not having sponsor lighting talks, or moving them to a separate (non-
plenary) session.  The vendor exhibition was much bigger this year,
and I think that's an adequate replacement for sponsor lighting
talks.  If there are sufficient Open Space rooms, they can also create
their own session.

 At first the morning plenary sessions -- where the entire conference
 audience was in a single room -- just seemed a bit commercial. But
 then I slowly figured out that the so-called diamond keynotes were
 actually sold to vendors. It must have sounded great to some

I liked the mini-keynotes and I don't think they detracted from the
main keynotes.  I did know what diamond meant so I knew they were
sponsor talks.  I guess that should be clearer on the schedule.

 What was supremely frustrating was discovering that the people wanting
 to give REAL lightning talks had been pushed off the end of the list

The worst part of scheduling Lighting Talks is there's always more
interesting speakers than time.  This seems to be an insolvable
problem.

The main problem I had at PyCon this year was the number of talk I
wanted to see that were scheduled at the same time as other talks I
wanted to see.

The highlight was the number of Open Space rooms and events.  I didn't
attend any of these, but they seemed unusually lively this year.

 On top of that, the quality of the presentations was unusually low.

I did feel that.  An advanced track would be a good idea. Because you
do need to repeat stuff for the newbies.  At least 30% of the
attendees were at PyCon for the first time.

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


Re: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard

2008-03-18 Thread geert
On Mar 14, 1:15 pm, [EMAIL PROTECTED] wrote:
 look 
 athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d...

 There is a macpython list that you can consult 
 athttp://www.nabble.com/Python---pythonmac-sig-f2970.html

Just wanted to let you know that I've solved my problem. The solution
is to compile mysql using

MACOSX_DEPLOYMENT_TARGET=10.5 \
CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
./configure --disable-dependency-tracking  --enable-thread-safe-client
--prefix=/usr/local/mysql

You then go this way to get it running on your machine:

http://hivelogic.com/articles/installing-mysql-on-mac-os-x/

Then reinstall MySQLdb. Magic!

Geert



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


Re: Regarding coding style

2008-03-18 Thread Tim Lesher
On Mar 9, 2:04 am, Ryan Ginstrom [EMAIL PROTECTED] wrote:
  On Behalf Of Grant Edwards
  I think docstrings are a great idea.  What's needed is a way
  to document the signature that can't get out-of-sync with
  what the fucntion really expects.

 Like doctests? (I know, smart-ass response)

 Regards,
 Ryan Ginstrom

Not a smart-ass response at all--a _smart_ response.

Doctests are one of the few mechanisms I've ever seen that even
attempt to make this happen.

--
Tim Lesher
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Generators

2008-03-18 Thread Marius Gedminas
On Mar 16, 9:24 am, Matt Nordhoff [EMAIL PROTECTED] wrote:
 mpc wrote:
  def concatenate(sequences):
      for seq in sequences:
          for item in seq:
              yield item

 You should check out itertools.chain(). It does this. You call it like
 chain(seq1, seq2, ...) instead of chain(sequences) though, which may
 be a problem for you.

Solved rather easily by chain(*sequences):

 from itertools import chain
 def concat(sequences):
... return chain(*sequences)
...
 concat([[1,2], [3, 4], [5], [6, 7, 8]])
itertools.chain object at 0xb7cffc0c
 list(concat([[1,2], [3, 4], [5], [6, 7, 8]]))
[1, 2, 3, 4, 5, 6, 7, 8]


wondering if google groups will add a .sig or not-ly,
Marius Gedminas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get actual call signature?

2008-03-18 Thread castironpi
On Mar 18, 5:40 am, Jarek Zgoda [EMAIL PROTECTED] wrote:
 Say, I have a function defined as:

 def fun(arg_one, arg_two='x', arg_three=None):
     pass

 Is there any way to get actual arguments that will be effectively used
 when I call this function in various ways, like:

 fun(5) = [5, 'x', None]
 fun(5, arg_three=['a', 'b']) = [5, 'x', ['a', 'b']]
 fun(5, 'something') = [5, 'something', None]

 (et caetera, using all possible mixes of positional, keyword and default
 arguments)

 I'd like to wrap function definition with a decorator that intercepts
 not only passed arguments, but also defaults that will be actually used
 in execution.

 If this sounds not feasible (or is simply impossible), I'll happily
 throw this idea and look for another one. ;)

It evaluates to a substantial problem.  The combinations include
things that Python disallows, such as double-spec. of keywords and
spec'n of keys w/out a dictionary arg; as well as double-spec'ing of
inspection.  How do you want to access the parameters?  What is the
least redundant way?  P.S.  Does there exist a possible authority who
doesn't want me to post this?

How about an index of value and list/tuple of name?

 def fun(arg_one, arg_two='x', arg_three=None):

 fun(5) = [5, 'x', None]
get_args( fun, 5 )-
 names= [ 'arg_one', 'arg_two', 'arg_three' ]
 vals= [ 5, 'x', None ]

 fun(5, arg_three=['a', 'b']) = [5, 'x', ['a', 'b']]
get_args( fun, 5, arg_three=['a', 'b'] )
 names= [ 'arg_one', 'arg_two', 'arg_three' ]
 vals= [ 5, 'x', ['a', 'b'] ]

 fun(5, 'something') = [5, 'something', None]
get_args( fun, 5, 'something' )-
 names= [ 'arg_one', 'arg_two', 'arg_three' ]
 vals= [ 5, 'something', None ]

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


Re: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom

2008-03-18 Thread George Sakkis
On Mar 18, 6:03 am, Gabriel Rossetti
[EMAIL PROTECTED] wrote:
 Carsten Haese wrote:
  On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote:

  Hello,

  I am reading core python python programming and it talks about using the
  idiom
  described on
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183.

  I'm using python 2.5.1 and if I try :

  class MyClass(object):
  def __init__(self):
  self._foo = foo
  self._bar = bar

  @property
  def foo():
  doc = property foo's doc string
  def fget(self):
  return self._foo
  def fset(self, value):
  self._foo = value
  def fdel(self):
  del self._foo
  return locals()  # credit: David Niergarth

  @property
  def bar():
  doc = bar is readonly
  def fget(self):
  return self._bar
  return locals()

  like suggested in the book (the decorator usage) I get this :

  a=MyClass()
  a.foo
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: foo() takes no arguments (1 given)

  but if I write it just like on the web page (without the decorator, using 
  x = property(**x()) instead) it works :

  a = MyClass()
  a.foo
 'foo'

  does anyone have an idea as of why this is happening?

  You're mixing two completely different approaches of building a
  property. If that code is actually in the book like that, that's a typo
  that you should mention to the author.

  The @property decorator can only be used to turn a single getter
  function into a read-only attribute, because this:

 @property
 def foo(...):
...

  is the same as this:

 def foo(...):
...
 foo = property(foo)

  and calling property() with one argument builds a property that has just
  a getter function that is the single argument you're giving it.

  The recipe you're referring to uses a magical function that returns a
  dictionary of getter function, setter function, deleter function, and
  docstring, with suitable key names so that the dictionary can be passed
  as a keyword argument dictionary into the property() constructor.
  However, that requires the magical foo=property(**foo()) invocation, not
  the regular decorator invocation foo=property(foo).

  HTH,

 I was able to get it t work with the decorator by doing this :

 def MyProperty(fcn):
 return property(**fcn())

 and using it like this :

 class MyClass(object):
def __init__(self):
self._foo = foo
self._bar = bar

@MyProperty
def foo():
doc = property foo's doc string
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
def fdel(self):
del self._foo
return locals()  # credit: David Niergarth

@MyProperty
def bar():
doc = bar is readonly
def fget(self):
return self._bar
return locals()

 Cheers,
 Gabriel

Also check out a related recipe that doesn't require returning
locals() explicitly: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698

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


Re: PyCon Feedback and Volunteers (Re: Pycon disappointment)

2008-03-18 Thread fumanchu
On Mar 17, 6:25 pm, dundeemt [EMAIL PROTECTED] wrote:
 I agree - the balance wasn't as good.  We can all agree that HowTos
 and Intros are a necessary part of the conference talks track, but as
 Robert pointed out some talks should be of a more advanced nature.  I
 enjoy those that stretch my brain.  Alex M, Pyke and NetworkIO and
 Mark Hammond's keynote were among my favorite talks.

Raymond Hettinger's talk on collections was not only one of my
favorites, it was apparently lots of other people's too--the room was
PACKED. I can't recall seeing any other talk that was even close to
seating capacity.


Robert Brewer
[EMAIL PROTECTED]

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


Re: Pycon disappointment

2008-03-18 Thread George Sakkis
On Mar 18, 1:49 pm, Mike Orr [EMAIL PROTECTED] wrote:
 On Mar 16, 6:10 am, Bruce Eckel [EMAIL PROTECTED] wrote:
 vendors:

  On top of that, the quality of the presentations was unusually low.

 I did feel that.  An advanced track would be a good idea. Because
 you do need to repeat stuff for the newbies.  At least 30% of the
 attendees were at PyCon for the first time.

Not all first-comers are newbies; I attended for the first time too
but I've been using Python for the last four years or so. My overall
(totally unscientific) impression was that most attendants had at
least a decent grasp of the language.

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


Re: PyCon Feedback and Volunteers (Re: Pycon disappointment)

2008-03-18 Thread Mike Driscoll
On Mar 18, 1:41 pm, fumanchu [EMAIL PROTECTED] wrote:
 On Mar 17, 6:25 pm, dundeemt [EMAIL PROTECTED] wrote:

  I agree - the balance wasn't as good.  We can all agree that HowTos
  and Intros are a necessary part of the conference talks track, but as
  Robert pointed out some talks should be of a more advanced nature.  I
  enjoy those that stretch my brain.  Alex M, Pyke and NetworkIO and
  Mark Hammond's keynote were among my favorite talks.

 Raymond Hettinger's talk on collections was not only one of my
 favorites, it was apparently lots of other people's too--the room was
 PACKED. I can't recall seeing any other talk that was even close to
 seating capacity.

 Robert Brewer
 [EMAIL PROTECTED]

The Using PyGame and PySight to Create an Interactive Halloween
Activity (#9) session with Mr. John Harrison was also quite full as
was the one for Pyglet. I think the nose presentation had people
sitting on the floor.

Geeks like games! I know I do!

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


Re: Decode email subjects into unicode

2008-03-18 Thread John Machin
On Mar 18, 9:09 pm, Laszlo Nagy [EMAIL PROTECTED] wrote:
 Sorry, meanwhile i found that email.Headers.decode_header can be used
 to convert the subject into unicode:

  def decode_header(self,headervalue):
  val,encoding = decode_header(headervalue)[0]
  if encoding:
  return val.decode(encoding)
  else:
  return val

 However, there are malformed emails and I have to put them into the
 database. What should I do with this:

 Return-Path: [EMAIL PROTECTED]
 X-Original-To: [EMAIL PROTECTED]
 Delivered-To: [EMAIL PROTECTED]
 Received: from 195.228.74.135 (unknown [122.46.173.89])
 by shopzeus.com (Postfix) with SMTP id F1C071DD438;
 Tue, 18 Mar 2008 05:43:27 -0400 (EDT)
 Date: Tue, 18 Mar 2008 12:43:45 +0200
 Message-ID: [EMAIL PROTECTED]
 From: Euro Dice Casino [EMAIL PROTECTED]
 To: [EMAIL PROTECTED]
 Subject: With 2'500 Euro of Welcome Bonus you can't miss the chance!
 MIME-Version: 1.0
 Content-Type: text/html; charset=iso-8859-1
 Content-Transfer-Encoding: 7bit

 There is no encoding given in the subject but it contains 0x92. When I
 try to insert this into the database, I get:

 ProgrammingError: invalid byte sequence for encoding UTF8: 0x92

 All right, this probably was a spam email and I should simply discard
 it. Probably the spammer used this special character in order to prevent
 mail filters detecting can't and 2500. But I guess there will be
 other important (ham) emails with bad encodings. How should I handle this?

Maybe with some heuristics about the types of mistakes made by do-it-
yourself e-mail header constructors. For example, 'iso-8859-1' often
should be construed as 'cp1252':

 import unicodedata as ucd
 ucd.name('\x92'.decode('iso-8859-1'))
Traceback (most recent call last):
  File stdin, line 1, in module
ValueError: no such name
 ucd.name('\x92'.decode('cp1252'))
'RIGHT SINGLE QUOTATION MARK'

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


Re: stdout custom

2008-03-18 Thread castironpi
On Mar 18, 8:51 am, Tim Golden [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  Can I allocate a second console window, so I can place certain output
  to that directly, and leave the original streams alone?  

 I've rather lost track of what you're trying to do, but I would
 second Gabriel's suggestion of the standard Windows method of
 debug output: using OutputDebugString. There's an example here:

 http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugStrin...

 and it shouldn't be too hard to wrap it in a file-like
 object for stderr-substitution use, say.

 Obviously there are 1,001 other ways of doing IPC but since this
 one's ready-made you might as well use it. You can distinguish
 between different processes' outputs by virtue of the PID which
 is the first item on the mmap.

 TJG

I want a handle to another window.

Create B with a command.
 ___   ___
|A  | |B  |
|___| |___|

B.stdin (the stdin to B).write( '?' )
 ___   ___
|A  | |B? |
|___| |___|

A.stdout.write( '*' )
 ___   ___
|A* | |B? |
|___| |___|

A big tease is good too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast 2D Raster Rendering with GUI

2008-03-18 Thread Ross Ridge
Chris Mellon [EMAIL PROTECTED] wrote:
OpenGL is totally unsuitable if the goal is to implement your own
pixel-level raster drawing.

Unfornately, any solution involving Python is likely to be unsuitable
if your goal is to set individual pixels one-by-one, and GDI would be no
better than OpenGL here.  The overhead of calling some sort of putpixel()
function over and over will domininate everything else.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anomaly in time.clock()

2008-03-18 Thread John Machin
On Mar 18, 9:43 pm, Godzilla [EMAIL PROTECTED] wrote:
 Thanks Roel. If there is a way to pass in the PRESERVE_PRECISION
 constant in the python time.clock library, that would be great

Re-read Roel's message. Something like PRESERVE_PRECISION is to be
passed to whatever is setting up DirectX.

 But
 I'm afraid it's not possible. I think I will change away from using
 time.clock() from now on... seems too edgy to me.

Are you using DirectX? If so, read the docs for more clues -- a quick
google for PRESERVE_PRECISION will tell you that something like
means what it says. If not, try posting some more info on what you are
actually doing. Consider providing a short piece of code that
demonstrates the actual problem.

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


Re: PyCon Feedback and Volunteers (Re: Pycon disappointment)

2008-03-18 Thread Jeff Schwab
Mike Driscoll wrote:
 On Mar 18, 1:41 pm, fumanchu [EMAIL PROTECTED] wrote:
 On Mar 17, 6:25 pm, dundeemt [EMAIL PROTECTED] wrote:

 I agree - the balance wasn't as good.  We can all agree that HowTos
 and Intros are a necessary part of the conference talks track, but as
 Robert pointed out some talks should be of a more advanced nature.  I
 enjoy those that stretch my brain.  Alex M, Pyke and NetworkIO and
 Mark Hammond's keynote were among my favorite talks.
 Raymond Hettinger's talk on collections was not only one of my
 favorites, it was apparently lots of other people's too--the room was
 PACKED. I can't recall seeing any other talk that was even close to
 seating capacity.

 Robert Brewer
 [EMAIL PROTECTED]
 
 The Using PyGame and PySight to Create an Interactive Halloween
 Activity (#9) session with Mr. John Harrison was also quite full as
 was the one for Pyglet. I think the nose presentation had people
 sitting on the floor.
 
 Geeks like games! I know I do!

Me too.

As I have never attended PyCon, the amount of entertainment already 
gleaned from this thread has wildly exceeded my expectations. :)  Are 
slides or notes from any of the presentations available online?  What 
was the topic of the well-received presentation from Google?
-- 
http://mail.python.org/mailman/listinfo/python-list


method to create class property

2008-03-18 Thread Joe P. Cool
Hi,

I like C#'s style of defining a property in one place. Can the
following way
to create a property be  considered reasonable Python style (without
the
print statements, of course)?

class sample(object):
def __init__(self):
sample.y = self._property_y()

def _property_y(self):
def _get(self):
print 'getting y.'
return self._y
def _set(self, value):
print 'setting y.'
self._y = value
def _del(self):
print 'bye, y!'
del self._y
return property(_get, _set, _del)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get actual call signature?

2008-03-18 Thread Jarek Zgoda
[EMAIL PROTECTED] pisze:
 On Mar 18, 5:40 am, Jarek Zgoda [EMAIL PROTECTED] wrote:
 Say, I have a function defined as:

 def fun(arg_one, arg_two='x', arg_three=None):
 pass

 Is there any way to get actual arguments that will be effectively used
 when I call this function in various ways, like:

 fun(5) = [5, 'x', None]
 fun(5, arg_three=['a', 'b']) = [5, 'x', ['a', 'b']]
 fun(5, 'something') = [5, 'something', None]

 (et caetera, using all possible mixes of positional, keyword and default
 arguments)

 I'd like to wrap function definition with a decorator that intercepts
 not only passed arguments, but also defaults that will be actually used
 in execution.

 If this sounds not feasible (or is simply impossible), I'll happily
 throw this idea and look for another one. ;)
 
 It evaluates to a substantial problem.  The combinations include
 things that Python disallows, such as double-spec. of keywords and
 spec'n of keys w/out a dictionary arg; as well as double-spec'ing of
 inspection.  How do you want to access the parameters?  What is the
 least redundant way?  P.S.  Does there exist a possible authority who
 doesn't want me to post this?

Well, after some thinking and research I found this much more
complicated than my first thoughts. However, I found that somebody
already wrote some code to solve similar problem and even described what
has to be done: http://wordaligned.org/articles/echo. Too bad for me,
the most interesting part relies on features introduced with Python 2.5,
while I am still on 2.4.
Anyway, basics still works and fortunately I am in control in both
function definitions and calls.

-- 
Jarek Zgoda
http://zgodowie.org/

We read Knuth so you don't have to - Tim Peters
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get actual call signature?

2008-03-18 Thread George Sakkis
On Mar 18, 6:40 am, Jarek Zgoda [EMAIL PROTECTED] wrote:
 Say, I have a function defined as:

 def fun(arg_one, arg_two='x', arg_three=None):
 pass

 Is there any way to get actual arguments that will be effectively used
 when I call this function in various ways, like:

 fun(5) = [5, 'x', None]
 fun(5, arg_three=['a', 'b']) = [5, 'x', ['a', 'b']]
 fun(5, 'something') = [5, 'something', None]

 (et caetera, using all possible mixes of positional, keyword and default
 arguments)

 I'd like to wrap function definition with a decorator that intercepts
 not only passed arguments, but also defaults that will be actually used
 in execution.

 If this sounds not feasible (or is simply impossible), I'll happily
 throw this idea and look for another one. ;)

I also needed this for a typecheck module I had written some time ago.
It is feasible, but it's rather hairy. I can dig up the code, polish
it and post it as a recipe (or maybe as a patch to the inspect stdlib
module where it belongs).

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


Re: finding items that occur more than once in a list

2008-03-18 Thread Hrvoje Niksic
Ninereeds [EMAIL PROTECTED] writes:

 As for the growth pattern, each time you grow the table you have to
 redistribute all the items previously inserted to new locations.
 Resizes would get rarer as more items are added due to the
 exponential growth, but every table resize would take longer too
 since there are more items to move. Inserting n items still
 intuitively looks like O(n^2) to me.

 That said, it does remind me of that old exponential realloc trick
 for array resizing. Same thing, I suppose, since a hash table is
 basically an array. Maybe my math intuition is just wrong.

That's it.  While table resizes grow linearly in complexity, they
become geometrically rarer.  This is exactly what happens when
resizing dynamic arrays such as Python lists.  Applying your
intuition, appending n elements to a Python list would also have
O(n^2) complexity, which it doesn't.  See, for example,
http://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdout custom

2008-03-18 Thread castironpi
   Can I allocate a second console window, so I can place certain output
   to that directly, and leave the original streams alone?  

  I've rather lost track of what you're trying to do, but I would
  second Gabriel's suggestion of the standard Windows method of
  debug output: using OutputDebugString. There's an example here:

 http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugStrin...

  and it shouldn't be too hard to wrap it in a file-like
  object for stderr-substitution use, say.

  Obviously there are 1,001 other ways of doing IPC but since this
  one's ready-made you might as well use it. You can distinguish
  between different processes' outputs by virtue of the PID which
  is the first item on the mmap.

  TJG

 I want a handle to another window.

 Create B with a command.
  ___   ___
 |A  | |B  |
 |___| |___|

 B.stdin (the stdin to B).write( '?' )
  ___   ___
 |A  | |B? |
 |___| |___|

 A.stdout.write( '*' )
  ___   ___
 |A* | |B? |
 |___| |___|

This is a little weird.  I visited your link, but couldn't make any
sense of it, so I tried something else myself.  I'm not even sure what
it accomplishes, but if you're on a different tack or way ahead of me,
that can happen.  However, it might be closer than I think to what I
want-- my next step is to CreateProcess in the separate executable...
then try to merge in back into python and subprocess.

Now I've tried:

 p= Popen( '\\astdin.exe', creationflags= 16, stdin= PIPE )
 p.stdin.write( b'123\r\n' )
5

and I get the message box (lower), but no ':' sentinel nor the
output.  However the p.stdin.write call still returns if I close the
new console window and call it after.

astdin.cpp:

#include windows.h
#include iostream
#include string

using namespace std;

DWORD WINAPI ThreadProc( LPVOID ) {
while (1)
{
Sleep( 1000 );
cout ':';
}
}

int main() {
MessageBox( NULL, none, NULL, 0 );
cout Ok endl;
CreateThread( NULL, 0, ThreadProc, NULL, 0, NULL );
while (1)
{
string s;
cin s;
cout '';
cout s;
}
return 0;
}
-- 
http://mail.python.org/mailman/listinfo/python-list


os.path.getsize() on Windows

2008-03-18 Thread Sean DiZazzo
Hi all,

I'm seeing some behavior that is confusing me.  I often use a simple
function to tell if a file is growing...ie being copied into a certain
location.  (Can't process it until it's complete)  My function is not
working on windows, and I'm wondering if I am missing something
simple, or if I have just never tried this before.  Here's what I'm
trying to do:

def isGrowing(f, timeout):
ssize = os.path.getsize(f)
time.sleep(timeout)
esize =os.path.getsize(f)
return esize != ssize

On windows, this returns the size of the file as it _will be_, not the
size that it currently is.  Is this a feature?  What is the proper way
to get the current size of the file?  I noticed
win32File.GetFileSize()  Does that behave the way I expect?

PS.  I also tried os.stat()[6]

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


Re: method to create class property

2008-03-18 Thread Diez B. Roggisch
Joe P. Cool schrieb:
 Hi,
 
 I like C#'s style of defining a property in one place. Can the
 following way
 to create a property be  considered reasonable Python style (without
 the
 print statements, of course)?
 
 class sample(object):
 def __init__(self):
 sample.y = self._property_y()
 
 def _property_y(self):
 def _get(self):
 print 'getting y.'
 return self._y
 def _set(self, value):
 print 'setting y.'
 self._y = value
 def _del(self):
 print 'bye, y!'
 del self._y
 return property(_get, _set, _del)



There are a few recipies, like this:


class Foo(object):

 @apply
 def foo():
 def fget(self):
 return self._foo
 def fset(self, value):
 self._foo = value
 return property(**locals())


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


Colorado Python training in May

2008-03-18 Thread Mark Lutz
Python author and trainer Mark Lutz will be teaching another
3-day Python class at a conference center in Longmont, Colorado,
on May 14-16, 2008.

This is a public training session open to individual enrollments,
and covers the same topics as the 3-day onsite sessions that Mark
teaches, with hands-on lab work.

For more information on this session, please visit its web page:

http://home.earthlink.net/~python-training/longmont-public-classes.htm

For additional background on the class itself, see our home page:

http://home.earthlink.net/~python-training

Thanks for your interest.
--Mark Lutz at Python Training Services
-- 
http://mail.python.org/mailman/listinfo/python-list


keyboard interrupt

2008-03-18 Thread John Fisher
Hi Group,

I have been absent a while, mainly because I have been getting better at
figuring out my own Python problems. But not this one...

I have a timed loop performing certain tasks until a total period of
time has elapsed. I would like to be able to interrupt the loop or set
various flags during execution via keyboard input. raw_input seems to
just stop everything cold. I want the ability to just sacn the keyboard
buffer and see if something is there, then proceed normally in the loop
if there is no input in the buffer. Make sense? Totally easy? Let me
know...

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


Re: finding items that occur more than once in a list

2008-03-18 Thread sturlamolden
On 18 Mar, 10:57, Simon Forman [EMAIL PROTECTED] wrote:

 def f(L):
 '''Return a set of the items that occur more than once in L.'''
 L = list(L)
 for item in set(L):
 L.remove(item)
 return set(L)


def nonunique(lst):
   slst = sorted(lst)
   return list(set([s[0] for s in
  filter(lambda t : not(t[0]-t[1]), zip(slst[:-1],slst[1:]))]))




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


ftp recursively

2008-03-18 Thread Jeff Schwab
I need to move a directory tree (~9GB) from one machine to another on 
the same LAN.  What's the best (briefest and most portable) way to do 
this in Python?

I see that urllib has some support for getting files by FTP, but that it 
has some trouble distinguishing files from directories.

 http://docs.python.org/lib/module-urllib.html

 The code handling the FTP protocol cannot differentiate
  between a file and a directory.

I tried it anyway, but got an authentication problem.  I don't see a 
how to log into the FTP server section on docs.python.org.  Is there a 
tutorial I should read?

I am particularly looking for a quick, good enough solution that I can 
use this afternoon.  Thanks in advance to any kind-hearted soul who 
chooses to help me out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-18 Thread sturlamolden
On 18 Mar, 22:22, sturlamolden [EMAIL PROTECTED] wrote:

 def nonunique(lst):
slst = sorted(lst)
return list(set([s[0] for s in
   filter(lambda t : not(t[0]-t[1]), zip(slst[:-1],slst[1:]))]))


Or perhaps better:

def nonunique(lst):
   slst = sorted(lst)
   return list(set([s[0] for s in
   filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))]))



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


  1   2   3   4   >