Re: Question to python C API

2009-04-15 Thread Andreas Otto
Hi,

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

http://libmsgque.sourceforge.net

  is this possible ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: need to start a new project , can python do all that ?

2009-04-15 Thread Aahz
In article <9061ea8f-b4aa-4dbc-89c9-ae6848033...@k2g2000yql.googlegroups.com>,
Deep_Feelings   wrote:
>
>now going into python i found that python 3 is just out but recourses
>are limited (including IDEs) any help on that ?

Stick with Python 2.x
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

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


Re: CrystalFontz 635 project

2009-04-15 Thread Scott Flynn
I think I found the answer to the last question. "A primitive lock is
a synchronization primitive that is not owned by a particular thread
when locked." -17.2.2. Lock Objects

So that's a no.

On Wed, Apr 15, 2009 at 8:55 PM, Scott Flynn  wrote:
>
> I'm finally around to playing around with my LCD module. I chose Linux for 
> OS, pygtk for the GUI, a CF635 Python library written by Thomas Cauley (found 
> on CF website) for a starting point in sending commands to the LCD, and 
> gobject.io_add_watch for listening for packets coming from the LCD. It became 
> clear as soon as I started receiving packets that I would need some threading 
> support. My attempts at working that in have been successful to some degree, 
> but there's still something, and while I doubt many can run the program to 
> see what it does, I was hoping someone could possibly tell me if I'm just 
> going about this threading business "the wrong way."
>
> You can download the files from http://starlon.net/files/CF635.1.tar.gz
>
> Pertinate files: CF635.py (main file), CFListener.py, CFFans.py, 
> pyCF635Driver.py
>
> Basically, when I set a fan or more to report, the packets come in fine and 
> the program processes them, but every once in a while the GUI hangs. I'm not 
> sending commands to the LCD during this time. I'm just letting the program 
> run. I realize outgoing commands aren't wrapped/threaded yet. I'm not sure if 
> they need to be. I have a threading.Lock setup in SendCommand though, so I'm 
> also wondering if I need the threading.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Falcon - powering innovation

2009-04-15 Thread JanC
Gerhard Häring wrote:

> I've never heard of tabular programming before.

I guess something similar/related to SQL or LINQ?

I don't think this is really a bad idea if you want to support
sublanguages for common programming problems... (which seems to be one of
their primary language design ideas).


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


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Aahz
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.  ;-)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

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


Re: Modifying the value of a float-like object

2009-04-15 Thread Aahz
In article <3b01d8f1-6a77-4374-b1c2-25bee7cdf...@x3g2000yqa.googlegroups.com>,
  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 (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

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


Re: How to create a virtual serial port?

2009-04-15 Thread JanC
Stuart Davenport wrote:

> My point in all this is actually that I ordered a USB GPS Receiver and

I just bought one myself a couple of weeks ago.  They sell them at 10-13
euro on computer fairs these days, that's too cheap to not buy one... ;)

> it wont arrive for another two weeks, being my impatient self, I am
> writing an app for my iPhone to broadcast its GPS location over the
> network to my laptop. I then want to get this data into the NMEA
> format and push this data onto a PTY - this will in-effect replace the
> USB GPS Receiver and the GPS software can read it :)

Well, on normal linux/unix systems it would be easy, as in general
applications there use 'gpsd'[1] to access GPS data, which you can then
access from every application (instead of one application monopolizing the
serial port) and it even supports access over TCP/IP.

I don't know if gpsd works on Mac OS X[2] and the iPhone *and* with your
application though (it doesn't emulate a serial port, so I think not...).

Applications shouldn't monopolize a resource like a GPS without giving
access to the data for others (like gpsd does)...


[1] 
[2] well, [1] says that it does, but is not officially supported

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


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Brendon Wickham
> On IDE's, I'm afraid I'm not going to be much help because I don't use
> them.  I prefer to use a decent editor (Emacs in my case, others have
> their own preferences) and run my scripts from the command line.  That
> said, IDLE (which comes packaged with Python) is a perfectly decent
> little IDE.  It's surprising how little you really need given the
> flexibility and immediacy of working with Python.
>

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.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Scott David Daniels

Ben Finney wrote:

... the upgrade police have not been given your address yet


Don't be so sure!  We of the Python Secret Upgradepolice ...
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-15 Thread Aaron Watters

> You should perhaps contrast WHIFF with the other offerings for creating
> web applications.
>
> -- Gerhard

You're right.  Thanks for visiting!  I'll have to think.
Basically I don't want something which takes over the controls.
I'll have to think about a better way to explain what I mean.

   -- Aaron Watters ( http://whiff.sourceforge.net )

===
Sisyphus got ripped.
--
http://mail.python.org/mailman/listinfo/python-list


CrystalFontz 635 project

2009-04-15 Thread Scott Flynn
I'm finally around to playing around with my LCD module. I chose Linux for
OS, pygtk for the GUI, a CF635 Python library written by Thomas Cauley
(found on CF website) for a starting point in sending commands to the LCD,
and gobject.io_add_watch for listening for packets coming from the LCD. It
became clear as soon as I started receiving packets that I would need some
threading support. My attempts at working that in have been successful to
some degree, but there's still something, and while I doubt many can run the
program to see what it does, I was hoping someone could possibly tell me if
I'm just going about this threading business "the wrong way."

You can download the files from http://starlon.net/files/CF635.1.tar.gz

Pertinate files: CF635.py (main file), CFListener.py, CFFans.py,
pyCF635Driver.py

Basically, when I set a fan or more to report, the packets come in fine and
the program processes them, but every once in a while the GUI hangs. I'm not
sending commands to the LCD during this time. I'm just letting the program
run. I realize outgoing commands aren't wrapped/threaded yet. I'm not sure
if they need to be. I have a threading.Lock setup in SendCommand though, so
I'm also wondering if I need the threading.
--
http://mail.python.org/mailman/listinfo/python-list


Developing modules with ‘pkgutil’

2009-04-15 Thread Ben Finney
Howdy all,

With all the current fuss about namespace packages, I'm dealing with a
similar goal that I hope is possible with stock Python 2.x.

When developing a module intended to be part of an existing package
installed on the system, I want to write programs that will import the
*in-development* module from my current working tree, but the
*system-installed* modules from the rest of the package.

The specific case is that of a new writer for Docutils. The module will
eventually be installed such that it is accessed via ‘import
docutils.writers.foo’, but while developing it I explicitly *don't* want
the module to come from the system-installed ‘docutils/writers/’
directory since that will fail to get the one I'm developing.

But the rest of the Docutils infrastructure I *need* to come from the
system-installed package when I do ‘docutils.bar.baz’. So I need to
somehow have a module in one location appear, for the purpose of
imports, as though it's part of a package defined in a different
location.

A naive first try would be:

/usr/lib/python2.5/site-packages/
docutils/
__init__.py
core.py
…
readers/
__init__.py
…
transforms/
__init__.py
…
writers/
__init__.py
…

$HOME/projects/foo-writer/
tools/
rst2foo
docutils/
__init__.py
writers/
__init__.py
foo.py

So, while developing the ‘foo.py’ module, I need to run ‘tools/rst2foo’
in order to make use of the module and exercise its in-development
functionality (and *not* whatever ‘foo.py’ might exist in the system
library location). But whenever I import anything *else* from the
‘docutils’ package, it's not going to find the system-installed package.

The ‘pkgutil’ module http://docs.python.org/library/pkgutil>, which
I only partly understand (with thanks to Doug Hellman for
http://blog.doughellmann.com/2008/02/pymotw-pkgutil.html>), appears
to offer a solution for this, by allowing my in-development ‘docutils’
shim package to also include the real one:

$ cd $HOME/projects/foo-writer/
$ cat docutils/__init__.py
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
__path__.reverse()

Which, according to Doug, should allow me to have ‘tools/rst2foo’ say:

from docutils.core import publish_cmdline, default_description
from docutils.writers import foo

as it will look when installed for the end user; and the ‘docutils’
namespace will, because of the in-development shim package, be searched
both there and the system-installed directory, finding both the
system-installed ‘docutils.core’ and the in-development
‘docutils.writers.manpage’.

Then I should be able to run the program while developing, like this:

$ PYTHONPATH=.  python ./tools/rst2foo

and it should find everything it needs.


However, this approach doesn't seem to be complete: there is code in the
system-installed ‘docutils/__init__.py’ that is not being found:

Traceback (most recent call last):
  File "./tools/rst2foo", line 21, in 
from docutils.core import publish_cmdline, default_description
  File "/usr/lib/python2.5/site-packages/docutils/core.py", line 20, in 

from docutils import __version__, __version_details__, SettingsSpec
ImportError: cannot import name __version__

What's happening, of course, is that the name ‘__version__’ is defined
in the system-installed ‘docutils/__init__.py’, but that's not being
found because the in-development ‘docutils/__init__.py’ is found first,
which doesn't have that name.

A simple ‘from docutils import *’ clearly doesn't work, for the same
reason. Catch-22.

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?

-- 
 \ “Smoking cures weight problems. Eventually.” —Steven Wright |
  `\   |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


client-server socket script that crashes on Mac

2009-04-15 Thread Bad Mutha Hubbard
Hi.  I know I have some bugs in this, but I'm trying to find out one
thing in particular: why the accept() method in the server never returns
in OSX.  It announces that it is waiting, and the client announces that
it is attempting to connect, and both print the same port number, but it
just hangs.  On Linux, it connects, sends the data, and terminates.  I
run the command:
python ./client.py
There are two files below (I was unable to attach a zip).

 Any ideas? Thanks.
-Chuckk


## client.py

#!/usr/bin/env python

import os
import threading
import sys
import subprocess
import socket
#import select
import Queue
import time

class client(object):
def __init__(self):
self.cbport = 5899
self.outport = 5880
self.playing = 0
self.allowed2play = 1
self.play()
time.sleep(1)
self.stop()

def waitforconnect(self, sock, q):
conn = sock.accept()
q.put(conn)

def delegatecallbacks(self, sock):
cbtext = ''
while self.playing == 1:
#if select.select((sock,),(),())[0]:
try:
cbtext += sock.recv(32)
while cbtext.count('CB'):
cb, cbtext = cbtext.split('CB', 1)
print self.__class__.__name__, "-", "Callback:", cb
if cb == 'END':
print self.__class__.__name__, "-", "END received"
self.stop()
except:
print self.__class__.__name__, "-", "Callback Socket 
Unavailable"

def play(self):
if self.allowed2play:
self.allowed2play = 0
if True:
cbwait = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
count = 0
while count < 3:
try:
cbwait.bind(('127.0.0.1', self.cbport))
print self.__class__.__name__, "-", 'Callback Port: %s' 
% str(self.cbport)
count = 3
except:
self.cbport += 1
count += 1
if count == 3:
print self.__class__.__name__, "-", "NO PORTS 
AVAILABLE FOR CALLBACK"

cbwait.listen(2)
self.outsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#thread to wait for callback to connect
q = Queue.Queue()
wait = threading.Thread(target=self.waitforconnect, 
args=(cbwait, q))
wait.start()

count = 0
while count < 1:
tmpsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
tmpsoc.bind(('127.0.0.1', self.outport))
print self.__class__.__name__, "-", 'outport:', 
self.outport
count = 1
del tmpsoc
except:
self.outport += 1
count += 1
print self.__class__.__name__, "-", "count:", count
del tmpsoc

self.server = subprocess.Popen((sys.executable, 'server.py', 
str(self.outport), str(self.cbport)))

#success = self.server.poll()
#if success:
#print self.__class__.__name__, "-", success
#break

connected = False
tries = 1
while not connected:
try:
self.outsock.connect(('127.0.0.1', self.outport))
print self.__class__.__name__, "-", 'outsock connected 
to:', self.outport
connected = True
except:
print self.__class__.__name__, "-", "outsock failed to 
connect to:", self.outport, tries, "times"
tries += 1
if tries >= 10:
raise connectionError
time.sleep(.1)

try: self.cbsock = q.get()[0]
except: pass
while wait.isAlive():
try: self.cbsock = q.get()[0]
except: pass

#cleanup dead thread
if not wait.isAlive():
del wait

self.playing = 1
threading.Thread(target=self.delegatecallbacks, 
args=(self.cbsock,)).start()

self.outsock.sendall('inputmsgENDMESSAGE')

def stop(self):
if self.playing == 1:
try:
self.playing = 0
#print self.__class__.__name__, "-", "Stop"
self.outsock.sendall('ENDMESSAGEstopENDMESSAGE')
#print self.__class__.__name__, "-", 'closing...'
#print self.__class__.__name__, "-", self.server.poll()
ended = self.server.comm

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

2009-04-15 Thread Miles
On Wed, Apr 15, 2009 at 8:48 PM, Paul Rubin wrote:
> I'd use:
>
>   from operator import eq
>   all_the_same = reduce(eq, mylist)

That won't work for a sequence of more than two items, since after the
first reduction, the reduced value that you're comparing to is the
boolean result:

>>> reduce(eq, [0, 0, 0])
False
>>> reduce(eq, [0, 1, False])
True

I'd use:

# my preferred:
def all_same(iterable):
it = iter(iterable)
first = it.next()
return all(x == first for x in it)

# or, for the pathologically anti-generator-expression crowd:
from functools import partial
from operator import eq
from itertools import imap
def all_same(iterable):
it = iter(iterable)
return all(imap(partial(eq, it.next()), it))

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


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Fabio Zadrozny
> 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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where to find options for add_command?

2009-04-15 Thread John Machin
On Apr 16, 6:55 am, 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!

If you tell us the name of the module or package that contains the
Menu class or factory function that you are calling, we should be able
to search the web to find the documentation for you.

If you tell yourself the name of the module or package that contains
the Menu class etc that you are calling, you should be able to search
the web to find the documentation for yourself. Hint: bookmark the
link when you find it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyprocessing and exceptions

2009-04-15 Thread Jesse Noller
On Wed, Apr 15, 2009 at 11:32 AM, garyrob  wrote:
> Hi,
>
> We're still using Python 2.5 so this question is about the
> pyprocessing module rather than the multiprocessing module, but I'm
> guessing the answer is the same.
>
> I tend to use the Pool() object to create slave processes. If
> something goes wrong in the slave, an exception is raised there, which
> is then raised in the master or parent process, which is great.
>
> The problem is that if the master aborts due to the exception, it
> doesn't show the usual stack trace info for the slave, which would
> show (among other things) the line number the error occurred on.
> Instead, it shows the line in the master where work was sent to the
> slave (such as a call to pool.map()).
>
> I'm wondering what the recommended way is to write code that will
> reveal what went wrong in the slave. One obvious possibility is to
> have functions that are invoked in the slave incorporate their own
> exception handling that prints a stack trace. But I'd rather handle
> this issue in the master, rather than have to handle it in every
> function in the slave module that the master may invoke.
>
> Is there a way to do that? If not, what's the recommended approach?
>
> Thanks,
> Gary
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You should handle the exception in the child.

Also, multiprocessing was backported to python 2.5 and earlier.

http://pypi.python.org/pypi/multiprocessing/

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


Re: Equivalent to C bitmasks and enumerations

2009-04-15 Thread John Machin
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 = enum
>         self.name = name
>         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 = Color.RED
> print type(b)
> print str(b)
>
> a = Color.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

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


Re: Where to find options for add_command?

2009-04-15 Thread Steven D'Aprano
On Wed, 15 Apr 2009 13:55:39 -0700, 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!


This website will tell you what you need to solve your problem:

http://www.catb.org/~esr/faqs/smart-questions.html





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


Re: Re: Modifying the value of a float-like object

2009-04-15 Thread Dave Angel



Steven D'Aprano wrote:
   


Oh nonsense. Many programming languages have mutable floats.



  

That's irrelevant.  Python doesn't.  So introducing one will quite
likely alter the OP's code's behavior.  It doesn't matter if it's
possible, it matters whether the existing code's behavior might change,
and of course if a future maintainer might have trouble making sense of
it.



What are you talking about? Python introduces new types quite frequently. 
We now have sets, frozensets, rationals, decimals and namedtuples, and 
we'll soon be getting ordereddicts and probably others as well. People 
create new types in their code *all the time*, using the class statement. 
If the OP wants to create a MutableFloat type, that's his prerogative.


  
  
The OP has existing code, and apparently a good deal of it, which he 
wants to run unchanged.  That's the whole purpose behind the 
discussion.  All I've been asserting is that  changing the variables 
that used to be floats to some new mutable-type would be risky to his 
code.  Since he's willing to assume the risk, then he can use the code 
which I proposed.  I'd much rather point out the risks, than have 
somebody paste something in and assume it'll work like before.



We'd better skip the discussion of other languages, since you're mixing 
terminology something awful.


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


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

2009-04-15 Thread Paul Rubin
John Posner  writes:
>   # get list of object-IDs
>   ids = map(lambda x: id(x), mylist)
>   # ALL THE SAME? ... test whether "average ID" matches "first ID"
>   sum(ids)/len(ids) == ids[0]

I don't think you can rely on id's being the same if what
you want is that the values are the same:

>>> a = "foo" + "bar"
>>> b = "foobar"
>>> a==b
True
>>> id(a) == id(b)
False

I'd use:

   from operator import eq
   all_the_same = reduce(eq, mylist)

I don't see how to do all_different in less than quadratic time,
without using hashing or sorting:

  all_different = all(sum(1 for y in mylist if x==y)==1 for x in mylist)
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-15 Thread John Machin
On Apr 16, 8:14 am, Chris Rebert  wrote:
> > On Wed, Apr 15, 2009 at 5:49 PM, Chris Rebert  wrote:
>
> >> On Wed, Apr 15, 2009 at 2:36 PM, Gaurav Moghe  wrote:

> > Thanks for the reply. But I am interested in analysing the contents of just
> > one list. For example,
>
> > list1=[1,2,3,4,5,6]
> > So, the logical statement would probably be:
> > if list1==(contains all same values), print "Same"    >False
> > if list1==(contains all different values), print "Different"  >True
>
> > I wanted to know here whether there is a command/function that can do
> > exactly this.  I hope I am more clearer than my last try!

@ OP: Not much ... what do you want to print if it contains *some*
different (but not all)?


> Ah, okay. Then you want:
>
> def all_same(lst):
>     return len(set(lst)) == 1
>
> def all_different(lst):
>     return len(set(lst)) == len(lst)

@ OP: These are very reasonable interpretations of "all same" and "all
different" but of course can both return False for the same input.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent to C bitmasks and enumerations

2009-04-15 Thread Dave Angel

Ulrich Eckhardt wrote:

Greetings!

I'm currently using Python to implement a set of tests for code that is
otherwise written in C. This code was wrapped using Boost.Python and is
then loaded into Python as module.

What I often have in C is this:

  // bitfield (several flags combined)
  #define STATUS_OVERTEMP 1u
  #define STATUS_ON_FIRE 2u
  #define STATUS_BORED 4u
  unsigned get_status(void);

  // enumeration (distinct values from a set)
  enum color { color_red=1, color_green=13, color_mauve=42 };
  enum color get_color(void);

What I'm looking for is a suggestion how to handle this in Python. Note that
technically, this works without problem, I'm rather looking for stylistic
advise. What I currently have is these (note: I'm retyping this, so ignore
any syntax errors, please):

 STATUS_OVERTEMP = 1
 STATUS_ON_FIRE = 2
 STATUS_BORED = 4
 def status_as_string(st):
 tmp = []
 if st&STATUS_OVERTEMP:
 tmp.append("OVERTEMP")
 if st&STATUS_ON_FIRE:
 tmp.append("ON_FIRE")
 if st&STATUS_BORED:
 tmp.append("BORED")
 return "|".join(tmp)

 COLOR_RED = 1
 COLOR_GREEN = 13
 COLOR_MAUVE = 42
 def color_as_string(c):
 names = {
 COLOR_RED:"RED",
 COLOR_GREEN:"GREEN",
 COLOR_MAUVE:"MAUVE"}
 return names[c];

Further, I also tried defining a separate class:

 class Color(int):
 RED = 1
 GREEN = 13
 MAUVE = 42
 names = { RED:"RED", GREEN:"GREEN", MAUVE:"MAUVE"}

 def __str__(self):
 return names[c];
 ...
  


To be a bit more explicit about what I would like, here is an example how I
would like to use it:

  c = Color.RED
  type(c) # should yield class Color
  str(c) # should yield "RED"
  Color(999) # should signal the invalid color value


Any other suggestions how to structure this or rewrite this?

thanks!

Uli

  

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


class Color(object):
   def __init__(self, name, enum):
   self.enum = enum
   self.name = name
   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 = Color.RED
print type(b)
print str(b)

a = Color.GREEN
print a
print a.enum

k = Color
xx = Color("aaa", 42)  #error



  
  

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


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

2009-04-15 Thread John Posner

Scott David Daniels wrote:

Assuming you really are going for "is" comparison, how about:
max(id(x) for x in mylist) == min(id(x) for x in mylist)

It has the advantage that if [id(x) for x in mylist] = [2N, 1N, 3N],
you get the answer you desire.


Oops -- got me!  -John
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Rhodri James
On Wed, 15 Apr 2009 23:51:24 +0100, Deep_Feelings   
wrote:



On Apr 16, 1:45 am, Benjamin Peterson  wrote:

Deep_Feelings  gmail.com> writes:

> 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

Why do you think you're wasting time with 2.x?


yes..

should i write 2.x code then after a year or so i have to upgrade to
3.0 :( ?


The only difference between 2.x and 3.0 that will trip you up as a
beginner is that print is a function rather than a statement.  Unless
you're a colleague of mine, who started to learn Python a week ago by
poking its Unicode handling very hard :-)

On IDE's, I'm afraid I'm not going to be much help because I don't use
them.  I prefer to use a decent editor (Emacs in my case, others have
their own preferences) and run my scripts from the command line.  That
said, IDLE (which comes packaged with Python) is a perfectly decent
little IDE.  It's surprising how little you really need given the
flexibility and immediacy of working with Python.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Deep_Feelings
On Apr 16, 2:35 am, Ben Finney  wrote:
> Deep_Feelings  writes:
> > On Apr 16, 1:45 am, Benjamin Peterson  wrote:
> > > Why do you think you're wasting time with 2.x?
>
> > yes..
>
> The question was, why do you think that?
>
> > should i write 2.x code then after a year or so i have to upgrade to
> > 3.0 :( ?
>
> What gives you the impression you will “have to upgrade to 3.0”?
> Python 2.x will be around for a long time, and the upgrade police have
> not been given your address yet. Also, the differences are not great;
> when the time comes, your experience with Python 2.x will easily serve
> you well in Python 3.x.
>
> --
>  \           “Self-respect: The secure feeling that no one, as yet, is |
>   `\                                    suspicious.” —Henry L. Mencken |
> _o__)                                                                  |
> Ben Finney

that is great

THANK YOU VERY MUCH
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Ben Finney
Deep_Feelings  writes:

> On Apr 16, 1:45 am, Benjamin Peterson  wrote:
> > Why do you think you're wasting time with 2.x?
> 
> yes..

The question was, why do you think that?

> should i write 2.x code then after a year or so i have to upgrade to
> 3.0 :( ?

What gives you the impression you will “have to upgrade to 3.0”?
Python 2.x will be around for a long time, and the upgrade police have
not been given your address yet. Also, the differences are not great;
when the time comes, your experience with Python 2.x will easily serve
you well in Python 3.x.

-- 
 \   “Self-respect: The secure feeling that no one, as yet, is |
  `\suspicious.” —Henry L. Mencken |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: need to start a new project , can python do all that ?

2009-04-15 Thread Deep_Feelings
On Apr 16, 1:59 am, "Rhodri James" 
wrote:
> On Wed, 15 Apr 2009 15:54:45 +0100, Deep_Feelings   
> wrote:
>
> > thank you so much ,rest assured that the code will me tested very well
> > (in real world situation) before using it.
>
> That's not sufficient.  It isn't enough that your program works, it also
> has to satisfy the regulatory authorities otherwise (depending on what
> country you're in) you could end up on the wrong end of some very
> expensive law-suits without actually having done anything wrong.  Check
> first.
>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses

that is true , thank you
--
http://mail.python.org/mailman/listinfo/python-list


Re: reading arguments in python script when passed from URL

2009-04-15 Thread Rhodri James
On Wed, 15 Apr 2009 07:24:24 +0100, phaneendra s   
wrote:



hi alll..


iam invoking a python script from a standalone client which looks lik  
this



String command="ln -s /usr/lib /tmp/lin";   //creating a soft link

URL url = new URL("http://server-name/cgi-bin/finalexec1.py?command=
"+command);

but iam not able to read this command in the python script

in my script i tried doing
for arg in sys.argv;
print arg


but the command is not being read..

is  it the right way of reading arguments in python script?


If you fix the indentation, and use a colon instead of a
semi-colon, and import sys first, then yes.  Your "standalone
client" however makes no sense to me at all.  How *exactly*
are you invoking your Python script?

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-15 Thread Scott David Daniels

John Posner wrote:

...This solution relies on the object ID -- no hashability required:
 # get list of object-IDs
 ids = map(lambda x: id(x), mylist)
 # ALL THE SAME? ... test whether "average ID" matches "first ID"
 sum(ids)/len(ids) == ids[0]


Assuming you really are going for "is" comparison, how about:
max(id(x) for x in mylist) == min(id(x) for x in mylist)

It has the advantage that if [id(x) for x in mylist] = [2N, 1N, 3N],
you get the answer you desire.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-15 Thread Rhodri James

On Wed, 15 Apr 2009 23:56:45 +0100, John Posner  wrote:


Chris Rebert wrote:

Ah, okay. Then you want:

def all_same(lst):
return len(set(lst)) == 1

def all_different(lst):
return len(set(lst)) == len(lst)

Note that these require all the elements of the list to be hashable.


This solution relies on the object ID -- no hashability required:

  # get list of object-IDs
  ids = map(lambda x: id(x), mylist)
  # ALL THE SAME? ... test whether "average ID" matches "first ID"
  sum(ids)/len(ids) == ids[0]


Oh John!  After all the recent discussion of identity versus equality too.


my_list = [ 1024 ]
my_list.append(1024) # Defeat the interpreter's cunningness
ids = map(lambda x: id(x), ml)
ids

[9864656, 9864704]

sum(ids)/len(ids) == ids[0]

False


--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: need to start a new project , can python do all that ?

2009-04-15 Thread Rhodri James
On Wed, 15 Apr 2009 15:54:45 +0100, Deep_Feelings   
wrote:



thank you so much ,rest assured that the code will me tested very well
(in real world situation) before using it.


That's not sufficient.  It isn't enough that your program works, it also
has to satisfy the regulatory authorities otherwise (depending on what
country you're in) you could end up on the wrong end of some very
expensive law-suits without actually having done anything wrong.  Check
first.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-15 Thread John Posner

Chris Rebert wrote:

Ah, okay. Then you want:

def all_same(lst):
return len(set(lst)) == 1

def all_different(lst):
return len(set(lst)) == len(lst)

Note that these require all the elements of the list to be hashable.
  

This solution relies on the object ID -- no hashability required:

 # get list of object-IDs
 ids = map(lambda x: id(x), mylist)
 # ALL THE SAME? ... test whether "average ID" matches "first ID"
 sum(ids)/len(ids) == ids[0]

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


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Deep_Feelings
On Apr 16, 1:45 am, Benjamin Peterson  wrote:
> Deep_Feelings  gmail.com> writes:
>
>
>
> > 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
>
> Why do you think you're wasting time with 2.x?

yes..

should i write 2.x code then after a year or so i have to upgrade to
3.0 :( ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-15 Thread Benjamin Peterson
Deep_Feelings  gmail.com> writes:

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

Why do you think you're wasting time with 2.x?




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


Re: Testing in Python mailing list broken?

2009-04-15 Thread Scott David Daniels

Scott David Daniels wrote:

Does anyone know if the Testing in Python mailing list
is broken or turned off?  It was running almost too many
messages, but now there has been a _huge_ silence.

--Scott David Daniels
scott.dani...@acm.org

Never mind, I've seen a couple posts.
--
http://mail.python.org/mailman/listinfo/python-list


Re: RELEASED Python 2.6.2

2009-04-15 Thread Scott David Daniels

Barry Warsaw wrote:
On behalf of the Python community, I'm happy to announce the 
availability of Python 2.6.2.  This is the latest production-ready 
version in the Python 2.6 series.  Dozens of issues have been fixed 
since Python 2.6.1 was released back in December.  Please see the NEWS 
file for all the gory details.

Congratulations.  A great success.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-15 Thread Gaurav Moghe
Thanks! That works!

On Wed, Apr 15, 2009 at 6:14 PM, Chris Rebert  wrote:

> > On Wed, Apr 15, 2009 at 5:49 PM, Chris Rebert  wrote:
> >>
> >> On Wed, Apr 15, 2009 at 2:36 PM, Gaurav Moghe  wrote:
> >> > Hi,
> >> >
> >> > I am an amateur python user I wanted to know how do I know whether all
> >> > the
> >> > contents of a list are all same or all different? Now, I could
> certainly
> >> > write a loop with a counter. But is there a ready command for that?
> >> > Checked
> >> > a lot of docs and this mailing list, but didnt get anything
> worthwhile.
> >> > Would be glad to know.
> >>
> >> All same:
> >>
> >> list_1 == list_2
> >>
> >> All different:
> >>
> >> all(x != y for x, y in zip(list_1, list_2))
> >>
> On Wed, Apr 15, 2009 at 2:55 PM, Gaurav Moghe  wrote:
> > Hi Chris,
> >
> > Thanks for the reply. But I am interested in analysing the contents of
> just
> > one list. For example,
> >
> > list1=[1,2,3,4,5,6]
> > So, the logical statement would probably be:
> > if list1==(contains all same values), print "Same">False
> > if list1==(contains all different values), print "Different"  >True
> >
> > I wanted to know here whether there is a command/function that can do
> > exactly this.  I hope I am more clearer than my last try!
>
> Ah, okay. Then you want:
>
> def all_same(lst):
>return len(set(lst)) == 1
>
> def all_different(lst):
>return len(set(lst)) == len(lst)
>
> Note that these require all the elements of the list to be hashable.
>
> Cheers,
> Chris
> --
> I have a blog:
> http://blog.rebertia.com
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent to C bitmasks and enumerations

2009-04-15 Thread Wojtek Walczak
On Wed, 15 Apr 2009 12:51:31 +0200, Ulrich Eckhardt wrote:

Hi,

> I'm currently using Python to implement a set of tests for code that is
> otherwise written in C. This code was wrapped using Boost.Python and is
> then loaded into Python as module.
...
> What I'm looking for is a suggestion how to handle this in Python. Note that
> technically, this works without problem, I'm rather looking for stylistic
> advise. What I currently have is these (note: I'm retyping this, so ignore
> any syntax errors, please):
...
> Any other suggestions how to structure this or rewrite this?

It's not exactly what you're searching for, but with a bit of work
it should fit your needs:

-
class Colors(object):
   def __init__(self):
  self.colors_reg = {}
  self.colors_set = 0

   def register_color(self, name):
  self.colors_reg.setdefault(name, 1 << len(self.colors_reg))

   def set_color(self, name):
  self.colors_set |= self.colors_reg[name]

   def has_color(self, color):
  return bool(self.colors_reg[color]&self.colors_set)

   def status_as_string(self, st):
  tmp = []
  for k in self.colors_reg:
 if st & self.colors_reg[k]:
tmp.append(k)
  return '|'.join(tmp)


c = Colors()
# register your colors
c.register_color('RED')
c.register_color('BLUE')
c.register_color('YELLOW')

# set colors 'on'
c.set_color('RED')
c.set_color('YELLOW')

print c.has_color('RED')
print c.has_color('BLUE')
print c.status_as_string(5)


HTH,
-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


What IDE support python 3.0.1 ?

2009-04-15 Thread Deep_Feelings
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

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


Re: pdftk

2009-04-15 Thread ThomasHeetderks


Bugzilla from r.ba...@fz-juelich.de wrote:
> 
> 
> Does one know about a python interface to pdftk?
> Or something similar which can be used to fill a form by fdf data.
> 

...Or if you want to return the PDF as a Django response:

from subprocess import Popen, PIPE

cmd = 'pdftk.exe %s fill_form - output - flatten' % PDF_SOURCE
proc = Popen(cmd,stdin=PIPE,stdout=PIPE,stderr=PIPE)
cmdout,cmderr = proc.communicate(fdf)
if cmderr: raise Hppt404
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'inline; filename=filename.pdf'
response.write(cmdout)
return response

Hope this is useful.

- Thomas
-- 
View this message in context: 
http://www.nabble.com/pdftk-tp22188221p23068300.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


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

2009-04-15 Thread Chris Rebert
> On Wed, Apr 15, 2009 at 5:49 PM, Chris Rebert  wrote:
>>
>> On Wed, Apr 15, 2009 at 2:36 PM, Gaurav Moghe  wrote:
>> > Hi,
>> >
>> > I am an amateur python user I wanted to know how do I know whether all
>> > the
>> > contents of a list are all same or all different? Now, I could certainly
>> > write a loop with a counter. But is there a ready command for that?
>> > Checked
>> > a lot of docs and this mailing list, but didnt get anything worthwhile.
>> > Would be glad to know.
>>
>> All same:
>>
>> list_1 == list_2
>>
>> All different:
>>
>> all(x != y for x, y in zip(list_1, list_2))
>>
On Wed, Apr 15, 2009 at 2:55 PM, Gaurav Moghe  wrote:
> Hi Chris,
>
> Thanks for the reply. But I am interested in analysing the contents of just
> one list. For example,
>
> list1=[1,2,3,4,5,6]
> So, the logical statement would probably be:
> if list1==(contains all same values), print "Same">False
> if list1==(contains all different values), print "Different"  >True
>
> I wanted to know here whether there is a command/function that can do
> exactly this.  I hope I am more clearer than my last try!

Ah, okay. Then you want:

def all_same(lst):
return len(set(lst)) == 1

def all_different(lst):
return len(set(lst)) == len(lst)

Note that these require all the elements of the list to be hashable.

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


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

2009-04-15 Thread Gaurav Moghe
Hi Chris,

Thanks for the reply. But I am interested in analysing the contents of just
one list. For example,

list1=[1,2,3,4,5,6]
So, the logical statement would probably be:
if list1==(contains all same values), print "Same">False
if list1==(contains all different values), print "Different"  >True

I wanted to know here whether there is a command/function that can do
exactly this.  I hope I am more clearer than my last try!

Thanks!
Gaurav


On Wed, Apr 15, 2009 at 5:49 PM, Chris Rebert  wrote:

> On Wed, Apr 15, 2009 at 2:36 PM, Gaurav Moghe  wrote:
> > Hi,
> >
> > I am an amateur python user I wanted to know how do I know whether all
> the
> > contents of a list are all same or all different? Now, I could certainly
> > write a loop with a counter. But is there a ready command for that?
> Checked
> > a lot of docs and this mailing list, but didnt get anything worthwhile.
> > Would be glad to know.
>
> All same:
>
> list_1 == list_2
>
> All different:
>
> all(x != y for x, y in zip(list_1, list_2))
>
> Cheers,
> Chris
> --
> I have a blog:
> http://blog.rebertia.com
>



-- 
Gaurav Moghe
Graduate Student
Evolutionary Genomics Lab
Dept of Plant Biology
Michigan State University
USA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda alternative?

2009-04-15 Thread Paul Rubin
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.
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-15 Thread Chris Rebert
On Wed, Apr 15, 2009 at 2:36 PM, Gaurav Moghe  wrote:
> Hi,
>
> I am an amateur python user I wanted to know how do I know whether all the
> contents of a list are all same or all different? Now, I could certainly
> write a loop with a counter. But is there a ready command for that? Checked
> a lot of docs and this mailing list, but didnt get anything worthwhile.
> Would be glad to know.

All same:

list_1 == list_2

All different:

all(x != y for x, y in zip(list_1, list_2))

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


python twitter

2009-04-15 Thread Wes James
Anyone know if there is a twit for python?  I did
http://twitter.com/python, but nope on that  I was looking for
twit py announcements, etc...

thx,

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


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

2009-04-15 Thread Gaurav Moghe
Hi,

I am an amateur python user I wanted to know how do I know whether all the
contents of a list are all same or all different? Now, I could certainly
write a loop with a counter. But is there a ready command for that? Checked
a lot of docs and this mailing list, but didnt get anything worthwhile.
Would be glad to know.

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


Re: Interrupt Python C API

2009-04-15 Thread googler . 1 . webmaster
hi, yes, thats true, Alan Touring told us, so it would be nice to let
the user abort it.

Is there a chance for windows, too?
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] RELEASED Python 2.6.2

2009-04-15 Thread Barry Warsaw

On Apr 15, 2009, at 4:47 PM, 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?

Most recent releases have not been; the only way I know to make a
compatible build is to build the installer on a machine that already  
has

a 3rd party Tcl/Tk installed; the resulting binary is then compatible
with both 3rd party versions of Tcl/Tk and also with Apple's ancient
built in version.


I can't answer this, but Ronald is building the OS X image for 2.6.2,  
AFAIK.  I think it will be out soon, and maybe he can answer your Tcl/ 
Tk question.


-Barry



PGP.sig
Description: This is a digitally signed message part
--
http://mail.python.org/mailman/listinfo/python-list


Re: zProblem

2009-04-15 Thread norseman

Gabriel Genellina wrote:
En Tue, 14 Apr 2009 18:42:32 -0300, norseman  
escribió:



Gabriel Genellina wrote:
En Mon, 13 Apr 2009 15:13:53 -0300, norseman  
escribió:

Gabriel Genellina wrote:




Below there is an attempt to reproduce the layout you describe in the 
PDF:



from Tkinter import *
root = Tk()
pane = Frame(root, width=400, height=300)
pane.pack(fill="both", expand=1)
w1 = Label(pane, text="1", bg="white")
w1.place(relwidth=0.1, relheight=0.5)
w2 = Label(pane, text="2", bg="yellow")
w2.place(relwidth=0.25, relheight=0.3, relx=0.1)
w3 = Label(pane, text="3", bg="red")
w3.place(relwidth=0.2, relheight=0.2, relx=0.1, rely=0.3)
[...]


Anyone having the same problem I have had needs to copy/paste the 
effort and play with it a bit.


WOW! - it's what I've been trying to do!  (much more YES than not)

One can substitute a Frame widget for the Label widget and see how it 
will work.  Do take note that as you traverse away from the 0,0 (here 
assumed to be top left) point the prior (sum) of the prior widget(s) 
relwidth (to left) goes into the relx and the same addition to the 
prior relheight(s) (above) goes into the rely displacements of the 
current. Also take note of how the parcels flush out at logical places.
Place is not a grid (it's parcelling) and it's based on units of "%" 
of Frame it is used in.  That is: Place uses a "%" value rather than a 
finite distance. Thus, to have two different, but same screen size, 
frames, each in a differently fixed sized frame of it own, YOU WILL 
HAVE TO REDO THE MATH. Even if both are hooked at the 0,0 of their 
respective masters.


That's not really true. "place" takes a position and a size; both can be 
relative (percent, based on its parent), absolute (in pixels, inches, or 
other units), and you can even mix both types. x,y are absolute; 
relx,rely are relative; same goes for height,width and relheight,relwidth.


The available absolute units are: 200 (an integer, *not* 200.0) means 
200 pixels; "200m" (a string) means 200 mm, "200p" means 200 points 
(1/72"), "200i" means 200 inches, and finally "200c" means 200 cm. So 
you can define the exact size and position for each element.


I had tried these in "grid" and didn't get very far so I assumed things 
had changed since the docs were written. Good to know.


Relative sizes and positions are automatically scaled when the container 
is resized -- in my example, if you resize the window all the "parcels" 
grow and shrink accordingly.



YES - very nicely so.

With absolute sizes, you don't have to redo the math each time, but 
resizing isn't automatic. Perhaps absolute sizes are better suited for 
your application.




Yes. Mine is rather like a dashboard that unfortunatly takes up more 
cockpit (screen) than I like. If the user shrinks it they will have a 
hard time trying to pick the selection of choice and if they expand it 
(unlikely) it will put enough off screen to cause another problem, 
omissions.



Gabriel - THANK YOU VERY MUCH!
May not be politically correct but:
Whatever your gender - Please give yourself a good hug for me.


Glad to be of any help. I'm a male, btw.




Mucho obligó al Señor;


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


Re: sharing/swapping items between lists

2009-04-15 Thread MRAB

samwyse wrote:

On Apr 15, 8:13 am, Aaron Brady  wrote:

On Apr 15, 6:57 am, samwyse  wrote:


Here's my idea:  generate all possible pairs:

import itertools
players = [chr(c) for c in xrange(ord('a'),ord('z')+1)]
all_pairs = list(itertools.combinations(players,2))

partition the list:

def choose_nonoverlapping(pairs):

chosen, leftover, used = list(), list(), list()
for p in pairs:
a, b = p
if a in used or b in used:
leftover.append(p)
else:
chosen.append(p)
used.append(a)
used.append(b)
return chosen, leftover

court_count = 10
week_count = 10
pairs = all_pairs
for week in xrange(week_count):

print 'week', week+1
this_week, pairs = choose_nonoverlapping(pairs)
print ', '.join(map(lambda t: ' vs '.join(t), this_week
[:court_count]))
pairs[0:0] = this_week[court_count:]

snip

Your idea arrives at a sub-optimal solution on players= 'abcdef',
court_count= 3.

Correct, by hand (5 weeks):

ab cd ef
ac be df
ad ce bf
ae bd cf
af bc de

Program (7 weeks):


[snip]

However, you do correctly arrive at all the combinations, in better
than the naive 'one pair per week' solution.  Further, you produced
the correct solution for players= 'abcdef', for court_count= 1 and
court_count= 2, which I also tested.  Damage report?


It does work better when there are a limited number of courts, but
since that was in the original description, I didn't worry too much.

One could product several random shuffles of the list of combinations
and see which produced the shortest list of results.  That would add
indeterminancy without guaranteeing an optimal result.  But I think
that other people have algorithms for that case, so I'm not too
worried.

I've tried generalizing to competitions  with more than two player
(e.g. the Pinewood Derby, where up four cars are in each heat), but
the algorithm falls apart, mostly due to the way
itertools.combinations returns its results.


Here's the basics of my algorithm, for what it's worth. It just returns
the pairs:

def get_pair(player_queue, done_pair):
for first in player_queue:
for second in player_queue:
pair = first, second
if first != second and pair not in done_pair:
return pair
return None

def round_robin(players):
player_queue = players[:]
done_pair = set()
while True:
pair = get_pair(player_queue, done_pair)
if pair is None:
player_queue = players[:]
break
else:
done_pair.add(pair)
done_pair.add((pair[1], pair[0]))
player_queue = [p for p in player_queue if p not in pair] + 
list(pair)

yield pair

for pair in round_robin('abcdef'):
print pair
--
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython newbie: not clear on imports and assemblies

2009-04-15 Thread Mike Driscoll
On Apr 15, 3:31 pm, Thomas Gagne  wrote:
> OK--I also haven't programmed on .NET before.
>
> My goal is to play with the "EssentialPDF" libraries inside IronPython.
>   But I'm not clear on how to import (load?) Essential's .dll files.  Of
> course, all the samples files are in C# and VB.  I guess I"m wondering
> if Essential's libraries (assemblies?) should already be in my path or
> if I need to provide a path to them, and whether or not I'm going to use
> "import" or Assembly.Load(), and if the latter, where am I to find
> Assembly?  I'm pretty sure that has to be imported as well 'cause
> whenever I try to use it I'm told it doesn't exist...
>
> Anyway, I'll keep Googling around and reading tutorials to catch-up.  I
> haven't used Python since 1999 so I need some refreshing...
> --
> Visit  to read
> my rants on technology and the finance and consulting industries.

First of all, you should join the IronPython mailing list and ask
there. They can probably give quicker, better answers. See
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com

You might also want to buy Michal Foord's new book: IronPython in
Action from Manning.

I'm pretty new to IronPython too, but my guess is that you'd have to
do something like this:


import clr
clr.AddReference("EssentialPDF")

# now EssentialPDF should be in your python namespace
# so you can do something like this:

from EssentialPDF import SomeModule

# or

EssentialPDF.SomeModule



At least, that's how it seems to work for most .NET libraries. Hope
that helps.

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


Re: RELEASED Python 2.6.2

2009-04-15 Thread Ned Deily
In article ,
 "Russell E. Owen"  wrote:
> 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?
> 
> Most recent releases have not been; the only way I know to make a 
> compatible build is to build the installer on a machine that already has 
> a 3rd party Tcl/Tk installed; the resulting binary is then compatible 
> with both 3rd party versions of Tcl/Tk and also with Apple's ancient 
> built in version.

Thanks for the reminder.  FWIW, that issue has recently been documented 
and there is a patch for the build script to ensure that the 3rd party 
Tcl/Tk is present during the installer build.  I don't think it made it 
into the 2.6.2 source tree, though.



-- 
 Ned Deily,
 n...@acm.org

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


Re: Lambda alternative?

2009-04-15 Thread Caleb Hattingh

On Wed, 15 Apr 2009 15:47:05 +0200,  wrote:


But, lambda functions can't be pickled. I would like to pickle my
objects, and i would really like to use parallel python (which
requires pickling).


If you are fixated on using lambda, you could probably use Recipe 7.6:  
Pickling Code Objects in the Python Cookbook, 2nd Edition, or here:


http://www.ubookcase.com/book/Oreilly/Python.Cookbook.2nd.edition/0596007973/pythoncook2-chp-7-sect-6.html

However, it is better to use named functions as all the other posters have  
already mentioned.

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


Where to find options for add_command?

2009-04-15 Thread Muddy Coder
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!


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


Re: RELEASED Python 2.6.2

2009-04-15 Thread Russell E. Owen
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?

Most recent releases have not been; the only way I know to make a 
compatible build is to build the installer on a machine that already has 
a 3rd party Tcl/Tk installed; the resulting binary is then compatible 
with both 3rd party versions of Tcl/Tk and also with Apple's ancient 
built in version.

-- Russell

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


Re: show PDF in wxPython?

2009-04-15 Thread alejandro
Thank you both! 


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


Re: Serialization format of gdb trace data between many different machines.

2009-04-15 Thread joshbaptiste
On Apr 15, 2:21 pm, MRAB  wrote:
> joshbaptiste wrote:
> > I have a corewatch.py program on ~400+ Linux machines that collect
> > core file gdb output and sends the output traces via email to
> > developers. I what to convert the script for all output to be sent to
> > a centralized server also written in python and displayed via
> > webpage.  My first thought was a simple HTTP POST to server from all
> > nodes but since the gdb output can be very large, multiplied my the #
> > of servers, worries me as network traffic of 400+ nodes sending to 1
> > server may cause saturation.
>
> > What would be the most efficient/small serialization format to use to
> > send this trace data from nodes to server over network.. would
> > Pickling be ok?
>
> I'd probably compress the data first using the zipfile module.

ok.. zipfile,  sounds good thanks..
--
http://mail.python.org/mailman/listinfo/python-list


Re:

2009-04-15 Thread Benjamin Kaplan
On Wed, Apr 15, 2009 at 4:35 PM, fridash13  wrote:

> i am quite new to python ...
>
> i made a small script ,, for active directory using python
>
> all the script does is basicly explor the AD for a number of tasks ..
>
> * 1 .Find a user (quick method)
> * 2 .Find a computer (quick method)
> * 3 .List all users
> * 4 .List users in an OU
> * 5 .List all groups
> * 6 .Show the members of a group
> * 7 .Show the types of a group
> * 8 .List the groups a user is in
>
> i have used the AD moudle for this script ..
>
> my question is this i have the follwing code :
>
> # find user (
> elif choice == "1":
> import active_directory
> user = active_directory.find_user ("ron")
> print user
>
> how can i make the entry for the "user" (in this case ("ron")
> shift according to raw input from the user
>
> so if the user typs jhonny it will replace ("ron")
>
> i need the ability to replace the name
> how can i accomplise this ?
>

Python tries to be pretty intuitive. You get raw input from the user by
using raw_input.

name = raw_input("enter a user: ")
user = active_directory.find_user(name)

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


[no subject]

2009-04-15 Thread fridash13
i am quite new to python ...

i made a small script ,, for active directory using python

all the script does is basicly explor the AD for a number of tasks ..

* 1 .Find a user (quick method)
* 2 .Find a computer (quick method)
* 3 .List all users
* 4 .List users in an OU
* 5 .List all groups
* 6 .Show the members of a group
* 7 .Show the types of a group
* 8 .List the groups a user is in

i have used the AD moudle for this script ..

my question is this i have the follwing code :

# find user (
elif choice == "1":
import active_directory
user = active_directory.find_user ("ron")
print user

how can i make the entry for the "user" (in this case ("ron")
shift according to raw input from the user

so if the user typs jhonny it will replace ("ron")

i need the ability to replace the name
how can i accomplise this ? 

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


Re: platform.machine(): ImportError: No module named select

2009-04-15 Thread Ali H. Caliskan
I'm using Arch Linux and the current python version is 2.6.1, so I did
create a custom python3 package by myself and tried to install it on /opt
directory. I believe it's a installation issue, because I skipped "make
test" part during compilation, which failed with some errors.

ali


>
> It should work.  The select module should be there; if not, the Python
> build/installation is probably faulty.  From the path names, I'll guess
> this is on Solaris.  If so, there seems to be a long history of problems
> building select and friends.  See, for example:
> 
>
> Someone with current Solaris experience may be able to help.
>  
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython newbie: not clear on imports and assemblies

2009-04-15 Thread Benjamin Kaplan
On Wed, Apr 15, 2009 at 4:31 PM, Thomas Gagne wrote:

> OK--I also haven't programmed on .NET before.
>
> My goal is to play with the "EssentialPDF" libraries inside IronPython.
>  But I'm not clear on how to import (load?) Essential's .dll files.  Of
> course, all the samples files are in C# and VB.  I guess I"m wondering if
> Essential's libraries (assemblies?) should already be in my path or if I
> need to provide a path to them, and whether or not I'm going to use "import"
> or Assembly.Load(), and if the latter, where am I to find Assembly?  I'm
> pretty sure that has to be imported as well 'cause whenever I try to use it
> I'm told it doesn't exist...
>
> Anyway, I'll keep Googling around and reading tutorials to catch-up.  I
> haven't used Python since 1999 so I need some refreshing...
> --


I haven't used IronPython that much, but I think you have to load the
assembly using clr.AddReference and then you can import the library just
like you import any other python module.

>
> Visit  to read
> my rants on technology and the finance and consulting industries.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2009-04-15 Thread fridash13
i am quite new to python ...

i made a small script ,, for active directory using python

all the script does is basicly explor the AD for a number of tasks ..

* 1 .Find a user (quick method)
* 2 .Find a computer (quick method)
* 3 .List all users
* 4 .List users in an OU
* 5 .List all groups
* 6 .Show the members of a group
* 7 .Show the types of a group
* 8 .List the groups a user is in

i have used the AD moudle for this script ..

my question is this i have the follwing code :

# find user (
elif choice == "1":
import active_directory
user = active_directory.find_user ("ron")
print user

how can i make the entry for the "user" (in this case ("ron")
shift according to raw input from the user

so if the user typs jhonny it will replace ("ron")

i need the ability to replace the name
how can i accomplise this ? 

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


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

2009-04-15 Thread Gerhard Häring
Aaron Watters wrote:
> On Apr 15, 3:49 am, Tim Hoffman  wrote:
> 
>> There are plenty of python web frameworks, some have quite different
>> approaches,
>> what suits you will depend very much on your own bias, interest.
> 
> I've had a lot of luck with WHIFF
> ( http://whiff.sourceforge.net )
> Of course I wrote it and just released it publicly
> recently.
> 
> I'm a bit disappointed because I know a lot of people have looked
> at the docs and demos and there have been a number of downloads,
> but I haven't gotten one comment yet :( zilch nada.  (There is
> one comment attached to one of the docs, but that was me testing
> the comments feature :) ).
> 
> Back in the old days you could at least count on someone yelling
> at you about how your design was such a bad idea

[Just read the docs for ca. 5 minutes.]

That's perhaps because a lot of people had the same thought after short
reading/trying out as me:

WTF?! This is weird stuff! Why the hell would I use this instead of a
Python web framework like Django/Pylons/etc.

You should perhaps contrast WHIFF with the other offerings for creating
web applications.

-- Gerhard

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


Re: need to start a new project , can python do all that ?

2009-04-15 Thread Stef Mientki

there's even already written an EPD in Python,
but I can't find it right now,
googling is difficult,
because EPD stand for the more popular Ebthought Python Distro :-(

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


IronPython newbie: not clear on imports and assemblies

2009-04-15 Thread Thomas Gagne

OK--I also haven't programmed on .NET before.

My goal is to play with the "EssentialPDF" libraries inside IronPython. 
 But I'm not clear on how to import (load?) Essential's .dll files.  Of 
course, all the samples files are in C# and VB.  I guess I"m wondering 
if Essential's libraries (assemblies?) should already be in my path or 
if I need to provide a path to them, and whether or not I'm going to use 
"import" or Assembly.Load(), and if the latter, where am I to find 
Assembly?  I'm pretty sure that has to be imported as well 'cause 
whenever I try to use it I'm told it doesn't exist...


Anyway, I'll keep Googling around and reading tutorials to catch-up.  I 
haven't used Python since 1999 so I need some refreshing...

--
Visit  to read
my rants on technology and the finance and consulting industries.
--
http://mail.python.org/mailman/listinfo/python-list


Testing in Python mailing list broken?

2009-04-15 Thread Scott David Daniels

Does anyone know if the Testing in Python mailing list
is broken or turned off?  It was running almost too many
messages, but now there has been a _huge_ silence.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: platform.machine(): ImportError: No module named select

2009-04-15 Thread Ned Deily
In article 
,
 "Ali H. Caliskan"  wrote:
> I'm trying to use "platform.machine()" function, but it doesn't work on
> python 3.0.1. Am I doing something wrong here or is it suppose to not work
> on py3k? The errors I get while using the python interpreter:
> 
> >>> import platform
> >>> platform.machine()
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/opt/lib/python3.0/platform.py", line 1222, in machine
> return uname()[4]
>   File "/opt/lib/python3.0/platform.py", line 1152, in uname
> processor = _syscmd_uname('-p','')
>   File "/opt/lib/python3.0/platform.py", line 905, in _syscmd_uname
> f = os.popen('uname %s 2> /dev/null' % option)
>   File "/opt/lib/python3.0/os.py", line 629, in popen
> import subprocess, io
>   File "/opt/lib/python3.0/subprocess.py", line 361, in 
> import select
> ImportError: No module named select

It should work.  The select module should be there; if not, the Python 
build/installation is probably faulty.  From the path names, I'll guess 
this is on Solaris.  If so, there seems to be a long history of problems 
building select and friends.  See, for example:


Someone with current Solaris experience may be able to help.

-- 
 Ned Deily,
 n...@acm.org

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


Re: need to start a new project , can python do all that ?

2009-04-15 Thread Deep_Feelings
now going into python i found that python 3 is just out but recourses
are limited (including IDEs) any help on that ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying the value of a float-like object

2009-04-15 Thread Dan Goodman

eric.le.bi...@spectro.jussieu.fr wrote:

I initially tried to create a Float_ref class that inherits from
numpy.array, so that objects of the new class behave like numpy.array
in calculations, but also contain an "uncertainty" atribute, but this
is apparently not allowed ("cannot create 'builtin_function_or_method'
instances").

So I thought I'd directly add an attribute to a numpy.array: "x =
numpy.array(3.14); x.uncertainty = 0.01", but this is not allowed
either.

Thus, it is not obvious for me to extend the 1x1 numpy.array object so
that it also contains an "uncertainty" attribute.


Subclassing numpy arrays is possible but it can be a bit fiddly. You 
can't add attributes to a numpy array unless it's a subclass.


The first place to look is:

http://www.scipy.org/Subclasses

Actually, I haven't read this (new) page in the numpy docs, but it looks 
better:


http://docs.scipy.org/doc/numpy/user/basics.subclassing.html

It also seems to include a simple example of how to write a subclass 
that just adds a single attribute.


Dan

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


Re: Equivalent to C bitmasks and enumerations

2009-04-15 Thread Scott David Daniels

Ulrich Eckhardt wrote:

Greetings!

I'm currently using Python to implement a set of tests for code that is
otherwise written in C. This code was wrapped using Boost.Python and is
then loaded into Python as module.

What I often have in C is this:

  // bitfield (several flags combined)
  #define STATUS_OVERTEMP 1u
  #define STATUS_ON_FIRE 2u
  #define STATUS_BORED 4u
  unsigned get_status(void);

  // enumeration (distinct values from a set)
  enum color { color_red=1, color_green=13, color_mauve=42 };
  enum color get_color(void);

What I'm looking for is a suggestion how to handle this in Python. Note that
technically, this works without problem, I'm rather looking for stylistic
advise. What I currently have is these (note: I'm retyping this, so ignore
any syntax errors, please):

 STATUS_OVERTEMP = 1
 STATUS_ON_FIRE = 2
 STATUS_BORED = 4
 def status_as_string(st):
 tmp = []
 if st&STATUS_OVERTEMP:
 tmp.append("OVERTEMP")
 if st&STATUS_ON_FIRE:
 tmp.append("ON_FIRE")
 if st&STATUS_BORED:
 tmp.append("BORED")
 return "|".join(tmp)

 COLOR_RED = 1
 COLOR_GREEN = 13
 COLOR_MAUVE = 42
 def color_as_string(c):
 names = {
 COLOR_RED:"RED",
 COLOR_GREEN:"GREEN",
 COLOR_MAUVE:"MAUVE"}
 return names[c];

Further, I also tried defining a separate class:

 class Color(int):
 RED = 1
 GREEN = 13
 MAUVE = 42
 names = { RED:"RED", GREEN:"GREEN", MAUVE:"MAUVE"}

 def __str__(self):
 return names[c];
 ...
  


To be a bit more explicit about what I would like, here is an example how I
would like to use it:

  c = Color.RED
  type(c) # should yield class Color
  str(c) # should yield "RED"
  Color(999) # should signal the invalid color value


Any other suggestions how to structure this or rewrite this?

thanks!

Uli

  

Here's a hack:

class Status(int):
_bits = [('OVERTEMP', 1), ('ON_FIRE', 2), ('BORED', 4)]

def __repr__(self):
parts = []
v = int(self)
for name, value in self._bits:
if v & value:
parts.append(name)
v ^= value
if v or not parts:
parts.append(hex(v))
return '%s(%s)' % (self.__class__.__name__,
   '|'.join(parts))
for _name, _value in Status._bits:
setattr(Status, _name, Status(_value))


--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] Correction: Python Bug Day on April 25

2009-04-15 Thread Maciej Fijalkowski
On Wed, Apr 15, 2009 at 1:10 PM, Georg Brandl  wrote:
> Hi,
>
> I managed to screw up the date, so here it goes again:
>
> I'd like to announce that there will be a Python Bug Day on April 25.
> As always, this is a perfect opportunity to get involved in Python
> development, or bring your own issues to attention, discuss them and
> (hopefully) resolve them together with the core developers.
>
> We will coordinate over IRC, in #python-dev on irc.freenode.net,
> and the Wiki page http://wiki.python.org/moin/PythonBugDay has all
> important information and a short list of steps how to get set up.
>
> Please spread the word!
>
> Georg
>
> ___
> Python-Dev mailing list
> python-...@python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: 
> http://mail.python.org/mailman/options/python-dev/fijall%40gmail.com
>

Are you aware that this directly conflicts with TurboGears world-wide sprint?

Not sure if this is relevant, just a notice.

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


Re: zProblem

2009-04-15 Thread norseman

Steven D'Aprano wrote:

On Tue, 14 Apr 2009 14:42:32 -0700, norseman wrote:


Grids are uniform! Same size, non-changing across whole backdrop. There
is nothing in uniform that says X==Y. Units along axis need not be same.
  Corners don't even have to be 90degrees. (Spherical) But they must
measure as same size cells across the board. Just like any grid paper.


Except for log paper, log-log paper, normal-probability paper, and other 
non-uniform grids.


http://en.wikipedia.org/wiki/File:Log_paper.svg

Or Penrose tilings:

http://en.wikipedia.org/wiki/Penrose_tiles



For those reading this that just said "AH-Hah!", Spherical (Lat./Long.)
is not measured in Cartesian (distance like feet or meter) but in angles
(like 7 and 1/2 minute USGS Quads). 7.5minutes of Longitude at the
equator does not have the same arc length as 7.5minutes at the poles.
But both are 7.5minutes and thus form a (polar) grid. ENOUGH OF THIS -
sorry for being long winded.

Whoever wrote Tk was not crazy. Just didn't use a dictionary.


Nor should they. "Grid" has technical meanings (note plural) that are not 
well-suited to a dictionary definition. I'm amused that Wiktionary gives 
one definition for grid as a rectangular array of uniformly sized squares 
or rectangles, and illustrated it with a curvilinear grid of non-uniform 
pieces!


http://en.wiktionary.org/wiki/grid





Log grids are actually same units apart. Find a picture of a Slide Rule.
Circular... are polar and again lines increase by same unit.
Again - nothing dictates X==Y as the only choice. Each axis may be 
different from any other.  Relief models usually hold X & Y and 
exaggerate the Z by many multiples of the other scale(s). Even the Grand 
Canyon when displayed on a small table without an exaggerated Z is very 
unimpressive.
Not all dimensional objects can be depicted in planar mode without 
distortion. But grids are defined as same unit spacing.
Google up some geodetics and geo-referencing and check the "maps" of the 
world in different planar projections.


Trying to display an object of n Dimensions on an object of less than n 
dimensions is the nightmare of every mapmaker.
If that's not clear, try:  get an orange and peal the skin off in one 
contiguous piece and place it flat on the table.


Actually, to be fully correct, to display any n dimensional object on 
any non-n dimensional object will result in distortion.


The location of a point on the Earth being depicted on paper is put 
through a (compound) formula to properly convert grid locations.

Same in reverse, but the algorithm is different.


ps. I used to have a "ball" made of pentagons. It had no holes.

Homework assignment: generate the math to properly display tiny objects 
glued to all surfaces of that "ball", maintaining proper spatial 
relationships, on paper.  Hint: define the grid for the paper first. You 
will also need one for the "ball".



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


Re: ANN: PyGUI 2.0.1

2009-04-15 Thread Suraj Barkale
Greg Ewing  canterbury.ac.nz> writes:
> 
> PyGUI 2.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


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


Correction: Python Bug Day on April 25

2009-04-15 Thread Georg Brandl
Hi,

I managed to screw up the date, so here it goes again:

I'd like to announce that there will be a Python Bug Day on April 25.
As always, this is a perfect opportunity to get involved in Python
development, or bring your own issues to attention, discuss them and
(hopefully) resolve them together with the core developers.

We will coordinate over IRC, in #python-dev on irc.freenode.net,
and the Wiki page http://wiki.python.org/moin/PythonBugDay has all
important information and a short list of steps how to get set up.

Please spread the word!

Georg

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


Re: binary file compare...

2009-04-15 Thread Nigel Rantor

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.


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


Re: binary file compare...

2009-04-15 Thread Adam Olsen
On Apr 15, 11:04 am, Nigel Rantor  wrote:
> The fact that two md5 hashes are equal does not mean that the sources
> they were generated from are equal. To do that you must still perform a
> byte-by-byte comparison which is much less work for the processor than
> generating an md5 or sha hash.
>
> If you insist on using a hashing algorithm to determine the equivalence
> of two files you will eventually realise that it is a flawed plan
> because you will eventually find two files with different contents that
> nonetheless hash to the same value.
>
> The more files you test with the quicker you will find out this basic truth.
>
> This is not complex, it's a simple fact about how hashing algorithms work.

The only flaw on a cryptographic hash is the increasing number of
attacks that are found on it.  You need to pick a trusted one when you
start and consider replacing it every few years.

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.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to abort a FTP command?

2009-04-15 Thread Scott David Daniels

_...@163.com wrote:

Thank you. You are right, retrbinary did not notice I want to abort,
so it won't break the recv loop and close data connection
def getpart(self, ftp_filename, rest, cnt, out_filename):
self.outf = open(out_filename, 'wb')
self.cnt = cnt
self.handle.voidcmd('TYPE I')
conn = self.handle.transfercmd('RETR ' + ftp_filename, rest)
while 1:
data = conn.recv(8192)
if not data:
break
if self.getpart_callback(data):
try:
self.handle.abort()
break
except:
pass
self.outf.close()
self.handle.voidresp()
conn.close()


How about:
 import logging
 ...

 def getpart(self, ftp_filename, rest, cnt, out_filename):
 with open(out_filename, 'wb') as outf:
 self.outf = outf
 self.cnt = cnt
 self.handle.voidcmd('TYPE I')
 conn = self.handle.transfercmd('RETR ' + ftp_filename,
rest)
 data = conn.recv(8192)
 while data:
 if self.getpart_callback(data):
 try:
 self.handle.abort()
 break
 except BaseException, why:
 # "except BaseException as why:" if >= Py2.6
 logging.error('%s: %s encountered' % (
   (why.__class__.__name__, why))
 if not isinstance(why, Exception):
 raise
 data = conn.recv(8192)
 self.handle.voidresp()
 conn.close()

--Scott David Daniels
scott.dani...@acm.org

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


platform.machine(): ImportError: No module named select

2009-04-15 Thread Ali H. Caliskan
Hi!

I'm trying to use "platform.machine()" function, but it doesn't work on
python 3.0.1. Am I doing something wrong here or is it suppose to not work
on py3k? The errors I get while using the python interpreter:

>>> import platform
>>> platform.machine()
Traceback (most recent call last):
  File "", line 1, in 
  File "/opt/lib/python3.0/platform.py", line 1222, in machine
return uname()[4]
  File "/opt/lib/python3.0/platform.py", line 1152, in uname
processor = _syscmd_uname('-p','')
  File "/opt/lib/python3.0/platform.py", line 905, in _syscmd_uname
f = os.popen('uname %s 2> /dev/null' % option)
  File "/opt/lib/python3.0/os.py", line 629, in popen
import subprocess, io
  File "/opt/lib/python3.0/subprocess.py", line 361, in 
import select
ImportError: No module named select


Kind regards,
Ali
--
http://mail.python.org/mailman/listinfo/python-list


Re: Serialization format of gdb trace data between many different machines.

2009-04-15 Thread MRAB

joshbaptiste wrote:

I have a corewatch.py program on ~400+ Linux machines that collect
core file gdb output and sends the output traces via email to
developers. I what to convert the script for all output to be sent to
a centralized server also written in python and displayed via
webpage.  My first thought was a simple HTTP POST to server from all
nodes but since the gdb output can be very large, multiplied my the #
of servers, worries me as network traffic of 400+ nodes sending to 1
server may cause saturation.

What would be the most efficient/small serialization format to use to
send this trace data from nodes to server over network.. would
Pickling be ok?


I'd probably compress the data first using the zipfile module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-15 Thread M.-A. Lemburg
On 2009-04-15 19:59, P.J. Eby wrote:
> At 06:15 PM 4/15/2009 +0200, M.-A. Lemburg wrote:
>> The much more common use case is that of wanting to have a base package
>> installation which optional add-ons that live in the same logical
>> package namespace.
> 
> Please see the large number of Zope and PEAK distributions on PyPI as
> minimal examples that disprove this being the common use case.  I expect
> you will find a fair number of others, as well.
> 
> In these cases, there is NO "base package"...  the entire point of using
> namespace packages for these distributions is that a "base package" is
> neither necessary nor desirable.
> 
> In other words, the "base package" scenario is the exception these days,
> not the rule.  I actually know specifically of only one other such
> package besides your mx.* case, the logilab ll.* package.

So now you're arguing against having base packages... at least you've
dropped the strange idea of using Linux distribution maintainers
as central use case ;-)

Think of base namespace packages (the ones providing the __init__.py
file) as defining the namespace. They setup ownership and the basic
infrastructure needed by add-ons.

If you take Zope as example, the Products/ package dir is a good
example: the __init__.py file in that directory is provided by the
Zope installation (generated during Zope instance creation), so Zope
"owns" the package.

With the proposal, Zope could declare this package dir a namespace
base package by adding a __pkg__.py file to it.

Zope add-ons could then be installed somewhere else on sys.path
and include a Products/ dir as well, only this time it doesn't have
the __init__.py file, but only a __pkg__.py file.

Python would then take care of integrating the add-on Products/ dir
Python module/package contents with the base package.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Apr 15 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2009-03-19: Released mxODBC.Connect 1.0.1  http://python.egenix.com/

::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-15 Thread James Y Knight


On Apr 15, 2009, at 12:15 PM, M.-A. Lemburg wrote:

The much more common use case is that of wanting to have a base  
package

installation which optional add-ons that live in the same logical
package namespace.

The PEP provides a way to solve this use case by giving both  
developers

and users a standard at hand which they can follow without having to
rely on some non-standard helpers and across Python implementations.


I'm not sure I understand what advantage your proposal gives over the  
current mechanism for doing this.


That is, add to your __init__.py file:

from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

Can you describe the intended advantages over the status-quo a bit  
more clearly?


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


Serialization format of gdb trace data between many different machines.

2009-04-15 Thread joshbaptiste
I have a corewatch.py program on ~400+ Linux machines that collect
core file gdb output and sends the output traces via email to
developers. I what to convert the script for all output to be sent to
a centralized server also written in python and displayed via
webpage.  My first thought was a simple HTTP POST to server from all
nodes but since the gdb output can be very large, multiplied my the #
of servers, worries me as network traffic of 400+ nodes sending to 1
server may cause saturation.

What would be the most efficient/small serialization format to use to
send this trace data from nodes to server over network.. would
Pickling be ok?

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


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-15 Thread M.-A. Lemburg
On 2009-04-15 19:38, James Y Knight wrote:
> 
> On Apr 15, 2009, at 12:15 PM, M.-A. Lemburg wrote:
> 
>> The much more common use case is that of wanting to have a base package
>> installation which optional add-ons that live in the same logical
>> package namespace.
>>
>> The PEP provides a way to solve this use case by giving both developers
>> and users a standard at hand which they can follow without having to
>> rely on some non-standard helpers and across Python implementations.
> 
> I'm not sure I understand what advantage your proposal gives over the
> current mechanism for doing this.
> 
> That is, add to your __init__.py file:
> 
> from pkgutil import extend_path
> __path__ = extend_path(__path__, __name__)
> 
> Can you describe the intended advantages over the status-quo a bit more
> clearly?

Simple: you don't need the above lines in your __init__.py file
anymore and can rely on a Python standard for namespace packages
instead of some helper implementation.

The fact that you have a __pkg__.py file in your package dir
will signal the namespace package character to Python's importer
and this will take care of the lookup process for you.

Namespace packages will be just as easy to write, install and
maintain as regular Python packages.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Apr 15 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2009-03-19: Released mxODBC.Connect 1.0.1  http://python.egenix.com/

::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
--
http://mail.python.org/mailman/listinfo/python-list


Re: sharing/swapping items between lists

2009-04-15 Thread Aaron Brady
On Apr 15, 11:29 am, samwyse  wrote:
> On Apr 15, 8:56 am, Aaron Brady  wrote:
>
>
>
> > The randomizing solution isn't quite suitable for 16 teams.  With 5
> > teams/1 court, and 5 teams/2 courts, 6 teams/2 courts, the solution
> > comes within seconds.  For 7 teams/3 courts, the solution takes a few
> > minutes.
>
> 7 teams/3 courts is the same as 8 teams/4 courts, where the extra
> player is named "bye".  In other words, it's an uncontrained problem.

For 9 teams, there are (9*8/2), or 36 pairs, so 36!, or
3719933267899012174679994481508352, or 3.7e+41 permutations of
arranging them.  (Thanks to Python's long ints.)  Many of them work on
2 courts.

There are 5x10^68 hydrogen atoms in a galaxy.

There was a discussion on python-ideas about whether ran.shuffle( ) is
even guaranteed to find a solution eventually.  I forget if 36! was
within its bounds.  It may run for years and fail.

On the 8 teams/3 courts trial, a depth-first search can improve your
results in a few seconds, but only by getting one team in one round
earlier.  That figure is interesting, because there are 28! or 3e+29
possible permutations.  It seems many of them work.

The rest of the combinations are impractical to try with a DFS, or
your algorithm does just as good.  Here is the DFS.  Mine is currently
tinkering around on the 25th place of 36 total slots.

The Pinewood Derby case doesn't show much more promise, though you can
eliminate more possibilities from your round, which may speed it up.

from itertools import combinations, permutations
import string
from copy import deepcopy
def circulate( num_players, num_courts ):
''' 2 players per court '''
assert num_players<= 26, '26 players max'
player_set= sorted( string.ascii_lowercase[ :num_players ] )
combs= sorted( ''.join( x ) for x in combinations( player_set,
2 ) )
print( combs )

obs= [ [ x, 0 ] for x in combs ]
# obs[ 1 ]-- 0: not used, 1: one player of combination
#used in round, 2: combination used
stack= [ None ]* len( combs )
def rec( obs, dep ):
if dep< len( combs )- 12:
print( '%i teams %i courts dep %i\nobs %r\nstack %r\n'%
( num_players, num_courts, dep, obs, stack ) )
if all( [ x[ 1 ]== 2 for x in obs ] ):
return True
if ( dep+ 1 )% num_courts== 0:
for x in obs: # new round, clear 'obs'
if x[ 1 ]== 1:
x[ 1 ]= 0
else:
for x in obs: # mark 'obs' so player not tried again
if x[ 1 ]!= 0:
continue
for y in stack[ dep ]:
if y in x[ 0 ]:
x[ 1 ]= 1
for i in range( len( combs ) ):
if obs[ i ][ 1 ]== 0:
obs[ i ][ 1 ]= 2
stack[ dep+ 1 ]= obs[ i ][ 0 ]
res= rec( deepcopy( obs ), dep+ 1 )
if res: return True
obs[ i ][ 1 ]= 0
stack[ dep+ 1 ]= None
return False
rec( deepcopy( obs ), -1 )
return [ stack[ i: i+ num_courts ] for i in range( 0, len
( stack ), num_courts ) ]
--
http://mail.python.org/mailman/listinfo/python-list


Re: segmentation fault while using ctypes

2009-04-15 Thread sanket
On Apr 14, 9:00 pm, bieff...@gmail.com wrote:
> On Apr 15, 12:39 am, sanket  wrote:
>
>
>
> > Hello All,
>
> > I am dealing with this weird bug.
> > I have a function in C and I have written python bindings for it using
> > ctypes.
>
> > I can call this function for couple of times and then suddenly it
> > gives me seg fault.
> > But I can call same function from a C code for any number of times.
>
> > I cannot get what's going on.
>
> > here is my code.
>
> > /**/
> > /* C Function I am calling */
> > int get_hash(char *filename,int rate,int ch,unsigned char* hash,
> > unsigned int* hash_size,short* avg_f,short* avg_d){
>
> > /* some variable declarations here */
> > fp = fopen(filename,"rb");
>
> > data = (signed short *)malloc(sizeof(signed short) * N_BLOCKS);
>
> > whereami = WAVE_HEADER_SIZE;
> > while((!feof(fp)) && (fp_more == 1) && !ferror(fp)){
> >      fp_data_size = fread(data,sizeof(signed short),N_BLOCKS,fp);
> >      whereami += fp_data_size;
> >      fp_more = fp_feed_short(fooid,data,fp_data_size); // call to some
> > library funtion
> >  } //end while
>
> > /* some arithmetic calculations here */
>
> >   n = my_fp_calculate(fooid,audio_length,fp_fingerprint,&fit,&dom);
>
> >   if (data != NULL)
> >       free(data)
> >   fclose(fp)
> >   return n;
>
> > }
>
> > /* END OF C FUNCTION
> > */
> > 
> > Python code
> > -
> > from ctypes import *
> > lib = cdll.LoadLibrary("/usr/lib/libclient.so")
>
> > def my_func(filename,rate,ch):
> >     hash = (c_ubyte * 424)()
> >     hash_size = c_uint()
> >     avg_f = c_short(0)
> >     avg_d = c_short(0)
> >     n = lib.get_hash(filename,rate,ch,hash,byref(hash_size),byref
> > (avg_f),byref(avg_d))
> >     hash = None
>
> > def main():
> >     for filename in os.listdir(MY_DIR):
> >             print filename
> >             my_func(filename,100,10)
> >             print
> > ""
>
> > if __name__ == "__main__":
> >     main()
>
> > == END OF PYTHON CODE ==
>
> > Thank you in advance,
> > sanket
>
> You don't show how the C function make use of parameters hash,
> hash_size, avg_f, avg_d. Since you pass them by address,
> I guess that are output parameters, but how do they get written? In
> particular,make sure you don't write into hash more
> than the  424 bytes you allocated for it in the calling python
> code ...
>
> Ciao
> 
> FB

Yes, I am making sure that hash wouldn't be written more that 424
bytes in to it.
This is something really weird. I can call this function from C as
many times as I want but not from python

I tracked down the problem and came to know that call to
my_fp_calculate causes the seg fault.
I will debug it and let you guys know.

Thank you all so much for the help. I appreciate it.
sanket
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-15 Thread P.J. Eby

At 06:15 PM 4/15/2009 +0200, M.-A. Lemburg wrote:

The much more common use case is that of wanting to have a base package
installation which optional add-ons that live in the same logical
package namespace.


Please see the large number of Zope and PEAK distributions on PyPI as 
minimal examples that disprove this being the common use case.  I 
expect you will find a fair number of others, as well.


In these cases, there is NO "base package"...  the entire point of 
using namespace packages for these distributions is that a "base 
package" is neither necessary nor desirable.


In other words, the "base package" scenario is the exception these 
days, not the rule.  I actually know specifically of only one other 
such package besides your mx.* case, the logilab ll.* package.


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


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-15 Thread P.J. Eby

At 09:10 AM 4/15/2009 -0700, Aahz wrote:

For the benefit of us bystanders, could you summarize your vote at this
point?  Given the PEP's intended goals, if you do not oppose the PEP, are
there any changes you think should be made?


I'm +1 on Martin's original version of the PEP, subject to the point 
brought up by someone that .pkg should be changed to a different extension.


I'm -1 on all of MAL's proposed revisions, as IMO they are a step 
backwards: they "standardize" an approach that will create problems 
that don't need to exist, and don't exist now.  Martin's proposal is 
an improvement on the status quo, Marc's proposal is a dis-improvement.


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


Re: How to query object of GUI?

2009-04-15 Thread Scott David Daniels

John McMonagle wrote:

Muddy Coder wrote:

I need to query the ID of GUI, in Tkinter, but don't know how to do
it. This is my code: ...


Pass the name of the label as an argument to the callback.  Below is a
short working example:
...
lab = 'test'
menubar.add_command(label=lab, command=lambda l=lab: do_menu(l))
lab = 'quit'
menubar.add_command(label=lab, command=lambda l=lab: do_menu(l))

> ...

Another way to do the same thing (a way to "avoid" lambda):
from functools import partial
...
class MyGUI(object):
...
def make_menu(self):
top = Menu(self)
menObj = Menu(top)
for n, lab in enumerate(read_from_database()):
menObj.add_command(label=lab,
command=partial(self.do_menu, n, lab))

def do_menu(self, sequence, label):
# here you know it was the (sequence+1)th entry named label
...

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-15 Thread SpreadTooThin
On Apr 15, 8:04 am, Grant Edwards  wrote:
> On 2009-04-15, Martin  wrote:
>
>
>
> > Hi,
>
> > On Mon, Apr 13, 2009 at 10:03 PM, Grant Edwards  wrote:
> >> On 2009-04-13, SpreadTooThin  wrote:
>
> >>> I want to compare two binary files and see if they are the same.
> >>> I see the filecmp.cmp function but I don't get a warm fuzzy feeling
> >>> that it is doing a byte by byte comparison of two files to see if they
> >>> are they same.
>
> >> Perhaps I'm being dim, but how else are you going to decide if
> >> two files are the same unless you compare the bytes in the
> >> files?
>
> > I'd say checksums, just about every download relies on checksums to
> > verify you do have indeed the same file.
>
> That's slower than a byte-by-byte compare.
>
> >> You could hash them and compare the hashes, but that's a lot
> >> more work than just comparing the two byte streams.
>
> > hashing is not exactly much mork in it's simplest form it's 2
> > lines per file.
>
> I meant a lot more CPU time/cycles.
>
> --
> Grant Edwards                   grante             Yow! Was my SOY LOAF left
>                                   at               out in th'RAIN?  It tastes
>                                visi.com            REAL GOOD!!

I'd like to add my 2 cents here.. (Thats 1.8 cents US)
All I was trying to get was a clarification of the documentation of
the cmp method.
It isn't clear.

byte by byte comparison is good enough for me as long as there are no
cache issues.
a check sum is not good because it doesn't guarantee that  1 + 2 + 3
== 3 + 2 + 1
a crc of any sort is more work than a byte by byte comparison and
doesn't give you any more information.


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


Re: Using Python after a few years of Ruby

2009-04-15 Thread Aaron Watters
On Apr 15, 3:49 am, Tim Hoffman  wrote:

> There are plenty of python web frameworks, some have quite different
> approaches,
> what suits you will depend very much on your own bias, interest.

I've had a lot of luck with WHIFF
( http://whiff.sourceforge.net )
Of course I wrote it and just released it publicly
recently.

I'm a bit disappointed because I know a lot of people have looked
at the docs and demos and there have been a number of downloads,
but I haven't gotten one comment yet :( zilch nada.  (There is
one comment attached to one of the docs, but that was me testing
the comments feature :) ).

Back in the old days you could at least count on someone yelling
at you about how your design was such a bad idea

  -- Aaron Watters

===
HELP! HELP! I'M BEING REPRESSED!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Play sound at wanted frequency

2009-04-15 Thread Scott David Daniels

Diez B. Roggisch wrote:

Matteo schrieb:

I need to playback a sound on a linux machine of a pre-determined
frequency like, say, 440 Hz. How can I do that with python? I found
the ossaudiodev package, but it says that the ossaudiodev.write()
method accepts data as a raw string. It doesn't explain what the
string should be like, and the oss documentation is mainly about C++.

Do you have any tips to share?


Try pygame. You can create samples with it, and play them.

See e.g. this: http://www.pygame.org/docs/ref/sndarray.html


And realize that if you can get that to work, you can always cut into
pygame to see how _it_ accomplishes your task, and mimic that.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying the value of a float-like object

2009-04-15 Thread Suraj Barkale
  spectro.jussieu.fr> writes:
> 
> Hello,
> 
> Is there a way to easily build an object that behaves exactly like a
> float, but whose value can be changed?  The goal is to maintain a list
> [x, y,…] of these float-like objects, and to modify their value on the
> fly (with something like x.value = 3.14) so that any expression like "x
> +y" uses the new value.
> 

Have you looked at sympy (http://code.google.com/p/sympy/)? It implements
symbolic mathematics so you can define the equations & put in the values to get
the result. You should be able to derive from the Symbol class to implement the
accuracy behavior.

Regards,
Suraj

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


Re: binary file compare...

2009-04-15 Thread Nigel Rantor

Grant Edwards wrote:

We all rail against premature optimization, but using a
checksum instead of a direct comparison is premature
unoptimization.  ;)


And more than that, will provide false positives for some inputs.

So, basically it's a worse-than-useless approach for determining if two 
files are the same.


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


Re: binary file compare...

2009-04-15 Thread Nigel Rantor

Martin wrote:

On Wed, Apr 15, 2009 at 11:03 AM, Steven D'Aprano
 wrote:

The checksum does look at every byte in each file. Checksumming isn't a
way to avoid looking at each byte of the two files, it is a way of
mapping all the bytes to a single number.


My understanding of the original question was a way to determine
wether 2 files are equal or not. Creating a checksum of 1-n files and
comparing those checksums IMHO is a valid way to do that. I know it's
a (one way) mapping between a (possibly) longer byte sequence and
another one, how does checksumming not take each byte in the original
sequence into account.


The fact that two md5 hashes are equal does not mean that the sources 
they were generated from are equal. To do that you must still perform a 
byte-by-byte comparison which is much less work for the processor than 
generating an md5 or sha hash.


If you insist on using a hashing algorithm to determine the equivalence 
of two files you will eventually realise that it is a flawed plan 
because you will eventually find two files with different contents that 
nonetheless hash to the same value.


The more files you test with the quicker you will find out this basic truth.

This is not complex, it's a simple fact about how hashing algorithms work.

  n

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


Re: Question to python C API

2009-04-15 Thread Stefan Behnel
Andreas Otto wrote:
>   I have the following question ...
> 
>   I write a custom "*.init" method and expect a variable number or arguments

What's a "*.init" method? Do you mean SomeType.__init__() ?


>   This are my questions:
> 
>   1.I need something like a for loop to analyse this arguments
> For now I try the "PyArg_ParseTupleAndKeywords" but i missing 
> somehing 
> like an Object-Array return value as "format" 
> 
>   2.can i combine variable args with keywords ?
> because it will fit into my spec to use both together
> 
>   3.I want to retrieve a bool object as int value, where is a format "O"
> and "O!" for a type object  HOWTO put the type into the function 
> from
> above

You might want to take a look at Cython. It allows you to write C
extensions in a Python-like language, so all of the above become trivial, e.g.

cdef class MyExtensionType(object):
def __init__(self, bint some_c_bool):
 print type(self) is MyExtensionType
 print some_c_bool == 1

Cython will translate this to efficient C code for you.

http://cython.org/

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


Re: Lambda alternative?

2009-04-15 Thread Duncan Booth
mousemeat  wrote:

> Will i then be able to pickle 'rock', and any object that may contain
> 'rock' as one of it's fields?  I'm not sure that i will, but i'll give
> it a shot.
> 
So long as the functions are defined at module level, not nested inside 
some other namespace it will work fine.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda alternative?

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

> Duncan Booth  writes:
>> What exactly is your objection to using a named function here?...
>> Surely that would solve your pickle problem *and* give you more
>> meaningful tracebacks in your exceptions?
> 
> I don't think it would help the pickle problem.

Why wouldn't you think that?

class material(object):
def __init__(self,density):
self.density=density

def airdensity(T):
return 10/(287*T)
air=material(airdensity)

steeldensity=lambda T:interp(T,[0,1000],[7856,7813])
steel=material(steeldensity)

from pickle import dumps, loads

dumped = dumps(air)
t = loads(dumped)
print t # works fine

dumped = dumps(steel) # pickle.PicklingError: Can't pickle  at 0x02C78A58>: it's not found as __main__.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Bug Day on April 23

2009-04-15 Thread MRAB

Georg Brandl wrote:

Hi,

I'd like to announce that there will be a Python Bug Day on April 23.
As always, this is a perfect opportunity to get involved in Python
development, or bring your own issues to attention, discuss them and
(hopefully) resolve them together with the core developers.

We will coordinate over IRC, in #python-dev on irc.freenode.net,
and the Wiki page http://wiki.python.org/moin/PythonBugDay has all
important information and a short list of steps how to get set up.

Please spread the word!

Georg


First bug! The webpage says Saturday, April 25, 2009.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and XML Help

2009-04-15 Thread Scott David Daniels

ookrin wrote:

 I am still learning. And it's not that I won't take the advice
for using ElementTree, I just currently don't know anything about it.
I just didn't want to say, "I have no idea what you're talking about!"
to Scott cause I figured that would be rude, but I guess so is not
saying anything, sorry. So I'll need to read up on it before I
actually try to do anything with that approach.

Seeing the errors - I changed the two classes to this:
  ... [some code that actually says a _little_ bit about his target] 


If you had done a better job of asking your question, you'd have found a
quick answer.  That is why everyone points people at smartquestions, not
to pick on them.

Presuming you have an xml structure like:
txt = ''' something 
Some contents. 
   Other contents.
   '''
import xml.etree.ElementTree as ET
structure = ET.fromstring(xmls)
for node in structure.findall('def/name'):
print '%s: %s / %s: %s' % (node.tag, node.attrib['name'],
  node.attrib['characterID'], node.text)

or a file named 'my.xml' with the same contents:
import xml.etree.ElementTree as ET
structure = ET.parse('my.xml')
for node in structure.findall('def/name'):
print '%s: %s / %s: %s' % (node.tag, node.attrib['name'],
  node.attrib['characterID'], node.text)


--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >