Re: Where to find options for add_command?

2009-04-16 Thread Eric Brunel
Muddy Coder wrote:
> Hi Folks,
>
> When I make Menu, and add in menu items, by using add_command, such
> as:
>
> menuObj.add_command(label='Open File', command=self.open_file)
>
> It works. But, I want to make the GUI looking better. So, I want to
> change color, font, size, background, for the label of Open File. I
> got clobbered. I tried relief, fg, color, no one worked. Can somebody
> points me a website to visit, to check out what options available for
> add_command? Thanks!

Assuming you're using Tkinter, the best resource for it are the tk manual
pages, that you can find here:
http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm
It requires a little adaptation to understand how to convert tcl syntax to
Python syntax, but it's quite straightforward and doesn't take long. You'll
find the answer to your question here:
http://www.tcl.tk/man/tcl8.5/TkCmd/menu.htm#M32

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


Re: HTML Generation

2009-04-16 Thread Nick Craig-Wood
J Kenneth King  wrote:
>  Stefan Behnel  writes:
> > See here for another example that uses lxml.html:
> >
> > http://codespeak.net/lxml/lxmlhtml.html#creating-html-with-the-e-factory
> >
> > Stefan
> 
>  Ah, looks good. Have never used nor finished the example I had given --
>  only meant as inspiration. I'm not surprised it has been done by someone
>  else.

Something more like what the OP wanted is HTMLgen.

I'm not sure it is maintained any more, but I used it quite a lot a
few years ago.

Debian still have the source and a package here

  http://packages.debian.org/sid/python-htmlgen

But I think its original website is gone.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to extract from regex in if statement

2009-04-16 Thread Nick Craig-Wood
Paul McGuire  wrote:
>  On Apr 3, 9:26 pm, Paul Rubin  wrote:
> > bwgoudey  writes:
> > > elif re.match("^DATASET:\s*(.+) ", line):
> > >         m=re.match("^DATASET:\s*(.+) ", line)
> > >         print m.group(1))
> >
> > Sometimes I like to make a special class that saves the result:
> >
> >   class Reg(object):   # illustrative code, not tested
> >      def match(self, pattern, line):
> >         self.result = re.match(pattern, line)
> >         return self.result
> >
>  I took this a little further, *and* lightly tested it too.
> 
>  Since this idiom makes repeated references to the input line, I added
>  that to the constructor of the matching class.
> 
>  By using __call__, I made the created object callable, taking the RE
>  expression as its lone argument and returning a boolean indicating
>  match success or failure.  The result of the re.match call is saved in
>  self.matchresult.
> 
>  By using __getattr__, the created object proxies for the results of
>  the re.match call.
> 
>  I think the resulting code looks pretty close to the original C or
>  Perl idiom of cascading "elif (c=re_expr_match("..."))" blocks.
> 
>  (I thought about cacheing previously seen REs, or adding support for
>  compiled REs instead of just strings - after all, this idiom usually
>  occurs in a loop while iterating of some large body of text.  It turns
>  out that the re module already caches previously compiled REs, so I
>  left my cacheing out in favor of that already being done in the std
>  lib.)
> 
> 
>  import re
> 
>  class REmatcher(object):
>  def __init__(self,sourceline):
>  self.line = sourceline
>  def __call__(self, regexp):
>  self.matchresult = re.match(regexp, self.line)
>  self.success = self.matchresult is not None
>  return self.success
>  def __getattr__(self, attr):
>  return getattr(self.matchresult, attr)

That is quite similar to the one I use...

"""
Matcher class encapsulating a call to re.search for ease of use in conditionals.
"""

import re

class Matcher(object):
"""
Matcher class

m = Matcher()

if m.search(r'add (\d+) (\d+)', line):
do_add(m[0], m[1])
elif m.search(r'mult (\d+) (\d+)', line):
do_mult(m[0], m[1])
elif m.search(r'help (\w+)', line):
show_help(m[0])

"""
def search(self, r, s):
"""
Do a regular expression search and return if it matched.
"""
self.value = re.search(r, s)
return self.value
def __getitem__(self, n):
"""
Return n'th matched () item.

Note so the first matched item will be matcher[0]
"""
return self.value.group(n+1)
def groups(self):
"""
Return all the matched () items.
"""
return self.value.groups()

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: interacting with an updatedb generated data file within python

2009-04-16 Thread Nick Craig-Wood
birdsong  wrote:
>  Does anybody have any recommendations on how to interact with the data
>  file that updatedb generates?  I'm running through a file list in
>  sqlite that I want to check against the file system. updatedb is
>  pretty optimized for building an index and storing it, but I see no
>  way to query the db file other than calling locate itself.  This would
>  require me to fork and exec for every single file I want to verify -
>  I'd be better off doing the stat myself in that case, but I'd really
>  rather let updatedb build the index for me.

Hmm..

There are several different implementations of locate and I'm not sure
they all use the same database.  On this ubuntu machine the database
is only root readable also.

$ ls -l /var/lib/mlocate/mlocate.db
-rw-r- 1 root mlocate 7013090 2009-04-14 07:54 /var/lib/mlocate/mlocate.db

>  I searched high and low for any sort of library that is well suited
>  for reading these data files, but I've found nothing for any language
>  other than the source for locate and updatedb itself.

You can use this to extract the database from the locate database

from subprocess import Popen, PIPE
from time import time

start = time()

all_files = set()
p = Popen(["locate", "*"], stdout=PIPE)
for line in p.stdout:
path = line[:-1]
all_files.add(path)

print "Found", len(all_files), "files in", time()-start, "seconds"

This builds a set of all the files on the filesystem and prints

Found 314492 files in 1.152987957 seconds

on my laptop, using about 19 MB total memory

You could easily enough put that into an sqlite table instead of a set().

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question to python C API

2009-04-16 Thread Ben Kaplan



On Apr 16, 2009, at 1:53 AM, Andreas Otto   
wrote:



Hi,

I want to make a language binding for an existing C library

   http://libmsgque.sourceforge.net

 is this possible ?
--


Not only is itpossible, it's pretty common. All of the major GUI  
toolkits do this. Look at www.swig.org if you don't want to write it  
all manually.





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

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


Re: PEP 382: Namespace Packages

2009-04-16 Thread syt
On Apr 14, 6:27 pm, "P.J. Eby"  wrote:
> I think you've misunderstood something about the use case.  System
> packaging tools don't like separate packages to contain the *same
> file*.  That means that they *can't* split a larger package up with
> your proposal, because every one of those packages would have to
> contain a __pkg__.py -- and thus be in conflict with each
> other.  Either that, or they would have to make a separate system
> package containing *only* the __pkg__.py, and then make all packages
> using the namespace depend on it -- which is more work and requires
> greater co-ordination among packagers.

I've maybe missed some point, but doesn't the PEP requires
coordination so that *.pkg files have different names in each portion,
and the same if one want to provide a non empty __init__.py.

Also providing a main package with a non empty __init__.py and others
with no __init__.py turns all this in the "base package" scenario
described later in this discussion, right?

BTW, It's unclear to me what difference do you make between this usage
and zope or peak's one.

> Allowing each system package to contain its own .pkg or .nsp or
> whatever files, on the other hand, allows each system package to be
> built independently, without conflict between contents (i.e., having
> the same file), and without requiring a special pseudo-package to
> contain the additional file.

As said above, provided some conventions are respected...

What's worrying me is that as the time goes, import mecanism becomes
more and more complicated, with more and more trick involved. Of
course I agree we should unify the way namespace packages are handled,
and this should live in the python std lib. What I like in MAL's
proposal is that it makes things simplier... Another point: I don't
like .pth, .pkg files. Isn't this pep an opportunity to at least unify
them?
--
Sylvain Thénault
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-16 Thread Adam Olsen
On Apr 15, 12:56 pm, Nigel Rantor  wrote:
> Adam Olsen wrote:
> > The chance of *accidentally* producing a collision, although
> > technically possible, is so extraordinarily rare that it's completely
> > overshadowed by the risk of a hardware or software failure producing
> > an incorrect result.
>
> Not when you're using them to compare lots of files.
>
> Trust me. Been there, done that, got the t-shirt.
>
> Using hash functions to tell whether or not files are identical is an
> error waiting to happen.
>
> But please, do so if it makes you feel happy, you'll just eventually get
> an incorrect result and not know it.

Please tell us what hash you used and provide the two files that
collided.

If your hash is 256 bits, then you need around 2**128 files to produce
a collision.  This is known as a Birthday Attack.  I seriously doubt
you had that many files, which suggests something else went wrong.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyGUI 2.0.1

2009-04-16 Thread fyaqq
On 4月16日, 上午3时05分, Suraj Barkale  wrote:
> Greg Ewing  canterbury.ac.nz> writes:
>
> >PyGUI2.0.1 is available:
>
> Thank you very much for this GUI toolkit. I always wanted something like this 
> on
> windows. I installed this and tried out the tests on Python 2.6.1 and Windows 
> XP
> SP3. Following are my observations. I will try to send some patches once I 
> have
> looked at the code in detail.
>
> After installing on windows I had to manually delete
> "C:\python26\lib\site-packages\GUI\Win32\__init__.py" in order to get it work.
>
> Test 02-window.py:
> 1. Resizing window produces white horizontal bars. Use double buffering to
> prevent this?
>
> Test 05-checkbox.py:
> 1. Checkbok background is a black rectangle.
>
> Test 06-radiobutton.py:
> 1. Radiobutton has a white background.
>
> Test 09-textfield.py:
> 1. All textfields have black area at right & bottom.
> 2. For multiline textfield, the black are is not painted over during 
> repaint.
> 3. Textfields no not have XP style borders.
>
> Test 15-dialog.py:
> 1. Alt+F4 does not work. However Ctrl+Q works fine.
> 2. Initially keyboard navigation is not possible. Once a button is 
> clicked,
> it is focused and keyboard navigation is possible.
> 2. If Cancel button has focus, pressing Enter should print Cancel. 
> Currently
> it prints OK.
> 3. Pressing spacebar should activate focused button.
>
> Test 18-exceptions.py:
> 1. Printing traceback to console is not sufficient on windows.
>
> Test 29-slider.py:
> 1. Defenitions of 'live' and 'non-live' are swapped in the printed 
> message.
>
> Test 33-mouse-events.py:
> 1. mouse-enter and mouse-leave events are not reported.
>
> Test 37-image-cursor.py:
> 1. Mouse pointer hotspot is in the middle of the image.
>
> Test 38-keys.py:
> 1. Key combinations with Ctrl & Alt are not detected properly.
> 2. Scroll-lock is reported as f14
> 3. Pause/Break is reported as f15
> 4. Caps-lock & Num-lock are detected as keycodes but 'key' is not 
> reported.
>
> Regards,
> Suraj

As Suraj sugguested, I deleted the __init__.py file.  After that I had
no problem running these test files.
But when I ran the blobedit demo, it raied
attributeNotFoundException.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda alternative?

2009-04-16 Thread Duncan Booth
Paul Rubin  wrote:

> Duncan Booth  writes:
>> dumped = dumps(air)
>> t = loads(dumped)
>> print t # works fine
> 
> 
> Hmm, well, that doesn't really pickle the function; it pickles a class
> instance that records where the class definition was and (on
> unpickling) imports that module.  Maybe that is sufficient for this
> purpose.

It pickles a class instance which contains a reference to a function and 
on unpickling it recreates the class instance with a new reference to 
the function of the same name.

That's how pickling works: it records where the class or function is 
defined and creates a new reference to the class or function of the same 
name when you unpickle. The classes and functions have to be defined at 
module scope otherwise it won't be able to reference them. You don't 
ever actually get either a class or function in the pickle so if you 
want you can update the code and the unpickled object gets the new one.

>>> import pickle
>>> class C(object):
def __init__(self, fn):
self.fn = fn
def callfn(self):
self.fn()


>>> def foo():
print "Hello I'm foo"


>>> inst = C(foo)
>>> inst.callfn()
Hello I'm foo
>>> p = pickle.dumps(inst)
>>> def foo():
print "I'm a new foo"


>>> inst2 = pickle.loads(p)
>>> inst2.callfn()
I'm a new foo
>>> inst.callfn()
Hello I'm foo

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Developing modules with ‘pkgutil’

2009-04-16 Thread Peter Otten
Ben Finney wrote:

> At this point I'm stuck. I can't see how to have the
> ‘docutils/__init__.py’ stop shadowing the names in the system-installed
> ‘docutils/__init__.py’, while still doing the namespace shuffle
> necessary to have my in-development module appear part of the wider
> package namespace. What should I be doing instead?

Weird idea. Try putting the following in your __init__.py files:

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
__path__.reverse()
import __init__
globals().update(vars(__init__))
__path__.reverse()

If that doesn't work add

import docutils
docutils.__path__.insert(0, path_to_modified_version)

to your main script. Repeat for every subpackage.

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


Re: Lambda alternative?

2009-04-16 Thread mousemeat
On 16 Apr, 09:39, Duncan Booth  wrote:
> Paul Rubin  wrote:
> > Duncan Booth  writes:
> >> dumped = dumps(air)
> >> t = loads(dumped)
> >> print t # works fine
>
> > Hmm, well, that doesn't really pickle the function; it pickles a class
> > instance that records where the class definition was and (on
> > unpickling) imports that module.  Maybe that is sufficient for this
> > purpose.
>
> It pickles a class instance which contains a reference to a function and
> on unpickling it recreates the class instance with a new reference to
> the function of the same name.
>
> That's how pickling works: it records where the class or function is
> defined and creates a new reference to the class or function of the same
> name when you unpickle. The classes and functions have to be defined at
> module scope otherwise it won't be able to reference them. You don't
> ever actually get either a class or function in the pickle so if you
> want you can update the code and the unpickled object gets the new one.
>
> >>> import pickle
> >>> class C(object):
>
>         def __init__(self, fn):
>                 self.fn = fn
>         def callfn(self):
>                 self.fn()
>
> >>> def foo():
>
>         print "Hello I'm foo"
>
> >>> inst = C(foo)
> >>> inst.callfn()
> Hello I'm foo
> >>> p = pickle.dumps(inst)
> >>> def foo():
>
>         print "I'm a new foo"
>
> >>> inst2 = pickle.loads(p)
> >>> inst2.callfn()
> I'm a new foo
> >>> inst.callfn()
>
> Hello I'm foo
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com


Thank you for everyone's explanations, help and interest on this one.
I have reworked my code as described and promised myself not to use
lambdas ever again (i still think they are an elegant idea, but if
they are incompatible with frequently used modules, then the
inelegance of reality quickly overshadows the elegance of the theory).

I think my problem now is that parallel python will want to unpickle
my objects but can't find the modules.  I've asked the pp forum for
insight, but i think i'm going to have to plug away with this one.

Thanks again,

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


Re: Interrupt Python C API

2009-04-16 Thread Piet van Oostrum
> [email protected] (g1w) wrote:

>g1w> hi, yes, thats true, Alan Touring told us, so it would be nice to let
>g1w> the user abort it.

>g1w> Is there a chance for windows, too?

I don't know. I have no access to Python on Windows. Maybe there is
setitimer support on Windows. Or maybe you can use the threading.Timer
object, like this:

import signal, os
import threading

signalcode = signal.SIGALRM # on Windows, choose one that exists there.

class AlarmError(Exception):
pass

def interrupt():
os.kill(os.getpid(), signalcode)

def execute(command, timeout):
threading.Timer(timeout, interrupt).start()
try:
exec(command)
except AlarmError, e:
print e
print 'Aborted "%s"' % (command,)
print "continue work"

print "The everlasting command"
execute("while 1: pass", 10)
print "The End"

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check all elements of a list are same or different

2009-04-16 Thread Piet van Oostrum
> John Machin  (JM) wrote:

>JM> On Apr 16, 8:14 am, Chris Rebert  wrote:
>>> 
>>> def all_same(lst):
>>>     return len(set(lst)) == 1
>>> 
>>> def all_different(lst):
>>>     return len(set(lst)) == len(lst)

>JM> @ OP: These are very reasonable interpretations of "all same" and "all
>JM> different" but of course can both return False for the same input.

They can even both return True for the same input!
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list


compiler package vs parser

2009-04-16 Thread Robin Becker

Is the compiler package actually supposed to be equivalent to the parser module?

I ask because the following code

 start p.py
def func(D):
for k in D:
exec '%s=D[%r]' % (k,k)
print i, j, k
print locals()
print i, j, k

if __name__=='__main__':
func(dict(i=1,j=33))
 end p.py

when run through the compiler package to produce a module has different code to 
that produced by the standard compilation (detected by dis.dis). In particular 
the variables i and j in func above are treated differently; in the standard 
compiler case LOAD_NAME is used and in the code from the package LOAD_GLOBAL is 
used.


The code used to create the synthetic module is

 start tp.py
from compiler import parse, pycodegen, misc, syntax
import time, struct, marshal
txt=open('p.py','r').read()

tree=parse(txt)
print 'tree\n',tree

def _get_tree(tree,filename):
misc.set_filename(filename, tree)
syntax.check(tree)
return tree

def getPycHeader():
mtime = time.time()
mtime = struct.pack('The module synp.pyc fails with a traceback (as expected because there are no 
global i,j), but p.py runs OK.


I assume that my attempt to compile the tree is broken (is missing some special 
traverse etc) otherwise the code would end up the same (except for line 
numbering which I have ignored).

--
Robin Becker

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


Re: What IDE support python 3.0.1 ?

2009-04-16 Thread mousemeat
Use eclipse with the pydev module.  I use python(x,y) which is a big
bundle of most of the python stuff you could possibly want (including
scientific stuff, but its not mandatory to use it) configured to work
together.  It uses python 2.5.

You can have the best of both worlds.  Search for 'from __future__
import'  to see how to get 3.0 features into 2.x, minimizing the
eventual upgrade hassles.
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-16 Thread Adam Olsen
On Apr 16, 3:16 am, Nigel Rantor  wrote:
> Adam Olsen wrote:
> > On Apr 15, 12:56 pm, Nigel Rantor  wrote:
> >> Adam Olsen wrote:
> >>> The chance of *accidentally* producing a collision, although
> >>> technically possible, is so extraordinarily rare that it's completely
> >>> overshadowed by the risk of a hardware or software failure producing
> >>> an incorrect result.
> >> Not when you're using them to compare lots of files.
>
> >> Trust me. Been there, done that, got the t-shirt.
>
> >> Using hash functions to tell whether or not files are identical is an
> >> error waiting to happen.
>
> >> But please, do so if it makes you feel happy, you'll just eventually get
> >> an incorrect result and not know it.
>
> > Please tell us what hash you used and provide the two files that
> > collided.
>
> MD5
>
> > If your hash is 256 bits, then you need around 2**128 files to produce
> > a collision.  This is known as a Birthday Attack.  I seriously doubt
> > you had that many files, which suggests something else went wrong.
>
> Okay, before I tell you about the empirical, real-world evidence I have
> could you please accept that hashes collide and that no matter how many
> samples you use the probability of finding two files that do collide is
> small but not zero.

I'm afraid you will need to back up your claims with real files.
Although MD5 is a smaller, older hash (128 bits, so you only need
2**64 files to find collisions), and it has substantial known
vulnerabilities, the scenario you suggest where you *accidentally*
find collisions (and you imply multiple collisions!) would be a rather
significant finding.

Please help us all by justifying your claim.

Mind you, since you use MD5 I wouldn't be surprised if your files were
maliciously produced.  As I said before, you need to consider
upgrading your hash every few years to avoid new attacks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check all elements of a list are same or different

2009-04-16 Thread Arnaud Delobelle
Piet van Oostrum  writes:

>> John Machin  (JM) wrote:
>
>>JM> On Apr 16, 8:14 am, Chris Rebert  wrote:
 
 def all_same(lst):
     return len(set(lst)) == 1
 
 def all_different(lst):
     return len(set(lst)) == len(lst)
>
>>JM> @ OP: These are very reasonable interpretations of "all same" and "all
>>JM> different" but of course can both return False for the same input.
>
> They can even both return True for the same input!

I didn't see the simple:

>>> def all_same(l):
... return all(l[i]==l[i+1] for i in range(len(l)-1))
... 
>>> all_same([1,2,3])
False
>>> all_same([1])
True
>>> all_same([1,1,1])
True
>>> all_same([1,1,1,2])
False
>>> all_same([])
True
>>> 

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


Re: binary file compare...

2009-04-16 Thread Nigel Rantor

Adam Olsen wrote:

On Apr 16, 3:16 am, Nigel Rantor  wrote:

Adam Olsen wrote:

On Apr 15, 12:56 pm, Nigel Rantor  wrote:

Adam Olsen wrote:

The chance of *accidentally* producing a collision, although
technically possible, is so extraordinarily rare that it's completely
overshadowed by the risk of a hardware or software failure producing
an incorrect result.

Not when you're using them to compare lots of files.
Trust me. Been there, done that, got the t-shirt.
Using hash functions to tell whether or not files are identical is an
error waiting to happen.
But please, do so if it makes you feel happy, you'll just eventually get
an incorrect result and not know it.

Please tell us what hash you used and provide the two files that
collided.

MD5


If your hash is 256 bits, then you need around 2**128 files to produce
a collision.  This is known as a Birthday Attack.  I seriously doubt
you had that many files, which suggests something else went wrong.

Okay, before I tell you about the empirical, real-world evidence I have
could you please accept that hashes collide and that no matter how many
samples you use the probability of finding two files that do collide is
small but not zero.


I'm afraid you will need to back up your claims with real files.
Although MD5 is a smaller, older hash (128 bits, so you only need
2**64 files to find collisions), and it has substantial known
vulnerabilities, the scenario you suggest where you *accidentally*
find collisions (and you imply multiple collisions!) would be a rather
significant finding.


No. It wouldn't. It isn't.

The files in question were millions of audio files. I no longer work at 
the company where I had access to them so I cannot give you examples, 
and even if I did Data Protection regulations wouldn't have allowed it.


If you still don't beleive me you can easily verify what I'm saying by 
doing some simple experiemnts. Go spider the web for images, keep 
collecting them until you get an MD5 hash collision.


It won't take long.


Please help us all by justifying your claim.


Now, please go and re-read my request first and admit that everything I 
have said so far is correct.



Mind you, since you use MD5 I wouldn't be surprised if your files were
maliciously produced.  As I said before, you need to consider
upgrading your hash every few years to avoid new attacks.


Good grief, this is nothing to do with security concerns, this is about 
someone suggesting to the OP that they use a hash function to determine 
whether or not two files are identical.


Regards,

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


Re: binary file compare...

2009-04-16 Thread Nigel Rantor

Adam Olsen wrote:

On Apr 15, 12:56 pm, Nigel Rantor  wrote:

Adam Olsen wrote:

The chance of *accidentally* producing a collision, although
technically possible, is so extraordinarily rare that it's completely
overshadowed by the risk of a hardware or software failure producing
an incorrect result.

Not when you're using them to compare lots of files.

Trust me. Been there, done that, got the t-shirt.

Using hash functions to tell whether or not files are identical is an
error waiting to happen.

But please, do so if it makes you feel happy, you'll just eventually get
an incorrect result and not know it.


Please tell us what hash you used and provide the two files that
collided.


MD5


If your hash is 256 bits, then you need around 2**128 files to produce
a collision.  This is known as a Birthday Attack.  I seriously doubt
you had that many files, which suggests something else went wrong.


Okay, before I tell you about the empirical, real-world evidence I have 
could you please accept that hashes collide and that no matter how many 
samples you use the probability of finding two files that do collide is 
small but not zero.


Which is the only thing I've been saying.

Yes, it's unlikely. Yes, it's possible. Yes, it happens in practice.

If you are of the opinion though that a hash function can be used to 
tell you whether or not two files are identical then you are wrong. It 
really is that simple.


I'm not sitting here discussing this for my health, I'm just trying to 
give the OP the benefit of my experience, I have worked with other 
people who insisted on this route and had to find out the hard way that 
it was a Bad Idea (tm). They just wouldn't be told.


Regards,

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


Re: Question to python C API

2009-04-16 Thread Andreas Otto
Yes, you are right ...

  I read more and found the doc about this ...

  the problem I have is something more tricky ...

  I allready have an extension written for java
  and the easyest thing would be use this as template
  and replace the java specific calls with python calls ...

  but the python C API is much more complex than java JNI.

  I don't understand why because the task is allways the 
  same

  the problem is that i have a C api but don't want to
  use a 1 to 1 translation of the C functions to python.

  java generate the stub with java.h and you have to fill
  the stub with code even if it is just a function call
  of a C api function with near the same name.

  for me as user I would prefer the exact same way in python
  to:   1. write a python wrapper class
