Re: is there enough information?

2008-02-25 Thread castironpi
> Clarify:
>
> def thdloop( thd ):
>    while thd.cont:
>       thd.sig1event.wait()
>       ret= thd.cmd()
thd.result= ret
>       thd.sig2event.set()
>       thd.seg3event.wait()
>
> and

def consumer( thd ):
   thd.cmd= function
   thd.sig1event.set()
   thd.sig2event.wait()
   ret= thd.result
   thd.sig3event.set()

Except, I missed the shot on the sigevent.clear() placement, and spent
the better part of the day debugging it.

Two options occurred to me, which the first showed up in the earlier
extremely skeletal and cryptic post:  Create a class which will ensure
turn-taking of events, using a get method with and integer index, by
waiting for the prior index to complete before starting the next.

You could name the steps in the class and take a specific order of
them too:

class CmdStep( Step ):
   order= SetCommand, CallCommand, ReadResult

so cmdstep= CmdStep() / with cmdstep.SetCommand: or with
cmdstep[SetCommand]: blocks until the specified time.

The other option, was to join both these threads, execute the command,
then split them again: if that's simpler and just as general, then
Step is cool, but rather useless.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there enough information?

2008-02-25 Thread castironpi
On Feb 25, 11:52 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Feb 25, 9:30 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Is it enough?
>
> (Reminds me of the movie Marathon Man, in which Dustin Hoffman is
> repeatedly asked by Laurence Olivier, "Is it safe?"  Hoffman had no
> idea what Olivier was talking about.  So Olivier tortured Hoffman some
> more to get the answer.)
>
> Enough for what?
>
> Is "th" short for "thread"?  Maybe a little too short - try "thd" at
> least, and spelling out "thread" isn't out of the question.
>
> What happened to step[0]?  Did you know that lists start at 0?  Why
> are you using a list of synchronization objects?
>
> You would be better off using attributes of th with meaningful names,
> instead of elements of a generically named list attribute, "th.step".
> Names like "th.assign_command_synch", "th.return_value_synch", etc.
> And since there is no synch object that is locked in both methods,
> then the methods will run completely devoid of any synchronization.

I recently ran into a case (* would that be helpful to describe here?)
where thread1 had to do something, thread2 had to do something after
that, and thread1 had to wait for that, then do something else, and
thread2 again had to wait before starting the first thing again.

Clarify:

def thdloop( thd ):
   while thd.cont:
  thd.sig1event.wait()
  ret= thd.cmd()
  thd.sig2event.set()
  thd.seg3event.wait()

and

def consumer( thd ):


EXCEPT that,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property data-descriptor - how to pass additional constants to the get/set method

2008-02-25 Thread Gabriel Genellina
En Mon, 25 Feb 2008 18:50:20 -0200, <[EMAIL PROTECTED]> escribió:

> Hi,
> I would like to pass additional constants to the property data-
> descriptor, so it is not necessary to write many methods which differ
> just by constant defined in the method body.
> Till now I can do this:
>
> class MyClass(object):
>
> def _getValue(self, myConstant):
> print 'myConstant:', myConstant
> return myConstant+10
>
> def _setValue(self, inputValue, myConstant):
> print 'inputValue:', inputValue, 'myConstant:', myConstant
> return inputValue*myConstant
>
> fistAttribte = property(fget = lambda self:
> self._getValue(myConstant=0),
>fset = lambda self, inputValue, myConstant=0:
> self._setValue(inputValue, myConstant))
>
> secAttribute = property(fget = lambda self:
> self._getValue(myConstant=1),
>fset = lambda self, inputValue, myConstant=1:
> self._setValue(inputValue, myConstant))
>
> It works, but it does not look very nice to me.
> Is there some different/nicer/more pythonic way how to achieve above
> mentioned?

Try using functools.partial

-- 
Gabriel Genellina

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


Re: print help content in a Command Prompt

2008-02-25 Thread Gabriel Genellina
En Mon, 25 Feb 2008 10:18:19 -0200, <[EMAIL PROTECTED]> escribió:

> On Feb 25, 12:59 pm, Necmettin Begiter <[EMAIL PROTECTED]>
> wrote:
>> 25 February 2008 Monday 11:15:14 tarihinde [EMAIL PROTECTED] şunları  
>> yazmıştı:
>>
>> > Hi,
>> > This is a basic problem, but I want to print help content in a Command
>> > Prompt in WinXP and scrolling back to see the first lines. If I start
>> > a command prompt and run python, and then for example,
>>
>> > >>> help(list)
>>
>> > it starts showing the help, which can be controlled by page or raw
>> > using Spacebar or Enter but after this ends, it seems that I can't
>> > scroll back to see again the first lines.
>> > In the  Command Prompt Properties, layout tab, my Screen buffer size
>> > is Width:80, Height:3000 and windows size 80x40 (W&H).
>>
>> > Any idea...? thanks in advance!!
>> > /Ben
>>
>> Try PgUp when in Python help view.
>>
>> Try "python -c 'help(list)'" to get the help without Python prompt.
>
> Even this doesn't help. But I think I've found a reason for this.
> If I change the "start in" directory to C:\WINDOWS\system32\ (this is
> where the cmd.exe file is located), then the printed text doesn't get
> hide. Don't ask me why...

I usually open a new console pressing [windows key]+R, "run", no "start  
in" directory is involved.
I've seen that after executing a 16-bit program, the console "switches" to  
16 bit "compatibility mode", or something like that. The prompt is  
displayed using short file names, and the screen buffer is disabled.

-- 
Gabriel Genellina

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

Re: running a daemon in python

2008-02-25 Thread rishi pathak
Use the function goDaemon just before starting the server loop:

###Begin Module###
import os
import sys
# Default daemon parameters.
# File mode creation mask of the daemon.
UMASK = 0
# Default working directory for the daemon.
WORKDIR = "/"
# Default maximum for the number of available file descriptors.
MAXFD = 1024
# The standard I/O file descriptors are redirected to /dev/null by default.
if (hasattr(os, "devnull")):
   REDIRECT_TO = os.devnull
else:
   REDIRECT_TO = "/dev/null"
def goDaemon():
   try:
  pid = os.fork()
   except OSError, e:
  raise Exception, "%s [%d]" % (e.strerror, e.errno)
   if (pid == 0):   # The first child.
  os.setsid()
  try:
 pid = os.fork()# Fork a second child.
  except OSError, e:
 raise Exception, "%s [%d]" % (e.strerror, e.errno)
  if (pid == 0):# The second child.
 os.chdir(WORKDIR)
 os.umask(UMASK)
  else:
 os._exit(0)
   else:
  os._exit(0)   # Exit parent of the first child.
   import resource
   maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
   if (maxfd == resource.RLIM_INFINITY):
  maxfd = MAXFD
   for fd in range(0, maxfd):
  try:
 os.close(fd)
  except OSError:   # ERROR, fd wasn't open to begin with (ignored)
 pass
   os.open(REDIRECT_TO, os.O_RDWR)  # standard input (0)
   os.dup2(0, 1)# standard output (1)
   os.dup2(0, 2)# standard error (2)
   return(0)
###End Module###

On Tue, Feb 26, 2008 at 12:06 PM, bharath venkatesh <[EMAIL PROTECTED]>
wrote:

> hi ..
>hi i want a program to start running as daemon in background .. my
> program is server listen to a client ... so i want to make that program run
> as daemon .. when i execute the program the program for ex server.py it
> should automatically start running as daemon in the background even if i
> close the terminal it shouldn't stop executing.. (right now if i close the
> terminal the process exits) can any one tell how to do it  in python as i
> have implemented the server  in python  ...
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
Regards--
Rishi Pathak
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pprint, __repr__ and inheritance, how does it works?

2008-02-25 Thread Gabriel Genellina
En Mon, 25 Feb 2008 10:19:43 -0200, Jorge Vargas <[EMAIL PROTECTED]>  
escribió:

> Hello list, I'm having a little bit of trouble making this all work  
> together.
>
> I have a base class in which I want to define the __repr__ for all
> subclasses which in this case will be to output all the __dict__
> atributes. Using [1] as reference I have come up with the following
> but it has 2 problems, first the type call it's not generating valid
> python code and second this doesn't seems to work with pprint as it's
> just printing the string as a one-liner making it equivalente as
> calling repr(obj)

Perhaps this is a bit closer to what you want, but still not perfect:

 from pprint import pprint,pformat

class node(object):
 def __init__(self,a,b,c):
 self.a,self.b,self.c = a,b,c
 def __repr__(self):
 return "%s(%s)" % (type(self).__name__, pformat(self.__dict__))

class extendedNode(node):
 def __init__(self,d,e):
 self.d,self.e = d,e

n = node(111,22,
   extendedNode(333,4))
pprint(n)

-- 
Gabriel Genellina

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


Re: PHP Developer highly interested in Python (web development) with some open questions...

2008-02-25 Thread Gabriel Genellina
En Mon, 25 Feb 2008 06:42:39 -0200, Bruno Desthuilliers  
<[EMAIL PROTECTED]> escribió:

> Diez B. Roggisch a écrit :
>>>
>>> It's also some kind of a Rube Goldberg thingie...
>>> http://en.wikipedia.org/wiki/Rube_Goldberg_machine
>>>
>>> If you're into web applications, better to have a look at Pylons or
>>> Django IMHO.
>>
>> You are entitled to your opinion, but calling Zope a
>> Rube-Goldberg-machine is strong. To put it mildly. How about sharing
>> some of the reasons for this?
>
> A few years experience with it - both using it 'barebones' and working
> with cmf-based apps like Plone and CPS. There are quite a few very
> interesting and/or clever things in Zope, and a lot to learn from it's
> strong and weak spots, but in it's current state, Zope2.x is layers
> above layers of ill-documented base classes and not-always-that-clever
> hacks. And Zope3 - which is indeed way cleaner - seems to be wanting to
> be more xmlish than any Java thingie ever.

I completely agree. Zope had a strong and powerful idea in the beginnings:  
let's publish objects on the Web! let's make a URL to invoke an object's  
methods with arguments! let's use persistent objects!
Compared with the CGI spaghetti code mixing HTML and application logic and  
infrastructure in the same script (PHP/perl/ASP/whatever) that was so  
common some years ago, Zope was a blessing.
But the original idea degenerated in a mamooth-like framework, rigid,  
convoluted, and hard to use. In Zope2 there is an extremely deep class  
hierarchy almost for anything (30 and more base classes wasn't uncommon -  
who can tell from *where* an attribute comes from?). And so much black  
magic - strange name conventions for all, that probably originated from  
the stone age, when Python had no decorators, no writeable function  
attributes, no metaclasses... and that lasted for a long time, Zope was  
stuck at using old-style classes years after they were introduced in  
Python 2.2
I might consider using Plone -not Zope alone!- if I had to build a portal  
exactly like Plone likes it. But nothing more. There are many other  
alternatives right now so I can stay far away from Zope, even given my  
masochistic tendencies.

-- 
Gabriel Genellina

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


running a daemon in python

2008-02-25 Thread bharath venkatesh
hi ..
   hi i want a program to start running as daemon in background .. my
program is server listen to a client ... so i want to make that program run
as daemon .. when i execute the program the program for ex server.py it
should automatically start running as daemon in the background even if i
close the terminal it shouldn't stop executing.. (right now if i close the
terminal the process exits) can any one tell how to do it  in python as i
have implemented the server  in python  ...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: is there enough information?

2008-02-25 Thread Paul McGuire
On Feb 25, 9:30 pm, [EMAIL PROTECTED] wrote:
>
> Is it enough?

(Reminds me of the movie Marathon Man, in which Dustin Hoffman is
repeatedly asked by Laurence Olivier, "Is it safe?"  Hoffman had no
idea what Olivier was talking about.  So Olivier tortured Hoffman some
more to get the answer.)

Enough for what?

Is "th" short for "thread"?  Maybe a little too short - try "thd" at
least, and spelling out "thread" isn't out of the question.

What happened to step[0]?  Did you know that lists start at 0?  Why
are you using a list of synchronization objects?

You would be better off using attributes of th with meaningful names,
instead of elements of a generically named list attribute, "th.step".
Names like "th.assign_command_synch", "th.return_value_synch", etc.
And since there is no synch object that is locked in both methods,
then the methods will run completely devoid of any synchronization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to make "rainbow" RGB values?

2008-02-25 Thread Andrew McNamara
>>Consider using an HSV->RGB conversion function. Saturation (S) and value
>>(V) should remain constant, while Hue (H) varies to get your rainbow
>>effect.
>
>Hey thank you very much, that worked like a charm!  :]
>
>There's even a library function in the colorsys module (http://
>docs.python.org/lib/module-colorsys.html)

Well, now you've helped me - I had no idea there was an HSV->RGB
conversion function in the standard library. 8-)

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is crawling the stack "bad"? Why?

2008-02-25 Thread Russell Warren
Thanks Ian... I didn't know about threading.local before but have been
experimenting and it will likely come in quite handy in the future.
For this particular case it does basically seem like a replacement for
the threadID indexed dictionary, though.  ie: I'll still need to set
up the RpcContainer, custom request handler, and custom server in
order to get the info handed around properly.  I will likely go with
this approach since it lets me customize other aspects at the same
time, but for client IP determination alone I still half think that
the stack crawler is cleaner.

No convincing argument yet on why crawling the stack is considered
bad?  I kind of hoped to come out of this with a convincing argument
that would stick with me...

On Feb 25, 12:30 pm, Ian Clark <[EMAIL PROTECTED]> wrote:
> On 2008-02-25, Russell Warren <[EMAIL PROTECTED]> wrote:
>
>
>
> >> the threading.local class seems defined for that purpose, not that I've 
> >> ever
> >> used it ;)
>
> > I hadn't heard of that... it seems very useful, but in this case I
> > think it just saves me the trouble of making a stash dictionary...
> > unless successive calls to threading.local return the same instance?
> > I'll have to try that, too.
>
> No, successive calls to threading.local() will return different objects.
> So, you call it once to get your 'data store' and then use that one
> object from all your threads. It takes care of making sure each thread
> gets it's own data.
>
> Here is your example, but using threading.local instead of your own
> version of it. :)
>
> Ian
>
> import xmlrpclib, threading, sys, thread
> from SimpleXMLRPCServer import SimpleXMLRPCServer, 
> SimpleXMLRPCRequestHandler
>
> thread_data = threading.local()
>
> class RpcContainer(object):
>   def __init__(self):
> self._Handlers = {} #keys = thread IDs, values=requestHandlers
>   def _GetRpcClientIP(self):
> #connection = self._Handlers[thread.get_ident()].connection
> connection = thread_data.request.connection
> ip = connection.getpeername()[0]
> return ip
>   def WhatIsMyIP(self):
> return "Your IP is: %s" % self._GetRpcClientIP()
>
> class ThreadCapableRequestHandler(SimpleXMLRPCRequestHandler):
>   def do_POST(self, *args, **kwargs):
> #make the handler available to the RPCs, indexed by threadID...
> thread_data.request = self
> SimpleXMLRPCRequestHandler.do_POST(self, *args, **kwargs)
>
> class MyXMLRPCServer(SimpleXMLRPCServer):
>   def __init__(self, RpcContainer, *args, **kwargs):
> self.RpcContainer = RpcContainer
> SimpleXMLRPCServer.__init__(self, *args, **kwargs)
>
> class DaemonicServerLaunchThread(threading.Thread):
> def __init__(self, RpcServer, **kwargs):
> threading.Thread.__init__(self, **kwargs)
> self.setDaemon(1)
> self.server = RpcServer
> def run(self):
> self.server.serve_forever()
>
> container = RpcContainer()
> rpcServer = MyXMLRPCServer(
>  RpcContainer = container,
>  addr = ("", 12390),
>  requestHandler = ThreadCapableRequestHandler,
>  logRequests = False)
> rpcServer.register_function(container.WhatIsMyIP)
> slt = DaemonicServerLaunchThread(rpcServer)
> slt.start()
>
> sp = xmlrpclib.ServerProxy("http://localhost:12390";)
> print sp.WhatIsMyIP()

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


Re: network programming: how does s.accept() work?

2008-02-25 Thread Steve Holden
Roy Smith wrote:
> In article <[EMAIL PROTECTED]>,
>  Steve Holden <[EMAIL PROTECTED]> wrote:
> 
>>  TCP guarantees 
>> that no two ephemeral port connections from the same client will use the 
>> same port.
> 
> Where "client" is defined as "IP Address".  You could certainly have a 
> remote machine that has multiple IP addresses using the same remote port 
> number on different IP addresses for simultaneous connections to the same 
> local port.

Correct.
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: network programming: how does s.accept() work?

2008-02-25 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Steve Holden <[EMAIL PROTECTED]> wrote:

>  TCP guarantees 
> that no two ephemeral port connections from the same client will use the 
> same port.

Where "client" is defined as "IP Address".  You could certainly have a 
remote machine that has multiple IP addresses using the same remote port 
number on different IP addresses for simultaneous connections to the same 
local port.
-- 
http://mail.python.org/mailman/listinfo/python-list


freeze.py - resolving dependencies

2008-02-25 Thread Rakesh Kumar
hi -
  I wrote a wxWidgets program and was trying to convert the python
script to native python code.

After running freeze.py on my source file - I am getting the following
unknown modules error.


Warning: unknown modules remain: _bisect _heapq _locale _random
_socket _ssl _struct _tkinter array binascii cStringIO collections
fcntl itertools math operator pyexpat readline select strop termios
time wx._controls_ wx._core_ wx._gdi_ wx._misc_ wx._windows_


I had contacted the wxPython about the dependencies of modules wx.* .

But can somebody please help me with details regarding the other
modules that we are discussing about.


I am using python 2.5 with Mandriva Linux 2008 - wxWidgets 2.8

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


Re: python based BB system

2008-02-25 Thread amar888
On Feb 26, 12:10 pm, CE <[EMAIL PROTECTED]> wrote:
> Hi,
> I have been searching for a while for a complete and fast Bulletin Board
> System for a mature community.
>
> any recommendation guys?

AFAIK pocoo is one good choice but it lacks alot of primitive
functionalities like image attachments or calendar let alone the
advanced features (WYSUWYG editor or the user selectable themes).

There are also some projects like CCQ and tBoard which i don't recall
they saw the light.

to be honest BB systems in python are not so common as in php or perl
& i don't really know the reason!

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


Re: network programming: how does s.accept() work?

2008-02-25 Thread Steve Holden
7stud wrote:
> On Feb 25, 10:56 am, Thomas Bellman <[EMAIL PROTECTED]> wrote:
>> 7stud <[EMAIL PROTECTED]> wrote:
>>> The question I'm really trying to answer is: if a client connects to a
>>> host at a specific port, but the server changes the port when it
>>> creates a new socket with accept(), how does data sent by the client
>>> arrive at the correct port?  Won't the client be sending data to the
>>> original port e.g. port 5052 in the client code above?
>> The answer is that the server *doesn't* change its port.  As you
>> could see in the output of your server, the socket that accept()
>> returned also had local port 5052.  Each *client* will however
>> get a unique local port at *its* end.
>>
>> A TCP connection is identified by a four-tuple:
>>
>> ( localaddr, localport, remoteaddr, remoteport )
>>
>> Note that what is local and what is remote is relative to which
>> process you are looking from.  If the four-tuple for a specific
>> TCP connection is ( 127.0.0.1, 5052, 127.0.0.1, 50816 ) in your
>> server, it will be ( 127.0.0.1, 50816, 127.0.0.1, 5052 ) in the
>> client for the very same TCP connection.
>>
>> Since your client hasn't bound its socket to a specific port, the
>> kernel will chose a local port for you when you do a connect().
>> The chosen port will be more or less random, but it will make
>> sure that the four-tuple identifying the TCP connection will be
>> unique.
>>
> 
> You seem to be describing what I see:
> 
> server output-
> original socket: ('0.0.0.0', 5053)
> new socket, self: ('127.0.0.1', 5053)
> new socket, peer: ('127.0.0.1', 49302)
> 
> original socket: ('0.0.0.0', 5053)
> new socket, self: ('127.0.0.1', 5053)
> new socket, peer: ('127.0.0.1', 49303)
> 
> ---client1 output-
> ('0.0.0.0', 0)
> ('127.0.0.1', 49302)
> 
> ---client2 output-
> ('0.0.0.0', 0)
> ('127.0.0.1', 49303)
> 
> 
> But your claim that the server doesn't change its port flies in the
> face of every description I've read about TCP connections and
> accept().  The articles and books I've read all claim that the server
> port 5053 is a 'listening' port only.  Thereafter, when a client sends
> a request for a connection to the listening port, the accept() call on
> the server creates a new socket for communication between the client
> and server, and then the server goes back to listening on the original
> socket.  Here are two sources for that claim:
> 
There can be many TCP connections to a server all using the same 
endpoint. Take a look at the traffic coming out of any busy web server: 
everything that comes out of the same server comes from port 80. That 
doesn't stop it listening for more connections on port 80.

The server disambiguates the packets when it demultiplexes the 
connection packet streams by using the remote endpoint to differentiate 
between packets that are part of different connections. TCP guarantees 
that no two ephemeral port connections from the same client will use the 
same port.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: network programming: how does s.accept() work?

2008-02-25 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> En Mon, 25 Feb 2008 20:03:02 -0200, 7stud <[EMAIL PROTECTED]>  
> escribió:
> > On Feb 25, 10:56 am, Thomas Bellman <[EMAIL PROTECTED]> wrote:
> >> 7stud <[EMAIL PROTECTED]> wrote:
> 
> > In either case, there are still some things about the output that
> > don't make sense to me.  Why does the server initially report that its
> > ip address is 0.0.0.0:
> >
> > original socket: ('0.0.0.0', 5053)
> 
> Because you called "bind" with None (or '' ?) as its first argument; that  
> means: "listen on any available interface"

It really means, "Listen on ALL available interfaces".
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: network programming: how does s.accept() work?

2008-02-25 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 7stud <[EMAIL PROTECTED]> wrote:

> But your claim that the server doesn't change its port flies in the
> face of every description I've read about TCP connections and
> accept().  The articles and books I've read all claim that the server
> port 5053 is a 'listening' port only.  Thereafter, when a client sends
> a request for a connection to the listening port, the accept() call on
> the server creates a new socket for communication between the client
> and server, and then the server goes back to listening on the original
> socket.

You're confusing "port" and "socket".

A port is an external thing.  It exists in the minds and hearts of packets 
on the network, and in the RFCs which define the TCP protocol (UDP too, but 
let's keep this simple).

A socket is an internal thing.  It is a programming abstraction.  Sockets 
can exist that aren't bound to ports, and several different sockets can be 
bound to the same port.  Just like there can be multiple file descriptors 
which are connected to a given file on disk.

The TCP protocol defines a state machine which determines what packets 
should be sent in response when certain kinds of packets get received.  The 
protocol doesn't say how this state machine should be implemented (or even 
demands that it be implemented at all).  It only requires that a TCP host 
behave in a way which the state machine defines.

In reality, whatever operating system you're running on almost certainly 
implements in the kernel a state machine as described by TCP.  That state 
machine has two sides.  On the outside is the network interface, which 
receives and transmits packets.  On the inside is the socket interface to 
user-mode applications.  The socket is just the API by which a user program 
interacts with the kernel to get it to do the desired things on the network 
interface(s).

Now, what the articles and books say is that there is a listening SOCKET.  
And when you accept a connection on that socket (i.e. a TCP three-way 
handshake is consummated on the network), the way the socket API deals with 
that is to generate a NEW socket (via the accept system call).  There 
really isn't any physical object that either socket represents.  They're 
both just programming abstractions.

Does that help?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd behaviour of *.pth files and Apache

2008-02-25 Thread Gabriel Genellina
En Sat, 23 Feb 2008 12:52:45 -0200, D'Arcy J.M. Cain <[EMAIL PROTECTED]>  
escribió:

> On Thu, 21 Feb 2008 13:55:25 -0500
> "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
>> I tried searching the archives for information on this but nothing
>> seemed to be germane.  I am running Python sripts as CGI under Apache
>> and I have a .pth file in site-packages that includes directory that
>> has another .pth in it.  Sometimes it picks up the paths in the
>> second .pth and sometimes it does not.  It always seems to work if I am
>> working in a location not in the ServerRoot but if I use the main site
>> it does not pick up the directories in the included .pth.
>
> I have more information now.  It seems that it recurses the .pth files
> it finds in PYTHONPATH but not for directories found in the .pth files
> in site-packages.  Is this expected behaviour?  The documentation
> suggests that it should pick up both.

If a .pth file contains a valid directory, it is added to sys.path but  
it's not searched for additional .pth files. From  
http://docs.python.org/lib/module-site.html

"A path configuration file is a file whose name has the form 
package.pth  
AND EXISTS IN ONE OF THE FOUR DIRECTORIES MENTIONED ABOVE" (emphasis by me)

(the four directories being .../lib/python2.5/site-packages, site-python,  
etc.)

(Mmm, what the 2.5 docs say is not exactly the same as the actual code in  
site.py, and the version in http://docs.python.org/dev/library/site.html  
is not the same as the svn version of site.py... anyway, directories added  
by mean of .pth files are not recursively searched for more .pth files)

-- 
Gabriel Genellina

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


What does this bogus code in urlparse do?

2008-02-25 Thread John Nagle
See 
"http://svn.python.org/view/python/trunk/Lib/urlparse.py?rev=60163&view=markup";

Look at "urljoin".

What does the code marked "# XXX The stuff below is bogus in various
ways..." do?

I think it's an attempt to remove leading "../" components in URLs, which are
generally ignored.  But it also does something with commas, and it's not
clear why.

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


Re: __getattribute__ meta class?

2008-02-25 Thread Carl Banks
On Feb 25, 9:43 pm, "bambam" <[EMAIL PROTECTED]> wrote:
> I have a class containing a series of classes like this:
>
> class Th(Externaldevice):
>   class _Communicate(commandset2.CommandSet_Communicate):
> def __getattribute__(self,attrname):
>   attr =
> commandset2.CommandSet_Communicate.__getattribute__(self,attrname)
>   if "__call__" in dir(attr):
> return functools.partial(Th._wrapper_function, self.parent, attr)
>   else:
> return attr
>
>   class _System(commandset2.CommandSet_System):
> def __getattribute__(self,attrname):
>   attr = commandset2.System_Communicate.__getattribute__(self,attrname)
>   if "__call__" in dir(attr):
> return functools.partial(Th._wrapper_function, self.parent, attr)
>   else:
>return attr
>
> That is, a a wrapper function is applied to a bunch of methods in a bunch of
> classes.
> The class declarations are simple, but even so, repetitive.
> Can anyone suggest a more compact representation for the class declarations?


Looks like you want a class factory here:


def create_wrapper_class(name,base):
def getattribute(self,attrname):
attr = base.__getattr__(self,attrname)
if hasattr(attr,"__call__"):
return functools.partial(Th._wrapper_function,
 self.parent, attr)
return attr
clsdict = { '__getattribute__': getattribute }
return type(name,(base,),clsdict)

class Th(Externaldevice):
_Communicate = create_wrapper_class('_Communicate',
commandset2.CommandSet_Communicate)
_System = create_wrapper_class('_System',
commandset2.CommandSet_System)


The class factory calls type directly to create the class here rather
than using the class statement since the name can vary.  I took the
liberty of making a few improvements to the __getattribute__ function;
hasattr is a lot faster than building a list with dir, and the final
else was redundant.


> Also, because the parent class name is given explicitly in the class
> declarations, I can't over-ride the _wrapper_function in a child class,
> except by over-riding each of the class declarations. Is there a way to
> reference the _wrapper_function just to the containing class?

It looks like your wrapped classes have an attribute, self.parent,
that refers to the Th object in question.  It should be possible to
access its wrapper function directly then:

def create_wrapper_class(name,base):
def getattribute(self,attrname):
attr = base.__getattr__(self,attrname)
if hasattr(attr,"__call__"):
return functools.partial(
self.parent._wrapper_function, attr)
return attr
clsdict = { '__getattribute__': getattribute }
return type(name,(base,),clsdict)


Perhaps self.parent is not the Th in question, which could be the case
if _wrapper_function is a staticmethod.  In that case, you'd have to
pass it to the wrapper class somehow.

Presumably you have some other methods in Th that create instances of
these embedded classes.  I'm guessing your Th class has a __getattr__
(or properties) that does this when accessing attributes of Th?

What you'd normally do in cases like this is to modify the class's
constructor to accept the object.  For instance, if your __getattr__
looks like this:


def __getattr__(self,attr):
if attr == 'System':
return self._System()
...

then you could change it to look like this:

def __getattr__(self,attr):
if attr == 'System':
return self._System(self)
...


And then you'd change the _System class to accept and store the
argument passed to it.  That way your system class will be able to see
what object called it and figure out the appropriate type that way.


def create_wrapper_class(name,base):
def init(self,thobject):
self.thobject = thobject
def getattribute(self,attrname):
attr = base.__getattr__(self,attrname)
if hasattr(attr,"__call__"):
wrapper = self.thobject._wrapper_function
return functools.partial(wrapper,self.parent,attr)
return attr
clsdict = { '__init__': init,
'__getattribute__': getattribute }
return type(name,(base,),clsdict)


That's some pretty advanced stuff you're doing there, chief.  My
examples probably wouldn't work out of the box, but hopefully it'll
give you enough ideas to do it.


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


Re: network programming: how does s.accept() work?

2008-02-25 Thread Gabriel Genellina
En Mon, 25 Feb 2008 20:03:02 -0200, 7stud <[EMAIL PROTECTED]>  
escribió:
> On Feb 25, 10:56 am, Thomas Bellman <[EMAIL PROTECTED]> wrote:
>> 7stud <[EMAIL PROTECTED]> wrote:

> In either case, there are still some things about the output that
> don't make sense to me.  Why does the server initially report that its
> ip address is 0.0.0.0:
>
> original socket: ('0.0.0.0', 5053)

Because you called "bind" with None (or '' ?) as its first argument; that  
means: "listen on any available interface"

> I would expect the reported ip address to be '127.0.0.1'.  Also, since
> a socket is uniquely identified by an ip address and port number, then
> the ('0.0.0.0', 5053) socket is not the same as this socket:
>
> new socket, self: ('127.0.0.1', 5053)

You got this *after* a connection was made, coming from your own PC.   
127.0.0.1 is your "local" IP; the name "localhost" should resolve to that  
number. If you have a LAN, try running the client on another PC. Or  
connect to Internet and run the "netstat" command to see the connected  
pairs.

-- 
Gabriel Genellina

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


python based BB system

2008-02-25 Thread CE

Hi,
I have been searching for a while for a complete and fast Bulletin Board 
System for a mature community.

any recommendation guys?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for up to date documentation for Python/Tkinter

2008-02-25 Thread Gabriel Genellina
En Thu, 21 Feb 2008 13:47:35 -0200, Kintaro <[EMAIL PROTECTED]>  
escribió:

> Please speak unto me the URL which contain the latest documentation on
> Python/Tkinter programming.

For Python itself, the starting points are http://docs.python.org and  
http://wiki.python.org/moin/

-- 
Gabriel Genellina

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


Fwd: Problem with threads in python????????

2008-02-25 Thread Manikandan R
Hai,

  Is it possible to share a single variable between multiple
threads. For eg:

Class A:
 thread_init()

   def run():
  fun1()

def fun():
  assume some arithmatic operation is going on according to the
input given and each fun will *give different output*
.

count = 10
while count:
 call the class which will call the thread,
 count--

now call   list.join()

Now 10 Thread will be running and each thread will have there individual
output.

   Here is the problem now i want the sum of output of all the function.
How can i do this ??? Can any one give me some idea. With example. Quite
urgent help me please...

Thank's and Regard's,
R.Manikandan.
-- 
http://mail.python.org/mailman/listinfo/python-list

buliding log files

2008-02-25 Thread diljeet kaur
  hi
  im working on pyqt environment
  i want to know how to take log or how to build log files of the output

   
-
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: iter(lambda:f.read(8192),'')

2008-02-25 Thread Gabriel Genellina
En Sun, 24 Feb 2008 10:18:31 -0200, Dustan <[EMAIL PROTECTED]>  
escribió:
> On Feb 24, 5:11 am, gert <[EMAIL PROTECTED]> wrote:

>> what is the difference between iter(lambda:f.read(8192), ') and
>> iter(f.read(8192),'') ?
>
> iter(lambda:f.read(8192), '') (what you probably meant) is what it
> looks like: iter(some_func, '').

Just to make it more clear, and guessing the original context:

f = open(...)
for data in iter(lambda: f.read(8192), ''):
   do_something_with(data)

is the way to iterate over a file in blocks of 8192 bytes each.

-- 
Gabriel Genellina

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


is there enough information?

2008-02-25 Thread castironpi
Specify


def thloop( th ):
while th.cont:
with th.step[2]:
th.ret= th.cmd+ 1

def acq( th ):
with th.step[1]:
th.cmd= 100
with th.step[3]:
ret1= th.ret
th.step.reset()
assert ret1== 101

Is it enough?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to flush child_stdin

2008-02-25 Thread Gabriel Genellina
En Fri, 22 Feb 2008 17:53:55 -0200, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribió:
> On Feb 22, 2:01 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>> On Fri, 22 Feb 2008 08:35:03 -0800 (PST), "[EMAIL PROTECTED]"
>> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>>
>> > I don't think that is the problem, I'm feeding it newline characters.
>>
>> It wasn't shown in your sample, so I jumped on the first likely
>> thing...
>>
>> The second is in the hands of the subprocess... While you are
>> flushing output /to/ the subprocess, is IT flushing its output (the
>> stuff you are trying to read). A common problem seems to be that, as
>> soon as the process detects a pipe, it goes to buffered I/O, and if the
>> buffer isn't filled, the parent has no access...
>
> I'm actually running something like : r, w, e = popen2.popen3('python -
> u slave.py')

That was not on your posted example either...

> to try and force unbuffered.  slave.py is basically outputting by
> using print.
> I guess it might still be buffering?
> Anyway, thanks for your thoughts... I may have to take an entirely
> difference approach.  I was hoping not to have to touch the code base
> represented by slave.py.

[master.py]

import popen2
r, w, e = popen2.popen3('python -u slave.py')

w.write('command 1\n')
w.flush()
print r.readline()
w.write('command 2\n')
w.flush()
print r.readline()
w.write('\n')
w.flush()
print r.readline()

[slave.py]

while True:
   line = raw_input().strip()
   if not line:
 print "bye!"
 break
   print "echo:",line

That works OK for me on Windows XP.

-- 
Gabriel Genellina

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


Re: exchange service side rules

2008-02-25 Thread bambam
Wrong message, wrong group. Sorry.

"bambam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Junk E-Mail Options, Protection is set to High. All of my messages are 
> coming through with a SCL of 9 (I checked), but none of them are going to 
> the Junk E-Mail folder.
>
> I thought this was a server-side rule?
>
> Can anyone explain, and also tell me what I need to do?
>
> 


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


__getattribute__ meta class?

2008-02-25 Thread bambam
I have a class containing a series of classes like this:

class Th(Externaldevice):
  class _Communicate(commandset2.CommandSet_Communicate):
def __getattribute__(self,attrname):
  attr = 
commandset2.CommandSet_Communicate.__getattribute__(self,attrname)
  if "__call__" in dir(attr):
return functools.partial(Th._wrapper_function, self.parent, attr)
  else:
return attr

  class _System(commandset2.CommandSet_System):
def __getattribute__(self,attrname):
  attr = commandset2.System_Communicate.__getattribute__(self,attrname)
  if "__call__" in dir(attr):
return functools.partial(Th._wrapper_function, self.parent, attr)
  else:
   return attr

That is, a a wrapper function is applied to a bunch of methods in a bunch of 
classes.
The class declarations are simple, but even so, repetitive.
Can anyone suggest a more compact representation for the class declarations?
Also, because the parent class name is given explicitly in the class 
declarations, I can't over-ride the _wrapper_function in a child class, 
except by over-riding each of the class declarations. Is there a way to 
reference the _wrapper_function just to the containing class?

Steve 


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


exchange service side rules

2008-02-25 Thread bambam
Junk E-Mail Options, Protection is set to High. All of my messages are 
coming through with a SCL of 9 (I checked), but none of them are going to 
the Junk E-Mail folder.

I thought this was a server-side rule?

Can anyone explain, and also tell me what I need to do?


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


Re: Web site for comparing languages syntax

2008-02-25 Thread Mel
Sebastian Bassi wrote:
> I know there is one site with wikimedia software installed, that is
> made for comparing the syntax of several computer languages (Python
> included). But don't remember the URL. Anyone knows this site?

http://99-bottles-of-beer.net/

is one such site, though I don't know about wikimedia.

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


along the lines, hash and obj. id.

2008-02-25 Thread castironpi
I'd like to do this:

a= list( range( 5 ) )
assert a== [ 0, 1, 2, 3, 4 ]
for i in ref( a ):
i.ref*= 2
a= deref( a )
assert a== [ 0, 2, 4, 6, 8 ]

In the for loop, i objects maintain their identities, while still
being reassigned.  The first way I think of is this:

class Ref:
def __init__( self, ref ):
self.ref= ref
def __repr__( self ):
return ''% self.ref

def ref( it ):
for i, e in enumerate( it ):
it[i]= Ref(e)
return it

def deref( it ):
return [ i.ref for i in it ]

Dictionaries, sets, and the primitives all have ways to do this, in
particular, to reset them: a= {} is equivalent to a.clear(), except
that other references to it corefer before, and in the former, don't
after.

class A:
def __init__( self, d ):
self.d= d

d= {}
a= A( d )
d= {}

is different than:

d= {}
a= A( d )
d.clear()

a.d still refers to d in the second, whereas the identity is broken in
the first.

Can perhaps a subclass of List return references to its elements, so
that L[2] is L[2], even if you assign it to a different value later,
and even in the case of integers.?

(*This came out a little funny.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a keypress

2008-02-25 Thread Jeff Schwab
Dennis Lee Bieber wrote:
> On Mon, 25 Feb 2008 10:35:54 -0800 (PST), wyleu
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
>> I'm trying to read a single keypress on Linux but expect to have the
>> programme running on Windows platform as well and find the mention in
>> the FAQ:
> 
>   UNIX terminal control stuff snipped.
> 
>   There is NO directly portable way to do low-level I/O with the
> console.

What about curses?

http://docs.python.org/lib/module-curses.html
http://adamv.com/dev/python/curses/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object identity and hashing

2008-02-25 Thread Jeff Schwab
[EMAIL PROTECTED] wrote:
> On Feb 24, 9:28 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
>>
>> [1]http://www.martinfowler.com/eaaCatalog/identityMap.html
> 
> [1] illustrates a case in which 'a is a' returns False, and in the
> other corner of the DeMorgan table, there is 'a is b' returns True for
> 'a == b' False.

What is the 'a is a' == False case?  I don't see anything like that 
illustrated on the Identity Map page.  Is it "P of EAA?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distutils and data files

2008-02-25 Thread Gabriel Genellina
En Fri, 22 Feb 2008 05:28:22 -0200, Sam Peterson  
<[EMAIL PROTECTED]> escribió:
> Robert Bossy <[EMAIL PROTECTED]> on Wed, 20 Feb 2008 09:29:12
> +0100 didst step forth and proclaim thus:
>
>> Sam Peterson wrote:
>>> I've been googling for a while now and cannot find a good way to deal
>>> with this.
>>>
>>> I have a slightly messy python program I wrote that I've historically
>>> just run from the extracted source folder.  I have pictures and sound
>>> files in this folder that this program uses.  I've always just used
>>> the relative path names of these files in my program.
>>>
>>> Lately, I had the idea of cleaning up my program and packaging it with
>>> distutils, but I've been stuck on a good way to deal with these
>>> resource files.  The package_data keyword seems to be the way to go,
>>> but how can I locate and open my files once they've been moved?  In
>>> other words, what should I do about changing the relative path names?
>>> I need something that could work from both the extracted source
>>> folder, AND when the program gets installed via the python setup.py
>>> install command.
>>>
>> This seems to be a classic distutils  question:  how a python module
>> can access to data files *after* being installed?
>
>
> I think I'll kill the idea of using distutils for my program.  It
> seems like distutils was primarily designed for modules and
> extensions.

And packages. The package_data directive specifies data subdirectories  
that will be installed under the package directory; you can use a relative  
path starting at the package dir. (the thread above is about the  
install-data command-line option, but package_data isn't affected by that).

That is, if you have:

pkg/
__init__.py
images/
foo.jpg
sounds/
bar.snd

At the top of __init__.py, you can say:

pkg_path = os.path.dirname(__file__)
images_path = os.path.join(pkg_path, "images")
sounds_path = os.path.join(pkg_path, "sounds")

It doesn't matter *where* pkg is actually installed, you can always reach  
its subdirectories.

-- 
Gabriel Genellina

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


boost and ctypes

2008-02-25 Thread zaley
I am a newbie to python .I know it is easy  to access Windows API and
DLL using ctypes in python .And it is easy  to access python class and
function using boost libs in C. Can boost and ctypes work together?
-- 
http://mail.python.org/mailman/listinfo/python-list


Unsubscribing from python-list (was Re: Python code for 2.5 and 2.4?)

2008-02-25 Thread Robert Kern
Bhatt, Omkar wrote:
> PLEASE TAKE ME OFF THIS LIST!

You can unsubscribe yourself using the link at the bottom of every message:

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

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: Backup Script over ssh

2008-02-25 Thread Gabriel Genellina
En Thu, 21 Feb 2008 09:32:23 -0200, Christian Kortenhorst  
<[EMAIL PROTECTED]> escribió:

> I am new to python and the list.

Welcome?

> I want to create backup script for my windows PC and upload to Linux  
> server
> over ssh but whats the best way to go about this.

rsync? No need to reinvent the wheel...

-- 
Gabriel Genellina

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


Re: Reading a keypress

2008-02-25 Thread Rolf van de Krol
wyleu wrote:
> Aaah it doesn't work from idle but it does from the command line...
>
>   
You are right. You can't read STDIN from IDLE. There has been a topic 
about that before: 
http://groups.google.com/group/comp.lang.python/browse_thread/thread/9f9c90cfe52378fe

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


RE: Python code for 2.5 and 2.4?

2008-02-25 Thread Bhatt, Omkar
PLEASE TAKE ME OFF THIS LIST!

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Paul Rubin
Sent: Monday, February 25, 2008 5:47 PM
To: python-list@python.org
Subject: Re: Python code for 2.5 and 2.4?

Arnaud Delobelle <[EMAIL PROTECTED]> writes:
> Ok.  In that case, the following is probably faster (in fact for long
> iterables it may be equivalent to the builtin all):
> 
> from itertools import ifilterfalse...

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


Re: Hyphenation module PyHyphen-0.3 released

2008-02-25 Thread thebjorn
On Feb 25, 3:56 am, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> > I don't know if I'm just doing it wrong, or if I can't use extensions
> > compiled with mingw32 with the standard distribution Python
> > executable?
>
> I was able to install on Windows XP with mingw:
>
> setup.py build -c mingw32
> setup.py install --skip-build
>
> It works fine with English dictionary, but hangs with Russian
> dictionary from Mozilla.

This is unfortunately deceptive :-(  The C-runtime mismatch problem
happens when memory malloc'd in an extension module is free'd by the
interpreter (or vice versa). Things might work for a while with this
mismatch, but will (almost) always crash/hang/etc. in hard to track
down ways later.

Using the link that max provided above, I managed to build and install
without passing any switches and getting no error messages.

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


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Paul Rubin
Arnaud Delobelle <[EMAIL PROTECTED]> writes:
> Ok.  In that case, the following is probably faster (in fact for long
> iterables it may be equivalent to the builtin all):
> 
> from itertools import ifilterfalse...

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


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Arnaud Delobelle
On Feb 25, 11:17 pm, Paul Rubin  wrote:
> Arnaud Delobelle <[EMAIL PROTECTED]> writes:
> >     def all(iterable):
> >         for x in iterable:
> >             if not x: return False
> >         return True
>
> from itertools import imap
> def all(iterable):
>    return False not in imap(bool, iterable)

Ok.  In that case, the following is probably faster (in fact for long
iterables it may be equivalent to the builtin all):

from itertools import ifilterfalse

def all(iterable):
for _ in ifilterfalse(None, iterable):
return False
return True


But my point was really about not checking for the version but just
checking for the existence of the name 'all'.

--
Arnaud

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


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Paul Rubin
Arnaud Delobelle <[EMAIL PROTECTED]> writes:
> def all(iterable):
> for x in iterable:
> if not x: return False
> return True

from itertools import imap
def all(iterable):
   return False not in imap(bool, iterable)

def any(iterable):
   return True in imap(bool, iterable)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyEuler

2008-02-25 Thread bearophileHUGS
Arnaud Delobelle:
> I disagree; the generator function has no right to keep a and b to
> itself.  a and b cry out to be function parameters.

I see. Then that's a generator for a generalized Fibonacci
sequence :-)
Your version too is useful.

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


Re: Accessing "sub elements" with xml.sax ?

2008-02-25 Thread Diez B. Roggisch
erikcw schrieb:
> Hi,
> 
> I'm trying to use xml.sax (from xml.sax.handler import ContentHandler)
> to processes the following data:
> 
> 
>  masterAccountName="CraftShowSuccess.Com-US"
> dateStart="2008-02-24-0600" dateEnd="2008-02-24-0600"
> booksClosedTimestamp="2008-02-25T01:15:00.000-0600" booksClosed="true"
> createDate="2008-02-25T02:00:27.041-0600" sortColumn="cost"
> sortOrder="desc">
>  averagePosition="9.305993690851736"/>
>  tacticName="Paid Placement" qualityScore="2"> ctr="0.0" numClick="0" cost="0.0" averagePosition="9.305993690851736"/
>> 
> 
> 
> 
> I've figured out how to access the attributes in "row" - but I want to
> also access the "analytics" child element.
> 
> I've tried:
> class YahooHandler(ContentHandler):
> ccountNum)
> 
> def startElement(self, name, attrs):
> if name == 'row' or name == 'analytics':
> self.campaign = attrs.get('cmpgnName',"")
> self.adgroup = attrs.get('adGrpName',"")
> self.headline = attrs.get('adName',"")
> self.imps = attrs.get('numImpr',None)
> self.clicks = attrs.get('numClick',None)
> self.cost = attrs.get('cost',"")
> 
> def endElement(self, name):
> if name == 'row':
> if self.campaign not in self.data:
> self.data[self.campaign] = {}
> if self.adgroup not in self.data[self.campaign]:
> self.data[self.campaign][self.adgroup] = []
> self.data[self.campaign][self.adgroup].append({'campaign':
> self.campaign,
> 'adgroup': self.adgroup,
> 'headline': self.headline,
> 'imps': self.imps,
> 'clicks': self.clicks,
> 'ctr': self.ctr,
> 'cost': self.cost,
> })
> print self.data
> 
> But it the data comes out as seperate dictionaries - I want the
> analytics and the row elements in one dictionary.
> 
> What am I doing wrong?

With sax, you can't access a child directly - you need to build up that 
hierarchy yourself, using a stack of elements.

Better go for DOM or better even element-tree, these do that work for 
you and you can easily access child elemements.

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


Re: PyEuler

2008-02-25 Thread Arnaud Delobelle
On Feb 25, 10:52 pm, [EMAIL PROTECTED] wrote:
> Arnaud Delobelle:
>
> > In this case why not:
>
> > def xfib(a=1, b=1):
> >     while True:
> >         yield a
> >         a += b
> >         yield b
> >         b += a
>
> That's a bit less easy to understand than my version, for me.
> In my version is easy to see the values of the variables.

I disagree; the generator function has no right to keep a and b to
itself.  a and b cry out to be function parameters.  The user may want
to start a fibonacci sequence with any two initial values.  IMHO one
of the great qualities of Python is that it makes this very easy in
most cases.

> And using a
> longer function name is better.

Up to a certain length :-)

--
Arnaud

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


Re: Reading a keypress

2008-02-25 Thread wyleu
Aaah it doesn't work from idle but it does from the command line...

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


Re: PyEuler

2008-02-25 Thread bearophileHUGS
Arnaud Delobelle:
> In this case why not:
>
> def xfib(a=1, b=1):
> while True:
> yield a
> a += b
> yield b
> b += a

That's a bit less easy to understand than my version, for me.
In my version is easy to see the values of the variables. And using a
longer function name is better.

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


Web site for comparing languages syntax

2008-02-25 Thread Sebastian Bassi
Hello,

I know there is one site with wikimedia software installed, that is
made for comparing the syntax of several computer languages (Python
included). But don't remember the URL. Anyone knows this site?

-- 
Sebastián Bassi (セバスティアン). Diplomado en Ciencia y Tecnología.
Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6
GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PyEuler

2008-02-25 Thread Arnaud Delobelle
On Feb 25, 10:25 pm, [EMAIL PROTECTED] wrote:
> Paul Rubin:
>
> >     def ggenfib():
> >       a,b = 1,2
> >       while True:
> >          yield a
> >          a,b = b, a=b
>
> Your version is the nice basic generator version (the last line
> contains a +, I presume), but I like this other version too:
>
> def xfibonacci():
>     a = b = 1
>     yield a
>     yield b
>     while True:
>         a = a + b
>         yield a
>         b = b + a
>         yield b
>
> It's a bit faster, longer, and I find it a bit more readable.

In this case why not:

def xfib(a=1, b=1):
while True:
yield a
a += b
yield b
b += a

--
Arnaud

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


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Joseph Turian
On 25 fév, 16:02, Robert Kern <[EMAIL PROTECTED]> wrote:
> Joseph Turian wrote:
> > I was given code that was written for python 2.5, and uses simple
> > functions like 'all' which are not present in 2.4
>
> > I want to make the code 2.4 compatible. What is the best way to do
> > this?
>
> If it's a single file, put something like the following code near the top. If
> you have multiple modules, put it into a separate module, say 
> compatibility.py,
> and change the other modules to import these functions from there.
>
> import sys
> if sys.version_info[:2] < (2,5):
>  def all(*args):
>  ...
>  def any(*args):
>  ...
> else:
>  # Only bother with this else clause and the __all__ line if you are 
> putting
>  # this in a separate file.
>  import __builtin__
>  all = __builtin__.all
>  any = __builtin__.any
>
> __all__ = ['all', 'any']
>
> > If I define function 'all', then won't I break 2.5 compatability?
>
> No. Defining a function named the same thing as a builtin function will not
> break anything. You just wouldn't be using the efficient implementation 
> already
> in Python 2.5. Using the if: else: suite above lets you have both at the 
> expense
> of some clunkiness.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>-- Umberto Eco

This is what I was looking for. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding a literal "\u" in a unicode raw string.

2008-02-25 Thread rmano
On Feb 25, 11:27 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Raw
> > should be raw...
>
> Right. IMO, this is just a plain design mistake in the Python Unicode
> handling. Unfortunately, there was discussion about this specific issue
> in the past, and the proponent of the status quo always defended it,
> with the rationale (IIUC) that a) without that, you can't put arbitrary
> Unicode characters into a string, and b) the semantics of \u in Java and
> C is so that \u gets processed even before tokenization even starts, and
> it should be the same in Python.

Well, I do not know Java, but C AFAIK has no raw strings, so you have
nevertheless
to use double backslashes. Raw strings are a handy shorthand when you
can generate
the characters with your keyboard, and this asymmetry quite defeat it.

Is it decided or it is possible to lobby for it? :-)

Thanks,
   Romano

BTW, 2to3.py should warn when a raw string (not unicode) with \u in
it, I think.
I tried it and it seems to ignore the problem...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird cgi error

2008-02-25 Thread gherzig
>
>> This is some kind of crooked game, right? Your code works fine on a
>> local server, and there's no reason why it shouldn't work just fine on
>> yours either. All you are changing is the standard input to the process.
>>
>> Since you claim to have spotted this specific error, perhaps you'd like
>> to explain just exactly how you came across it. I mean that's a pretty
>> specific input to test with ...
>>
>> Frankly I am not sure you are telling the truth about the code behind
>> that page. If you *are* then you'd better provide specifics: Python
>> version, Apache version, httpd.conf file, and so on. April 1 is still
>> over a month away.
>>
>> regards
>>   Steve
>>
>> PS: consider closing the  tag on the same line as the opening
>> tag to avoid spurious spaces in your pristine form.
>> --
>> Steve Holden+1 571 484 6266   +1 800 494 3119
>> Holden Web LLC  http://www.holdenweb.com/
>
> Thanks for the reply.
>
> No, it's not a game, crookedgames.com is a mostly defunct games site
> that I was working on for a while.  I'm just hosting the script
> there.  What I am actually working on is a tool used to compare
> various things.  Check it out here:
> http://crookedgames.com/cgi-bin/Language_Comparison.py
> Here's some input you can use to test with:
>
> Cats
>   +2 Fuzzy
>   -1 Medium Maintenance
>
> Fish
>   +1 Low Maintenance
>   -1 Stupid
>
> Dogs
>   +2 Fuzzy
>   -2 High Maintenance
>
> (note that there's supposed to be two spaces before the +/- symbols --
> in case my formatting doesn't go through)
>
> I originally created that tool because I wanted to compare programming
> languages, python among them, thus leading me discover this issue.
>
> Now, I'm very new to this web development stuff (this is my first real
> app), so it's quite likely that I'm just doing something stupid, but I
> can't figure out what.
>
> I'm using LunarPages.  CPanel reports my Apache version as: 1.3.37
> (Unix)
>
> I added the line "print sys.version" to the test script, and that
> spits out: "2.3.4 (#1, Dec 11 2007, 05:27:57) [GCC 3.4.6 20060404 (Red
> Hat 3.4.6-9)]"
>
> I can't find any file called httpd.conf.  It would be in /etc, right?
> I guess I don't have one.
>
> Still having the same problem.
>
> Here's the new contents of test.py:
>
> #!/usr/bin/python
> import cgitb, sys
> cgitb.enable()
>
> print "Content-Type: text/html\n"
> print sys.version
> print """
> 
> 
>   
>  
> 
>   
> 
> 
> """
>
> It's not a joke, honest :)
> --
It just doesnt make sense to me. I guess we all agree that is not a python
problem, because that code does actually nothing but showing the form.

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


Re: network programming: how does s.accept() work?

2008-02-25 Thread Grant Edwards
On 2008-02-25, 7stud <[EMAIL PROTECTED]> wrote:
> On Feb 25, 10:56 am, Thomas Bellman <[EMAIL PROTECTED]> wrote:
>> 7stud <[EMAIL PROTECTED]> wrote:
>> > The question I'm really trying to answer is: if a client connects to a
>> > host at a specific port, but the server changes the port when it
>> > creates a new socket with accept(), how does data sent by the client
>> > arrive at the correct port?  Won't the client be sending data to the
>> > original port e.g. port 5052 in the client code above?
>>
>> The answer is that the server *doesn't* change its port.  As you
>> could see in the output of your server, the socket that accept()
>> returned also had local port 5052.  Each *client* will however
>> get a unique local port at *its* end.
>>
>> A TCP connection is identified by a four-tuple:
>>
>>     ( localaddr, localport, remoteaddr, remoteport )
>>
>> Note that what is local and what is remote is relative to which
>> process you are looking from.  If the four-tuple for a specific
>> TCP connection is ( 127.0.0.1, 5052, 127.0.0.1, 50816 ) in your
>> server, it will be ( 127.0.0.1, 50816, 127.0.0.1, 5052 ) in the
>> client for the very same TCP connection.
>>
>> Since your client hasn't bound its socket to a specific port, the
>> kernel will chose a local port for you when you do a connect().
>> The chosen port will be more or less random, but it will make
>> sure that the four-tuple identifying the TCP connection will be
>> unique.


> But your claim that the server doesn't change its port flies in the
> face of every description I've read about TCP connections and
> accept().

Then the descriptions are wrong.

> The articles and books I've read all claim that the server
> port 5053 is a 'listening' port only.

Not true.

> Thereafter, when a client sends a request for a connection to
> the listening port, the accept() call on the server creates a
> new socket for communication between the client and server,

True.  But, it doesn't change the local port number.  

Both the listing socket and the connected socket are using
local port number 5053.

> and then the server goes back to listening on the original
> socket.

That's true.

> I would expect the reported ip address to be '127.0.0.1'.
> Also, since a socket is uniquely identified by an ip address
> and port number,

It isn't.

1) You seem to be conflating sockets and TCP connections.  A
   socket is a kernel-space data structure used to provide a
   user-space API to the network stack.  In user-space it's
   identified by an integer index into a per-process table of
   file-like-objects.  That socket may or may not have a TCP
   connection associated with it.  It may or may not be bound
   to an IP address and/or port.  It is not uniquely identified
   by an IP address and port number.

2) A tcp connection is a _different_ thing (though it also
   corresponds to a kernel-space data structure), and as Thomas
   said, it is uniquely identified by the a four-tuple:

     (localaddr, localport, remoteaddr, remoteport)

   [Technically, it's probably a 5-tuple with the above
   elements along with a 'connection type' element, but since
   we're only discussing TCP in this thread, we can ignore the
   connection type axis and only consider the 4-axis space of
   TCP connections.]
 
   When a second client connects to the server on port 5053,
   the first two elements in the tuple will be the same.  One
   or both of the last two elements will be different.
 
> then the ('0.0.0.0', 5053) socket is not the same as this
> socket:
>
> new socket, self: ('127.0.0.1', 5053)

Referring to sockets using that notation doesn't really make
sense.  There can be more than one socket associated with the
local address ('127.0.0.1', 5053) or to any other ip/port tuple
you'd like to pick.

-- 
Grant Edwards   grante Yow! YOU PICKED KARL
  at   MALDEN'S NOSE!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding a literal "\u" in a unicode raw string.

2008-02-25 Thread Martin v. Löwis
> Yes, I think I will do something like that, although... I really do
> not understand why \x5c is not interpreted in a raw string but \u005c
> is interpreted  in a unicode raw string... is, well, not elegant. Raw
> should be raw...

Right. IMO, this is just a plain design mistake in the Python Unicode
handling. Unfortunately, there was discussion about this specific issue
in the past, and the proponent of the status quo always defended it,
with the rationale (IIUC) that a) without that, you can't put arbitrary
Unicode characters into a string, and b) the semantics of \u in Java and
C is so that \u gets processed even before tokenization even starts, and
it should be the same in Python.

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


Re: PyEuler

2008-02-25 Thread bearophileHUGS
Paul Rubin:
> def ggenfib():
>   a,b = 1,2
>   while True:
>  yield a
>  a,b = b, a=b

Your version is the nice basic generator version (the last line
contains a +, I presume), but I like this other version too:

def xfibonacci():
a = b = 1
yield a
yield b
while True:
a = a + b
yield a
b = b + a
yield b

It's a bit faster, longer, and I find it a bit more readable.


> There is a full set of solutions on the haskell wiki, if anyone cares.

Thank you for the suggestion, I have found it:
http://www.haskell.org/haskellwiki/Euler_problems
In the last months lot of people are suddenly talking about Haskell
(and sometimes even F#!). I think the Haskell language is too much
complex for me for bigger programs, but for such small mathematical
programs it looks very nice and almost readable.

This is a curious comment from that Wiki about a solution to the
Problem 2:
>The first two solutions work because 10^6 is small. The following solution 
>also works for much larger numbers (up to at least 10^100 on my computer):<

What I like of the Haskell community is how much they keep things tidy
and ordered. And every function used on the Wiki points to the
documentation! They create a spotless wiki about Shootout benchmarks,
Euler problems, and so on, they discuss al lot and they try to find
fast & correct solutions. They even *improve* their language when they
find some benchmarks of the Shootout run too much slow with Haskell,
because they have understood that despite being most little (silly)
programs, the benchmarks of the Shootout site are rather well thought
out. Both the Python and D communities that I know (and I appreciate)
aren't like that. I presume the Haskell language itself appeals to
people that like tidy and well ordered things, and when you use that
language a lot it may encourage your mind to think even more in that
way. Computer languages too make the man :-)

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


Re: Weird cgi error

2008-02-25 Thread Jesse Aldridge

> This is some kind of crooked game, right? Your code works fine on a
> local server, and there's no reason why it shouldn't work just fine on
> yours either. All you are changing is the standard input to the process.
>
> Since you claim to have spotted this specific error, perhaps you'd like
> to explain just exactly how you came across it. I mean that's a pretty
> specific input to test with ...
>
> Frankly I am not sure you are telling the truth about the code behind
> that page. If you *are* then you'd better provide specifics: Python
> version, Apache version, httpd.conf file, and so on. April 1 is still
> over a month away.
>
> regards
>   Steve
>
> PS: consider closing the  tag on the same line as the opening
> tag to avoid spurious spaces in your pristine form.
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/

Thanks for the reply.

No, it's not a game, crookedgames.com is a mostly defunct games site
that I was working on for a while.  I'm just hosting the script
there.  What I am actually working on is a tool used to compare
various things.  Check it out here: 
http://crookedgames.com/cgi-bin/Language_Comparison.py
Here's some input you can use to test with:

Cats
  +2 Fuzzy
  -1 Medium Maintenance

Fish
  +1 Low Maintenance
  -1 Stupid

Dogs
  +2 Fuzzy
  -2 High Maintenance

(note that there's supposed to be two spaces before the +/- symbols --
in case my formatting doesn't go through)

I originally created that tool because I wanted to compare programming
languages, python among them, thus leading me discover this issue.

Now, I'm very new to this web development stuff (this is my first real
app), so it's quite likely that I'm just doing something stupid, but I
can't figure out what.

I'm using LunarPages.  CPanel reports my Apache version as: 1.3.37
(Unix)

I added the line "print sys.version" to the test script, and that
spits out: "2.3.4 (#1, Dec 11 2007, 05:27:57) [GCC 3.4.6 20060404 (Red
Hat 3.4.6-9)]"

I can't find any file called httpd.conf.  It would be in /etc, right?
I guess I don't have one.

Still having the same problem.

Here's the new contents of test.py:

#!/usr/bin/python
import cgitb, sys
cgitb.enable()

print "Content-Type: text/html\n"
print sys.version
print """


  
 

  


"""

It's not a joke, honest :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: float / rounding question

2008-02-25 Thread John Machin
On Feb 26, 7:14 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | Hi I'm very much a beginner with Python.
> | I want to write a function to convert celcius to fahrenheit like this
> | one:
> |
> | def celciusToFahrenheit(tc):
> |tf = (9/5)*tc+32
> |return tf
>
> Unless you are importing 'integer division' or using 3.0, that should be
> 9.0/5.0.

Has the syntax changed? I thought it was:
from __future__ import division

The OP may wish to avoid the confusion and the pointless division by
using:
   tf = 1.8 * tc + 32


>
> | I want the answer correct to one decimal place, so
> | celciusToFahrenheit(12) would return 53.6.
>
> As written, running above on 2.x returns 44.
>
> tjr

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


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Mike Driscoll
Joseph,

On 2/25/08, Joseph Turian <[EMAIL PROTECTED]> wrote:
>
>  > Seehttp://docs.python.org/lib/built-in-funcs.htmlwhich shows the
>  > current built-ins for Python. It also shows an equivalent function for
>  > all() that should work in 2.4.
>
>  Yes, I see that.
>
>  > You can do a check at the beginning of your file by importing the sys
>  > module. Something like this:
>  > 
>  > # untested
>  > import sys
>  > version = sys.version.split(' ')[0]
>  >
>  > if '2.5' not in version:
>  ># use custom all() script
>  >
>  > 
>
>  Okay.
>  I guess I was asking how do I nicely package the above into a file
>  python25.py from which I can do:
>   from python25 import all
>  And python25 figures out the python version and returns either the
>  hand-coded version or the library version.
>  How can I write python25.py ?
>

Well one way to do this would be something like this:



def all(iterable):
 for element in iterable:
 if not element:
 return False
 return True



And combine that with the code that Robert gave you. I'm not sure of
the exact syntax, but I would think you could do an IF statement that
creates the custom definition and returns it if Python 2.4 or less is
installed and return the normal version for 2.5 if it is installed.

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


Re: network programming: how does s.accept() work?

2008-02-25 Thread 7stud
On Feb 25, 10:56 am, Thomas Bellman <[EMAIL PROTECTED]> wrote:
> 7stud <[EMAIL PROTECTED]> wrote:
> > The question I'm really trying to answer is: if a client connects to a
> > host at a specific port, but the server changes the port when it
> > creates a new socket with accept(), how does data sent by the client
> > arrive at the correct port?  Won't the client be sending data to the
> > original port e.g. port 5052 in the client code above?
>
> The answer is that the server *doesn't* change its port.  As you
> could see in the output of your server, the socket that accept()
> returned also had local port 5052.  Each *client* will however
> get a unique local port at *its* end.
>
> A TCP connection is identified by a four-tuple:
>
>     ( localaddr, localport, remoteaddr, remoteport )
>
> Note that what is local and what is remote is relative to which
> process you are looking from.  If the four-tuple for a specific
> TCP connection is ( 127.0.0.1, 5052, 127.0.0.1, 50816 ) in your
> server, it will be ( 127.0.0.1, 50816, 127.0.0.1, 5052 ) in the
> client for the very same TCP connection.
>
> Since your client hasn't bound its socket to a specific port, the
> kernel will chose a local port for you when you do a connect().
> The chosen port will be more or less random, but it will make
> sure that the four-tuple identifying the TCP connection will be
> unique.
>

You seem to be describing what I see:

server output-
original socket: ('0.0.0.0', 5053)
new socket, self: ('127.0.0.1', 5053)
new socket, peer: ('127.0.0.1', 49302)

original socket: ('0.0.0.0', 5053)
new socket, self: ('127.0.0.1', 5053)
new socket, peer: ('127.0.0.1', 49303)

---client1 output-
('0.0.0.0', 0)
('127.0.0.1', 49302)

---client2 output-
('0.0.0.0', 0)
('127.0.0.1', 49303)


But your claim that the server doesn't change its port flies in the
face of every description I've read about TCP connections and
accept().  The articles and books I've read all claim that the server
port 5053 is a 'listening' port only.  Thereafter, when a client sends
a request for a connection to the listening port, the accept() call on
the server creates a new socket for communication between the client
and server, and then the server goes back to listening on the original
socket.  Here are two sources for that claim:

Socket Programming How To:
http://www.amk.ca/python/howto/sockets/

Tutorial on Network Programming with Python:
http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf

In either case, there are still some things about the output that
don't make sense to me.  Why does the server initially report that its
ip address is 0.0.0.0:

original socket: ('0.0.0.0', 5053)

I would expect the reported ip address to be '127.0.0.1'.  Also, since
a socket is uniquely identified by an ip address and port number, then
the ('0.0.0.0', 5053) socket is not the same as this socket:

new socket, self: ('127.0.0.1', 5053)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Arnaud Delobelle
On Feb 25, 8:47 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
> You can do a check at the beginning of your file by importing the sys
> module. Something like this:
>
> 
> # untested
> import sys
> version = sys.version.split(' ')[0]
>
> if '2.5' not in version:
>    # use custom all() script
>
> 

Or simply:

try:
all
except NameError:
def all(iterable):
for x in iterable:
if not x: return False
return True

--
Arnaud

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


ANN: Python cgkit v2.0.0alpha8

2008-02-25 Thread matthias . baas
The eigth alpha release of cgkit2 is available at http://cgkit.sourceforge.net

What is it?
---

The Python Computer Graphics Kit is an Open Source software package
containing a collection of Python modules, plugins and utilities that
are meant to be useful for any domain where you have to deal with 3D
data of any kind, be it for visualization, creating photorealistic
images, Virtual Reality or even games.

What's new?
---

- New module "cri" that contains a ctypes-based RenderMan binding
- New module "mayabinary" to parse Maya Binary (.mb) files
- Various smaller fixes and additions (see the changelog for a full
list)

For more information, visit:

http://cgkit.sourceforge.net

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


Re: PyEuler

2008-02-25 Thread Mark Dickinson
On Feb 25, 4:24 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> def genfib(a=0, b=1):
>     for a, b in iter(lambda:(b, a+b), None):
>         yield a
>
> ;-)
>
> Ahem.  I admit that somehow, I am proud of this.


You're one sick puppy dog.  :-)
(P.S.  Your mother was a hamster, and your father smelt of
elderberries.)

Gratuitous insulting'ly yours,

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


Re: How to manipulate elements of a list in a single line of code?

2008-02-25 Thread mrstephengross
> Yes, it's called a "list comprehension", and is many people's favourite

Awesome!

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


Re: How to manipulate elements of a list in a single line of code?

2008-02-25 Thread Paulo da Costa
mrstephengross wrote:
> 1  list1 = ['a', 'b', 'c']
> 2  list2 = []
> 3  for item in list1: list2.append(item + 'foo')
> 
> Is there a way to express lines 2-3 sort-of ilke this:
> 
>   list2 = [ for item in list1: item + 'foo' ]

list2 = [ item + 'foo' for item in list1 ]

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


Re: How to manipulate elements of a list in a single line of code?

2008-02-25 Thread D'Arcy J.M. Cain
On Mon, 25 Feb 2008 13:39:26 -0800 (PST)
mrstephengross <[EMAIL PROTECTED]> wrote:
> 1  list1 = ['a', 'b', 'c']
> 2  list2 = []
> 3  for item in list1: list2.append(item + 'foo')
> 
> Is there a way to express lines 2-3 sort-of ilke this:
> 
>   list2 = [ for item in list1: item + 'foo' ]

You almost have it.

  list2 = [item + 'foo' for item in list1]

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


Re: How to manipulate elements of a list in a single line of code?

2008-02-25 Thread Ben C
On 2008-02-25, mrstephengross <[EMAIL PROTECTED]> wrote:
> I would like to translate the contents of a list. For instance, let's
> say I've got a list of strings and I want to append "foo" to each
> element. I might do the following;
>
>   list1 = ['a', 'b', 'c']
>   for i in range(0, len(list1)): list1[i] += 'foo'
>
> Ok, that much works. But what if I don't want to modify the contents
> of list1. Instead, I want list2 to hold the modified contents, like
> so:
>
> 1  list1 = ['a', 'b', 'c']
> 2  list2 = []
> 3  for item in list1: list2.append(item + 'foo')
>
> Is there a way to express lines 2-3 sort-of ilke this:
>
>   list2 = [ for item in list1: item + 'foo' ]

Yes, it's called a "list comprehension", and is many people's favourite
Python feature.

list2 = [x + 'foo' for x in list1]

You can also add a condition

list2 = [x + 'foo' for x in list1 if x != "bar"]

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


Re: How to manipulate elements of a list in a single line of code?

2008-02-25 Thread Dan
On Feb 25, 4:39 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
> I would like to translate the contents of a list. For instance, let's
> say I've got a list of strings and I want to append "foo" to each
> element. I might do the following;
>
>   list1 = ['a', 'b', 'c']
>   for i in range(0, len(list1)): list1[i] += 'foo'
>
> Ok, that much works. But what if I don't want to modify the contents
> of list1. Instead, I want list2 to hold the modified contents, like
> so:
>
> 1  list1 = ['a', 'b', 'c']
> 2  list2 = []
> 3  for item in list1: list2.append(item + 'foo')
>
> Is there a way to express lines 2-3 sort-of ilke this:
>
>   list2 = [ for item in list1: item + 'foo' ]
>
> Any ideas?
>
> Thanks,
> --Steve

You're so close.

>>> list2 = [ item+"foo" for item in list1 ]

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


Re: Order of evaluation in conditionals

2008-02-25 Thread Karlo Lozovina
Paul Hankin wrote:

> Did you try to find the answer to your question in the python
> reference manual? The relevant page is
> http://docs.python.org/ref/Booleans.html

Of course I first Googled (even Google Groups-ed) it, but I didn't notice
that in the results.
 
> To quote it:
> The expression 'x and y' first evaluates x; if x is false, its value
> is returned; otherwise, y is evaluated and the resulting value is
> returned.

Thanks (to both of you :>), that's it.

-- 
Karlo Lozovina -- Mosor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib slow on Leopard

2008-02-25 Thread mark
mark wrote:
> I've recently switched from Ubuntu to OS X Leopard. I have some python 
> scripts which download info from the web. The scripts were working fine 
> before on Ubuntu, but urllib seems to work really slowly on Leopard.
> 
> I tried an example from the docs:
> 
>  >>> import urllib2
>  >>> f = urllib2.urlopen('http://www.python.org/')
>  >>> print f.read(100)
>  "http://www.w3.org/TR/xhtml1/DTD/xhtm
>  >>>
> 
> The line f = ... takes about a minute to return - but otherwise returns 
> the predicted result. My web connection seems fine, so has anyone got 
> any ideas as to what the problem might be?

I found that by configuring the network manually (specifying static IP 
address, etc.) it sped the whole thing up. Go figure.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to manipulate elements of a list in a single line of code?

2008-02-25 Thread mrstephengross
I would like to translate the contents of a list. For instance, let's
say I've got a list of strings and I want to append "foo" to each
element. I might do the following;

  list1 = ['a', 'b', 'c']
  for i in range(0, len(list1)): list1[i] += 'foo'

Ok, that much works. But what if I don't want to modify the contents
of list1. Instead, I want list2 to hold the modified contents, like
so:

1  list1 = ['a', 'b', 'c']
2  list2 = []
3  for item in list1: list2.append(item + 'foo')

Is there a way to express lines 2-3 sort-of ilke this:

  list2 = [ for item in list1: item + 'foo' ]

Any ideas?

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


Re: Is there any method to urlretrieve to a file the html source from a url with "Transfer-encoding": chunked

2008-02-25 Thread 7stud
On Feb 25, 8:25 am, Aldo Ceccarelli <[EMAIL PROTECTED]> wrote:
> Thank you All for your suggestions:
>
> I could finally assess that
>
> besides partial read from chunked url - by-passed thanks to a socket
> approach:
>
> f.i. this was good for 
> me:http://python.about.com/od/networkingwithpython/ss/beg_web_client_9.htm
>
> I have still two kind of problems that quit this post's aims (original
> url is redirected and has password protections too, I will go for
> these now)
>
> Again SUPER thanks to You All:-) Aldo

Don't use that code--it's merely a bare bones example.  Post the url
that is giving you problems.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Order of evaluation in conditionals

2008-02-25 Thread Tim Chase
> if () and () and ():
>   do_something()
> 
> Is there a guarantee that Python will evaluate those conditions in order (1,
> 2, 3)? I know I can write that as a nested if, and avoid the problem
> altogether, but now I'm curious about this ;).

Yes, Python does short-circuit evaluation, from left-to-right

http://docs.python.org/tut/node7.html#SECTION00770

That means that if  returns false, condition[2|3] 
will not be evaluated (and similarly, if condition2 returns 
false, condition3 won't be evaluated).

-tkc



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


Re: network programming: how does s.accept() work?

2008-02-25 Thread Thomas Bellman
7stud <[EMAIL PROTECTED]> wrote:

> The question I'm really trying to answer is: if a client connects to a
> host at a specific port, but the server changes the port when it
> creates a new socket with accept(), how does data sent by the client
> arrive at the correct port?  Won't the client be sending data to the
> original port e.g. port 5052 in the client code above?

The answer is that the server *doesn't* change its port.  As you
could see in the output of your server, the socket that accept()
returned also had local port 5052.  Each *client* will however
get a unique local port at *its* end.

A TCP connection is identified by a four-tuple:

( localaddr, localport, remoteaddr, remoteport )

Note that what is local and what is remote is relative to which
process you are looking from.  If the four-tuple for a specific
TCP connection is ( 127.0.0.1, 5052, 127.0.0.1, 50816 ) in your
server, it will be ( 127.0.0.1, 50816, 127.0.0.1, 5052 ) in the
client for the very same TCP connection.

Since your client hasn't bound its socket to a specific port, the
kernel will chose a local port for you when you do a connect().
The chosen port will be more or less random, but it will make
sure that the four-tuple identifying the TCP connection will be
unique.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"There are many causes worth dying for, but  !  bellman @ lysator.liu.se
 none worth killing for." -- Gandhi  !  Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Order of evaluation in conditionals

2008-02-25 Thread Paul Hankin
On Feb 25, 9:18 pm, Karlo Lozovina <[EMAIL PROTECTED]> wrote:
> Hi all! Here is what's bugging me: let's say I have this code:
>
> if () and () and ():
>   do_something()
>
> Is there a guarantee that Python will evaluate those conditions in order (1,
> 2, 3)? I know I can write that as a nested if, and avoid the problem
> altogether, but now I'm curious about this ;).

Did you try to find the answer to your question in the python
reference manual? The relevant page is http://docs.python.org/ref/Booleans.html

To quote it:
The expression 'x and y' first evaluates x; if x is false, its value
is returned; otherwise, y is evaluated and the resulting value is
returned.

--
Paul Hankin

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


Re: PyEuler

2008-02-25 Thread Arnaud Delobelle
On Feb 25, 7:25 pm, Paul Rubin  wrote:
> Are you kidding?
>     def ggenfib():
>       a,b = 1,2
>       while True:
>          yield a
>          a,b = b, a=b

Or:

def genfib(a=0, b=1):
for a, b in iter(lambda:(b, a+b), None):
yield a

;-)

Ahem.  I admit that somehow, I am proud of this.

--
Arnaud

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


Re: String compare question

2008-02-25 Thread Robert Dailey
Thanks for your help. I knew of a way to solve this issue, but being a C++
programmer I tend to think of the expanded solutions for things. I wasn't
sure if there was a more compact solution for python. Thanks again!

On Mon, Feb 25, 2008 at 11:27 AM, Tim Chase <[EMAIL PROTECTED]>
wrote:

> >> ignored_dirs = (
> >>r".\boost\include",  # It's that comma that makes this a tuple.
> >> )
> >>
> >
> > Thanks for reminding me of this. I always forget that!
> >
> > Now that it is correctly doing *only* whole string matches, what if I
> want
> > to make it do a substring compare to each string in my ignored_dirs
> tuple?
>
> Sounds like a good opportunity for the underused for/break/else
> construct:
>
> ##
> ignored_dirs = (
> r".\boost\include",
>  )
>
> if __name__ == "__main__":
> # Walk the directory tree rooted at 'source'
> for root, dirs, files in os.walk( source ):
> for dirname in ignored_dirs:
> # may need to normalize to root.lower()
> if dirname in root:
> print 'Skipping', root
> break
> else:
> CopyFiles( root, files, ".dll" )
> ##
>
> -tkc
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Order of evaluation in conditionals

2008-02-25 Thread Karlo Lozovina
Hi all! Here is what's bugging me: let's say I have this code:

if () and () and ():
  do_something()

Is there a guarantee that Python will evaluate those conditions in order (1,
2, 3)? I know I can write that as a nested if, and avoid the problem
altogether, but now I'm curious about this ;).

Thanks...

-- 
Karlo Lozovina -- Mosor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-25 Thread Paul Rubin
Robert Brown <[EMAIL PROTECTED]> writes:
> > Python's dynamic typing is just fine.  But if I know the type, I want
> > the ability to nail it.  ...local variables, arguments, return values,
> > etc  And if I don't know or care, I'd leave it to dynamic typing.
> 
> This is the approach taken by Common Lisp.  Often just a few type
> declarations, added to code in inner loops, results in vastly faster code.

That is just a dangerous hack of improving performance by turning off
some safety checks, I'd say.  Static typing in the usual sense of the
phrase means that the compiler can guarantee at compile time that a
given term will have a certain type.  That can be done by automatic
inference or by checking user annotations, but either way, it should
be impossible to compile code that computes improperly typed values.
Lisp and Python don't attempt to make any such compile time checks.
They check at runtime, or (in the case of Lisp with the checks turned
off) they don't check at all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Robert Kern
Joseph Turian wrote:
> I was given code that was written for python 2.5, and uses simple
> functions like 'all' which are not present in 2.4
> 
> I want to make the code 2.4 compatible. What is the best way to do
> this?

If it's a single file, put something like the following code near the top. If 
you have multiple modules, put it into a separate module, say compatibility.py, 
and change the other modules to import these functions from there.


import sys
if sys.version_info[:2] < (2,5):
 def all(*args):
 ...
 def any(*args):
 ...
else:
 # Only bother with this else clause and the __all__ line if you are putting
 # this in a separate file.
 import __builtin__
 all = __builtin__.all
 any = __builtin__.any

__all__ = ['all', 'any']


> If I define function 'all', then won't I break 2.5 compatability?

No. Defining a function named the same thing as a builtin function will not 
break anything. You just wouldn't be using the efficient implementation already 
in Python 2.5. Using the if: else: suite above lets you have both at the 
expense 
of some clunkiness.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Accessing "sub elements" with xml.sax ?

2008-02-25 Thread erikcw
Hi,

I'm trying to use xml.sax (from xml.sax.handler import ContentHandler)
to processes the following data:








I've figured out how to access the attributes in "row" - but I want to
also access the "analytics" child element.

I've tried:
class YahooHandler(ContentHandler):
ccountNum)

def startElement(self, name, attrs):
if name == 'row' or name == 'analytics':
self.campaign = attrs.get('cmpgnName',"")
self.adgroup = attrs.get('adGrpName',"")
self.headline = attrs.get('adName',"")
self.imps = attrs.get('numImpr',None)
self.clicks = attrs.get('numClick',None)
self.cost = attrs.get('cost',"")

def endElement(self, name):
if name == 'row':
if self.campaign not in self.data:
self.data[self.campaign] = {}
if self.adgroup not in self.data[self.campaign]:
self.data[self.campaign][self.adgroup] = []
self.data[self.campaign][self.adgroup].append({'campaign':
self.campaign,
'adgroup': self.adgroup,
'headline': self.headline,
'imps': self.imps,
'clicks': self.clicks,
'ctr': self.ctr,
'cost': self.cost,
})
print self.data

But it the data comes out as seperate dictionaries - I want the
analytics and the row elements in one dictionary.

What am I doing wrong?

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


Re: Reading a keypress

2008-02-25 Thread wyleu

>
> A recipe that supposedly does this in a cross-platform 
> way:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892

class _Getch:
"""Gets a single character from standard input.  Does not echo to
the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()

def __call__(self): return self.impl()


class _GetchUnix:
def __init__(self):
import tty, sys

def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch


class _GetchWindows:
def __init__(self):
import msvcrt

def __call__(self):
import msvcrt
return msvcrt.getch()


getch = _Getch()



Sadly this also fails with:


Traceback (most recent call last):
  File "", line 1, in -toplevel-
a = getch()
  File "/home/chris/getch.py", line 10, in __call__
def __call__(self): return self.impl()
  File "/home/chris/getch.py", line 19, in __call__
fd = sys.stdin.fileno()
AttributeError: fileno


What is fileno, and why might I not  have it?







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


property data-descriptor - how to pass additional constants to the get/set method

2008-02-25 Thread petr . jakes . tpc
Hi,
I would like to pass additional constants to the property data-
descriptor, so it is not necessary to write many methods which differ
just by constant defined in the method body.
Till now I can do this:

class MyClass(object):

def _getValue(self, myConstant):
print 'myConstant:', myConstant
return myConstant+10

def _setValue(self, inputValue, myConstant):
print 'inputValue:', inputValue, 'myConstant:', myConstant
return inputValue*myConstant

fistAttribte = property(fget = lambda self:
self._getValue(myConstant=0),
   fset = lambda self, inputValue, myConstant=0:
self._setValue(inputValue, myConstant))

secAttribute = property(fget = lambda self:
self._getValue(myConstant=1),
   fset = lambda self, inputValue, myConstant=1:
self._setValue(inputValue, myConstant))

It works, but it does not look very nice to me.
Is there some different/nicer/more pythonic way how to achieve above
mentioned?

regards

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


Re: Python code for 2.5 and 2.4?

2008-02-25 Thread Mike Driscoll
On Feb 25, 2:40 pm, Joseph Turian <[EMAIL PROTECTED]> wrote:
> I was given code that was written for python 2.5, and uses simple
> functions like 'all' which are not present in 2.4
>
> I want to make the code 2.4 compatible. What is the best way to do
> this?
> If I define function 'all', then won't I break 2.5 compatability?
>
> Thanks,
>   Joseph

See http://docs.python.org/lib/built-in-funcs.html which shows the
current built-ins for Python. It also shows an equivalent function for
all() that should work in 2.4.

You can do a check at the beginning of your file by importing the sys
module. Something like this:


# untested
import sys
version = sys.version.split(' ')[0]

if '2.5' not in version:
   # use custom all() script



HTH

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


Re: Article of interest: Python pros/cons for the enterprise

2008-02-25 Thread Robert Brown
Larry Bugbee <[EMAIL PROTECTED]> writes:
> Python's dynamic typing is just fine.  But if I know the type, I want
> the ability to nail it.  ...local variables, arguments, return values,
> etc  And if I don't know or care, I'd leave it to dynamic typing.

This is the approach taken by Common Lisp.  Often just a few type
declarations, added to code in inner loops, results in vastly faster code.
Also, although I don't tend to use type declarations while interactively
developing code, I often add them later.  Mostly, I add them to document the
code, but the added safety and faster execution time are nice benefits.

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


Python code for 2.5 and 2.4?

2008-02-25 Thread Joseph Turian
I was given code that was written for python 2.5, and uses simple
functions like 'all' which are not present in 2.4

I want to make the code 2.4 compatible. What is the best way to do
this?
If I define function 'all', then won't I break 2.5 compatability?

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


Re: Using lambda [was Re: Article of interest: Python pros/cons fortheenterprise]

2008-02-25 Thread Terry Reedy

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| On Sun, 24 Feb 2008 21:13:08 -0500, Terry Reedy wrote:
|
| > | I even use "named anonymous functions" *cough* by assigning lambda |
| > functions to names:
| > |
| > | foo = lambda x: x+1
| >
| > Even though I consider the above to be clearly inferior to
| >
| > def foo(x): return x+1
| >
| > since the latter names the function 'foo' instead of the generic
| > ''.
|
| Absolutely. If foo() was a function that the user would see, I would
| certainly use the def form to create it.
|
| But in a situation like this:
|
|
| def parrot(x, y, z, func=None):
|if func is None:
|func = lambda x: x+1
|return func(x+y+z)

Since functions are constants with respect to code attribute, you might as 
well condense that to

def parrot(x,y,z, func = lambda xyz: xyz+1):
   return func(x+y+z)

Then you can claim some actual space saving.

| I don't see any advantage to writing it as:
|
| def parrot(x, y, z, func=None):
|if func is None:
|def func(x): return x+1
|return func(x+y+z)

Good habit?
Don't mislead the newbies ;-?

tjr




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


Re: Article of interest: Python pros/cons for the enterprise

2008-02-25 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jeff Schwab  <[EMAIL PROTECTED]> wrote:
>Bruno Desthuilliers wrote:
>> 
>> Stating the obvious is not bashing. In my last shop I was working with 
>> (very talented BTW) Perl programmer, and he was the first to make jokes 
>> on Perl's abuse of cryptic syntax.
>
>It's not abuse.  It's meaningful and compact.  The $scalars are 
>intuitive to anybody who has ever written a shell script, the @arrays 
>are immediately recognizable...  I agree it takes some getting used to, 
>but then it becomes clear as day.

You're entitled to your opinion, but speaking as a former expert Perl
programmer, I disagree with you.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bin2chr("01110011") # = 15 function ?

2008-02-25 Thread Tim Chase
> I'm searching for a simple
> bin2chr("01110011") function that can convert all my 8bit data to a
> chr so I can use something like this:

> print ord("s") # = 115
> print bin(ord("s")) # = 01110011
> 
> test= open('output.ext,'wb')
> test.write(bin2chr("01110011"))
> test.write(bin2chr("0011"))
> test.write(bin2chr("01110111"))
> test.close()

I think this simple one-liner should do it for you:

   >>> bin2char = lambda s: chr(int(s,2))
   >>> bin2char('01110011')
   's'

which exploits int()'s ability to take a base (2, in this case).

-tkc



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


bin2chr("01110011") # = 15 function ?

2008-02-25 Thread gcmartijn
H!

I'm searching for a simple
bin2chr("01110011") function that can convert all my 8bit data to a
chr so I can use something like this:

def bin(i):
l = ['', '0001', '0010', '0011', '0100', '0101', '0110',
'0111',
 '1000', '1001', '1010', '1011', '1100', '1101', '1110',
'']
s = ''.join(map(lambda x, l=l: l[int(x, 16)], hex(i)[2:]))
if s[0] == '1' and i > 0:
s = '' + s
return s

print ord("s") # = 115
print bin(ord("s")) # = 01110011

test= open('output.ext,'wb')
test.write(bin2chr("01110011"))
test.write(bin2chr("0011"))
test.write(bin2chr("01110111"))
test.close()

I think this is very easy but I'm not very good in python.
In a other program I use I do something like this

Function bin2int(b$)
blen=Len(b)
For f=1 To blen
n=n Shl 1 + (Mid(b,f,1)="1")
Next
Return n
End Function
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: float / rounding question

2008-02-25 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi I'm very much a beginner with Python.
| I want to write a function to convert celcius to fahrenheit like this
| one:
|
| def celciusToFahrenheit(tc):
|tf = (9/5)*tc+32
|return tf

Unless you are importing 'integer division' or using 3.0, that should be 
9.0/5.0.

| I want the answer correct to one decimal place, so
| celciusToFahrenheit(12) would return 53.6.

As written, running above on 2.x returns 44.

tjr



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


Re: PyEuler

2008-02-25 Thread Paul Rubin
[EMAIL PROTECTED] writes:

> def takenth(n, iterable):
> "Returns the nth item"
> return list(islice(iterable, n, n+1))[0]
> 

return islice(iterable, n).next()

> isanymultiple = lambda x: any((x % y == 0) for y in nums)
> return sum(filter(isanymultiple, xrange(end)))

This isn't so good, you really want to apply the filters recursively.

> def fibonacci(n):
> """Return nth element of the fibonacci serie"""
> if n == 0 or n == 1:
> return n
> return fibonacci(n-1) + fibonacci(n-2)

uggh exponential blowup!

> def euler2(end):
> genfib = imap(fibonacci, count())

Are you kidding?
def ggenfib():
  a,b = 1,2
  while True: 
 yield a
 a,b = b, a=b

> What I think about such code:
> - It's not much readable (but usually it can be read). ...

Your observations are generally good; I'd say it was done
without enough attention to the math too.

There is a full set of solutions on the haskell wiki, if anyone cares.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a keypress

2008-02-25 Thread Mike Driscoll
On Feb 25, 12:35 pm, wyleu <[EMAIL PROTECTED]> wrote:
> I'm trying to read a single keypress on Linux but expect to have the
> programme running on Windows platform as well and find the mention in
> the FAQ:
>
> import termios, fcntl, sys, os
> fd = sys.stdin.fileno()
>
> oldterm = termios.tcgetattr(fd)
> newattr = termios.tcgetattr(fd)
> newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
> termios.tcsetattr(fd, termios.TCSANOW, newattr)
>
> oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
> fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
>
> try:
> while 1:
> try:
> c = sys.stdin.read(1)
> print "Got character", `c`
> except IOError: pass
> finally:
> termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
> fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
>
> However this fails on the second line as sys.stdin seems to have no
> method fileno.
> Any idea how I might proceed?

I've never done this sort of thing (except in wxPython), but with a
little Google-magic I found the following:

A recipe that supposedly does this in a cross-platform way:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892

And a Windows only module:
http://effbot.org/librarybook/msvcrt.htm

HTH

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


Re: PyEuler

2008-02-25 Thread Mark Dickinson
On Feb 25, 11:25 am, [EMAIL PROTECTED] wrote:
> This is the first time I write something that looks like a little
> rant :-) Surely I'll be wrong in many points, but I presume this isn't
> going to damage people, so...

Agreed on all points. :-)  This looks a lot like someone trying to
write
Haskell in Python.  And that's a truly horrible way of finding a least
common multiple:  much better to do lcm(a, b) = a*(b//gcd(a, b)), with
gcd computed using the usual algorithm (written *iteratively*, not
recursively).

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


Re: Article of interest: Python pros/cons for the enterprise

2008-02-25 Thread Nicola Musatti
On Feb 25, 3:17 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Feb 25, 8:29 am, Nicola Musatti <[EMAIL PROTECTED]> wrote:
>
> > On Feb 24, 9:14 pm, Larry Bugbee <[EMAIL PROTECTED]> wrote:
> > > Corporate marketing, and corporate attention in general, saw to it
> > > that Java was well equipped with libraries and frameworks addressing
> > > enterprise application needs.  ...but the *big* reason Java won over C+
> > > + is because your application became stable sooner.  ...with arguably
> > > fewer problems later.
>
> > The number of libraries you get "out of the box" appear to me as more
> > likely explanations for the productivity increase.
>
> The productivity increase of the language appears to me as a more
> likely explanation for the number of libraries you get "out of the
> box".

In the case of Python I suspect you have a point even without the
smiley, given how much of what's available was developed without any
major corporation's support. On the other hand, had the kind of money
that's been poured into Java and/or .NET been poured into *standard* C+
+, I dont' think it would be so far behind. Witness the kind of
libraries/framework that used to and still come with some commercial C+
+ implementation, and even some free/open source ones; Boost, ACE and
wxWidgets are the first that come to mind.

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


Reading a keypress

2008-02-25 Thread wyleu
I'm trying to read a single keypress on Linux but expect to have the
programme running on Windows platform as well and find the mention in
the FAQ:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", `c`
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

However this fails on the second line as sys.stdin seems to have no
method fileno.
Any idea how I might proceed?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.fork() not working on windows (help)

2008-02-25 Thread Ian Clark
On 2008-02-25, A. Joseph <[EMAIL PROTECTED]> wrote:
> Please i`m trying to create a process using the os.fork() but it keep

If you're not trying to clone your current process, just make a new one,
you should look at the subprocess module.

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

Ian

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


  1   2   3   >