2. declare all external function with "native"
3. call python_h to create the necessary C header
4. and let the user bill the body
5. this require to have a clean and small language
native interface (JNI fit on one web page 
that's it)

  but i have helper functions which , for example, create 
  threads and python module have to attach to this thread.

  the problem with such kind of framework is usually
  that you start with the easy stuff and than (after a couple
  of days/weeks) you come to the difficult stuff and you
  have to figure out that this kind of problem does not
  fit into the tool.

  stuff what I do is:

1. create objects on the fly as connection handle
2. do callbacks from C to Python
3. create and delete threads or manage to continue
work after an fork 
4. is server mode start an event-loop and never come
back


  what I want:

I want to use this tool but still be able to intermix
parts of my "C" helper code with the python code

  question:

it is possible to write C and python code into the 
same file ?


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


Re: Lambda alternative?

2009-04-16 Thread Hrvoje Niksic
mousemeat  writes:

> Thank you for everyone's explanations, help and interest on this
> one.  I have reworked my code as described and promised myself not
> to use lambdas ever again (i still think they are an elegant idea,
> but if they are incompatible with frequently used modules, then the
> inelegance of reality quickly overshadows the elegance of the
> theory).

I think you're going too far concluding that lambdas are unusable.
lambdas are a problem only when they are stored as data attributes
that need to be pickled, but that's far from being the only use case.
You can still use them for what they're meant to be used: tiny anonymous
function-expressions, typically passed as parameters to functions that
expect a callback.

Avoiding lambdas because they're unpicklable is like avoiding bound
methods because they're just as unpicklable.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interrupt Python C API

2009-04-16 Thread googler . 1 . webmaster
On 16 Apr., 11:08, Piet van Oostrum  wrote:
> > [email protected] (g1w) wrote:
> >g1w> hi, yes, thats true, Alan Touring told us, so it would be nice to let
> >g1w> the user abort it.
> >g1w> Is there a chance for windows, too?
>
> I don't know. I have no access to Python on Windows. Maybe there is
> setitimer support on Windows. Or maybe you can use the threading.Timer
> object, like this:
>
> import signal, os
> import threading
>
> signalcode = signal.SIGALRM # on Windows, choose one that exists there.
>
> class AlarmError(Exception):
>     pass
>
> def interrupt():
>     os.kill(os.getpid(), signalcode)
>
> def execute(command, timeout):
>     threading.Timer(timeout, interrupt).start()
>     try:
>         exec(command)
>     except AlarmError, e:
>         print e
>         print 'Aborted "%s"' % (command,)
>     print "continue work"
>
> print "The everlasting command"
> execute("while 1: pass", 10)
> print "The End"
>
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: [email protected]

thx, i will check... :) merci
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda alternative?

2009-04-16 Thread Aaron Brady
On Apr 16, 5:25 am, mousemeat  wrote:
> On 16 Apr, 10:21, Hrvoje Niksic  wrote:
>
>
>
> > mousemeat  writes:
> > > Thank you for everyone's explanations, help and interest on this
> > > one.  I have reworked my code as described and promised myself not
> > > to use lambdas ever again (i still think they are an elegant idea,
> > > but if they are incompatible with frequently used modules, then the
> > > inelegance of reality quickly overshadows the elegance of the
> > > theory).
>
> > I think you're going too far concluding that lambdas are unusable.
> > lambdas are a problem only when they are stored as data attributes
> > that need to be pickled, but that's far from being the only use case.
> > You can still use them for what they're meant to be used: tiny anonymous
> > function-expressions, typically passed as parameters to functions that
> > expect a callback.
>
> > Avoiding lambdas because they're unpicklable is like avoiding bound
> > methods because they're just as unpicklable.
>
> Correct me if i am wrong, but i can pickle an object that contains a
> bound method (it's own bound method).  I cannot pickle an object that
> contains a lambda function.  Doesn't that make lambda's less
> pickleable?  (I don't mean to be argumentative, i'm trying to
> understand python's syntax a little better.)

When you pickle an instance, you get its data and the name of its
class.  If you don't have the class later, you can't unpickle it.

Pickle is intended for persistence, and the only real kinds of
persistent code are a self-contained library file, and the source,
especially given access to function-external variables, i.e.
closures.  Pickling a function is like taking an excerpt from a binary
executable.  It can only be used in highly limited contexts, and as
such not good for a standard module.

It is most likely you want to transmit the source-- either the entire
module, which you can then import dynamically, or an excerpt from it,
which is known to have no closures, etc., and carefully call 'eval' on
it.

I disagree that Andres Tremols & Peter Cogolo's 'Recipe 7.6. Pickling
Code Objects' is applicable.  It's highly specialized, delicate, and
brittle.
--
http://mail.python.org/mailman/listinfo/python-list


Library/classes to burn DVDs given a set of .AVI files

2009-04-16 Thread Aldo Ceccarelli
Hi All,

do you have any experience about any library tool suitable to burn
video DVDs from video (f.i. .avi) file formats?
In negative case and as an alternative: do you have any in other
programming languages?

thanks in advance

WKR,
Aldo
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda alternative?

2009-04-16 Thread mousemeat
On 16 Apr, 10:21, Hrvoje Niksic  wrote:
> mousemeat  writes:
> > Thank you for everyone's explanations, help and interest on this
> > one.  I have reworked my code as described and promised myself not
> > to use lambdas ever again (i still think they are an elegant idea,
> > but if they are incompatible with frequently used modules, then the
> > inelegance of reality quickly overshadows the elegance of the
> > theory).
>
> I think you're going too far concluding that lambdas are unusable.
> lambdas are a problem only when they are stored as data attributes
> that need to be pickled, but that's far from being the only use case.
> You can still use them for what they're meant to be used: tiny anonymous
> function-expressions, typically passed as parameters to functions that
> expect a callback.
>
> Avoiding lambdas because they're unpicklable is like avoiding bound
> methods because they're just as unpicklable.

Correct me if i am wrong, but i can pickle an object that contains a
bound method (it's own bound method).  I cannot pickle an object that
contains a lambda function.  Doesn't that make lambda's less
pickleable?  (I don't mean to be argumentative, i'm trying to
understand python's syntax a little better.)
--
http://mail.python.org/mailman/listinfo/python-list


Is there any way to find out the definition of a function in a file of C language?

2009-04-16 Thread Jebel
Hi ,everyone. I have the name of a function of C language, and have
the source file which the function is defined in. And I want to find
out the type and name of the parameters. If I need to analyze the file
by myself, or have some way to do it more easily?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying the value of a float-like object

2009-04-16 Thread Eric . Le . Bigot
Th^H^H

On Apr 16, 5:51 am, [email protected] (Aahz) wrote:
> In article <[email protected]>,
>
>   wrote:
>
> >Steven, I'd appreciate if you could refrain from criticizing so
> >bluntly so many points.  I'd be great if you trusted me more for
> >knowing what I'm talking about; I've been a programmer for 25 years,
> >now, and I pretty well know what my own code looks like!  I appreciate
> >your input, but please soften your style!
>
> Fair enough -- but could you please fix your quoting style?  Notice how
> everyone else is putting quotes above commentary.
>
> A: Because it messes up the order in which people normally read text.
> Q: Why is top-posting such a bad thing?
> A: Top-posting.
> Q: What is the most annoying thing on usenet?
> --
> Aahz ([email protected])           <*>        http://www.pythoncraft.com/
>
> Why is this newsgroup different from all other newsgroups?

Thanks for this good piece of advice!  :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda alternative?

2009-04-16 Thread Hrvoje Niksic
mousemeat  writes:

> Correct me if i am wrong, but i can pickle an object that contains a
> bound method (it's own bound method).

No, you can't:

>>> import cPickle as p
>>> p.dumps([])
'(l.'
>>> p.dumps([].append)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: expected string or Unicode object, NoneType found
  
> (I don't mean to be argumentative, i'm trying to understand python's
> syntax a little better.)

Note that this has nothing to do with syntax, but with the
(intentional) limitations of the "pickle" module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: get text from rogramms runn by subprocess.Popen immediatetly

2009-04-16 Thread Diez B. Roggisch

Rüdiger Ranft schrieb:

Hi all,

I need to call some programms and catch their stdout and stderr streams.
While the Popen class from subprocess handles the call, I get the
results of the programm not until the programm finishes. Since the
output of the programm is used to generate a progress indicator, I need
a way to acces the values written to stdout/stderr as fast as possible.


Use the communicate()-method of Popen-objects.

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


Re: Equivalent to C bitmasks and enumerations

2009-04-16 Thread Dave Angel

John Machin wrote:

On Apr 16, 10:13 am, Dave Angel  wrote:
  

For the Color example, how's this for a starting place:

class Color(object):
def __init__(self, name, enum):
self.enum =num
self.name =ame
setattr(Color, name, self)

@staticmethod
def seal():
del Color.__init__
del Color.seal

def __str__(self):
return self.name

Color("RED", 4)
Color("GREEN", 11)
Color.seal()#prevent any new instances from being created

b =olor.RED
print type(b)
print str(b)

a =olor.GREEN
print a



So when you use Color.GREEN in an expression or pass it as a function/
method argument, it produces "GREEN" ... doesn't emulation of a C-
style enum require it to produce 11?

  

print a.enum



  
C-style enums have their limitations.  In any case, the OP had specific 
requirements, and I came close to meeting them.  I figured the purpose 
was to accomplish the same goal (or better) as enums do in C.  So the 
object should be able to be passed around without regard to its 
"value."  And it's printable value is "GREEN".  But if it's used as a 
lookup in a dictionary, it just works right, without getting confused 
with an integer that might also be in the dictionary.


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


Re: What IDE support python 3.0.1 ?

2009-04-16 Thread Ryniek90





Temat:
Re: What IDE support python 3.0.1 ?
Od:
Fabio Zadrozny 
Data:
Wed, 15 Apr 2009 22:25:36 -0300
Do:
Deep_Feelings 

Do:
Deep_Feelings 
Kopia:
[email protected]



I want to start learning python and not wanna waste my time learning
python 2.x ,so i need your advise to what IDE to use for python 3.0.1




Pydev supports Python 2.x and 3.x.

Cheers,

Fabio

  


Komodo IDE, Wing IDE, PyDev, don't know if NetBeans too.
Imo, you should give a chance to Python 2.x.
Turning to the need of rewriting code for Py3k: check the py2to3 script.
--
http://mail.python.org/mailman/listinfo/python-list


get text from rogramms runn by subprocess.Popen immediatetly

2009-04-16 Thread Rüdiger Ranft
Hi all,

I need to call some programms and catch their stdout and stderr streams.
While the Popen class from subprocess handles the call, I get the
results of the programm not until the programm finishes. Since the
output of the programm is used to generate a progress indicator, I need
a way to acces the values written to stdout/stderr as fast as possible.

Beneath is a test which shows what I did

TIA
Rudi

8<---8<---8<-- iodummy.cpp -8<---8<---
#include 
#include 

int main()
{
for( int i = 0; i < 10; i++ )
{
std::cerr << i << std::endl;
sleep(2);
}
}

from subprocess import Popen, PIPE
from time import sleep

p = Popen('./iodummy',stdin=PIPE, stdout=PIPE, stderr=PIPE)
sleep(3)
# now I expect '0\n1\n' in stderr, but read() blocks until
# the end of iodummy.
print p.stderr.read()
p.wait()

-- 
GPG encrypted mails preferred.
GPG verschlüsselte Mails bevorzugt.
---> http://chaosradio.ccc.de/media/ds/ds085.pdf Seite 20 <



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


Re: Python interpreters in threads crash the application

2009-04-16 Thread Aahz
In article <74bec1d9-2109-4b9e-8e4d-541894a4d...@f41g2000pra.googlegroups.com>,
grbgooglefan   wrote:
>
>I have C application in which I have instantiated Python interpreter
>in each worker thread.
>
>When I start the program it crashes at different places in Python code
>but program never finishes normally.
>
>Can you please help me in following queries?
>1) Can we not use Python interpreters per thread instead of having a
>common shared Python interpreter at global level/ scope?

Theoretically you can, but each Python interpreter shares some objects
with others, so you still need to use the Python GIL.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?
--
http://mail.python.org/mailman/listinfo/python-list


Re: get text from rogramms runn by subprocess.Popen immediatetly

2009-04-16 Thread Jeremiah Dodds
On Thu, Apr 16, 2009 at 12:12 PM, Rüdiger Ranft <[email protected]> wrote:

> Hi all,
>
> I need to call some programms and catch their stdout and stderr streams.
> While the Popen class from subprocess handles the call, I get the
> results of the programm not until the programm finishes. Since the
> output of the programm is used to generate a progress indicator, I need
> a way to acces the values written to stdout/stderr as fast as possible.
>
> Beneath is a test which shows what I did
>
> TIA
> Rudi
>
> 8<---8<---8<-- iodummy.cpp -8<---8<---
> #include 
> #include 
>
> int main()
> {
>for( int i = 0; i < 10; i++ )
>{
>std::cerr << i << std::endl;
>sleep(2);
>}
> }
>
> from subprocess import Popen, PIPE
> from time import sleep
>
> p = Popen('./iodummy',stdin=PIPE, stdout=PIPE, stderr=PIPE)
> sleep(3)
> # now I expect '0\n1\n' in stderr, but read() blocks until
> # the end of iodummy.
> print p.stderr.read()
> p.wait()
>
> --
> GPG encrypted mails preferred.
> GPG verschlüsselte Mails bevorzugt.
> ---> http://chaosradio.ccc.de/media/ds/ds085.pdf Seite 20 <
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

Depending on what exactly you're doing (like if you need to send info back
to the program you're spawning), the socket module might be of use. I use it
to communicate between Perl and Python for some stuff I have to do at work,
and it works out rather well.

Specifically, I've found sockets and JSON to work really nicely for
inter-language program communication.
--
http://mail.python.org/mailman/listinfo/python-list


RE: get text from rogramms runn by subprocess.Popen immediatetly

2009-04-16 Thread Barak, Ron
Maybe try:

p = Popen('./iodummy',stdin=PIPE, stdout=PIPE, stderr=PIPE).p

(see "18.1.3.4. Replacing the os.spawn family" in 
http://docs.python.org/library/subprocess.html)

Bye,
Ron. 

> -Original Message-
> From: Rüdiger Ranft [mailto:[email protected]] 
> Sent: Thursday, April 16, 2009 14:13
> To: [email protected]
> Subject: get text from rogramms runn by subprocess.Popen immediatetly
> 
> Hi all,
> 
> I need to call some programms and catch their stdout and 
> stderr streams.
> While the Popen class from subprocess handles the call, I get 
> the results of the programm not until the programm finishes. 
> Since the output of the programm is used to generate a 
> progress indicator, I need a way to acces the values written 
> to stdout/stderr as fast as possible.
> 
> Beneath is a test which shows what I did
> 
> TIA
> Rudi
> 
> 8<---8<---8<-- iodummy.cpp -8<---8<--- 
> #include  #include 
> 
> int main()
> {
> for( int i = 0; i < 10; i++ )
> {
> std::cerr << i << std::endl;
> sleep(2);
> }
> }
> 
> from subprocess import Popen, PIPE
> from time import sleep
> 
> p = Popen('./iodummy',stdin=PIPE, stdout=PIPE, stderr=PIPE)
> sleep(3)
> # now I expect '0\n1\n' in stderr, but read() blocks until # 
> the end of iodummy.
> print p.stderr.read()
> p.wait()
> 
> --
> GPG encrypted mails preferred.
> GPG verschlüsselte Mails bevorzugt.
> ---> http://chaosradio.ccc.de/media/ds/ds085.pdf Seite 20 <
> 
> 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Library/classes to burn DVDs given a set of .AVI files

2009-04-16 Thread Weinhandl Herbert

Aldo Ceccarelli schrieb:

Hi All,

do you have any experience about any library tool suitable to burn
video DVDs from video (f.i. .avi) file formats?
In negative case and as an alternative: do you have any in other
programming languages?


see :
   http://www.rastersoft.com/programas/devede.html
or :
   http://tovid.wikia.com/wiki/Tovid_Wiki


thanks in advance

WKR,
Aldo


hth

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


Re: Re: get text from rogramms runn by subprocess.Popen immediatetly

2009-04-16 Thread Rüdiger Ranft
Diez B. Roggisch schrieb:
> Rüdiger Ranft schrieb:
>> Hi all,
>>
>> I need to call some programms and catch their stdout and stderr streams.
>> While the Popen class from subprocess handles the call, I get the
>> results of the programm not until the programm finishes. Since the
>> output of the programm is used to generate a progress indicator, I need
>> a way to acces the values written to stdout/stderr as fast as possible.
> 
> Use the communicate()-method of Popen-objects.

It gives the same behavior, the first call to communicate gets all text,
the second gives a closed handle error :(. I also tried
p.communicate(''), which gives the same as p.communicate(None) result.

bye
Rudi

cat run.py
from subprocess import Popen, PIPE
from time import sleep

p = Popen('./iodummy',stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=2)
sleep(3)
# now I expect '0\n1\n' in stderr
print 'Point1:', p.communicate(None)
sleep(3)
print 'Point2:', p.communicate(None)
p.wait()

python run.py
Point1: ('', '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n')
Point2:
Traceback (most recent call last):
  File "run.py", line 9, in ?
print 'Point2:', p.communicate('')
  File "/usr/lib/python2.4/subprocess.py", line 1028, in communicate
self.stdin.flush()
ValueError: I/O operation on closed file

-- 
GPG encrypted mails preferred.
GPG verschlüsselte Mails bevorzugt.
---> http://chaosradio.ccc.de/media/ds/ds085.pdf Seite 20 <
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question to python C API

2009-04-16 Thread Diez B. Roggisch


it is possible to write C and python code into the 
same file ?


Not as such.

And JNI is an atrocity, btw.

But what you can do (if you have a pure C-API, no C++) is to completely 
ditch the C from the equation and go for ctypes. This allows you to 
easily wrap the C-functions in pure python, and then write a simple 
layour for OO-goodness around it.


Callbacks from C to python work without a hitch, and generally it's 
really cool to work with ctypes.


You can also try & use Cython, a Python-like language that makes 
bridging between C and Python easier. I personally don't have any 
experience with it (only it's predecessor Pyrex, which worked well for 
me) - but to be honest: as long as you aren't in there for speed (Cython 
can make things faster, if you restrict yourself to the subset the 
language supports), ctypes is the easiest thing to go for. No compiler, 
no hassle.


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


Re: Is there any way to find out the definition of a function in a file of C language?

2009-04-16 Thread Diez B. Roggisch

Jebel schrieb:

Hi ,everyone. I have the name of a function of C language, and have
the source file which the function is defined in. And I want to find
out the type and name of the parameters. If I need to analyze the file
by myself, or have some way to do it more easily?



Google for ctypes and gccxml.

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


Re: Developing modules with ‘pkgutil’

2009-04-16 Thread Ben Finney
Peter Otten <[email protected]> writes:

> Weird idea. Try putting the following in your __init__.py files:
> 
> import pkgutil
> __path__ = pkgutil.extend_path(__path__, __name__)
> __path__.reverse()
> import __init__
> globals().update(vars(__init__))
> __path__.reverse()

That's rather astounding. It doesn't *quite* work, but here's what did
work:

=
# docutils/__init__.py
# Python package for in-development docutils packages.

import pkgutil

# Ensure we can also reach modules in the system package
__path__ = pkgutil.extend_path(__path__, __name__)

# Make this directory come last when importing from this package
__path__.reverse()

# Make this package gain all the attributes of the system package
_path_prev = __path__
import __init__
globals().update(vars(__init__))
__path__ = _path_prev
del _path_prev

# Make this directory come first when importing from this package
__path__.reverse()
=

Plus the same thing in ‘docutils/writers/__init__.py’.

Pretty ugly. I hope namespace packages can come along and save us from
this.

> If that doesn't work add
> 
> import docutils
> docutils.__path__.insert(0, path_to_modified_version)
> 
> to your main script. Repeat for every subpackage.

No, modifying the program is exactly what I'm trying to avoid; that
file, unlike these development-only shims, will actually be installed on
the end-user's system. The point of the exercise is to set up the
development working tree so that it presents the in-development module
transparently to the program, and the program remains untainted by these
ugly hacks :-)

But, since the above re-worked package module does the job, I'm able to
continue (though appalled at the hackiness required). Thank you!

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\ Brain, but isn't a cucumber that small called a gherkin?” |
_o__)   —_Pinky and The Brain_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Create standalone Windows program with simple graphics?

2009-04-16 Thread Poster28
Hi,

I'd like to program and compile a simple graphics program (showing something
like a chess board, some numbers and buttons, mouse support) and provide it
as a standalone binary for Windows users.

What is the easiest way to do that? Which libraries or compilers I should
use?
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-16 Thread Craig
Well i use netbean is alot better i think and it work with 2.6 and 3.0

--- On Thu, 4/16/09, mousemeat  wrote:

From: mousemeat 
Subject: Re: What IDE support python 3.0.1 ?
To: [email protected]
Date: Thursday, April 16, 2009, 4:41 AM

Use eclipse with the pydev module.  I use python(x,y) which is a big
bundle of most of the python stuff you could possibly want (including
scientific stuff, but its not mandatory to use it) configured to work
together.  It uses python 2.5.

You can have the best of both worlds.  Search for 'from __future__
import'  to see how to get 3.0 features into 2.x, minimizing the
eventual upgrade hassles.
--
http://mail.python.org/mailman/listinfo/python-list



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


Re: [Python-Dev] RELEASED Python 2.6.2

2009-04-16 Thread Ronald Oussoren


On 15 Apr, 2009, at 22:47, Russell E. Owen wrote:


Thank you for 2.6.2.

I see the Mac binary installer isn't out yet (at least it is not  
listed

on the downloads page). Any chance that it will be compatible with 3rd
party Tcl/Tk?


The Mac installer is late because I missed the pre-announcement of the  
2.6.2 tag. I sent the installer to Barry earlier today.


The installer was build using a 3th-party installation of Tcl/Tk.

Ronald

smime.p7s
Description: S/MIME cryptographic signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python unit tests.

2009-04-16 Thread alessiogiovanni . baroni
On 15 Apr, 16:18, [email protected] wrote:
>     > how do I read the info athttp://coverage.livinglogic.de? For
>     > example, inhttp://coverage.livinglogic.de/Objects/funcobject.c.html,
>     > the count field, what it means?
>
> Most likely it's the number of times that line was executed.  Strong support
> for that comes from the fact that the lines with a count of 0 are
> highlighted, implying they weren't executed at all.
>
> --
> Skip Montanaro - [email protected] -http://www.smontanaro.net/
>         "XML sucks, dictionaries rock" - Dave Beazley

Yes, I thinked to number of times. However, I ask the question because
here
( http://www.python.org/dev/contributing/ ) says to consider
http://coverage.livinglogic.de/
to contributing unit tests, and I asked how to interpret it.

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


Re: get text from rogramms runn by subprocess.Popen immediatetly

2009-04-16 Thread Diez B. Roggisch

Rüdiger Ranft schrieb:

Diez B. Roggisch schrieb:

Rüdiger Ranft schrieb:

Hi all,

I need to call some programms and catch their stdout and stderr streams.
While the Popen class from subprocess handles the call, I get the
results of the programm not until the programm finishes. Since the
output of the programm is used to generate a progress indicator, I need
a way to acces the values written to stdout/stderr as fast as possible.

Use the communicate()-method of Popen-objects.


It gives the same behavior, the first call to communicate gets all text,
the second gives a closed handle error :(. I also tried
p.communicate(''), which gives the same as p.communicate(None) result.


That's likely due to buffering then. You could try & see if flushing on 
the side of the subprocess works (you can't do that from python's side 
of things within this scenario).


Or you might want to use pexpect that emulates a pseudo-terminal which 
also changes the way data is displayed.


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


Passing all extra commandline arguments to python program, Optparse raises exception

2009-04-16 Thread sapsi
Hello,
Im using optparse and python 2.6 to parse some options, my commandline
looks like

prog [options] start|stop extra-args-i-will-pas-on

The options are --b --c --d

The extra options are varied are are passed onto another program e.g --
quiet --no-command , my program doesnt care what these are but instead
passes them onto another program.

I know these will always follow start|stop.

However optparse tries to process them and throws an exception - how
can i prevent this without placing all the extra-args in quotes.

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


Python-URL! - weekly Python news and links (Apr 16)

2009-04-16 Thread Gabriel Genellina
QOTW:  "Yes, by Daddy telling him so. That's how nature does it, and how you
should do it. Or do you think that because DNA-tests are available to us we
should just put all kids into a big pool and make them find out who their
parents are themselves, once they grew up?" - Diez B. Roggisch, on data-
structure design
 http://groups.google.com/group/comp.lang.python/msg/776c738705ad5bee


Python 2.6.2 is available:
http://groups.google.com/group/comp.lang.python/t/37a7dcb59d01eb12/

The behaviour of any()/all() with empty iterables isn't obvious at first:
http://groups.google.com/group/comp.lang.python/t/eaf78b9ed621e535/

Implementing numeric operators (__add__, etc.) without too much
boilerplate code:
http://groups.google.com/group/comp.lang.python/t/b204cf45cc49657c/

Be careful when using the filecmp module to compare file contents:
http://groups.google.com/group/comp.lang.python/t/70b4ad0605287c28/

Detect whether all items in a list are "all equal" or "all different":
http://groups.google.com/group/comp.lang.python/t/60b6527778b0b75f/

Getting back an object given its id():
http://groups.google.com/group/comp.lang.python/t/c81b87582a70fc9e/

In this (long) thread, alternatives to a "mutable float object" are
discussed:
http://groups.google.com/group/comp.lang.python/t/62ce0c5441dcd7ba/

Safe eval of moderately simple math expressions:
http://groups.google.com/group/comp.lang.python/t/c1aff28494ab5b59/

A nice recipe: in `a.b.c.d = x`, create all intermediate attributes
when they don't already exist:
http://groups.google.com/group/comp.lang.python/t/b63b9a420427bfde/

Still discussing PEP 382: Namespace Packages:
http://groups.google.com/group/comp.lang.python/t/aebfb3311a2f5eb6/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available, see:
http://www.python.org/channews.rdf
For more, see:
http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
T

Data uploading to a ftp server

2009-04-16 Thread Ahmed, Shakir

I am getting following error while uploading data to a ftp server. Any
help is highly appreciated.


ftp.storbinary("stor erp.shp", ffile2,8192)
  File "C:\Python24\lib\ftplib.py", line 419, in storbinary
conn.sendall(buf)
  File "", line 1, in sendall
error: (10054, 'Connection reset by peer')

Thanks 
sk

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


Re: Lambda alternative?

2009-04-16 Thread Duncan Booth
Hrvoje Niksic  wrote:

>> Correct me if i am wrong, but i can pickle an object that contains a
>> bound method (it's own bound method).
> 
> No, you can't:
> 
 import cPickle as p
 p.dumps([])
> '(l.'
 p.dumps([].append)
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: expected string or Unicode object, NoneType found

Not the best of examples: [].append is a built-in method rather than a 
bound method. You are correct that you can't pickle a bound method, but the 
actual error message is a bit different:

>>> C().foo
>
>>> [].append

>>> cPickle.dumps(C().foo)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python26\lib\copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
>>> cPickle.dumps([].append)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: expected string or Unicode object, NoneType found

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Create standalone Windows program with simple graphics?

2009-04-16 Thread Chris Rebert
On Thu, Apr 16, 2009 at 6:12 AM, Poster28  wrote:
> Hi,
>
> I'd like to program and compile a simple graphics program (showing something
> like a chess board, some numbers and buttons, mouse support) and provide it
> as a standalone binary for Windows users.
>
> What is the easiest way to do that? Which libraries or compilers I should
> use?

http://www.py2exe.org/

Cheers,
Chris
-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Unpreempted behavior with sys.setcheckinterval

2009-04-16 Thread k3xji
Hi all,

I want unpreempted behavior for some application and do some testing
as below. Well the unpreemption behavior is working fine with
sys.setcheckinterval(sys.maxint). However, when I set the interval to
a lower value, the thread does not being preempted anymore, it runs
until it is finished. The output of the below program is :

Thread 1 is printing out 2000 lines and then Thread 2 prints 2000
lines subsequently.

Here is the code:

import sys
import threading

class B(threading.Thread):
def __init__(self, tid):
threading.Thread.__init__(self)
self.cnt = 0
self.tid = tid
def run(self):
# open file as 'a' to append the line
f = open('preempt_output', 'a')
f.write('Thread '+str(self.tid)+'is starting...\n')
SetUnpreemptable(True)
while(1):
self.cnt += 1
f.write('Thread '+str(self.tid)+':'+str(self.cnt) +'\n')
if self.cnt == 200:
SetUnpreemptable(False)
if self.cnt == 2000:
break

f.close()

def SetUnpreemptable(b):
try:
if b:
sys.setcheckinterval(sys.maxint)
else:
raise
except:
sys.setcheckinterval(dflt_sysinterval)

if __name__ == "__main__":
dflt_sysinterval = sys.getcheckinterval()


thrd3 = B(1)
thrd4 = B(2)
thrd3.start()
thrd4.start()
--
http://mail.python.org/mailman/listinfo/python-list


Man Bites Python

2009-04-16 Thread Aahz
http://news.yahoo.com/s/nm/20090415/od_nm/us_python_odd_1/print
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Man Bites Python

2009-04-16 Thread Roy Hyunjin Han
Hahaha!

On Thu, Apr 16, 2009 at 10:27 AM, Aahz  wrote:
> http://news.yahoo.com/s/nm/20090415/od_nm/us_python_odd_1/print
> --
> Aahz ([email protected])           <*>         http://www.pythoncraft.com/
>
> Why is this newsgroup different from all other newsgroups?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: any(), all() and empty iterable

2009-04-16 Thread Dale Roberts
On Apr 14, 8:33 am, Tim Chase  wrote:
> ...
> I still prefer "Return False if any element of the iterable is
> not true" or "Return False if any element in the iterable is
> false" because that describes exactly what the algorithm does.

I agree that the original doc comment is not helpful as it stands
(even though the behavior of any() is of course correct!), and prefer
Tim's alternative. Since Python is used by programmers (hopefully!),
the doc comment should be directed toward that audience. It should be
unambiguous, and should not assume everyone has perfect knowledge of
mathematical logic operations, or that Python necessarily follows the
rules that a logician would expect (take the varying behavior of
"modulo" operators in various languages as an example).

Pure logic aside, if I was presented with the original comment
('Return True if all elements of the iterable are true.') as a
specification, as a programmer I would immediately have to ask what to
do in the case of an empty list. It might be that the user hadn't
thought about it, or would want to throw an exception, or return
False.

The doc should speak to the intended audience: programmers, who like
to make sure all bases and cases are covered.

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


Re: Create standalone Windows program with simple graphics?

2009-04-16 Thread Dave Angel

Poster28 wrote:

Hi,

I'd like to program and compile a simple graphics program (showing something
like a chess board, some numbers and buttons, mouse support) and provide it
as a standalone binary for Windows users.

What is the easiest way to do that? Which libraries or compilers I should
use?

  


Easiest?  Visual Basic, version 6.  The executables it produces aren't 
really standalone, but the needed DLL's are generally shipped with Windows


Of course, you're asking on a Python list, so presumably you prefer the 
Python programming model.  In that case, you need to look at Py2exe.  
Others here have experience with it, and can advise you whether it's 
close enough for your needs.  I do not think you'll get a single file on 
the user's machine, however.



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


Re: binary file compare...

2009-04-16 Thread Grant Edwards
On 2009-04-16, Adam Olsen  wrote:

> The chance of *accidentally* producing a collision, although
> technically possible, is so extraordinarily rare that it's
> completely overshadowed by the risk of a hardware or software
> failure producing an incorrect result.

 Not when you're using them to compare lots of files.
>>
 Trust me. Been there, done that, got the t-shirt.

I must admit, that is a bit hard to believe.

>> Okay, before I tell you about the empirical, real-world
>> evidence I have could you please accept that hashes collide
>> and that no matter how many samples you use the probability of
>> finding two files that do collide is small but not zero.
>
> I'm afraid you will need to back up your claims with real files.
> Although MD5 is a smaller, older hash (128 bits, so you only need
> 2**64 files to find collisions),

You don't need quite that many to have a significant chance of
a collision.  With "only" something on the order of 2**61
files, you still have about a 1% chance of a collision.

Just for fun here are a few data points showing the probability
of at least one collision in a sample of size n using a perfect
128-bit hash.  These were calculated using the taylor-series
approximation shown at

 http://en.wikipedia.org/wiki/Birthday_paradox#Calculating_the_probability

For "a few million files" (we'll say 4e6), the probability of a
collision is so close to 0 that it can't be calculated using
double-precision IEEE floats.

For a few _billion_ files, the taylor series approximation is
still 0 to about 15 significant digits.

For a few _trillion_ files, you finally get a "non-zero"
probability of about 2e-14.

Here are a few more points:

n = 1806791225998070; p(n) = 0.
n = 1987470348597877; p(n) = 0.0001
n = 2186217383457665; p(n) = 0.0001
n = 2404839121803431; p(n) = 0.0001
n = 2645323033983774; p(n) = 0.0001
n = 2909855337382151; p(n) = 0.0001
n = 3200840871120366; p(n) = 0.0002
n = 3520924958232403; p(n) = 0.0002
n = 3873017454055643; p(n) = 0.0002
n = 4260319199461207; p(n) = 0.0003
n = 4686351119407328; p(n) = 0.0003
n = 5154986231348061; p(n) = 0.0004
n = 5670484854482868; p(n) = 0.0005
n = 623759931155; p(n) = 0.0006
n = 6861286673924271; p(n) = 0.0007
n = 7547415341316699; p(n) = 0.0008
n = 8302156875448370; p(n) = 0.0010
n = 9132372562993208; p(n) = 0.0012
n =10045609819292530; p(n) = 0.0015
n =11050170801221784; p(n) = 0.0018
n =12155187881343964; p(n) = 0.0022
n =13370706669478362; p(n) = 0.0026
n =1470336426200; p(n) = 0.0032
n =16178555070068822; p(n) = 0.0038
n =17796410577075706; p(n) = 0.0047
n =19576051634783280; p(n) = 0.0056
n =21533656798261608; p(n) = 0.0068
n =23687022478087772; p(n) = 0.0082
n =26055724725896552; p(n) = 0.0100
n =28661297198486208; p(n) = 0.0121
n =31527426918334832; p(n) = 0.0146
n =34680169610168320; p(n) = 0.0177
n =38148186571185152; p(n) = 0.0214
n =41963005228303672; p(n) = 0.0259
n =46159305751134040; p(n) = 0.0313
n =50775236326247448; p(n) = 0.0379
n =55852759958872200; p(n) = 0.0458
n =61438035954759424; p(n) = 0.0555
n =67581839550235368; p(n) = 0.0671
n =74340023505258912; p(n) = 0.0812
n =81774025855784816; p(n) = 0.0983
n =89951428441363312; p(n) = 0.1189
n =98946571285499648; p(n) = 0.1439
n =   108841228414049616; p(n) = 0.1741
n =   119725351255454592; p(n) = 0.2106
n =   13169788638164; p(n) = 0.2548
n =   144867675019100096; p(n) = 0.3084
n =   159354442521010112; p(n) = 0.3731
n =   17528988677336; p(n) = 0.4515
n =   192818875450422272; p(n) = 0.5463
n =   212100762995464512; p(n) = 0.6610
n =   233310839295010976; p(n) = 0.7998
n =   256641923224512096; p(n) = 0.9678
n =   282306115546963328; p(n) = 0.00011710
n =   310536727101659712; p(n) = 0.00014169
n =   341590399811825728; p(n) = 0.00017144
n =   375749439793008320; p(n) = 0.00020744
n =   413324383772309184; p(n) = 0.00025099
n =   454656822149540160; p(n) = 0.00030369
n =   500122504364494208; p(n) = 0.00036745
n =   550134754800943680; p(n) = 0.00044460
n =   605148230281038080; p(n) = 0.00053794
n =   665663053309141888; p(n) = 0.00065088
n =   732229358640056192; p(n) = 0.00078751
n =   805452294504061824; p(n) = 0.00095280
n =   885997523954468096; p(n) = 0.00115278
n =   974597276349915008; p(n) = 0.00139469
n =  1072057003984906624; p(n) = 0.00168733
n =  1179262704383397376; p(n) = 0.00204131
n =  1297188974821737216; p(n) = 0.00246945
n =  1426907872303911168; p(n) = 0.00298726
n =  1569598659534302464; p(n) = 0.00361345
n =  1726558525487732736; p(n) = 0.00437061
n =  1899214378036506112; p(n) = 0.00528601
n =  2089135815840156928; p(n) = 

Re: Passing all extra commandline arguments to python program, Optparse raises exception

2009-04-16 Thread Dave Angel

sapsi wrote:

Hello,
Im using optparse and python 2.6 to parse some options, my commandline
looks like

prog [options] start|stop extra-args-i-will-pas-on

The options are --b --c --d

The extra options are varied are are passed onto another program e.g --
quiet --no-command , my program doesnt care what these are but instead
passes them onto another program.

I know these will always follow start|stop.

However optparse tries to process them and throws an exception - how
can i prevent this without placing all the extra-args in quotes.

Thank you
Saptarshi

  

Preprocess the sys.args before calling optparse.
Simply search sys.args for the string "start" and the string "stop", and 
note whichever comes first.  Then use slice operators to peel the extra 
arguments off of sys.args.


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


How to access C structures

2009-04-16 Thread Chris Helck
I have a couple dozen C structures that define binary file records. I
need to read the file and access the records. I need to do this very
efficiantly.

I am aware of the Python struct class, but the C structures contain
arrays of nested structures and I'm not sure if Python struct can handle
it. I am willing to give up portability for speed. I will run the Python
program on the same machine that the file was created on. 

Is there some way to directly expose a C struct to Python?

Regards,
C. Helck

**
This communication and all information (including, but not limited to,
 market prices/levels and data) contained therein (the "Information") is
 for informational purposes only, is confidential, may be legally
 privileged and is the intellectual property of ICAP plc and its affiliates
 ("ICAP") or third parties. No confidentiality or privilege is waived or
 lost by any mistransmission. The Information is not, and should not
 be construed as, an offer, bid or solicitation in relation to any
 financial instrument or as an official confirmation of any transaction.
 The Information is not warranted, including, but not limited, as to
 completeness, timeliness or accuracy and is subject to change
 without notice. ICAP assumes no liability for use or misuse of the
 Information. All representations and warranties are expressly
 disclaimed. The Information does not necessarily reflect the views of
 ICAP. Access to the Information by anyone else other than the
 recipient is unauthorized and any disclosure, copying, distribution or
 any action taken or omitted to be taken in reliance on it is prohibited. If
 you receive this message in error, please immediately delete it and all
 copies of it from your system, destroy any hard copies of it and
 notify the sender.
**

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


Can I use setup.py to ship and install only .pyc files?

2009-04-16 Thread Mike Kent
I'd like to ship only the .pyc files for a module.  I was hoping the
standard distutils setup.py could handle this, but so far, I've not
figured out how.

After a bit of work, I discovered that if I create a MANIFEST.in file,
and put 'include mymodule/*.pyc' and 'exclude mymodule/*.py' in it,
then running 'python setup.py sdist' would generate a tar.gz file for
me that contained the setup.py file and all my .pyc files, just like I
wanted.  However, when I then extract that tar.gz file, and try to run
'python setup.py install', it complains about the missing .py files,
and creates the 'mymodule' directory in the site-packages directory
but without putting any of the .pyc files in it.

At this point, I'm stumped.  I was hoping someone out there had gone
down this same route and could tell what I'm doing wrong.  Can
setup.py even handle this?
--
http://mail.python.org/mailman/listinfo/python-list


setuptools catch 22

2009-04-16 Thread Mac
We've got ActiveState Python 2.6 installed on a Windows XP box, and I
pulled down the latest archgenxml package (2.2) in order to get it
running under this installation of Python.  I unpacked the tarball for
the package and tried running `python setup.py build' but got an
ImportError exception: "no module named setuptools."  So back to
Google, where I find http://pypi.python.org/pypi/setuptools, which
says "[For Windows] install setuptools using the provided .exe
installer."  I go down to the bottom of the page and I see that there
is no .exe installer for Python 2.6.  All there is for that version of
Python is setuptools-0.6c9-py2.6.egg.  I get the impression from the
references to "Python Eggs" on the setuptools page that setuptools is
a utility for installing Python Eggs.  So we're supposed to use a
utility that isn't installed yet to install that utility?  Does anyone
else understand how lame this is?  From where I stand, the story for
installation of third-party packages in Python is a sad, confused
mess, and the Achilles heel of a language of which in all other
respects I think very highly.
--
http://mail.python.org/mailman/listinfo/python-list


Reading an exact number of characters from input

2009-04-16 Thread Paddy O'Loughlin
Hi,
How would I use python to simply read a specific number of characters
from standard input?

raw_input() only returns when the user inputs a new line (or some
other special character).
I tried
>>> import sys
>>> sys.stdin.read(15)

and that *returns* up to 15 characters, but it keeps accepting input
(and doesn't return) until I press Enter.

My initial thoughts are that a function like C's fgetc would be the
easiest way to do it, but I haven't been able to find an equivalent in
my google search, so I was wondering if anyone here might have some
ideas.

What say you?

Paddy

-- 
"Ray, when someone asks you if you're a god, you say YES!"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Create standalone Windows program with simple graphics?

2009-04-16 Thread Poster28
>> What is the easiest way to do that? Which libraries or compilers I should
>> use?
> 
> http://www.py2exe.org/

Will it work with any graphics library?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question to python C API

2009-04-16 Thread Stefan Behnel
Andreas Otto wrote:
>  I want to make a language binding for an existing C library
> 
> http://libmsgque.sourceforge.net
> 
>   is this possible ?

Quoting the third paragraph on Cython's homepage (i.e. the link I posted):

"""
This makes Cython the ideal language for wrapping external C libraries, and
for fast C modules that speed up the execution of Python code.
"""

If you want a fast wrapper module that is easy to write and maintain, while
having all the freedom to design the Python-level API the way you want, I
don't think there is any better way than Cython.

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


Re: setuptools catch 22

2009-04-16 Thread Kay Schluehr
On 16 Apr., 17:39, Mac  wrote:
> We've got ActiveState Python 2.6 installed on a Windows XP box, and I
> pulled down the latest archgenxml package (2.2) in order to get it
> running under this installation of Python.  I unpacked the tarball for
> the package and tried running `python setup.py build' but got an
> ImportError exception: "no module named setuptools."  So back to
> Google, where I findhttp://pypi.python.org/pypi/setuptools, which
> says "[For Windows] install setuptools using the provided .exe
> installer."  I go down to the bottom of the page and I see that there
> is no .exe installer for Python 2.6.  All there is for that version of
> Python is setuptools-0.6c9-py2.6.egg.  I get the impression from the
> references to "Python Eggs" on the setuptools page that setuptools is
> a utility for installing Python Eggs.  So we're supposed to use a
> utility that isn't installed yet to install that utility?  Does anyone
> else understand how lame this is?  

Yes, but there is a known workaround: just download the mantioned
setuptools egg and unpack it - it's basically just a zipped python
package - and place it at your PYTHONPATH. Then it will also be found
by every tool that imports setuptools.

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


Help improve program for parsing simple rules

2009-04-16 Thread pruebauno
Another interesting task for those that are looking for some
interesting problem:
I inherited some rule system that checks for programmers program
outputs that to be ported: given some simple rules and the values it
has to determine if the program is still working correctly and give
the details of what the values are. If you have a better idea of how
to do this kind of parsing please chime in. I am using tokenize but
that might be more complex than it needs to be. This is what I have
come up so far:

rules=[
 '( A - B ) = 0',
 '(A + B + C + D + E + F + G + H + I) = J',
 '(A + B + C + D + E + F + G + H) = I',
 '(A + B + C + D + E + F) = G',
 '(A + B + C + D + E) = (F + G + H + I + J)',
 '(A + B + C + D + E) = (F + G + H + I)',
 '(A + B + C + D + E) = F',
 '(A + B + C + D) = (E + F + G + H)',
 '(A + B + C) = (D + E + F)',
 '(A + B) = (C + D + E + F)',
 '(A + B) = (C + D)',
 '(A + B) = (C - D + E - F - G + H + I + J)',
 '(A + B) = C',
 '(A + B) = 0',
 '(A+B+C+D+E) = (F+G+H+I+J)',
 '(A+B+C+D) = (E+F+G+H)',
 '(A+B+C+D)=(E+F+G+H)',
 '(A+B+C)=(D+E+F)',
 '(A+B)=(C+D)',
 '(A+B)=C',
 '(A-B)=C',
 '(A/(B+C))',
 '(G + H) = I',
 '-0.99 LE ((A+B+C)-(D+E+F+G)) LE 0.99',
 '-0.99 LE (A-(B+C)) LE 0.99',
 '-1000.00 LE A LE 0.00',
 '-5000.00 LE A LE 0.00',
 'A < B',
 'A < 7000',
 'A = -(B)',
 'A = C',
 'A = 0',
 'A GT 0',
 'A GT 0.00',
 'A GT 7.00',
 'A LE B',
 'A LT -1000.00',
 'A LT -5000',
 'A LT 0',
 'A=(B+C+D)',
 'A=B',
 'I = (G + H)',
 '0.00 LE A LE 4.00',
 '4.00 LT A LE 7.00'
 ]
vars_={'A': 0, 'B': 1.1, 'C': 2.2, 'D': 3.3, 'E': 4.4, 'F': 5.5, 'G':
6.6, 'H':7.7, 'I':8.8, 'J':9.9}

import tokenize as TOK
import StringIO as SIO

COMP_REPLACERS={'LT':'<', 'GT':'>', 'LE':'<=', 'GE':'>=', '=':'==',
'=>':'=>', '=<':'=<'}

def get_tokens(string):
return [x[:2] for x in TOK.generate_tokens(SIO.StringIO
(string).readline)][:-1]

def replace_comps(toks,repl):
return [(TOK.OP, repl[x[1]]) if x[1] in repl else x for x in toks]

def replace_names(norm,vars_):
return [(TOK.NUMBER,str(vars_.get(x[1],x[1]))) if x[0]==TOK.NAME
else x for x in norm]

def split_seccions(subs,comp_split):
l=[]
g=[]
for type_,value in subs:
if value in comp_split:
g.append((l,value))
l=[]
else:
l.append((type_,value))
g.append((l,''))
return g

def all_seccions(grps):
return [(TOK.untokenize(lst),comper) for lst,comper in grps]

def calc_seccions(rep):
return [(str(eval(comp,{},{})),comper) for comp,comper in rep]

def calc_deltas(calc):
return [eval(calc[i][0]+'-'+calc[i+1][0],{},{}) for i in range(len
(calc)-1)]

def main():
for cur_rule in rules[20:26]:
tokens=get_tokens(cur_rule)
normal=replace_comps(tokens,COMP_REPLACERS)
subst=replace_names(normal,vars_)
groups=split_seccions(subst,COMP_REPLACERS.values())
rep=all_seccions(groups)
rep_out=''.join(x[0]+x[1] for x in rep)
calc=calc_seccions(rep)
calc_out=''.join(x[0]+x[1] for x in calc)
deltas=calc_deltas(calc)
result=eval(calc_out,{},{})
print
print 'Values:',', '.join(str(key)+': '+str(val) for key,val
in sorted(vars_.iteritems()))
print 'Read rule:   ',cur_rule
print 'Used rule:   ',TOK.untokenize(normal)
print 'Substitution:',rep_out
print 'Calculation: ',calc_out
print 'Result:  ','Successful' if result else 'Failed'
if  not result and '==' in calc_out:
print 'Difference:  ',', '.join(map(str,deltas))
print '='*40


if __name__=='__main__': main()
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-16 Thread Scott David Daniels

Aahz wrote:

In article ,
Brendon Wickham   wrote:

I agree, no IDE needed. Just don't use Notepad! I'm on Mac, so spoiled
for choice of text editors, but I'm sure there's one or 2 good uns if
you're on Windows.


Vim and emacs, of course.  ;-)


No, that is only one great editor and one abomination.
Opinions differ, however, on which one is the abomination. :-)

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Man Bites Python

2009-04-16 Thread alex goretoy
+1 Aahz

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

Mitch Hedberg
- "I drank some boiling water because I wanted to whistle."

On Thu, Apr 16, 2009 at 2:32 PM, Roy Hyunjin Han <
[email protected]> wrote:

> Hahaha!
>
> On Thu, Apr 16, 2009 at 10:27 AM, Aahz  wrote:
> > http://news.yahoo.com/s/nm/20090415/od_nm/us_python_odd_1/print
> > --
> > Aahz ([email protected])   <*>
> http://www.pythoncraft.com/
> >
> > Why is this newsgroup different from all other newsgroups?
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: compiler package vs parser

2009-04-16 Thread Aahz
In article ,
Robin Becker   wrote:
>
>Is the compiler package actually supposed to be equivalent to the
>parser module?

Before I poke my nose into this, what versions of Python have you tried?
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: setuptools catch 22

2009-04-16 Thread Diez B. Roggisch

Mac schrieb:

We've got ActiveState Python 2.6 installed on a Windows XP box, and I
pulled down the latest archgenxml package (2.2) in order to get it
running under this installation of Python.  I unpacked the tarball for
the package and tried running `python setup.py build' but got an
ImportError exception: "no module named setuptools."  So back to
Google, where I find http://pypi.python.org/pypi/setuptools, which
says "[For Windows] install setuptools using the provided .exe
installer."  I go down to the bottom of the page and I see that there
is no .exe installer for Python 2.6.  All there is for that version of
Python is setuptools-0.6c9-py2.6.egg.  I get the impression from the
references to "Python Eggs" on the setuptools page that setuptools is
a utility for installing Python Eggs.  So we're supposed to use a
utility that isn't installed yet to install that utility?  Does anyone
else understand how lame this is?  From where I stand, the story for
installation of third-party packages in Python is a sad, confused
mess, and the Achilles heel of a language of which in all other
respects I think very highly.



googling "setuptools bootstrap" yields this as first link:

http://peak.telecommunity.com/dist/ez_setup.py

Download that, and run "python ez_setup.py". That's it.


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


Re: What IDE support python 3.0.1 ?

2009-04-16 Thread Aahz
In article ,
Scott David Daniels   wrote:
>Aahz wrote:
>> In article ,
>> Brendon Wickham   wrote:
>>>
>>> I agree, no IDE needed. Just don't use Notepad! I'm on Mac, so spoiled
>>> for choice of text editors, but I'm sure there's one or 2 good uns if
>>> you're on Windows.
>> 
>> Vim and emacs, of course.  ;-)
>
>No, that is only one great editor and one abomination.
>Opinions differ, however, on which one is the abomination. :-)

Note that Brendon was careful to say "one or two" and that I followed
along.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading an exact number of characters from input

2009-04-16 Thread Diez B. Roggisch

Paddy O'Loughlin schrieb:

Hi,
How would I use python to simply read a specific number of characters
from standard input?

raw_input() only returns when the user inputs a new line (or some
other special character).
I tried

import sys
sys.stdin.read(15)


and that *returns* up to 15 characters, but it keeps accepting input
(and doesn't return) until I press Enter.

My initial thoughts are that a function like C's fgetc would be the
easiest way to do it, but I haven't been able to find an equivalent in
my google search, so I was wondering if anyone here might have some
ideas.


Maybe ncurses helps. Or you can use termios and set the terminal into 
non-canonical mode which will let you get characters as they appear, not 
only after a newline.


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


Re: Imports in python are static, any solution?

2009-04-16 Thread Ravi
On Apr 14, 1:23 am, norseman  wrote:
> AJ Mayorga wrote:
> > For something like this I generally create a superclass to hold
> > configuration variables that will change overtime, doing that will save you
> > from insanity.
>
> > Class configVar:
>
> >    #set initial values
> >    Def __init__(self):
> >            Self.A = 5
> >            Self.B = 10
> >            Self.C = 20
>
> > Class myMath(configVars):
> >    def __init__(self):
> >            pass
>
> >    def SubAandB(self):
> >            return self.A - self.B
>
> >    def AddCandB(self):
> >            return self.C + self.B
>
> >    def MultiplyXbyA(self, x):
> >            return self.A * x
>
> > m = myMath()
> > X = m.SubAandB()
> > Y = m.AddCandB()
> > Z = m.MultiplyXbyA(32)
>
> > Keeps your vars in a safer easier to handle, debug, and change kinda way
> > Good luck
>
> > AJ
>
> > -Original Message-
> > From: [email protected]
> > [mailto:[email protected]] On Behalf Of David
> > Stanek
> > Sent: Monday, April 13, 2009 12:12 PM
> > To: Ravi
> > Cc: [email protected]
> > Subject: Re: Imports in python are static, any solution?
>
> > On Mon, Apr 13, 2009 at 11:59 AM, Ravi  wrote:
> >> foo.py :
>
> >>    i = 10
>
> >>   def fi():
> >>      global i
> >>      i = 99
>
> >> bar.py :
>
> >>    import foo
> >>    from foo import i
>
> >>    print i, foo.i
> >>    foo.fi()
> >>    print i, foo.i
>
> >> This is problematic. Well I want i to change with foo.fi() .
>
> > Why not only import foo and using foo.i? In fi() when you set i = 99
> > you are creating a new object called i in foo's namespace.
>
> ===
>
> Aj is right. In foo.py there are two definitions for 'i'. The initial
> and the replacement initiated by fi(). While initially there is no 'i'
> definition in bar itself.
>
> To test, use my changes to bar.py
>
> import foo
> #from foo import i
>
> i= foo.i
> print i, foo.i
> x= foo.fi()
> print i, x, foo.i
> x= foo.i
> print  i, x, foo.i
>
> the output will be:
> 10 10
> 10 None 99
> 10 99 99
>
> output is same if you uncomment #from... and comment i=...
> The '...import i' creates the "same" var as the i=... in the current run
> If you comment out both the from and the i= then the print i will fail
> because i has not been defined in current space.
> foo.fi() returns None (nothing) per it's definition.
> whereas the first foo.i returns the initial i value and the foo.i after
> foo.fi() returns the 2nd value, foo's i reset to 99 by fi() inside foo.
>
> Clear as Mud???
>
> Steve

Yes I find the difference. Thank you all.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading an exact number of characters from input

2009-04-16 Thread Scott David Daniels

Paddy O'Loughlin wrote:

Hi,
How would I use python to simply read a specific number of characters
from standard input?

raw_input() only returns when the user inputs a new line (or some
other special character).
I tried

import sys
sys.stdin.read(15)


and that *returns* up to 15 characters, but it keeps accepting input
(and doesn't return) until I press Enter.

My initial thoughts are that a function like C's fgetc would be the
easiest way to do it, but I haven't been able to find an equivalent in
my google search, so I was wondering if anyone here might have some
ideas.


Terminal I/O via stdin is often line buffered, and for very good
reasons.  If, after executing sys.stdin.read(15) I typed 20 "A"s,
then 19 backspaces, then 19 "a"s, what would you want the result to be?
Now that you've answered that, how would a system that provided
you that behavior allow the other answer to someone who wanted
the opposite.

sys.stdin is not a keyboard driver.

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Getting Newsgroup Headers

2009-04-16 Thread aslkoi fdsda
I would like to read just the headers out of a newsgroup.
Being a Python newbie, I was wondering if this is possible and how difficult
it would be for a novice Python programmer.
Thanks for any reply!
--
http://mail.python.org/mailman/listinfo/python-list


Choose: class with static methods or module with functions

2009-04-16 Thread Ravi
I have to create a few helper/utility application-wide functions.
There are two options:

1. Create a Utility class and all functions as static method of that
class.

2. Create a module, utility.py and member functions.

Which is a better approach.

My personal view is that I should create a module with functions.
Classes are appropriate only when I am creating new types.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question to python C API

2009-04-16 Thread Stefan Behnel
Andreas Otto wrote:
>   the problem with such kind of framework is usually
>   that you start with the easy stuff and than (after a couple
>   of days/weeks) you come to the difficult stuff and you
>   have to figure out that this kind of problem does not
>   fit into the tool.

That is a very common problem with so-called "wrapper generators", such as
SWIG, PyBindGen, sip, and some others. They get you to a 1:1 wrapper
quickly, but as soon as you try to abstract your wrapper from the
underlying C API, you start reaching the limits of the tools almost as
quickly (or at least have a hard time pushing the tool the way you want).


>   stuff what I do is:
> 
> 1. create objects on the fly as connection handle
> 2. do callbacks from C to Python
> 3. create and delete threads or manage to continue
> work after an fork 
> 4. is server mode start an event-loop and never come
> back

Not uncommon for a C library wrapper at all. I assume that the "server
mode" event-loop calls back into Python from time to time? You will sooo
love the "with gil" function feature in Cython...


>   what I want:
> 
> I want to use this tool but still be able to intermix
> parts of my "C" helper code with the python code
> 
>   question:
> 
> it is possible to write C and python code into the 
> same file ?

I'm glad you asked :)

That's basically what the Cython language is all about. Think of it as a
programming language that is almost Python, but at the same time allows you
to work with C data types and do direct calls into C code. All of that gets
translated into very fast C code that you can easily hand-tune to your
needs. You basically have all the freedom of the Python language with all
the freedom of the C language.

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


Re: Choose: class with static methods or module with functions

2009-04-16 Thread bearophileHUGS
Ravi:
> Which is a better approach.
> My personal view is that I should create a module with functions.

When in doubt, use the simplest solution that works well enough. In
this case, module functions are simple and probably enough.

But there can be a situation where you want to keep functions even
closer, for example because in a module you have two classes and two
groups of functions related to each class. In such situation
staticmethods seem better.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Queue() question. This post is pretty long.

2009-04-16 Thread grocery_stocker
I don't get how   item = self.__queue.get() gets advanced to

if item is None:

in the following code.

>>> import time
>>> from threading import Thread
>>> import Queue
>>>
>>> WORKER = 2
>>>
>>> class Worker(Thread):
... def __init__(self, queue):
... Thread.__init__(self)
... self.__queue = queue
... def run(self):
... while 1:
...   item = self.__queue.get()
...   if item is None:
...  break
...   print "task", item, "finished"
...

>>> for i in range(WORKER):
... Worker(queue).start()
...
>>> for i in range(10):
... queue.put(i)
...
>>> task 0 finished
task 1 finished
task 2 finished
task 3 finished
task 4 finished
task 5 finished
task 6 finished
task 7 finished
task 8 finished
task 9 finished
>>> for i in range(WORKER):
... queue.put(None)
...

This because when I do something like

[cdal...@localhost ~]$ python
Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Queue
>>> queue = Queue.Queue()
>>>
>>> while 1:
...item = queue.get()
...if item == 'done':
...   break
...
this
is
a
test
done

[3]+  Stopped python
[cdal...@localhost ~]$ kill %3

It appears that only item = queue.get() called. Ie, the block never
advances to if item == 'done':
like in the first example

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


Re: binary file compare...

2009-04-16 Thread SpreadTooThin
On Apr 16, 3:16 am, Nigel Rantor  wrote:
> Adam Olsen wrote:
> > On Apr 15, 12:56 pm, Nigel Rantor  wrote:
> >> Adam Olsen wrote:
> >>> The chance of *accidentally* producing a collision, although
> >>> technically possible, is so extraordinarily rare that it's completely
> >>> overshadowed by the risk of a hardware or software failure producing
> >>> an incorrect result.
> >> Not when you're using them to compare lots of files.
>
> >> Trust me. Been there, done that, got the t-shirt.
>
> >> Using hash functions to tell whether or not files are identical is an
> >> error waiting to happen.
>
> >> But please, do so if it makes you feel happy, you'll just eventually get
> >> an incorrect result and not know it.
>
> > Please tell us what hash you used and provide the two files that
> > collided.
>
> MD5
>
> > If your hash is 256 bits, then you need around 2**128 files to produce
> > a collision.  This is known as a Birthday Attack.  I seriously doubt
> > you had that many files, which suggests something else went wrong.
>
> Okay, before I tell you about the empirical, real-world evidence I have
> could you please accept that hashes collide and that no matter how many
> samples you use the probability of finding two files that do collide is
> small but not zero.
>
> Which is the only thing I've been saying.
>
> Yes, it's unlikely. Yes, it's possible. Yes, it happens in practice.
>
> If you are of the opinion though that a hash function can be used to
> tell you whether or not two files are identical then you are wrong. It
> really is that simple.
>
> I'm not sitting here discussing this for my health, I'm just trying to
> give the OP the benefit of my experience, I have worked with other
> people who insisted on this route and had to find out the hard way that
> it was a Bad Idea (tm). They just wouldn't be told.
>
> Regards,
>
>    Nige

And yes he is right CRCs hashing all have a probability of saying that
the files are identical when in fact they are not.
--
http://mail.python.org/mailman/listinfo/python-list


Domain Driven Design and Python

2009-04-16 Thread José María
Hi,

I've been searching for information about the application of DDD
principles in
Python and I did'nt found anything!

Is DDD obvious in Python or is DDD inherent to static languages like
Java or C#?

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


Re: any(), all() and empty iterable

2009-04-16 Thread Raymond Hettinger
> The doc should speak to the intended audience: programmers, who like
> to make sure all bases and cases are covered.

FWIW, I wrote the docs.  The pure python forms were put in
as an integral part of the documentation.  The first
sentence of prose was not meant to stand alone.  It is a
lead-in to the code which makes explicit the short-circuiting
behavior and the behavior when the input is empty.

I will not change the sentence to "return false if any element
of the iterable is false."  The negations make the sentence
hard to parse mentally and do not provide a motivation for
the use of the word "all".  As it stands, the sentence provides
a clean lead-in for the code which is there "to make sure all
bases and cases are covered".  I put code in the docs to make
the docs precise.  We use code in the docs because it can
communicate clearly in cases where plain English prose is
either vague, awkward, hard to read, imprecise, or subject
to misinterpretation.

Of course, neither code nor accompanying prose help if prior
to reading them, a reader already has formed a strong but
incorrect mental picture of what the function does.  If
someone has a priori convinced themselves that all([]) returns
False or has never thought about that case, then a cursory
reading of the docs is unlikely to disabuse them of that notion.
At any rate, all readers of this thread now seem to be
dialed-in as to why the current behavior is desirable.

I will probably leave the lead-in sentence as-is but may
add another sentence specifically covering the case for
an empty iterable.


Raymond


P.S.  Now maybe we can start a new thread about why sum([])
returns zero ;-)


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


pyqt4: setText() inside a function

2009-04-16 Thread l . freschi
I'm developing a PyQt4 application.

I have created a button:
...
self.start_button=QtGui.QPushButton("start simulation", self)
...

that is connected to a function:
...
self.connect(self.start_button, QtCore.SIGNAL('clicked()'),
self.simulate)
...

This is the function:
...
def simulate(self):

self.log_inspector.setText('')
cmds=['rm engine','make engine', './
engine']
first_cmd="./parser "+str(self.filename)
cmds.insert(0, first_cmd)
for cmd in cmds:
self.status_inspector.setText(cmd)
status, output = commands.getstatusoutput(cmd)
output_list=output.split("\n")
output_list.reverse()
output_def="\n".join(output_list)
if status != 0:
self.log_inspector.setText(cmd"...
[ERROR]\n"+output_def)
return
self.status_inspector.setText("Done!")
...

I would like to change the value of status_inspector (It's a QLabel)
during the execution of the function.
Is it possible?

I'm a newbie with PyQt and OOP!

Thank you!

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


Re: get text from rogramms runn by subprocess.Popen immediatetly

2009-04-16 Thread norseman

Rüdiger Ranft wrote:

Hi all,

I need to call some programms and catch their stdout and stderr streams.
While the Popen class from subprocess handles the call, I get the
results of the programm not until the programm finishes. Since the
output of the programm is used to generate a progress indicator, I need
a way to acces the values written to stdout/stderr as fast as possible.

Beneath is a test which shows what I did

TIA
Rudi

8<---8<---8<-- iodummy.cpp -8<---8<---
#include 
#include 

int main()
{
for( int i = 0; i < 10; i++ )
{
std::cerr << i << std::endl;
sleep(2);
}
}

from subprocess import Popen, PIPE
from time import sleep

p = Popen('./iodummy',stdin=PIPE, stdout=PIPE, stderr=PIPE)
sleep(3)
# now I expect '0\n1\n' in stderr, but read() blocks until
# the end of iodummy.
print p.stderr.read()
p.wait()





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


Take a look at lib.pdf section 14.1.2  popen3
avoids PIPE problems


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


Re: pyqt4: setText() inside a function

2009-04-16 Thread Diez B. Roggisch

[email protected] schrieb:

I'm developing a PyQt4 application.

I have created a button:
...
self.start_button=QtGui.QPushButton("start simulation", self)
...

that is connected to a function:
...
self.connect(self.start_button, QtCore.SIGNAL('clicked()'),
self.simulate)
...

This is the function:
...
def simulate(self):

self.log_inspector.setText('')
cmds=['rm engine','make engine', './
engine']
first_cmd="./parser "+str(self.filename)
cmds.insert(0, first_cmd)
for cmd in cmds:
self.status_inspector.setText(cmd)
status, output = commands.getstatusoutput(cmd)
output_list=output.split("\n")
output_list.reverse()
output_def="\n".join(output_list)
if status != 0:
self.log_inspector.setText(cmd"...
[ERROR]\n"+output_def)
return
self.status_inspector.setText("Done!")
...

I would like to change the value of status_inspector (It's a QLabel)
during the execution of the function.
Is it possible?


If you want GUI-updates while performing time-consuming tasks, you need 
to make sure Qt's event-loop get's called every now and then. This 
should help you:


void QCoreApplication::processEvents ( QEventLoop::ProcessEventsFlags 
flags = QEventLoop::AllEvents )   [static]



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


Re: WHIFF - was: Re: Using Python after a few years of Ruby

2009-04-16 Thread Aaron Watters
On Apr 15, 4:35 pm, Gerhard Häring  wrote:
> WTF?! This is weird stuff! Why the hell would I use this instead of a
> Python web framework like Django/Pylons/etc.

Ok folks. I've added a page:

  "Whiff is cool because: How do you make a page
  like this using another package?"

  http://aaron.oirt.rutgers.edu/myapp/docs/W1500.whyIsWhiffCool

This doesn't compare WHIFF to Django/Pylons/etc
except to make the unsubstantiated claim that you
can't do the stuff demonstrated on the page as
easily using any other package.

The claim may be wrong, but not to my
knowledge.  I'm looking forward to learning
otherwise.  Please don't be too harsh.

   -- Thanks,  Aaron Watters

===
If all the economists in the world
were placed end to end
they'd still point in different directions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: any(), all() and empty iterable

2009-04-16 Thread Tim Chase

Raymond Hettinger wrote:

I will not change the sentence to "return false if any element
of the iterable is false."  The negations make the sentence
hard to parse mentally 


Just as a ribbing, that "return X if any element of the iterable 
is X" is of the same form as the original.  The negation is only 
of the X, not of the sentence structure.



I will probably leave the lead-in sentence as-is but may
add another sentence specifically covering the case for
an empty iterable.


as one of the instigators in this thread, I'm +1 on this solution.

Changing the implementation of all() would break wy too much 
stuff, so I'm -1 on that.  Adding a one-sentence clarification to 
the docs is a heckuva lot easier.



P.S.  Now maybe we can start a new thread about why sum([])
returns zero ;-)


Nooo!  (runs screaming) :-)

-tkc





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


Re: Create standalone Windows program with simple graphics?

2009-04-16 Thread norseman

Poster28 wrote:

Hi,

I'd like to program and compile a simple graphics program (showing something
like a chess board, some numbers and buttons, mouse support) and provide it
as a standalone binary for Windows users.

What is the easiest way to do that? Which libraries or compilers I should
use?
--
http://mail.python.org/mailman/listinfo/python-list


==

"as a standalone BINARY..."

Assembly, C or your choice of compilable language.  There are a number 
of graphic and raster libraries available from the net. Choose one you like.


"like a chess board"
Create the backdrop and embed it in your program and use the graphic (or 
raster) lib functions to send it to the screen. Be sure to up date the 
screen in proper sequence after each change to it. Last drawn goes on top.


If you are moving something like chess-pieces, build an icon for each 
piece and change the cursor to the correct one during the move. Reduces 
the CPU cycles. Only start and end locations need screen updates.


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


Re: any(), all() and empty iterable

2009-04-16 Thread Paul Rudin
Tim Chase  writes:

> Changing the implementation of all() would break wy too much
> stuff...

Not to mention it clearly works correctly as is. *If* there is an issue
it is a documentation one... not an implementation one.
--
http://mail.python.org/mailman/listinfo/python-list


[OT] large db question about no joins

2009-04-16 Thread Daniel Fetchinson
[off but interesting topic]

Hi folks, I've come across many times the claim that 'joins are bad'
for large databases because they don't scale. Okay, makes sense, we
agree. But what I don't get, although I watched a couple of online
videos on this topic (one by the creator of flickr who gave a talk at
djangoconf and another one by a dev guy from facebook, I think the
links were posted here too) is how do people solve most basic problems
without joins? I guess the whole database layout has to be designed
with this in mind but suppose I have the following layout, how would I
redesign it so that I can have the same functionalities?

Let's say I have a table called zoo, another one called cage, another
one called animal and another one called leg. Each animal has some
number of legs, each cage has animals in it and each zoo has a number
of cages in it. Obviously these are represented by foreign keys. If I
need the total number of animals in a zoo, or the total number of legs
in the zoo I would use a query with join(s).

What would be the corresponding database layout that would scale and I
could get the total number of legs in the zoo or total number of
animals in the zoo without join(s)?

Cheers,
Daniel

[/off but interesting topic]

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: any(), all() and empty iterable

2009-04-16 Thread Dale Roberts
On Apr 16, 2:27 pm, Tim Chase  wrote:
> Raymond Hettinger wrote:
> > I will not change the sentence to "return false if any element
> > of the iterable is false."  The negations make the sentence
> > hard to parse mentally
>
> Just as a ribbing, that "return X if any element of the iterable
> is X" is of the same form as the original.  The negation is only
> of the X, not of the sentence structure.
>
> > I will probably leave the lead-in sentence as-is but may
> > add another sentence specifically covering the case for
> > an empty iterable.
>
> as one of the instigators in this thread, I'm +1 on this solution.

Yes, I now appreciate the motivation for having the word "all" in the
text, and simply adding something like "or the iterable is empty"
might head off future confusion.

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


Re: Queue() question. This post is pretty long.

2009-04-16 Thread Piet van Oostrum
> grocery_stocker  (g) wrote:

>g> [cdal...@localhost ~]$ python
>g> Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
>g> [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
>g> Type "help", "copyright", "credits" or "license" for more information.
> import Queue
> queue = Queue.Queue()
> 
> while 1:
>g> ...item = queue.get()
>g> ...if item == 'done':
>g> ...   break
>g> ...
>g> this
>g> is
>g> a
>g> test
>g> done

>g> [3]+  Stopped python
>g> [cdal...@localhost ~]$ kill %3

>g> It appears that only item = queue.get() called. Ie, the block never
>g> advances to if item == 'done':
>g> like in the first example

You don't put anything in the queue here. The lines that you type there
don't get magically into the queue. So therefore the queue.get blocks.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Choose: class with static methods or module with functions

2009-04-16 Thread Chris Rebert
On Thu, Apr 16, 2009 at 9:55 AM,   wrote:
> Ravi:
>> Which is a better approach.
>> My personal view is that I should create a module with functions.
>
> When in doubt, use the simplest solution that works well enough. In
> this case, module functions are simple and probably enough.
>
> But there can be a situation where you want to keep functions even
> closer, for example because in a module you have two classes and two
> groups of functions related to each class. In such situation
> staticmethods seem better.

Using staticmethods also allows you to override some of functions by
subclassing if need be.
Usually that's not necessary and so plain module functions are
preferred, but I know the std lib uses staticmethods in a few places
for this reason, so it occasionally is useful to do it this way.

Cheers,
Chris
-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Domain Driven Design and Python

2009-04-16 Thread Chris Rebert
On Thu, Apr 16, 2009 at 10:44 AM, José María  wrote:
> Hi,
>
> I've been searching for information about the application of DDD
> principles in
> Python and I did'nt found anything!
>
> Is DDD obvious in Python or is DDD inherent to static languages like
> Java or C#?

Reading the Wikipedia article, it seems it was developed somewhat from
the viewpoint of someone who uses a static language, but I see
absolutely no reason why you couldn't apply the principles to coding
in Python; just beware of slavishly following static
conventions/patterns unnecessarily (Python != Java).

Cheers,
Chris
-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


How do I change the behavior of the 'python-docs' action in IDLE?

2009-04-16 Thread samwyse
In the Windows version of Python 2.5, pressing F1 brought up the
python.chm file.  I've just installed 2.6, and the same action opens
http://www.python.org/doc/current/.  I'd prefer the former behavior.
I know how to change the key bindings in config-keys.def, but I think
I want to change the action, not the key binding.  Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-16 Thread Adam Olsen
On Apr 16, 8:59 am, Grant Edwards  wrote:
> On 2009-04-16, Adam Olsen  wrote:
> > I'm afraid you will need to back up your claims with real files.
> > Although MD5 is a smaller, older hash (128 bits, so you only need
> > 2**64 files to find collisions),
>
> You don't need quite that many to have a significant chance of
> a collision.  With "only" something on the order of 2**61
> files, you still have about a 1% chance of a collision.

Aye, 2**64 is more of the middle of the curve or so.  You can still go
either way.  What's important is the order of magnitude required.


> For "a few million files" (we'll say 4e6), the probability of a
> collision is so close to 0 that it can't be calculated using
> double-precision IEEE floats.

≈ 0.023509887

Or 4253529600 to 1.

Or 42 trillion trillion to 1.


> Here's the Python function I'm using:
>
> def bp(n, d):
>     return 1.0 - exp(-n*(n-1.)/(2.*d))
>
> I haven't spent much time studying the numerical issues of the
> way that the exponent is calculated, so I'm not entirely
> confident in the results for "small" n values such that
> p(n) == 0.0.

Try using Qalculate.  I always resort to it for things like this.
--
http://mail.python.org/mailman/listinfo/python-list


Re: win32 wins settings

2009-04-16 Thread Tim Golden

Toff wrote:

hello
I don't understand why this doesn't woks.


def setwins(self):
from win32com.client import GetObject
objWMIService = GetObject("winmgmts:
{impersonationLevel=impersonate}!.\\root\\cimv2")
colNicConfigs = objWMIService.ExecQuery ("SELECT * FROM
Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
for nic in colNicConfigs:
print nic.Description
nic.SetWINSServer('','')

it looks good
http://msdn.microsoft.com/en-us/library/aa393624(VS.85).aspx



What happens when you try? An error? Nothing?

Can you try it using my wmi module:

 http://timgolden.me.uk/python/wmi.html


import wmi

c = wmi.WMI ()
for nic in c.Win32_NetworkAdapterConfiguration (IPEnabled=True):
 print nic.Description
 nic.SetWINSServer ("", "")



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


Re: Domain Driven Design and Python

2009-04-16 Thread Stef Mientki

José María wrote:

Hi,

I've been searching for information about the application of DDD
principles in
Python and I did'nt found anything!

Is DDD obvious in Python or is DDD inherent to static languages like
Java or C#?

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

I'm not a software guy, so I don't really understand those technical terms,
would call LabView a DDD ?
Are you looking for a specific domain or DDD in general ?

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting Newsgroup Headers

2009-04-16 Thread Chris Rebert
On Thu, Apr 16, 2009 at 9:25 AM, aslkoi fdsda  wrote:
> I would like to read just the headers out of a newsgroup.
> Being a Python newbie, I was wondering if this is possible and how difficult
> it would be for a novice Python programmer.
> Thanks for any reply!

See the `nntplib` [http://docs.python.org/library/nntplib.html] and
also (possibly) the `email`
[http://docs.python.org/library/email.html] modules in the standard
library.

Cheers,
Chris
-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: any(), all() and empty iterable

2009-04-16 Thread John Posner

Tim Chase wrote:

I will probably leave the lead-in sentence as-is but may
add another sentence specifically covering the case for
an empty iterable.


as one of the instigators in this thread, I'm +1 on this solution.

Thanks for weighing in, Raymond. As long as people are getting in their 
last licks on this one ...


Including the word "all" in the definition of "all()" is suboptimal. 
Especially since the everyday meaning of "all" is ambiguous. Sure, leave 
in the code-equivalent to clarify things, but why not clarify in text, 
also? Here's a compromise:


 all(iterable) -- Return True if all elements of the /iterable/ are 
true -- more
 precisely, if there does not exist an element of the iterable that is 
False.

 Equivalent to ...

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


Re: large db question about no joins

2009-04-16 Thread Aaron Brady
On Apr 16, 1:45 pm, Daniel Fetchinson 
wrote:
> [off but interesting topic]
>
> Hi folks, I've come across many times the claim that 'joins are bad'
> for large databases because they don't scale. Okay, makes sense, we
> agree. But what I don't get, although I watched a couple of online
> videos on this topic (one by the creator of flickr who gave a talk at
> djangoconf and another one by a dev guy from facebook, I think the
> links were posted here too) is how do people solve most basic problems
> without joins? I guess the whole database layout has to be designed
> with this in mind but suppose I have the following layout, how would I
> redesign it so that I can have the same functionalities?
>
> Let's say I have a table called zoo, another one called cage, another
> one called animal and another one called leg. Each animal has some
> number of legs, each cage has animals in it and each zoo has a number
> of cages in it. Obviously these are represented by foreign keys. If I
> need the total number of animals in a zoo, or the total number of legs
> in the zoo I would use a query with join(s).
>
> What would be the corresponding database layout that would scale and I
> could get the total number of legs in the zoo or total number of
> animals in the zoo without join(s)?
>
> Cheers,
> Daniel
>
> [/off but interesting topic]
>
> --
> Psss, psss, put it down! -http://www.cafepress.com/putitdown

for cage in zoo:
  for animal in cage:
for leg in animal:
  count+= 1



I think that relational algebra wasn't designed to be able to
sacrifice joins.

Wait a second., how many legs in the zoo??
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >