Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Shashwat Anand
Here is one simple solution :
 intext = Lorem [ipsum] dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor  incididunt ut [labore] et [dolore] magna aliqua.

 intext.replace('[', '{').replace(']',
'}')
'Lorem {ipsum} dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor  incididunt ut {labore} et {dolore} magna aliqua.'

*Some people, when confronted with a problem, think I know, I’ll use
regular expressions. Now they have two problems.* — Jamie
Zawinskittp://jwz.livejournal.comin comp.lang.emacs.


On Sun, Feb 7, 2010 at 11:15 AM, Schif Schaf schifsc...@gmail.com wrote:

 On Feb 7, 12:19 am, Alf P. Steinbach al...@start.no wrote:

 
  I haven't used regexps in Python before, but what I did was (1) look in
 the
  documentation,

 Hm. I checked in the repl, running `import re; help(re)` and the docs
 on the `sub()` method didn't say anything about using back-refs in the
 replacement string. Neat feature though.

  (2) check that it worked.
 
  code
  import re
 
  text = (
   Lorem [ipsum] dolor sit amet, consectetur,
   adipisicing elit, sed do eiusmod tempor,
   incididunt ut [labore] et [dolore] magna aliqua.
   )
 
  withbracks = re.compile( r'\[(.+?)\]' )
  for line in text:
   print( re.sub( withbracks, r'{\1}', line) )
  /code
 

 Seems like there's magic happening here. There's the `withbracks`
 regex that applies itself to `line`. But then when `re.sub()` does the
 replacement operation, it appears to consult the `withbracks` regex on
 the most recent match it just had.

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

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


Re: max / min / smallest float value on Python 2.5

2010-02-07 Thread Mark Dickinson
On Feb 7, 12:52 am, duncan smith buzz...@urubu.freeserve.co.uk
wrote:
 import platform
 if platform.architecture()[0].startswith('64'):
      TINY = 2.2250738585072014e-308
 else:
      TINY = 1.1754943508222875e-38

As Christian said, whether you're using 32-bit or 64-bit shouldn't
make a difference here.  Just use the first TINY value you give.

 I'm not 100% sure how reliable this will be across platforms.  Any ideas
 about the cleanest, reliable way of uncovering this type of information?

In practice, it's safe to assume that your 2.225e-308 value is
reliable across platforms.  That value is the one that's appropriate
for the IEEE 754 binary64 format, and it's difficult these days to
find CPython running on a machine that uses any other format for C
doubles (and hence for Python floats).

The smallest positive *normal* number representable in IEEE 754
binary64 is exactly 2**-1022 (or approximately
2.2250738585072014e-308).  The smallest positive *subnormal* number
representable is exactly 2**-1074, or approximately
'4.9406564584124654e-324'.  (Subnormals have fewer bits of precision
than normal numbers;  it's the presence of subnormals that allows for
'gradual underflow'.)  Some machines can/will treat subnormal numbers
specially for speed reasons, either flushing a subnormal result of a
floating-point operation to 0, or replacing subnormal inputs to an
floating-point operation with 0, or both.  So for maximal portability,
and to avoid numerical problems, it's best to avoid the subnormal
region.

 The precise issue is that I'm supplying a default value of
 2.2250738585072014e-308 for a parameter (finishing temperature for a
 simulated annealing algorithm) in an application.  I develop on
 Ubuntu64, but (I am told) it's too small a value when run on a Win32
 server.  I assume it's being interpreted as zero and raising an
 exception.

This is a bit surprising.  What's the precise form of the error you
get?  Do you still get the same error if you replace your TINY value
by something fractionally larger?  (E.g., 2.23e-308.)

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


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread @ Rocteur CC


On 07 Feb 2010, at 10:03, Shashwat Anand wrote:


Here is one simple solution :
 intext = Lorem [ipsum] dolor sit amet, consectetur  
adipisicing elit, sed do eiusmod tempor  incididunt ut [labore] et  
[dolore] magna aliqua.


 intext.replace('[', '{').replace(']', '}')
'Lorem {ipsum} dolor sit amet, consectetur adipisicing elit, sed do  
eiusmod tempor  incididunt ut {labore} et {dolore} magna aliqua.'


Some people, when confronted with a problem, think I know, I’ll use  
regular expressions. Now they have two problems. — Jamie Zawinski  
in comp.lang.emacs.


That is because regular expressions are what we learned in programming  
the shell from sed to awk and ksh and zsh and of course Perl and we've  
read the two books by Jeffrey and much much more!!!


How do we rethink and relearn how we do things and should we ?

What is the solution ?

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


ctypes Structure serialization

2010-02-07 Thread rych
I'm not quite familiar with python serialization but the picle module,
at least, doesn't seem to be able to serialize a ctypes Structure with
array-fields. Even if it was, the ASCII file produced is not in a
human-friendly format.

Could someone please suggest a method of saving and loading the fields
in ctypes' Structure derived class to a json or better yet, to
something like INFO
http://www.boost.org/doc/libs/1_41_0/doc/html/boost_propertytree/parsers.html#boost_propertytree.parsers.info_parser

For example, I have an object of
 class MyStruct(Structure):
..._fields_ = [(a, c_int),
...(b, c_float),
...(point_array, c_float * 4)]

I'd like the corresponding file to look like

a 1
b 1.0
point array 1.1 1.2 1.3 1.4

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


Re: new.instancemethod __iter__

2010-02-07 Thread Martin Drautzburg
Steven D'Aprano wrote:

 If you want iterator operations similar to itertools, why does this
 mean you need to replace anything? Just create your own iterators.
 
 Or use pre-processing and post-processing to get what you want.
 
 Can you show an example of what you would like to happen?

Steven, 

my classes repesent musical objects. The fundamental paradigm I want to
apply is that of a Sequence, i.e. the most abstract aspect of music is
that things occur in a certain order.

Then I have a TimedSequence class, which is a Sequences whose elements
have a time attribute. I now want to be able to append such Sequences
by writing

s1 = TimedSequence (time=1,'a') # one-element Sequence
s2 = TimedSequence (time=2,'b')

y = s1*2 + s2

Naively appending those sequences would give me
Time=1,'a'
Time=1,'a'
Time=2,'b'

but this is not what I want. Time needs to progress if I append a
sequence to another. So what I really want is something like

Time=1,'a'
Time=2,'a'
Time=3,'b'

This implies that time is shifted to the next integer, but this is not
always the case. I need to know about some kind of alignment. In
music this translates to let a sequence start at the beginning of a
bar, or half bar or quarter note or whatever.

So I want to write

y = s1*2 + s2(align=10)

which should iterate as

Time=1,'a'
Time=2,'a'
Time=10,'b'

I have no difficulty passing align to the object (using __call__) and
use it while I furnish my own __iter__() method. However I don't quite
see how I can do this with bare itertools, though I may be wrong here.

Bare in mind that it is not only about somehow getting the job done. The
beauty of the resulting syntax is also important.




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


Re: new.instancemethod __iter__

2010-02-07 Thread Martin Drautzburg
Christian Heimes wrote:


 If you *really* need to overwrite __iter__ on your instance rather
 than defining it on your class, you need to proxy the method call:
 
 class MyObject(object):
def __iter__(self):
   return self.myiter()
 
 obj = MyObject()
 obj.myiter = myiter
 
 That should do the trick.

Thanks a lot, that works.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xmlrpc slow in windows 7 if hostnames are used

2010-02-07 Thread News123
Hi JM,


Jean-Michel Pichavant wrote:
 News123 wrote:
 Jean-Michel Pichavant wrote:
  

 Well This was exactly my question.
 for virtual web servers I cannot just use the IP-address.
 some XMLRPC servers do need the histname within the HTTP-POST request.

   
 a valid IP address would make it

What I meant is: Window 7 seems to be w slower if an xmlrpc
client uses a host name ('localhost') than an IP-address ('127.0.0.1).
the speed difference is between 1 request per second or 10-20 requests
per second.


 if I just replaced the hostname with the IP address, then certain servers
 would not be accessable.

many computers host multiple web servers under the same IP-address.
( see for example http://httpd.apache.org/docs/1.3/vhosts/name-based.html )

So I cannot just replace a host name with an IP-address and expect
to receive the correct data / correct xmlrpc server.


 I had to use the IP-address for connecteing
 why not using the host names?

I did not want to use the hostname due to the slowdown of
locahost vs. 127.0.0.1  issue on my host.

You are right, that I did not verify whether this issue exists also with
external servers and I should verify this first.


 , but to pass the hostname in
 the HTTP-POST request.

 I wondered how to convince puthon's SimpleXMLRPCServer (or any other
 standard python xmlrpc server), such, that I can obtain above mentioned
 goal.

   
 I'm puzzled.
 Unless my english is failing me, everything would be solved using
 hostnames if I follow you. Why don't you do that ?
 I am no network/IP guru, but it sounds very weird to have requests
 rejected when using IP addresses. Are you sure your host names are
 resolved with the same IPM address you are using ?

The request would not be rejected, but apache can (if being configured
for name based virtual hosts) look at the hostname within the TCP/IP
payload (the entire url (including the host name) is normally also in
the GET / POST request ) and decide to deliver different data (or to
return HTTP errors) depending on the hostname in the payload.


I hope this clarifies.

Your answer gave me some thoughts though:

I still have to check whether the issue really exists with external
requests other than localhost.
Also I should probably try to attack the root cause
(  probably with help of ethereal or a similiar tool) instead of trying
to work around it.

I could just change the windows /etc/hosts equivalent and tell localhost
to have only an IPV4 address (perhaps this increases the performance)


On the other hand:
 Some people use name based virtual servers to provide special web
services by providing a 'fake-host name' in the http request. it might
be, that the fake host name doesn't even have a DNS entry.
( Though security by obscurity is a questionable practice )

so for some weird use cases it could be worth knowing how to connect to
one IP addres and to pass a different host name in the HTTP payload when
using an  xmlrpcclient


bye


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


Re: sshd in python for windows 7

2010-02-07 Thread News123
Hi Jerry,

Jerry Hill wrote:
 On Sat, Feb 6, 2010 at 7:07 PM, News123 news...@free.fr wrote:
 Hi,

 I wondered which modules would be best to perform following task:

 A user uses a standard ssh (e.g. putty or openssh) client and performs
 an ssh to a windows host

 The windows host would run a python script acting as ssh server.
 
 The Twisted library has an sshd implementation, called conch.  Here an
 article with a simple python sshd built with twisted:
 http://www.ibm.com/developerworks/linux/library/l-twist4.html


Thanks. I'll check whether twisted conch runs also under windows.
Yesterday I made the probably too fast conclusion, that twisted conch
exists only for liux as I could only find a twisted-conch tarball and
not a windows installer.

But probably twisted-conch is already part of the twisted installer for
windows.
I'll check it.


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


Re: sshd in python for windows 7

2010-02-07 Thread News123
Hi Jerry,

Jerry Hill wrote:
 On Sat, Feb 6, 2010 at 7:07 PM, News123 news...@free.fr wrote:
 Hi,

 I wondered which modules would be best to perform following task:

 A user uses a standard ssh (e.g. putty or openssh) client and performs
 an ssh to a windows host

 The windows host would run a python script acting as ssh server.
 
 The Twisted library has an sshd implementation, called conch.  Here an
 article with a simple python sshd built with twisted:
 http://www.ibm.com/developerworks/linux/library/l-twist4.html


Thanks. I'll check whether twisted conch runs also under windows.
Yesterday I made the probably too fast conclusion, that twisted conch
exists only for liux as I could only find a twisted-conch tarball and
not a windows installer.

But probably twisted-conch is already part of the twisted installer for
windows.
I'll check it.


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


Re: sshd in python for windows 7

2010-02-07 Thread News123
Hi Jerry,

Jerry Hill wrote:
 On Sat, Feb 6, 2010 at 7:07 PM, News123 news...@free.fr wrote:
 Hi,

 I wondered which modules would be best to perform following task:

 A user uses a standard ssh (e.g. putty or openssh) client and performs
 an ssh to a windows host

 The windows host would run a python script acting as ssh server.
 
 The Twisted library has an sshd implementation, called conch.  Here an
 article with a simple python sshd built with twisted:
 http://www.ibm.com/developerworks/linux/library/l-twist4.html


THanks a look at it in moe detail.
Yesterday I made the probably wrong assumption, that twisted-conch
exists only for linux as I just found a twisted-conch tarball.

Probably however twisted-conch is already part of the twisted windows
installer package I'll check this.

N

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


Simulating logging.exception with another traceback

2010-02-07 Thread Joan Miller
I would want to get the output from `logging.exception` but with
traceback from the caller function (I've already all that
information).

This would be the error with logging.exception:

ERROR:
  PipeError('/bin/ls -l |  ', 'no command after of pipe')
Traceback (most recent call last):
  File /data/neo/Proyectos/Python/Scripy/lib/scripy/shell.py, line
160, in __call__
raise PipeError(command, 'no command after of pipe')
PipeError: ('/bin/ls -l |  ', 'no command after of pipe')


And I've trying it with:

message = File \{0}\, line {1}, in {2}\n\n  {3}.format(
file, line, function, caller)
logging.error(message)

ERROR:
  File /data/neo/Proyectos/Python/Scripy/lib/scripy/shell.py, line
  163, in __call__return self.throw(PipeError, command, 'no
  command after of pipe')


Could be used `logging.LogRecord` [1] to get it? How?


[1] http://docs.python.org/library/logging.html#logging.LogRecord
-- 
http://mail.python.org/mailman/listinfo/python-list


Dynamic variable names

2010-02-07 Thread R (Chandra) Chandrasekhar

Dear Folks,

I have read that one should use a dictionary in python to accommodate 
dynamic variable names. Yet, I am puzzled how to achieve that in my 
case. Here is what I want to do:


1. The user inputs a number of six-digit hex numbers as a 
comma-separated list. These numbers represent colours, but the number of 
colours is not known beforehand.


2. Using these colours in pairs, I am generating image files whose names 
must be unique. I could use the respective hex numbers for this, but 
would like to explore generating filenames like


colour_1-colour_2.jpg

Because I do not know how many colours there would be in advance, I need 
to generate the colour_n names on the fly.


So, my two questions are:

1. How do I do this properly in python?

2. If there is a better scheme than what I have outlined, can someone 
please point me to a Web link?


Thank you.

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


Re: python admin abuse complaint

2010-02-07 Thread Steve Holden
Aahz wrote:
 In article 
 0c535d15-967d-4909-a9bb-b59708181...@l24g2000prh.googlegroups.com,
 Xah Lee  xah...@gmail.com wrote:
 This is a short complaint on admin abuse on #python irc channel on
 freenode.net.
 
 Let's see, you are complaining about getting banned from #python by
 CROSS-POSTING between c.l.py and comp.lang.lisp.  From my POV, that's
 grounds for extending the IRC ban permanently.

It certainly doesn't inspire any confidence that Xah's next trip to
#python is likely to last much longer than the last.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Dreaming of new generation IDE

2010-02-07 Thread Steve Holden
bartc wrote:
 Arnaud Delobelle arno...@googlemail.com wrote in message
 news:m28wb6ypfs@googlemail.com...
 Gabriel Genellina gagsl-...@yahoo.com.ar writes:

 En Fri, 05 Feb 2010 19:22:39 -0300, bartc ba...@freeuk.com escribió:
 Steve Holden st...@holdenweb.com wrote in message
 news:mailman.1998.1265399766.28905.python-l...@python.org...
 Arnaud Delobelle wrote:
 Robert Kern robert.k...@gmail.com writes:

 I prefer Guido's formulation (which, naturally, I can't find a
 direct
 quote for right now): if you expect that a boolean argument is only
 going to take *literal* True or False, then it should be split into
  ^^^
 two functions.

 So rather than three boolean arguments, would you have eight
 functions?

 If there's genuinely a need for that functionality, yes.

 So you want a function such as drawtext(s, bold=true, italic=false,
 underline=true) to be split into:

 drawtext(s)
 drawtextb(s)
 drawtexti(s)
 drawtextu(s)
 drawtextbi(s)
 drawtextbu(s)
 drawtextiu(s)
 drawtextbiu(s)

 Note the *literal* part. If you (the programmer) is likely to know the
 parameter value when writing the code, then the function is actually two
 separate functions.

 Thanks, I understand what Steve Holden meant now.
 
 I've just noticed that 'literal' part. But I think I still disagree.
 
 For a real-world example, it means instead of having a room with a
 light-switch in it, if I *know* I want the light on or off, I should
 have two rooms: one with the light permanently on, and one with it
 permanently off, and just walk into the right one.
 
Congratulations.  That has to be the most bogus analogy I've seen on
c.l.py this year.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: TABS in the CPython C source code

2010-02-07 Thread Steve Holden
Nobody wrote:
 On Sat, 06 Feb 2010 21:31:52 +0100, Alf P. Steinbach wrote:
 
 The size-8 tabs look really bad in an editor configured with tab size 4,
 as is common in Windows. I'm concluding that the CPython programmers
 configure their Visual Studio's to *nix convention.
 
 8-column tabs aren't a *nix convention; that's been the norm since
 the mechanical typewriter.
 
Clearly written by someone who has never *used* a mechanical typewriter.
The original mechanisms had tab set and tab clear keys, so you had
variable tabbing according to the needs of the particular document you
were working on. Look under T in

  http://www.mytypewriter.com/explorelearn/glossary.html

if you aren't old enough to have used one.

 Historically, software and hardware which knows what a tab could be
 split into two categories:
 
 1. Tab stops are fixed at 8-column intervals.
 2. Tab stops default to 8-column intervals but can be changed.
 
 Recently, a third category has appeared (tab stops default to something
 other than 8 columns). The most common example is Visual Studio. No
 surprise there: Microsoft has a track record of introducing slight
 incompatibilities into established standards. Just enough to inconvenience
 anyone using competing products, but not so much that anyone operating
 in a context where Microsoft isn't dominant has to abandon Microsoft's
 product.
 
Consider instead that perhaps this one time Microsoft did it for the
convenience of the user (there has to be some reason why it's such a
wealthy company).

 Given that:
 
 1. 8-column tabs have been the standard for longer than most of us
 have been alive, let alone programming, and
 2. even if a particular text editor supports some other value, there is no
 way to communicate this fact to anything else which might read the code,
 
 the logical conclusion is that using anything other than 8 columns lies
 somewhere between silly and assuming the world revolves around you.
 

Which is what you appear to be doing with your fantasy about mechanical
typewriters.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: TABS in the CPython C source code

2010-02-07 Thread Steve Holden
Dennis Lee Bieber wrote:
 On Sun, 07 Feb 2010 05:49:28 +, Nobody nob...@nowhere.com
 declaimed the following in gmane.comp.python.general:
 
 
 8-column tabs aren't a *nix convention; that's been the norm since
 the mechanical typewriter.

   Really? None of the various Royal, Remington, and Olivetti (sp?)
 typewriters I learned on had any knowledge of default tab stops. All had
 a row of sliding pins on the carriage, which were slid back and forth
 by the tab set and tab clear button (which required one to first
 position the carriage at the position at which the stop was to be
 placed). The tab key itself functioned by first pushing a lever into
 the area covered by the stop-row (after the current position stop, if
 one existed), then releasing the carriage to slide until the next stop
 -- uhm -- stopped the motion by impacting the lever; releasing the tab
 key would then re-engage the normal carriage motion control, and
 withdraw the lever.
 
   8-space tab stops were, I believe, the default for various computer
 terminals, DECwriter printers, and maybe teletype units (in which there
 was no moving carriage on which a physical stop could be placed). Not
 sure how an 029 keypunch machine would behave -- either punching the
 code the a tab character, or skipping to the next field defined on a
 drum-card.
 
When I started my computing career the main input medium at the
installation I worked was paper tape, and the Flexowriter (pretty much a
mechanical typewriter mechanism with a tape reader and punch attached)
was the data preparation device (though teletypes were used at other
installations). So it had adjustable tab settings.

The 029 punch (and the 026 before it) used a punch card mounte on a drum
to set the tab stops, which were therefore completely variable - one
would use a different tab card for Fortran and PL/1, for example. So a
tab was purely a spacing operation, no chads were punched from the card,
and indeed I was never aware of an EBCDIC tab character code (which is
by no means to say that there isn't one - Wikipedia says The EBCDIC
code for HT is 5).

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new.instancemethod __iter__

2010-02-07 Thread Steve Holden
Martin Drautzburg wrote:
 Steven D'Aprano wrote:
 
 If you want iterator operations similar to itertools, why does this
 mean you need to replace anything? Just create your own iterators.

 Or use pre-processing and post-processing to get what you want.

 Can you show an example of what you would like to happen?
 
 Steven, 
 
 my classes repesent musical objects. The fundamental paradigm I want to
 apply is that of a Sequence, i.e. the most abstract aspect of music is
 that things occur in a certain order.
 
 Then I have a TimedSequence class, which is a Sequences whose elements
 have a time attribute. I now want to be able to append such Sequences
 by writing
 
 s1 = TimedSequence (time=1,'a') # one-element Sequence
 s2 = TimedSequence (time=2,'b')
 
 y = s1*2 + s2
 
 Naively appending those sequences would give me
 Time=1,'a'
 Time=1,'a'
 Time=2,'b'
 
 but this is not what I want. Time needs to progress if I append a
 sequence to another. So what I really want is something like
 
 Time=1,'a'
 Time=2,'a'
 Time=3,'b'
 
 This implies that time is shifted to the next integer, but this is not
 always the case. I need to know about some kind of alignment. In
 music this translates to let a sequence start at the beginning of a
 bar, or half bar or quarter note or whatever.
 
 So I want to write
 
 y = s1*2 + s2(align=10)
 
 which should iterate as
 
 Time=1,'a'
 Time=2,'a'
 Time=10,'b'
 
 I have no difficulty passing align to the object (using __call__) and
 use it while I furnish my own __iter__() method. However I don't quite
 see how I can do this with bare itertools, though I may be wrong here.
 
 Bare in mind that it is not only about somehow getting the job done. The
 beauty of the resulting syntax is also important.
 
In that case why not just assume that the timing of a sequence is
relative to the current time unless the align argument is given?

You might also need an event of zero duration to set the start time for
a sequence.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: python admin abuse complaint

2010-02-07 Thread Daniel Fetchinson
 This is a short complaint on admin abuse on #python irc channel on
 freenode.net.

 Let's see, you are complaining about getting banned from #python by
 CROSS-POSTING between c.l.py and comp.lang.lisp.  From my POV, that's
 grounds for extending the IRC ban permanently.

 It certainly doesn't inspire any confidence that Xah's next trip to
 #python is likely to last much longer than the last.

Some humanity, please! If you look at the web page of the guy it
really strikes me as a poor bastard who deserves more pity than
bashing. IRC, newsgroups, email, web page, etc, these are the only
things that this guy is doing, if you take these things away from him
I don't know what will be left for him. Yes, he is annoying, yes, he
is trolling, but if this prevents him from jumping under the bus, then
I'd say let him do it. How many serial trolls are there on c.l.p? Not
many. The average troll should of course be kicked out from
everywhere, but guys like Xah are really rare and on humanitarian
grounds I think should be allowed to do their things. If you really
think about it the damage is not that great.

In medieval times 99% of crazy people (using a loose definition of
crazy) were either executed or tortured and executed, however, the one
lonely village clown or court clown was allowed to be crazy, he even
had a decent income from the king. I'm not suggesting a stipend for
Xah from the PSF :) but having a single c.l.p clown is tolerable if it
makes him happy.

Cheers,
Daniel



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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread Steve Holden
hzh...@gmail.com wrote:
 So it seems we both misunderstood the problem.

 I didn't read the top level article until now, and reading it, I can't make
 sense of it.

 
 Seems that you should read the whole thing before making a post, or
 else you cannot know what we are talking about.
 Steven doesn't misunderstand me. We are talking about what I need, and
 he tries to help.
 
 
 
 Given the function hashlib.sha256, enumerate all the possible inputs
 that give the hexadecimal result
 0a2591aaf3340ad92faecbc5908e74d04b51ee5d2deee78f089f1607570e2e91.
 I tried some parrot variants but no dice. :-(

 [snip]

 
 This is a hash collision problem. Nobody has proved that SHA-256 is
 collision free, even not in the random oracle model, because people
 always suppose that a random oracle exists, and make hash function its
 substitution. That means it may be broken someday. And any provable
 security based on random oracle model is not secure.
 
It's very easy to prove that no hash function is collision-free, since
the domain (all possible inputs) is much larger than the range (all
possible outputs). Hence there must be many inputs that map to the same
output.

A *good* hash function is unpredictable enough to make finding two
colliding strings impractical - and even the best hash functions that
cryptographers could devise at the time have been broken. We should
remember that broken to a cryptographer means something rather
different than it does in common usage, so a broken scheme need not
necessarily be dropped immediately - one would just stop using it in new
systems.

 
 I'm suggesting that, in general, there's no way to tell in advance which
 regexes will be easy and which will be hard, and even when they are easy,
 the enumeration will often be infinite.
 
 It is hard to tell in advance. However, we can add some timing limit
 or counting limit, to make it an algorithm, which can halt. For
 example, whenever the program outputs more than 100 expressions
 that match the input regex, we can halt because that exceeds our
 limit. But surely this is not efficient because of the post-decision.
 
 Essentially, any regexp that includes '+' or '*' (directly or via e.g. 
 notation
 that denotes digit sequence) yields an infinite number of strings.
 
 Infinity is really relative, not absolute. It is relative to the
 computing speed. For example, the regex '^[0|1]{2048}$' is rather
 simple and doesn't contain '+' or '$', but trying to output all
 expressions that match it has a complexity of 2^2048. If we can do
 that, then we can break RSA-2048.
 We must face the reality .
 
I have always understood that there's a pretty real distinction between
finite and infinite. Are you telling me I am wrong, or are you
merely saying that some finite cases might just as well be infinite for
practical purposes?

And I really don't see how simple enumeration of range(2^2048) breaks
RSA-2048, since that problem requires you to find two factors which,
when multiplied together, give that specific value.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Tim Chase

Schif Schaf wrote:

On Feb 7, 12:19 am, Alf P. Steinbach al...@start.no wrote:

I haven't used regexps in Python before, but what I did was (1) look in the
documentation,

[snip]

code
import re

text = (
 Lorem [ipsum] dolor sit amet, consectetur,
 adipisicing elit, sed do eiusmod tempor,
 incididunt ut [labore] et [dolore] magna aliqua.
 )

withbracks = re.compile( r'\[(.+?)\]' )
for line in text:
 print( re.sub( withbracks, r'{\1}', line) )
/code


Seems like there's magic happening here. There's the `withbracks`
regex that applies itself to `line`. But then when `re.sub()` does the
replacement operation, it appears to consult the `withbracks` regex on
the most recent match it just had.


I suspect Alf's rustiness with regexps caused him to miss the 
simpler rendition of


  print withbacks.sub(r'{\1}', line)

And to answer those who are reaching for other non-regex (whether 
string translations or .replace(), or pyparsing) solutions, it 
depends on what you want to happen in pathological cases like


  s = Dangling closing]
 with properly [[nested]] and
 complex [properly [nested] text]
 and [improperly [nested] text
 and with some text [straddling
 lines] and with
 dangling opening [brackets
 
where you'll begin to see the differences.

-tkc




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


Re: python admin abuse complaint

2010-02-07 Thread Shashwat Anand
LOL
pow(funny, sys.maxint)

On Sun, Feb 7, 2010 at 6:27 PM, Daniel Fetchinson fetchin...@googlemail.com
 wrote:

  This is a short complaint on admin abuse on #python irc channel on
  freenode.net.
 
  Let's see, you are complaining about getting banned from #python by
  CROSS-POSTING between c.l.py and comp.lang.lisp.  From my POV, that's
  grounds for extending the IRC ban permanently.
 
  It certainly doesn't inspire any confidence that Xah's next trip to
  #python is likely to last much longer than the last.

 Some humanity, please! If you look at the web page of the guy it
 really strikes me as a poor bastard who deserves more pity than
 bashing. IRC, newsgroups, email, web page, etc, these are the only
 things that this guy is doing, if you take these things away from him
 I don't know what will be left for him. Yes, he is annoying, yes, he
 is trolling, but if this prevents him from jumping under the bus, then
 I'd say let him do it. How many serial trolls are there on c.l.p? Not
 many. The average troll should of course be kicked out from
 everywhere, but guys like Xah are really rare and on humanitarian
 grounds I think should be allowed to do their things. If you really
 think about it the damage is not that great.

 In medieval times 99% of crazy people (using a loose definition of
 crazy) were either executed or tortured and executed, however, the one
 lonely village clown or court clown was allowed to be crazy, he even
 had a decent income from the king. I'm not suggesting a stipend for
 Xah from the PSF :) but having a single c.l.p clown is tolerable if it
 makes him happy.

 Cheers,
 Daniel



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

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


Re: max / min / smallest float value on Python 2.5

2010-02-07 Thread Steve Holden
duncan smith wrote:
 Christian Heimes wrote:
 duncan smith wrote:
 Hello,
I'm trying to find a clean and reliable way of uncovering
 information about 'extremal' values for floats on versions of Python
 earlier than 2.6 (just 2.5 actually).  I don't want to add a
 dependence on 3rd party modules just for this purpose.  e.g. For the
 smallest positive float I'm using,


 import platform
 if platform.architecture()[0].startswith('64'):
  TINY = 2.2250738585072014e-308
 else:
  TINY = 1.1754943508222875e-38


 where I've extracted the values for TINY from numpy in IDLE,


   float(numpy.finfo(numpy.float32).tiny)
 1.1754943508222875e-38
   float(numpy.finfo(numpy.float64).tiny)
 2.2250738585072014e-308

 You are confusing a 32 / 64bit build with 32 / 64bit floats. Python's
 float type is build upon C's double precision float type on both 32 and
 64 bit builds. The simple precision 32bit float type isn't used. The
 DBL_MIN and DBL_MAX values are equal on all platforms that have full
 IEEE 754 float point support. The radix may be different, though.

 Christian
 
 OK, this is the sort of confusion I suspected.  I wasn't thinking
 straight.  The precise issue is that I'm supplying a default value of
 2.2250738585072014e-308 for a parameter (finishing temperature for a
 simulated annealing algorithm) in an application.  I develop on
 Ubuntu64, but (I am told) it's too small a value when run on a Win32
 server.  I assume it's being interpreted as zero and raising an
 exception.  Thanks.
 
Whether this is relevant or not I can't say, but you must be careful to
note that the smallest representable floating-point value (i.e. the
smallest number distinguishable from zero) is not the same as the
smallest difference between two numbers of a given magnitude.

Consider a decimal floating-point system with a two-digit exponent and a
four-digit mantissa, and for convenience ignore negative mantissas. The
range of representable non-zero values runs from 1E-99 to E99. But
adding 1E-99 to (say) 1 will just give you 1 because the system has
insufficient precision to represent the true result.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Steve Holden
@ Rocteur CC wrote:
 
 On 07 Feb 2010, at 10:03, Shashwat Anand wrote:
 
 Here is one simple solution :
  intext = Lorem [ipsum] dolor sit amet, consectetur adipisicing
 elit, sed do eiusmod tempor  incididunt ut [labore] et [dolore] magna
 aliqua.

  intext.replace('[', '{').replace(']',
 '}')  
 'Lorem {ipsum} dolor sit amet, consectetur adipisicing elit, sed do
 eiusmod tempor  incididunt ut {labore} et {dolore} magna aliqua.'

 /Some people, when confronted with a problem, think I know, I’ll use
 regular expressions. Now they have two problems./ — Jamie Zawinski
 ttp://jwz.livejournal.com in comp.lang.emacs.
 
 That is because regular expressions are what we learned in programming
 the shell from sed to awk and ksh and zsh and of course Perl and we've
 read the two books by Jeffrey and much much more!!!
 
 How do we rethink and relearn how we do things and should we ?
 
 What is the solution ?
 
A rigorous focus on programming simplicity.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: python admin abuse complaint

2010-02-07 Thread Daniel Fetchinson
 LOL

assert funny  1

 pow(funny, sys.maxint)


  This is a short complaint on admin abuse on #python irc channel on
  freenode.net.
 
  Let's see, you are complaining about getting banned from #python by
  CROSS-POSTING between c.l.py and comp.lang.lisp.  From my POV, that's
  grounds for extending the IRC ban permanently.
 
  It certainly doesn't inspire any confidence that Xah's next trip to
  #python is likely to last much longer than the last.

 Some humanity, please! If you look at the web page of the guy it
 really strikes me as a poor bastard who deserves more pity than
 bashing. IRC, newsgroups, email, web page, etc, these are the only
 things that this guy is doing, if you take these things away from him
 I don't know what will be left for him. Yes, he is annoying, yes, he
 is trolling, but if this prevents him from jumping under the bus, then
 I'd say let him do it. How many serial trolls are there on c.l.p? Not
 many. The average troll should of course be kicked out from
 everywhere, but guys like Xah are really rare and on humanitarian
 grounds I think should be allowed to do their things. If you really
 think about it the damage is not that great.

 In medieval times 99% of crazy people (using a loose definition of
 crazy) were either executed or tortured and executed, however, the one
 lonely village clown or court clown was allowed to be crazy, he even
 had a decent income from the king. I'm not suggesting a stipend for
 Xah from the PSF :) but having a single c.l.p clown is tolerable if it
 makes him happy.

 Cheers,
 Daniel



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




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


Re: Dynamic variable names

2010-02-07 Thread Steve Holden
R (Chandra) Chandrasekhar wrote:
 Dear Folks,
 
 I have read that one should use a dictionary in python to accommodate
 dynamic variable names. Yet, I am puzzled how to achieve that in my
 case. Here is what I want to do:
 
 1. The user inputs a number of six-digit hex numbers as a
 comma-separated list. These numbers represent colours, but the number of
 colours is not known beforehand.
 
 2. Using these colours in pairs, I am generating image files whose names
 must be unique. I could use the respective hex numbers for this, but
 would like to explore generating filenames like
 
 colour_1-colour_2.jpg
 
 Because I do not know how many colours there would be in advance, I need
 to generate the colour_n names on the fly.
 
 So, my two questions are:
 
 1. How do I do this properly in python?
 
 2. If there is a better scheme than what I have outlined, can someone
 please point me to a Web link?
 
Here's one way, though not necessarily the best:

 import itertools
 ctr = itertools.count(1)
 for i in range(5):
...   print colour_%03d-colour%03d.jpg % (ctr.next(), ctr.next())
...
colour_001-colour002.jpg
colour_003-colour004.jpg
colour_005-colour006.jpg
colour_007-colour008.jpg
colour_009-colour010.jpg


I zero-filled the names so they sort in numerical order. If this isn't a
requirement then simply change the format string to

colour_%d-colour%d.jpg

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Anssi Saari
Schif Schaf schifsc...@gmail.com writes:

 (brackets replaced by braces). I can do that with Perl pretty easily:

 
 for () {
 s/\[(.+?)\]/\{$1\}/g;
 print;
 }
 

Just curious, but since this is just transpose, then why not simply
tr/[]/{}/? I.e. why use a regular expression at all for this?

In python you would do this with 

for line in text: 
 print line.replace('[', '{').replace(']', '}')

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


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Steve Holden
Tim Chase wrote:
 Schif Schaf wrote:
 On Feb 7, 12:19 am, Alf P. Steinbach al...@start.no wrote:
 I haven't used regexps in Python before, but what I did was (1) look
 in the
 documentation,
 [snip]
 code
 import re

 text = (
  Lorem [ipsum] dolor sit amet, consectetur,
  adipisicing elit, sed do eiusmod tempor,
  incididunt ut [labore] et [dolore] magna aliqua.
  )

 withbracks = re.compile( r'\[(.+?)\]' )
 for line in text:
  print( re.sub( withbracks, r'{\1}', line) )
 /code

 Seems like there's magic happening here. There's the `withbracks`
 regex that applies itself to `line`. But then when `re.sub()` does the
 replacement operation, it appears to consult the `withbracks` regex on
 the most recent match it just had.
 
 I suspect Alf's rustiness with regexps caused him to miss the simpler
 rendition of
 
   print withbacks.sub(r'{\1}', line)
 
 And to answer those who are reaching for other non-regex (whether string
 translations or .replace(), or pyparsing) solutions, it depends on what
 you want to happen in pathological cases like
 
   s = Dangling closing]
  with properly [[nested]] and
  complex [properly [nested] text]
  and [improperly [nested] text
  and with some text [straddling
  lines] and with
  dangling opening [brackets
  
 where you'll begin to see the differences.
 
Really? Under what circumstances does a simple one-for-one character
replacement operation fail?

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python admin abuse complaint

2010-02-07 Thread Steve Holden
Shashwat Anand wrote:
 LOL
 pow(funny, sys.maxint)
 
Yes, funny, but it overlooks the point that Xah is a nuisance to
multiple communities, not just to ours, and quite often concurrently.

I'm all in favor of tolerance, but I'd like to see some evidence that
rehabilitation is practical before the community has to tolerate too
much of that kind of nonsense.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread Tim Chase

hzh...@gmail.com wrote:

Given the function hashlib.sha256, enumerate all the possible inputs
that give the hexadecimal result
0a2591aaf3340ad92faecbc5908e74d04b51ee5d2deee78f089f1607570e2e91.


This is a hash collision problem. Nobody has proved that SHA-256 is
collision free


It's actually pretty easy to prove that it is *not* collision 
free.  The SHA-256 encodes 512 bits of data.  So the the process 
of encoding (2**512)+1 distinct inputs incurs a collision in 
SHA-256 space as soon as you've hit (2**512)+1 if not earlier.


to start you off:

  sha_backmap = {}
  for i in xrange((2**512)+2):
hash = sha(str(i))
if hash in sha_backmap:
  print Collision found: %i and %i % (
i, sha_backmap[hash])
break
sha_backmap[hash] = i

Though it might take a computer the size of the universe, so I'm 
guessing that the first collision encountered is with 42.  I 
leave the actual calculation and hashing of all possible 
combinations of 513 bits of data as an exercise to the reader 
with a lot of time on their hands or a quantum computer under 
their desk ;-)



It is hard to tell in advance. However, we can add some timing limit
or counting limit, to make it an algorithm, which can halt. For
example, whenever the program outputs more than 100 expressions
that match the input regex, we can halt because that exceeds our
limit. But surely this is not efficient because of the post-decision.


As mentioned, it sounds like you either want a depth-first of the 
solution space that raises exceptions on an infinite/unbounded 
operator (*, +, and {N,} as mentioned in another email), or 
if you want to handle those operators, do a breadth-first search 
of the solution-space and track your depth (or time taken, or 
previous number of multi-factor atoms if you desire) to ensure 
you don't exceed a certain depth.  But you're still talking a 
combinatorial number of solutions for even simple regexps.


-tkc


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


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Tim Chase

Steve Holden wrote:

Tim Chase wrote:

And to answer those who are reaching for other non-regex (whether string
translations or .replace(), or pyparsing) solutions, it depends on what
you want to happen in pathological cases like

  s = Dangling closing]
 with properly [[nested]] and
 complex [properly [nested] text]
 and [improperly [nested] text
 and with some text [straddling
 lines] and with
 dangling opening [brackets
 
where you'll begin to see the differences.


Really? Under what circumstances does a simple one-for-one character
replacement operation fail?


Failure is only defined in the clarified context of what the OP 
wants :)  Replacement operations only fail if the OP's desired 
output from the above mess doesn't change *all* of the ]/[ 
characters, but only those with some form of parity (nested or 
otherwise).  But if the OP *does* want all of the ]/[ characters 
replaced regardless of contextual nature, then yes, replace is a 
much better solution than regexps.


-tkc


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


Re: python admin abuse complaint

2010-02-07 Thread Daniel Fetchinson
 LOL
 pow(funny, sys.maxint)

 Yes, funny, but it overlooks the point that Xah is a nuisance to
 multiple communities, not just to ours, and quite often concurrently.

I don't think we need to worry about other communities or every
internet related problem. The only thing we need to make sure is that
c.l.p or the python community in general is friendly, tolerant,
healthy and perhaps shows a good example to other communities on how
to run a community, including how to handle problematic behavior.

 I'm all in favor of tolerance, but I'd like to see some evidence that
 rehabilitation is practical before the community has to tolerate too
 much of that kind of nonsense.

I don't think you get my point. Rehabilitation or cure is not the goal
here. A village clown or court clown never changed, never got cured,
never got reintroduced into the community as a 'normal' person. A
village clown is tolerated in the purest form of the word 'tolerance'
by nor wishing him to change. Let him be the clown, let everybody
accept him as such, including all the annoyance and weird behavior.
Hoping for someone to change is the same as assigning him to a
correctional facility.

I'd say let's designate a post Python Community Jester, or PCJ for
short, let's name Xah Lee the PCJ and make it clear that he can engage
in his activities on c.l.p and #python as he wishes without
retribution and fear, and nobody should really bother him. The only
people should do who don't like him is ignoring him. What is very
important is that there can be only one PCJ and everybody else with
objectionable behavior will be banned, blacklisted, etc. with the full
force of available methods.

This would I think send a very clear message to all other online
communities that the Python Community is able to think outside the
box, and is not afraid of taking unusual steps to maintain a healthy
community and is even able to incorporate revolutionary new tactics to
keep the community friendly and tolerant.

Cheers,
Daniel


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


Re: python admin abuse complaint

2010-02-07 Thread Daniel Fetchinson
 LOL
 pow(funny, sys.maxint)

 Yes, funny, but it overlooks the point that Xah is a nuisance to
 multiple communities, not just to ours, and quite often concurrently.

 I don't think we need to worry about other communities or every
 internet related problem. The only thing we need to make sure is that
 c.l.p or the python community in general is friendly, tolerant,
 healthy and perhaps shows a good example to other communities on how
 to run a community, including how to handle problematic behavior.

 I'm all in favor of tolerance, but I'd like to see some evidence that
 rehabilitation is practical before the community has to tolerate too
 much of that kind of nonsense.

 I don't think you get my point. Rehabilitation or cure is not the goal
 here. A village clown or court clown never changed, never got cured,
 never got reintroduced into the community as a 'normal' person. A
 village clown is tolerated in the purest form of the word 'tolerance'
 by nor wishing him to change. Let him be the clown, let everybody
 accept him as such, including all the annoyance and weird behavior.
 Hoping for someone to change is the same as assigning him to a
 correctional facility.

 I'd say let's designate a post Python Community Jester, or PCJ for
 short, let's name Xah Lee the PCJ and make it clear that he can engage
 in his activities on c.l.p and #python as he wishes without
 retribution and fear, and nobody should really bother him. The only
 people should do who don't like him is ignoring him. What is very
 important is that there can be only one PCJ and everybody else with
 objectionable behavior will be banned, blacklisted, etc. with the full
 force of available methods.

 This would I think send a very clear message to all other online
 communities that the Python Community is able to think outside the
 box, and is not afraid of taking unusual steps to maintain a healthy
 community and is even able to incorporate revolutionary new tactics to
 keep the community friendly and tolerant.

One more thing: if every online community (or only  programming
related newsgroup) would designate an XY Community Jester I believe
the relatively few number of serial trolls would all find their places
somewhere eventually. This approach would actually work and solve a
serious problem, as opposed to building more jails and more
correctional facilities.

Cheers,
Daniel



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


Re: merge stdin, stdout?

2010-02-07 Thread Anssi Saari
jonny lowe jonny.lowe.12...@gmail.com writes:

 The result is the same as before. I've tested in fedora11.

I don't think script is the answer here, since it only stores what's
displayed on a terminal and your program's input comes from a file and
is not displayed on the terminal.

Simplest solution is probably that you have your program echo every
line of input. Maybe some hairy terminal trickery could be done?
Really more of a Linux question than python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python admin abuse complaint

2010-02-07 Thread D'Arcy J.M. Cain
On Sun, 7 Feb 2010 15:11:41 +0100
Daniel Fetchinson fetchin...@googlemail.com wrote:
 I'd say let's designate a post Python Community Jester, or PCJ for
 short, let's name Xah Lee the PCJ and make it clear that he can engage
 in his activities on c.l.p and #python as he wishes without
 retribution and fear, and nobody should really bother him. The only

Are you sure you aren't lobbying for the position for yourself?  I
think you have a shot based on this proposal.

-- 
D'Arcy J.M. Cain da...@druid.net |  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: new.instancemethod __iter__

2010-02-07 Thread Martin Drautzburg
Steve Holden wrote:


 y = s1*2 + s2(align=10)
 
 which should iterate as
 
 Time=1,'a'
 Time=2,'a'
 Time=10,'b'
 
 I have no difficulty passing align to the object (using __call__)
 and use it while I furnish my own __iter__() method. However I don't
 quite see how I can do this with bare itertools, though I may be
 wrong here.
 
 Bare in mind that it is not only about somehow getting the job done.
 The beauty of the resulting syntax is also important.
 
 In that case why not just assume that the timing of a sequence is
 relative to the current time unless the align argument is given?

Well that's pretty much what I'm doing. I just fail to see how I can do
this with bare itertools. Currently I am doing it in the following way:

When I call a Sequence as in s2(align=2) I create a new Sequence where
the align value is simply stored in an instance variable. 

When creating the sum of two sequences, I create a Sequence with a new
iter() method which first iterates over self and then over the second
Sequence. But each time it has to look up the align value of the
respective sequence and adjust time accordingly. 

Appending the two Sequences is the easy part, but adjusting time is the
difficult part. My impression was, that itertools can only help to
solve the first part.

I may be missing something obvious. If that's the case, please let me
know.






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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread hzh...@gmail.com


 And I really don't see how simple enumeration of range(2^2048) breaks
 RSA-2048, since that problem requires you to find two factors which,
 when multiplied together, give that specific value.


I can tell you why is that. RSA-2048 has a composite of length less
than 2^2048, which is a product of two large primes. So one of its
factors cannot exceed 2^2047, and we can treat the multiplication as a
computation with constant complexity. So the time complexity of
enumerating 2^2048 strings is the same with factoring a composite with
length 2^2048 which is the product of two primes.

And obviously, whenever we successfully factor the composite, we can
calculate the Euler function of it. So that given any public key
(n,e), calculating the private key (n,d) is easy.

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


Re: new.instancemethod __iter__

2010-02-07 Thread Steve Holden
Martin Drautzburg wrote:
 Steve Holden wrote:
 
 
 y = s1*2 + s2(align=10)

 which should iterate as

 Time=1,'a'
 Time=2,'a'
 Time=10,'b'

 I have no difficulty passing align to the object (using __call__)
 and use it while I furnish my own __iter__() method. However I don't
 quite see how I can do this with bare itertools, though I may be
 wrong here.

 Bare in mind that it is not only about somehow getting the job done.
 The beauty of the resulting syntax is also important.

 In that case why not just assume that the timing of a sequence is
 relative to the current time unless the align argument is given?
 
 Well that's pretty much what I'm doing. I just fail to see how I can do
 this with bare itertools. Currently I am doing it in the following way:
 
 When I call a Sequence as in s2(align=2) I create a new Sequence where
 the align value is simply stored in an instance variable. 
 
 When creating the sum of two sequences, I create a Sequence with a new
 iter() method which first iterates over self and then over the second
 Sequence. But each time it has to look up the align value of the
 respective sequence and adjust time accordingly. 
 
 Appending the two Sequences is the easy part, but adjusting time is the
 difficult part. My impression was, that itertools can only help to
 solve the first part.
 
 I may be missing something obvious. If that's the case, please let me
 know.
 
Perhaps I am assuming too much of your simulation environment/player.

I presumed that there would be a global current time value that would
be passed into or available to the play method of the sequences. However
I can see that you might need something more complex if (e.g.) you want
to be able to start playing at an arbitrary point in time.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


still having problems with Nim. using python 2.6.4

2010-02-07 Thread Jordan Uchima
I have attached the file that the game is on. feel free to modify it to make
it better. all suggestions are welcome. if you don't want to download the
file then here's the code:

-
# Start with thirteen pieces and two players.
# Each player takes 1 - 4 pieces each turn.
# Player who takes the last piece loses.


# Declare constants.
NUMBER_OF_PLAYERS = 2
TOTAL_PIECES_AT_START = 13
namePlayer1 = raw_input(Hello Player 1, what is your name?\n)
namePlayer2 = raw_input(Hello Player 2, what is your name?\n)
# Declare functions.

def rules():
Print the rules of the game.
print 'The player that takes the last piece loses!'\
  'You can only take 1 - 4 pieces!\n\n'

def get_players():
Get the names of the players.
# Let's put the player's names in a list.
players = []
# Looping like this saves us repeating lines of code for each player.
for player in range(NUMBER_OF_PLAYERS):

players.append(player)
break
return players

def take_turn(player):
Handle a player's turn.
# Turn logic goes here.

player1Choice = int(raw_input(namePlayer1 +  how many pieces would you like
to take?\n)),
player2Choice = int(raw_input(namePlayer2 +  how many pieces would you like
to take?\n))
playerChoice = player1Choice and player2Choice
x = 13 - playerChoice
loss = x =2 and x = 0,
while player1Choice == loss is True:
print namePlayer1 +  loses!
while player2Choice == loss is True:
print namePlayer2, loss
while player1Choice and player2Choice == loss is True:
print It's a draw!
while player1Choice != loss is True:
print x
while player2Choice != loss is True:
print x
while player1Choice and player2Choice != loss is True:
print (Keep going! Only , x,  pieces left!)
validChoice = \
player1Choice == range(1, 4) is True,
print x
player1Choice == range(1, 4) is False,
print validChoice
player2Choice == range(1, 4) is True,
print x
player2Choice == range(1, 4) is False,
print validChoice


def main():
Run the game.
# Display the rules by calling rules function.
rules()
# Get the players by calling the get_players function.
players = get_players()
# Set up the game.
remaining_pieces = TOTAL_PIECES_AT_START
playing = True
# Main loop - let's play!
while playing:
# Take turns.
for player in players:
remaining_pieces = take_turn(player)
# Check if this player has lost.
if remaining_pieces = 1:
# Player has taken last piece.
print 'Sorry ', loser, ' you have lost.'
# Break out of the loop
playing = False
break


# Automatically run main function if we're run as a script.
if __name__ == '__main__':
main()

# End.


my problem is that i can't get it to make the players have more than 1 turn
each, it accepts any value for playerChoice, (it is only supposed to accept
values from 1 to 4), and x resets after each turn. i can get it to
subtract playerChoice from x, and display the result, which should be x,
but, then, x resets... by the way, i need this program finished by
wednesday, Feb.  10, 2010. Please help me!!!


--

Jordan (fuzzy.666.ch...@gmail.com)


Nim.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to print all expressions that match a regular expression

2010-02-07 Thread Steve Holden
hzh...@gmail.com wrote:
 And I really don't see how simple enumeration of range(2^2048) breaks
 RSA-2048, since that problem requires you to find two factors which,
 when multiplied together, give that specific value.

 
 I can tell you why is that. RSA-2048 has a composite of length less
 than 2^2048, which is a product of two large primes. So one of its
 factors cannot exceed 2^2047, and we can treat the multiplication as a
 computation with constant complexity. So the time complexity of
 enumerating 2^2048 strings is the same with factoring a composite with
 length 2^2048 which is the product of two primes.
 
 And obviously, whenever we successfully factor the composite, we can
 calculate the Euler function of it. So that given any public key
 (n,e), calculating the private key (n,d) is easy.
 
So all I have to do to break RSA is to count to 2^2048?

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: still having problems with Nim. using python 2.6.4

2010-02-07 Thread Steve Holden
Jordan Uchima wrote:
 I have attached the file that the game is on. feel free to modify it to
 make it better. all suggestions are welcome. if you don't want to
 download the file then here's the code:
 
[...]
 
 my problem is that i can't get it to make the players have more than 1
 turn each, it accepts any value for playerChoice, (it is only supposed
 to accept values from 1 to 4), and x resets after each turn. i can get
 it to subtract playerChoice from x, and display the result, which
 should be x, but, then, x resets... by the way, i need this program
 finished by wednesday, Feb.  10, 2010. Please help me!!!
 
The deadline implies an even higher probability that this is homework. I
don't know whether you declared this in your earlier post, but it's
always as well to do so. You've made a substantial effort to solve the
problem though, so I don't mind trying to help. I hope you regard the
following as helpful.

You need a program structure that keeps going until the required
termination condition is reached. One such structure would be:

while sticks_remaining  1:
taketurn(next_player())

So now you only need a next_player() function that returns alternate
values on successive calls and a taketurn() function that reduces the
number of sticks according to the instructions form the given player.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading+popen2 hang

2010-02-07 Thread Aahz
In article 188bfb67-3334-4325-adfc-3fa4d28f0...@d27g2000yqn.googlegroups.com,
lofic  louis.coill...@gmail.com wrote:

Works fine on RHEL5/python 2.4.3
Hangs on RHEL4/python 2.3.4

Then use Python 2.4 -- surely you don't expect anyone to provide bugfixes
for a release that's several years old?
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

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


Re: passing string for editing in input()

2010-02-07 Thread Aahz
In article mailman.1787.1265117353.28905.python-l...@python.org,
Chris Rebert  c...@rebertia.com wrote:
On Tue, Feb 2, 2010 at 5:24 AM, mk mrk...@gmail.com wrote:

 Is there an easy way to get an editing (readline) in Python that would
 contain string for editing and would not just be empty?

 I googled but found nothing.

Er...: http://docs.python.org/library/readline.html
It's the third hit for python readline.

Actually reading the page, sounds like you want readline.insert_text()
specifically.

That seems a tad harsh, especially after reading the docs and following
Peter Otten's link.  It's not at all obvious how to actually use
insert_text(), and although I probably could have figured it out on my
own, I might well have posted here myself.  Did you try using
insert_text() before posting?
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

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


Re: Your impression of for-novice writings on assertions

2010-02-07 Thread David

Hi Alf,

I think you talk too much... :-) Basically I am all for a verbose 
approach in a text for beginners, but on the other hand it is necessary 
to stick to the point you are making.
When, for example, you introduce your reader to the thoughts of Francis 
Glassborrow on page 5 of chapter three, then the only relevant point you 
are making is the following: Many programmers hide the structure of 
their code behind their comments [which is to be avoided]. If you 
insist on a proper citation here, then use a footnote, but even there I 
would suggest you merely offer the link. As it stands you are not to the 
point, and frankly, as a beginner I have enough stuff troubling my head 
so that I do not need superfluous information as to the evolution of the 
things you are talking about. Just the facts, please.


My 2 cents,

David



On 03/02/10 04:54, Alf P. Steinbach wrote:

I've started on ch 3 of my beginner's intro to programming, now delving
into the details of the Python language.

It's just a few pages yet, file [03 asd.pdf] (no real title yet!) at
url: http://tinyurl.com/programmingbookP3 which is at Google Docs.

The first topic is about assertions and exceptions. I wonder whether
this text is easy or difficult to understand for a beginner. Or any
improvements that could be made.


Cheers,

- Alf


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


Re: TABS in the CPython C source code

2010-02-07 Thread Terry Reedy

On 2/7/2010 7:39 AM, Steve Holden wrote:


Clearly written by someone who has never *used* a mechanical typewriter.
The original mechanisms had tab set and tab clear keys, so you had
variable tabbing according to the needs of the particular document you
were working on. Look under T in

   http://www.mytypewriter.com/explorelearn/glossary.html

if you aren't old enough to have used one.


I did start with real typewriters. The 'standard', if anything, was 1/2 
for paragraph indents. That was 5 chars with normal 10 cpi type, 6 with 
12 cpi 'elite' type. I used both. I always thought the 8 char unix 
indent to be excessive. If a power of 2 was needed, rounding 5 down to 4 
would have been more sensible.


Wordperfect, which I wrote a couple of books with, followed the 
typewriter model in defaulting tab stops to every 1/2 inch, regardless 
of font. Sensible software tab defaults were not pioneered by Microsoft.


Terry Jan Reedy

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


Re: WCK and PIL

2010-02-07 Thread darnzen
On Feb 6, 10:19 pm, Nobody nob...@nowhere.com wrote:
 On Fri, 05 Feb 2010 21:05:53 -0800, darnzen wrote:
  I've written an app using thewcklibrary (widget construction kit,
  seehttp://www.effbot.org), in addition to the wckGraph module. What
  I'd like to do, is take the output of one of my windows (happens to be
  a graph), and save it as a *.png or *.gif. I was planning on using the
 PILfor this. I'd like to use the code I have as is, without re-
  writing all the graphic calls to usePILmethods.

 WCKuses its own pixmap class for storing images in memory. I can't
  find any documentation or class reference for pixmap and what I find
  in the source is confusing.

 AWCKpixmap is a draw object whose underlying drawable is a pixmap
 (i.e. a Tk pixmap, which is the platform's native chunk of video memory
 pixmap type) rather than a window.

 From the source code,WCKdoesn't appear to offer any way to retrieve the
 pixel data (i.e. there's no way to do the opposite of draw.paste()).

I found a description of how to use a WCK drawing interface to draw
into a PIL image. (http://effbot.org/zone/pil-draw-wck.htm) but I'm
not sure how to use that class (SimpleDraw) to allow me to use
existing WCK code. Should I use it as a mix in to overwrite base
methods via inheritance?

class MyClass(SimpleDraw, Widget):
 pass

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


Checking the coding style

2010-02-07 Thread Pablo Recio Quijano
Hi!

I'm finishing a project writen in Python, and I realize about the document
PEP8 - Style Guide for Python Code [1].

Is there any app or script that checks if my project pass that style guide?
I also worked with Drupal, and I know there is some modules and scripts that
checks its coding standars [2] and it's very usefull to clean the code.

Thanks in advance!

[1] http://www.python.org/dev/peps/pep-0008/
[2] http://drupal.org/coding-standards

-- 
Pablo Recio Quijano

Estudiante de Ingeniería Informática (UCA)
Alumno colaborador del Departamento de Lenguajes y Sistemas Informáticos
Participante del IV Concurso Universitario de Software Libre
-- 
http://mail.python.org/mailman/listinfo/python-list


Executing Commands From Windows Service

2010-02-07 Thread T
I have a script, which runs as a Windows service under the LocalSystem
account, that I wish to have execute some commands.  Specifically, the
program will call plink.exe to create a reverse SSH tunnel.  Right now
I'm using subprocess.Popen to do so.  When I run it interactively via
an admin account, all is well.  However, when I'm running it via
service, no luck.  I'm assuming this is to do with the fact that it's
trying to run under the LocalSystem account, which is failing.  What
would be the best way around this?  Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking the coding style

2010-02-07 Thread Gerald Britton
pylint and pychecker are good options

On Sun, Feb 7, 2010 at 1:36 PM, Pablo Recio Quijano
rikuthero...@gmail.com wrote:
 Hi!
 I'm finishing a project writen in Python, and I realize about the document
 PEP8 - Style Guide for Python Code [1].
 Is there any app or script that checks if my project pass that style guide?
 I also worked with Drupal, and I know there is some modules and scripts that
 checks its coding standars [2] and it's very usefull to clean the code.
 Thanks in advance!
 [1] http://www.python.org/dev/peps/pep-0008/
 [2] http://drupal.org/coding-standards

 --
 Pablo Recio Quijano

 Estudiante de Ingeniería Informática (UCA)
 Alumno colaborador del Departamento de Lenguajes y Sistemas Informáticos
 Participante del IV Concurso Universitario de Software Libre

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





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


Re: Executing Commands From Windows Service

2010-02-07 Thread Stephen Hansen
On Sun, Feb 7, 2010 at 11:02 AM, T misceveryth...@gmail.com wrote:

 I have a script, which runs as a Windows service under the LocalSystem
 account, that I wish to have execute some commands.  Specifically, the
 program will call plink.exe to create a reverse SSH tunnel.  Right now
 I'm using subprocess.Popen to do so.  When I run it interactively via
 an admin account, all is well.  However, when I'm running it via
 service, no luck.  I'm assuming this is to do with the fact that it's
 trying to run under the LocalSystem account, which is failing.  What
 would be the best way around this?  Thanks!


I don't know what your specific issue is, but here's some tips for running
Python as a service on windows which are not always immediately obvious and
can cause failures:

- The search path is screwy: if you are importing a module that happens to
be the same name as a dll in system32 (even if this isn't at all a python
dll), it can get confused.
- There is *no* sys.stdout! This is a big one. If any piece of code you're
using ever does 'print', the whole thing can crash hard. I replace
sys.stdout and sys.stderr with a fake file-like object that catches errors
in attempting to .write to the real one and ignores them.

If neither of those two are a problem for you, you need to define no luck
before anyone will be able to help you. Are there errors in the event
viewer? Are you getting an exception that's killing out your service
(capture and write to a file with the logging module)? Or is the Popen call
being run and returning but just not doing anything (in which case, try
capturing output from the command and see if it indicates an error message
from plink.exe). Etc.

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


Re: Checking the coding style

2010-02-07 Thread Kev Dwyer
On Sun, 07 Feb 2010 19:36:10 +0100, Pablo Recio Quijano wrote:

 Hi!
 
 I'm finishing a project writen in Python, and I realize about the
 document PEP8 - Style Guide for Python Code [1].
 
 Is there any app or script that checks if my project pass that style
 guide? I also worked with Drupal, and I know there is some modules and
 scripts that checks its coding standars [2] and it's very usefull to
 clean the code.
 
 Thanks in advance!
 
 [1] http://www.python.org/dev/peps/pep-0008/ [2]
 http://drupal.org/coding-standards

Hello Pablo,

The pep8 package (http://pypi.python.org/pypi/pep8) can do this, though 
I have never used it myself.  PyLint is a customisable static analysis
program that checks style among other things.

Cheers,

Kev

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


Re: Checking the coding style

2010-02-07 Thread Pablo Recio Quijano
Thanks!

Pylint was what i was loking for

2010/2/7 Gerald Britton gerald.brit...@gmail.com

 pylint and pychecker are good options

 On Sun, Feb 7, 2010 at 1:36 PM, Pablo Recio Quijano
 rikuthero...@gmail.com wrote:
  Hi!
  I'm finishing a project writen in Python, and I realize about the
 document
  PEP8 - Style Guide for Python Code [1].
  Is there any app or script that checks if my project pass that style
 guide?
  I also worked with Drupal, and I know there is some modules and scripts
 that
  checks its coding standars [2] and it's very usefull to clean the code.
  Thanks in advance!
  [1] http://www.python.org/dev/peps/pep-0008/
  [2] http://drupal.org/coding-standards
 
  --
  Pablo Recio Quijano
 
  Estudiante de Ingeniería Informática (UCA)
  Alumno colaborador del Departamento de Lenguajes y Sistemas Informáticos
  Participante del IV Concurso Universitario de Software Libre
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 
 



 --
 Gerald Britton




-- 
Pablo Recio Quijano

Estudiante de Ingeniería Informática (UCA)
Alumno colaborador del Departamento de Lenguajes y Sistemas Informáticos
Participante del IV Concurso Universitario de Software Libre
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking the coding style

2010-02-07 Thread Andrej Mitrovic
On Feb 7, 8:22 pm, Kev Dwyer kevin.p.dw...@gmail.com wrote:
 On Sun, 07 Feb 2010 19:36:10 +0100, Pablo Recio Quijano wrote:
  Hi!

  I'm finishing a project writen in Python, and I realize about the
  document PEP8 - Style Guide for Python Code [1].

  Is there any app or script that checks if my project pass that style
  guide? I also worked with Drupal, and I know there is some modules and
  scripts that checks its coding standars [2] and it's very usefull to
  clean the code.

  Thanks in advance!

  [1]http://www.python.org/dev/peps/pep-0008/[2]
 http://drupal.org/coding-standards

 Hello Pablo,

 The pep8 package (http://pypi.python.org/pypi/pep8) can do this, though
 I have never used it myself.  PyLint is a customisable static analysis
 program that checks style among other things.

 Cheers,

 Kev

I've used pep8.py myself for some Python 3.x projects, and it's pretty
good. You don't need to install it either, a simple call via python
pep8.py 'yourpythonfile.py' should do.

I think PyLint can be used for Python 2.x, but I'm not sure about 3.x.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: max / min / smallest float value on Python 2.5

2010-02-07 Thread duncan smith

Steven D'Aprano wrote:

On Sun, 07 Feb 2010 03:02:05 +, duncan smith wrote:


The precise issue is that I'm supplying a default value of
2.2250738585072014e-308 for a parameter (finishing temperature for a
simulated annealing algorithm) in an application.  I develop on
Ubuntu64, but (I am told) it's too small a value when run on a Win32
server.  I assume it's being interpreted as zero and raising an
exception.  Thanks.


I'm trying to think of what sort of experiment would be able to measure 
temperatures accurate to less than 3e-308 Kelvin, and my brain boiled.


Surely 1e-100 would be close enough to zero as to make no practical 
difference? Or even 1e-30? Whatever you're simulating surely isn't going 
to require 300+ decimal points of accuracy.


I must admit I'm not really familiar with simulated annealing, so I could 
be completely out of line, but my copy of Numerical Recipes ... by 
Press et al has an example, and they take the temperature down to about 
1e-6 before halting. Even a trillion times lower that that is 1e-15.





It depends on the optimisation problem, but I suppose the fitness 
functions could be tweaked.  I could paste the actual code if anyone's 
interested, but the following pseudo-python gives the idea.  For an 
exponential cooling schedule the temperatures are generated as below. 
The lower the final temperature the greater the number of iterations, 
and the longer the algorithm spends searching locally for an optimal 
solution (having already searched more widely for areas of high fitness 
at higher temperatures).  The probability of moving to a less fit 
solution is given by exp(dF/temp) where dF is a (negative) change in 
fitness and temp is the current temperature.  So I could scale the 
fitness function to cope with higher finishing temperatures.


I'm going to have to think about the point raised by Steve (Holden).

I also think I can probably improve on raising StopIteration if 
exp(dF/temp) overflows by yielding False instead (although if it does 
overflow it probably indicates a poor choice of cooling schedule for the 
given problem).  Stuff to think about.  Cheers.


Duncan


import random
import math

def temps(start, final, mult):
t = start
while t  final:
yield t
t *= mult

def sim_anneal(permuter, start, final, mult):
rand = random.random
exp = math.exp
for temp in temps(start, final, mult):
dF = permuter.next()
if dF = 0:
yield True
else:
try:
yield rand()  exp(dF / temp)
except OverflowError:
raise StopIteration

class Permuter(object):
def __init__(self, obj):
self.obj = obj
self.proposed = None

def run(self, start, final, mult):
for decision in sim_anneal(self, start, final, mult):
if decision:
# commit proposed change to self.obj

def next():
# propose a change to self.obj
# calculate and return the change in fitness
self.proposed = proposed
return dF
--
http://mail.python.org/mailman/listinfo/python-list


Re: max / min / smallest float value on Python 2.5

2010-02-07 Thread Mark Dickinson
On Feb 7, 8:45 pm, duncan smith buzz...@urubu.freeserve.co.uk wrote:

[...]
 interested, but the following pseudo-python gives the idea.  For an
[...]

              try:
                  yield rand()  exp(dF / temp)

Practically speaking, the condition rand()  exp(dF / temp) is never
going to be satisfied if dF / temp  -40  (in fact, the output of
rand() is always an exact multiple of 2**-53, so the condition rand()
 exp(-40) is identical to the condition rand() == 0.0, which should
occur for one random sample out of every 9 thousand million million or
so).

So assuming that your fitness delta dF can't get smaller than 1e-16 or
so in absolute value (which seems reasonable, given that dF is
presumably the result of subtracting two numbers of 'normal'
magnitude), there would be little point having temp go much smaller
than, say, 1e-20.

IOW, I agree with Steven:  2.2e-308 seems extreme.

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


Re: TABS in the CPython C source code

2010-02-07 Thread Neil Hodgson
Aahz:

 BTW, in case anyone is confused, it's svn blame vs cvs annotate.

   Possibly earlier versions of SVN only supported blame but the
variants annotate, ann, and praise all work with the version of
SVN (1.6.5) I have installed.

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


Available for use: Tabs management software

2010-02-07 Thread James Harris
In case someone else finds it useful here is a program I wrote a year
or so ago to help manage tab characters. It will convert tabs to runs
of spaces, convert runs of spaces to tabs, or count or check for tab
characters as required. It supports tab stops at regular and irregular
positions.

  http://codewiki.wikispaces.com/tabs.py

It is written in Python and you can either use it from the command
line or call the functions from another Python script. Documentation
is included on the web page.

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


Re: Executing Commands From Windows Service

2010-02-07 Thread Sean DiZazzo
On Feb 7, 11:02 am, T misceveryth...@gmail.com wrote:
 I have a script, which runs as a Windows service under the LocalSystem
 account, that I wish to have execute some commands.  Specifically, the
 program will call plink.exe to create a reverse SSH tunnel.  Right now
 I'm using subprocess.Popen to do so.  When I run it interactively via
 an admin account, all is well.  However, when I'm running it via
 service, no luck.  I'm assuming this is to do with the fact that it's
 trying to run under the LocalSystem account, which is failing.  What
 would be the best way around this?  Thanks!

Try running/debugging your service from the commandline as
servicename debug  That should lead you to the error.

Otherwise, we need to see a traceback and some code to be better able
to help.

~Sean

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


Re: Executing Commands From Windows Service

2010-02-07 Thread T
On Feb 7, 4:43 pm, Sean DiZazzo half.ital...@gmail.com wrote:
 On Feb 7, 11:02 am, T misceveryth...@gmail.com wrote:

  I have a script, which runs as a Windows service under the LocalSystem
  account, that I wish to have execute some commands.  Specifically, the
  program will call plink.exe to create a reverse SSH tunnel.  Right now
  I'm using subprocess.Popen to do so.  When I run it interactively via
  an admin account, all is well.  However, when I'm running it via
  service, no luck.  I'm assuming this is to do with the fact that it's
  trying to run under the LocalSystem account, which is failing.  What
  would be the best way around this?  Thanks!

 Try running/debugging your service from the commandline as
 servicename debug  That should lead you to the error.

 Otherwise, we need to see a traceback and some code to be better able
 to help.

 ~Sean

It's working fine when I run it via servicename debug - that's how
I was testing before.  It's when I start the service that it fails -
and you can see that, when you run it with debug, plink.exe runs under
my username.  When I run it as a service, it runs under System...
-- 
http://mail.python.org/mailman/listinfo/python-list


question on using tarfile to read a *.tar.gzip file

2010-02-07 Thread m_ahlenius
Hi,

I have a number of relatively large number *tar.gzip files to
process.  With the py module tarfile, I see that I can access and
extract them, one at a time to a temporary dir, but that of course
takes time.

All that I need to do is to read the first and last lines of each file
and then move on to the next one.  I am not changing anything in these
files - just reading.  The file lines are not fixed lengths either,
which makes it a bit more fun.

Is there a way to do this, without decompressing each file to a temp
dir?  Like is there a method using some tarfile interface adapter to
read a compressed file?  Otherwise I'll just access each file, extract
it,  grab the 1st and last lines and then delete the temp file.

thx

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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread hzh...@gmail.com
That is a method called brute force. According to my computation,
2^2048=
32317006071311007300714876688669951960444102669715484032130345427524655138867890
89319720141152291346368871796092189801949411955915049092109508815238644828312063
08773673009960917501977503896521067960576383840675682767922186426197561618380943
3847617047058164585203630504288757589154106580860755239912393038552191489668
34242068497478656456949485617603532632205807780565933102619270846031415025859286
41771167259436037184618573575983511523016459044036976132332872312271256847108202
09725157101726931323469678542580656697935045997268352998638215525166389437335543
602135433229604645318478604952148193555853611059596230656L

which is a very large number.

There are some other algorithms for factoring integers, including
Generalized number field sieve. And in quantum computing, there is an
algorithm called Shor, which is claimed to be a polynomial algorithm
if run under quantum computers. But seems that kind of computers
haven't been successfully built, or else RSA and many other security
mechanisms based on computation complexity cannot be used any longer.

What I need in my application is just to list all expressions that
match a particular regex, which I believe will be more efficient to
deal with if there is a general function for this purpose.
Unfortunately there is not such a function, so I will write my own
function to deal with my particular regex, which can be enumerated.

Sincerely,

Zhuo

On Feb 7, 10:38 am, Steve Holden st...@holdenweb.com wrote:
 hzh...@gmail.com wrote:
  And I really don't see how simple enumeration of range(2^2048) breaks
  RSA-2048, since that problem requires you to find two factors which,
  when multiplied together, give that specific value.

  I can tell you why is that. RSA-2048 has a composite of length less
  than 2^2048, which is a product of two large primes. So one of its
  factors cannot exceed 2^2047, and we can treat the multiplication as a
  computation with constant complexity. So the time complexity of
  enumerating 2^2048 strings is the same with factoring a composite with
  length 2^2048 which is the product of two primes.

  And obviously, whenever we successfully factor the composite, we can
  calculate the Euler function of it. So that given any public key
  (n,e), calculating the private key (n,d) is easy.

 So all I have to do to break RSA is to count to 2^2048?

 regards
  Steve
 --
 Steve Holden           +1 571 484 6266   +1 800 494 3119
 PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
 Holden Web LLC                http://www.holdenweb.com/
 UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread Steven D'Aprano
On Sun, 07 Feb 2010 03:53:49 +0100, Alf P. Steinbach wrote:

 Given the function hashlib.sha256, enumerate all the possible inputs
 that give the hexadecimal result
 0a2591aaf3340ad92faecbc5908e74d04b51ee5d2deee78f089f1607570e2e91.
 
 I tried some parrot variants but no dice. :-(

Oh, everybody expects parrots! That's not unexpected -- as a clue, I 
wrote that the message is predictable for being totally unexpected.

The input was Nobody expects the Spanish Inquisition!, which is another 
Monty Python catchphrase.


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


Re: Executing Commands From Windows Service

2010-02-07 Thread Alf P. Steinbach

* T:

On Feb 7, 4:43 pm, Sean DiZazzo half.ital...@gmail.com wrote:

On Feb 7, 11:02 am, T misceveryth...@gmail.com wrote:


I have a script, which runs as a Windows service under the LocalSystem
account, that I wish to have execute some commands.  Specifically, the
program will call plink.exe to create a reverse SSH tunnel.  Right now
I'm using subprocess.Popen to do so.  When I run it interactively via
an admin account, all is well.  However, when I'm running it via
service, no luck.  I'm assuming this is to do with the fact that it's
trying to run under the LocalSystem account, which is failing.  What
would be the best way around this?  Thanks!

Try running/debugging your service from the commandline as
servicename debug  That should lead you to the error.

Otherwise, we need to see a traceback and some code to be better able
to help.

~Sean


It's working fine when I run it via servicename debug - that's how
I was testing before.  It's when I start the service that it fails -
and you can see that, when you run it with debug, plink.exe runs under
my username.  When I run it as a service, it runs under System...


This sounds like a Windows programming problem, not anything related to Python 
per se.


Windows services are generally limited in what they can do, such as interaction 
with the  user, and I guess that spills over to network access.


Also, services need to interact with the service control manager, the scum as 
it's known. Well, all right, that's just what my coworkers and I called it once. 
But essentially, it's an even-driven execution model, which means that it might 
not work to use just any program, such as [python.exe], directly as a service.


The Windows Resource Kit used to have a facility for running ordinary programs 
as services. I'm not sure what it did at the technical level, but it worked. Or 
it appeared to work.


You might also find it useful to look up the documentation on services that 
interact with the user. In the old times that was mostly a matter of configuring 
which account the service ran under. But I think it all got more complicated 
with Microsoft's introduction of Terminal services (generally, most of the 
complication in modern Windows is due to the shift in focus about 1995, ditching 
the personal computer user market in favor of the enterprise and MIS market).


Cross-posted to [comp.os.ms-windows.programmer.win32], follow-ups set to that 
group  --  that means, unless overridden you won't see follow-ups in [c.l.p].


I think that group may give more informative and helpful responses.


Cheers  hth.,

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


Re: passing string for editing in input()

2010-02-07 Thread Chris Rebert
On Sun, Feb 7, 2010 at 8:24 AM, Aahz a...@pythoncraft.com wrote:
 In article mailman.1787.1265117353.28905.python-l...@python.org,
 Chris Rebert  c...@rebertia.com wrote:
On Tue, Feb 2, 2010 at 5:24 AM, mk mrk...@gmail.com wrote:

 Is there an easy way to get an editing (readline) in Python that would
 contain string for editing and would not just be empty?

 I googled but found nothing.

Er...: http://docs.python.org/library/readline.html
It's the third hit for python readline.

Actually reading the page, sounds like you want readline.insert_text()
specifically.

 That seems a tad harsh, especially after reading the docs and following
 Peter Otten's link.  It's not at all obvious how to actually use
 insert_text(), and although I probably could have figured it out on my
 own, I might well have posted here myself.  Did you try using
 insert_text() before posting?

No; I've never used the readline module for that matter. I was just
giving a (hopefully helpful) suggestion based on a quick scan of the
docs (hence the tentative sounds like). The OP's comment about
finding /nothing/ on Google made it sound as though they hadn't
located/checked the readline module docs. In retrospect, I might have
misinterpreted in that regard; but in my defense, if they did check
the docs, it might have been good to say so, and if they had found
insert_text(), they ought to have made their question more specific.

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


Re: question on using tarfile to read a *.tar.gzip file

2010-02-07 Thread Tim Chase

Is there a way to do this, without decompressing each file to a temp
dir?  Like is there a method using some tarfile interface adapter to
read a compressed file?  Otherwise I'll just access each file, extract
it,  grab the 1st and last lines and then delete the temp file.


I think you're looking for the extractfile() method of the 
TarFile object:


  from glob import glob
  from tarfile import TarFile
  for fname in glob('*.tgz'):
print fname
tf = TarFile.gzopen(fname)
for ti in tf:
  print ' %s' % ti.name
  f = tf.extractfile(ti)
  if not f: continue
  fi = iter(f) # f doesn't natively support next()
  first_line = fi.next()
  for line in fi: pass
  f.close()
  print   First line: %r % first_line
  print   Last line: %r % line
tf.close()

If you just want the first  last lines, it's a little more 
complex if you don't want to scan the entire file (like I do with 
the for-loop), but the file-like object returned by extractfile() 
is documented as supporting seek() so you can skip to the end and 
then read backwards until you have sufficient lines.  I wrote a 
get the last line of a large file using seeks from the EOF 
function which you can find at [1] which should handle the odd 
edge cases of $BUFFER_SIZE containing more or less than a full 
line and then reading backwards in chunks (if needed) until you 
have one full line, handling a one-line file, and other 
odd/annoying edge-cases.  Hope it helps.


-tkc

[1]
http://mail.python.org/pipermail/python-list/2009-January/1186176.html


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


Re: Available for use: Tabs management software

2010-02-07 Thread James Harris
On 7 Feb, 21:25, James Harris james.harri...@googlemail.com wrote:
 In case someone else finds it useful here is a program I wrote a year
 or so ago to help manage tab characters. It will convert tabs to runs
 of spaces, convert runs of spaces to tabs, or count or check for tab
 characters as required. It supports tab stops at regular and irregular
 positions.

  http://codewiki.wikispaces.com/tabs.py

 It is written in Python and you can either use it from the command
 line or call the functions from another Python script. Documentation
 is included on the web page.

After posting this I realised the code had a dependence on a separate
debugging module. I've commented-out all such references and tested it
in isolation from other code. Everything behaved as it should so if
you download it you should find it just works. The only dependence is
on Python (i.e. Python 2.x; I gather 3.x needs print statements and
maybe other stuff to be changed). Any issues, feel free to post them
here.

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


Re: TABS in the CPython C source code

2010-02-07 Thread Nobody
On Sun, 07 Feb 2010 05:49:28 +, Nobody wrote:

 The size-8 tabs look really bad in an editor configured with tab size 4,
 as is common in Windows. I'm concluding that the CPython programmers
 configure their Visual Studio's to *nix convention.
 
 8-column tabs aren't a *nix convention; that's been the norm since
 the mechanical typewriter.

Okay, as everyone has pointed out, it's not quite that old. I've seen
typewriters with fixed tabs, but I'm not certain that they were at 8
columns, and even if they were, it wasn't common enough to be a standard.


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


Re: Your beloved python features

2010-02-07 Thread Anssi Saari
Julian maili...@julianmoritz.de writes:

 I've asked this question at stackoverflow a few weeks ago, and to make
 it clear: this should NOT be a copy of the stackoverflow-thread
 hidden features of Python.

Thanks for the hint, interesting stuff in there.

 For those guys would be a poster quite cool which describes the most
 popular and beloved python features.

For me as an electronics HW guy, I really like that I can easily
handle binary data without doing tedious and error prone shifting and
anding and oring.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question on using tarfile to read a *.tar.gzip file

2010-02-07 Thread m_ahlenius
On Feb 7, 5:01 pm, Tim Chase python.l...@tim.thechases.com wrote:
  Is there a way to do this, without decompressing each file to a temp
  dir?  Like is there a method using some tarfile interface adapter to
  read a compressed file?  Otherwise I'll just access each file, extract
  it,  grab the 1st and last lines and then delete the temp file.

 I think you're looking for the extractfile() method of the
 TarFile object:

    from glob import glob
    from tarfile import TarFile
    for fname in glob('*.tgz'):
      print fname
      tf = TarFile.gzopen(fname)
      for ti in tf:
        print ' %s' % ti.name
        f = tf.extractfile(ti)
        if not f: continue
        fi = iter(f) # f doesn't natively support next()
        first_line = fi.next()
        for line in fi: pass
        f.close()
        print   First line: %r % first_line
        print   Last line: %r % line
      tf.close()

 If you just want the first  last lines, it's a little more
 complex if you don't want to scan the entire file (like I do with
 the for-loop), but the file-like object returned by extractfile()
 is documented as supporting seek() so you can skip to the end and
 then read backwards until you have sufficient lines.  I wrote a
 get the last line of a large file using seeks from the EOF
 function which you can find at [1] which should handle the odd
 edge cases of $BUFFER_SIZE containing more or less than a full
 line and then reading backwards in chunks (if needed) until you
 have one full line, handling a one-line file, and other
 odd/annoying edge-cases.  Hope it helps.

 -tkc

 [1]http://mail.python.org/pipermail/python-list/2009-January/1186176.html

Thanks Tim - this was very helpful.  Just learning about tarfile.

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


Possible? Python 2.6.x and PythonWin on 64-bit Windows 7

2010-02-07 Thread escalation746
I am having a heck of a time doing the simplest thing: installing
Python and the pywin extensions, including the PythonWin editor I have
always relied on, into my new Windows 7 Professional 64-bit OS. I
tried the Python package from python.org and pywin32 from sourceforge.
But the latter would not install, saying that it could not find Python
2.6 in the registry. And apparently it will not let me specify the
location of same, although a dialogue window tantalises me with blank
text boxes I cannot type into.

I then tried the 64-bit version of ActiveState's Python, but this
installed sans the PythonWin editor, apparently. At least I cannot
find it either in the Start menu or in the Python folder.

What am I missing? What have I not been told?

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


Re: Possible? Python 2.6.x and PythonWin on 64-bit Windows 7

2010-02-07 Thread Stephen Hansen
On Sun, Feb 7, 2010 at 4:26 PM, escalation746 escalation...@yahoo.comwrote:

 I am having a heck of a time doing the simplest thing: installing
 Python and the pywin extensions, including the PythonWin editor I have
 always relied on, into my new Windows 7 Professional 64-bit OS. I
 tried the Python package from python.org and pywin32 from sourceforge.
 But the latter would not install, saying that it could not find Python
 2.6 in the registry. And apparently it will not let me specify the
 location of same, although a dialogue window tantalises me with blank
 text boxes I cannot type into.


Saying, the Python package from python.org is insufficiently specific; are
you sure you got the 64-bit version of BOTH packages? If you install 64-bit
Python, any extensions must also be 64-bit.

If you look at http://sourceforge.net/projects/pywin32/files/ you'll notice
separate builds for 64-bit, marked amd64. Are you sure you got the
pywin32-214.win-amd64-py2.6.exe and not the normal one?

Alternatively, you can just get the 32-bit version of both and install them.
But you can't mix and match, 32-bit one, 64-bit the other, in that case they
won't find each-other.

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


Re: Possible? Python 2.6.x and PythonWin on 64-bit Windows 7

2010-02-07 Thread Andrej Mitrovic
On Feb 8, 1:26 am, escalation746 escalation...@yahoo.com wrote:
 I am having a heck of a time doing the simplest thing: installing
 Python and the pywin extensions, including the PythonWin editor I have
 always relied on, into my new Windows 7 Professional 64-bit OS. I
 tried the Python package from python.org and pywin32 from sourceforge.
 But the latter would not install, saying that it could not find Python
 2.6 in the registry. And apparently it will not let me specify the
 location of same, although a dialogue window tantalises me with blank
 text boxes I cannot type into.

 I then tried the 64-bit version of ActiveState's Python, but this
 installed sans the PythonWin editor, apparently. At least I cannot
 find it either in the Start menu or in the Python folder.

 What am I missing? What have I not been told?

 -- robin

Perhaps you've accidentally downloaded the wrong version of PythonWin?
I think this should be the one:
http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/pywin32-214.win-amd64-py2.6.exe/download
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible? Python 2.6.x and PythonWin on 64-bit Windows 7

2010-02-07 Thread escalation746
Andrej Mitrovic wrote:

 Perhaps you've accidentally downloaded the wrong version of PythonWin?

Erk, yes, my bad.

Thanks for the quick help! Though I still wonder why the ActiveState
build does not include this.

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


Modifying Class Object

2010-02-07 Thread T
Ok, just looking for a sanity check here, or maybe something I'm
missing.  I have a class Test, for example:

class Test:
def __init__(self, param1, param2, param3):
self.param1 = param1
self.param2 = param2
self.param3 = param3

Next, I have a dictionary mytest that contains instances of Test.  If
I want to modify one of the Test instances within my dictionary, I
have to rewrite the entire entry, correct (since Python passes by
value, not reference)?  I.e. if I wish to change just param3 of an
instance, I would have to do:

def changevalue():
for key in mytest.keys():
currentparam = mytest[key]
param1 = currentparam.param1
param2 = currentparam.param2
param3 = currentparam.param3
param3 = newvalue
mytest[key] = Test(param1, param2, param3)

If there's an easier way to accomplish this that I'm missing, that'd
be great!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-07 Thread Chris Rebert
On Sun, Feb 7, 2010 at 5:05 PM, T misceveryth...@gmail.com wrote:
 Ok, just looking for a sanity check here, or maybe something I'm
 missing.  I have a class Test, for example:

 class Test:
    def __init__(self, param1, param2, param3):
        self.param1 = param1
        self.param2 = param2
        self.param3 = param3

 Next, I have a dictionary mytest that contains instances of Test.  If
 I want to modify one of the Test instances within my dictionary, I
 have to rewrite the entire entry, correct (since Python passes by
 value, not reference)?

Incorrect; Python uses neither. See
http://effbot.org/zone/call-by-object.htm for a excellent explanation
of what Python does use.

 I.e. if I wish to change just param3 of an
 instance, I would have to do:

 def changevalue():
    for key in mytest.keys():
        currentparam = mytest[key]
        param1 = currentparam.param1
        param2 = currentparam.param2
        param3 = currentparam.param3
        param3 = newvalue
        mytest[key] = Test(param1, param2, param3)

 If there's an easier way to accomplish this that I'm missing, that'd
 be great!

def changevalue():
for test in mytest.values():
test.param3 = newvalue

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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread Steve Holden
Steven D'Aprano wrote:
 On Sun, 07 Feb 2010 03:53:49 +0100, Alf P. Steinbach wrote:
 
 Given the function hashlib.sha256, enumerate all the possible inputs
 that give the hexadecimal result
 0a2591aaf3340ad92faecbc5908e74d04b51ee5d2deee78f089f1607570e2e91.
 I tried some parrot variants but no dice. :-(
 
 Oh, everybody expects parrots! That's not unexpected -- as a clue, I 
 wrote that the message is predictable for being totally unexpected.
 
 The input was Nobody expects the Spanish Inquisition!, which is another 
 Monty Python catchphrase.
 
 
Bugger - Got everything except the trailing exclamation mark ...

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-07 Thread T
On Feb 7, 8:16 pm, Chris Rebert c...@rebertia.com wrote:
 On Sun, Feb 7, 2010 at 5:05 PM, T misceveryth...@gmail.com wrote:
  Ok, just looking for a sanity check here, or maybe something I'm
  missing.  I have a class Test, for example:

  class Test:
     def __init__(self, param1, param2, param3):
         self.param1 = param1
         self.param2 = param2
         self.param3 = param3

  Next, I have a dictionary mytest that contains instances of Test.  If
  I want to modify one of the Test instances within my dictionary, I
  have to rewrite the entire entry, correct (since Python passes by
  value, not reference)?

 Incorrect; Python uses neither. 
 Seehttp://effbot.org/zone/call-by-object.htmfor a excellent explanation
 of what Python does use.

  I.e. if I wish to change just param3 of an
  instance, I would have to do:

  def changevalue():
     for key in mytest.keys():
         currentparam = mytest[key]
         param1 = currentparam.param1
         param2 = currentparam.param2
         param3 = currentparam.param3
         param3 = newvalue
         mytest[key] = Test(param1, param2, param3)

  If there's an easier way to accomplish this that I'm missing, that'd
  be great!

 def changevalue():
     for test in mytest.values():
         test.param3 = newvalue

 Cheers,
 Chris
 --http://blog.rebertia.com

Thanks so much - this makes life a lot easier!  And a great reference
as well.

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


Re: python admin abuse complaint

2010-02-07 Thread Jean-Michel Pichavant

Steve Holden wrote:

Shashwat Anand wrote:
  

LOL
pow(funny, sys.maxint)



Yes, funny, but it overlooks the point that Xah is a nuisance to
multiple communities, not just to ours, and quite often concurrently.

I'm all in favor of tolerance, but I'd like to see some evidence that
rehabilitation is practical before the community has to tolerate too
much of that kind of nonsense.

regards
 Steve
  
Actually for one Xah post I get, I then get 20 mails complaining about 
him. The fact is, for someone like me who subscribed  only to the python 
list (what's the purpose of subscribing the perl list when you know 
about python existence btw :o) ), the real annoying spam comes from the 
complains, not Xah. Speaking for myself, I may get 3 or 4 posts from Xah 
a month at most. Something I can live with.


So guys, just ignore him if you don't like him. Mailers  news readers 
have plenty of feature to make it happen.


Adding my contribution to complains...

JM

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


Re: Modifying Class Object

2010-02-07 Thread Steve Holden
T wrote:
 Ok, just looking for a sanity check here, or maybe something I'm
 missing.  I have a class Test, for example:
 
 class Test:
 def __init__(self, param1, param2, param3):
 self.param1 = param1
 self.param2 = param2
 self.param3 = param3
 
 Next, I have a dictionary mytest that contains instances of Test.  If
 I want to modify one of the Test instances within my dictionary, I
 have to rewrite the entire entry, correct (since Python passes by
 value, not reference)?  I.e. if I wish to change just param3 of an
 instance, I would have to do:
 
 def changevalue():
 for key in mytest.keys():
 currentparam = mytest[key]
 param1 = currentparam.param1
 param2 = currentparam.param2
 param3 = currentparam.param3
 param3 = newvalue
 mytest[key] = Test(param1, param2, param3)
 
 If there's an easier way to accomplish this that I'm missing, that'd
 be great!

def changevalue():
for key in mytest.keys():
mytest[key].param3 = newvalue

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: python admin abuse complaint

2010-02-07 Thread MRAB

Jean-Michel Pichavant wrote:

Steve Holden wrote:

Shashwat Anand wrote:
 

LOL
pow(funny, sys.maxint)



Yes, funny, but it overlooks the point that Xah is a nuisance to
multiple communities, not just to ours, and quite often concurrently.

I'm all in favor of tolerance, but I'd like to see some evidence that
rehabilitation is practical before the community has to tolerate too
much of that kind of nonsense.

regards
 Steve
  
Actually for one Xah post I get, I then get 20 mails complaining about 
him. The fact is, for someone like me who subscribed  only to the python 
list (what's the purpose of subscribing the perl list when you know 
about python existence btw :o) ), the real annoying spam comes from the 
complains, not Xah. Speaking for myself, I may get 3 or 4 posts from Xah 
a month at most. Something I can live with.


So guys, just ignore him if you don't like him. Mailers  news readers 
have plenty of feature to make it happen.


Adding my contribution to complains...


Alternatively, add [XAH] to the subject in the replies so that they can
be filtered out easily. :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-07 Thread Alf P. Steinbach

* Chris Rebert:

On Sun, Feb 7, 2010 at 5:05 PM, T misceveryth...@gmail.com wrote:

Ok, just looking for a sanity check here, or maybe something I'm
missing.  I have a class Test, for example:

class Test:
   def __init__(self, param1, param2, param3):
   self.param1 = param1
   self.param2 = param2
   self.param3 = param3

Next, I have a dictionary mytest that contains instances of Test.  If
I want to modify one of the Test instances within my dictionary, I
have to rewrite the entire entry, correct (since Python passes by
value, not reference)?


Incorrect; Python uses neither. See
http://effbot.org/zone/call-by-object.htm for a excellent explanation
of what Python does use.


Hm. While most everything I've seen at effbot.org has been clear and to the 
point, that particular article reads like a ton of obfuscation.


Python passes pointers by value, just as e.g. Java does.

There, it needed just 10 words or so. :-) Or perhaps some more words to point 
out that in the Java language spec those reference values are called pointers, 
but that this terminology isn't (apparently) used for Python, and isn't even 
well known among Java programmers. But that's just one extra little para.


One just has to be clear about exactly what it is that's passed by value.

Not Python objects, but references (pointers) to them, the id(o) values.



I.e. if I wish to change just param3 of an
instance, I would have to do:

def changevalue():
   for key in mytest.keys():
   currentparam = mytest[key]
   param1 = currentparam.param1
   param2 = currentparam.param2
   param3 = currentparam.param3
   param3 = newvalue
   mytest[key] = Test(param1, param2, param3)

If there's an easier way to accomplish this that I'm missing, that'd
be great!


def changevalue():
for test in mytest.values():
test.param3 = newvalue


Cheers,

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


Re: Modifying Class Object

2010-02-07 Thread MRAB

Alf P. Steinbach wrote:

* Chris Rebert:

On Sun, Feb 7, 2010 at 5:05 PM, T misceveryth...@gmail.com wrote:

Ok, just looking for a sanity check here, or maybe something I'm
missing.  I have a class Test, for example:

class Test:
   def __init__(self, param1, param2, param3):
   self.param1 = param1
   self.param2 = param2
   self.param3 = param3

Next, I have a dictionary mytest that contains instances of Test.  If
I want to modify one of the Test instances within my dictionary, I
have to rewrite the entire entry, correct (since Python passes by
value, not reference)?


Incorrect; Python uses neither. See
http://effbot.org/zone/call-by-object.htm for a excellent explanation
of what Python does use.


Hm. While most everything I've seen at effbot.org has been clear and to 
the point, that particular article reads like a ton of obfuscation.


Python passes pointers by value, just as e.g. Java does.

There, it needed just 10 words or so. :-) Or perhaps some more words to 
point out that in the Java language spec those reference values are 
called pointers, but that this terminology isn't (apparently) used for 
Python, and isn't even well known among Java programmers. But that's 
just one extra little para.


One just has to be clear about exactly what it is that's passed by value.

Not Python objects, but references (pointers) to them, the id(o) values.


A reference is not the same as a pointer.

A pointer tells you where something is; a reference doesn't.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-07 Thread Alf P. Steinbach

* MRAB:

Alf P. Steinbach wrote:

* Chris Rebert:

On Sun, Feb 7, 2010 at 5:05 PM, T misceveryth...@gmail.com wrote:

Ok, just looking for a sanity check here, or maybe something I'm
missing.  I have a class Test, for example:

class Test:
   def __init__(self, param1, param2, param3):
   self.param1 = param1
   self.param2 = param2
   self.param3 = param3

Next, I have a dictionary mytest that contains instances of Test.  If
I want to modify one of the Test instances within my dictionary, I
have to rewrite the entire entry, correct (since Python passes by
value, not reference)?


Incorrect; Python uses neither. See
http://effbot.org/zone/call-by-object.htm for a excellent explanation
of what Python does use.


Hm. While most everything I've seen at effbot.org has been clear and 
to the point, that particular article reads like a ton of obfuscation.


Python passes pointers by value, just as e.g. Java does.

There, it needed just 10 words or so. :-) Or perhaps some more words 
to point out that in the Java language spec those reference values are 
called pointers, but that this terminology isn't (apparently) used for 
Python, and isn't even well known among Java programmers. But that's 
just one extra little para.


One just has to be clear about exactly what it is that's passed by value.

Not Python objects, but references (pointers) to them, the id(o) values.


A reference is not the same as a pointer.


Depends on your choice terminology. I referred to the Java (language spec) 
terminology to make it clear.




A pointer tells you where something is; a reference doesn't.


Sorry, I don't know of any relevant terminology where that is the case.


Cheers  hth.,

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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread Steven D'Aprano
On Sun, 07 Feb 2010 20:19:53 -0500, Steve Holden wrote:

 Steven D'Aprano wrote:
 On Sun, 07 Feb 2010 03:53:49 +0100, Alf P. Steinbach wrote:
 
 Given the function hashlib.sha256, enumerate all the possible inputs
 that give the hexadecimal result
 0a2591aaf3340ad92faecbc5908e74d04b51ee5d2deee78f089f1607570e2e91.
 I tried some parrot variants but no dice. :-(
 
 Oh, everybody expects parrots! That's not unexpected -- as a clue, I
 wrote that the message is predictable for being totally unexpected.
 
 The input was Nobody expects the Spanish Inquisition!, which is
 another Monty Python catchphrase.
 
 
 Bugger - Got everything except the trailing exclamation mark ...


NOBODY EXPECTS THE TRAILING EXCLAMATION MARK!!!




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


Re: Modifying Class Object

2010-02-07 Thread Steve Holden
Alf P. Steinbach wrote:
 * MRAB:
 Alf P. Steinbach wrote:
 * Chris Rebert:
 On Sun, Feb 7, 2010 at 5:05 PM, T misceveryth...@gmail.com wrote:
 Ok, just looking for a sanity check here, or maybe something I'm
 missing.  I have a class Test, for example:

 class Test:
def __init__(self, param1, param2, param3):
self.param1 = param1
self.param2 = param2
self.param3 = param3

 Next, I have a dictionary mytest that contains instances of Test.  If
 I want to modify one of the Test instances within my dictionary, I
 have to rewrite the entire entry, correct (since Python passes by
 value, not reference)?

 Incorrect; Python uses neither. See
 http://effbot.org/zone/call-by-object.htm for a excellent explanation
 of what Python does use.

 Hm. While most everything I've seen at effbot.org has been clear and
 to the point, that particular article reads like a ton of obfuscation.

 Python passes pointers by value, just as e.g. Java does.

 There, it needed just 10 words or so. :-) Or perhaps some more words
 to point out that in the Java language spec those reference values
 are called pointers, but that this terminology isn't (apparently)
 used for Python, and isn't even well known among Java programmers.
 But that's just one extra little para.

 One just has to be clear about exactly what it is that's passed by
 value.

 Not Python objects, but references (pointers) to them, the id(o) values.

 A reference is not the same as a pointer.
 
 Depends on your choice terminology. I referred to the Java (language
 spec) terminology to make it clear.
 
 
 A pointer tells you where something is; a reference doesn't.
 
 Sorry, I don't know of any relevant terminology where that is the case.
 
Alf:

This topic was discussed at great, nay interminable, length about a year
ago. I'd appreciate it if you would search the archives and read what
was said then rather than hashing the whole topic over again to nobody's
real advantage.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Schif Schaf
On Feb 7, 8:57 am, Tim Chase python.l...@tim.thechases.com wrote:
 Steve Holden wrote:

  Really? Under what circumstances does a simple one-for-one character
  replacement operation fail?

 Failure is only defined in the clarified context of what the OP
 wants :)  Replacement operations only fail if the OP's desired
 output from the above mess doesn't change *all* of the ]/[
 characters, but only those with some form of parity (nested or
 otherwise).  But if the OP *does* want all of the ]/[ characters
 replaced regardless of contextual nature, then yes, replace is a
 much better solution than regexps.


I need to do the usual pipe text through and do various search/
replace thing fairly often. The above case of having to replace
brackets with braces is only one example. Simple string methods run
out of steam pretty quickly and much of my work relies on using
regular expressions. Yes, I try to keep focused on simplicity, and
often regexes are the simplest solution for my day-to-day needs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-07 Thread Stephen Hansen
On Sun, Feb 7, 2010 at 5:51 PM, Alf P. Steinbach al...@start.no wrote:

 Incorrect; Python uses neither. See
 http://effbot.org/zone/call-by-object.htm for a excellent explanation

 of what Python does use.


 Hm. While most everything I've seen at effbot.org has been clear and to
 the point, that particular article reads like a ton of obfuscation.

 Python passes pointers by value, just as e.g. Java does.

 There, it needed just 10 words or so. :-) Or perhaps some more words to
 point out that in the Java language spec those reference values are called
 pointers, but that this terminology isn't (apparently) used for Python, and
 isn't even well known among Java programmers. But that's just one extra
 little para.



 One just has to be clear about exactly what it is that's passed by value.

 Not Python objects, but references (pointers) to them, the id(o) values.


Sigh. Why does this always come up? And then someone makes a statement like
this, and now a /very/ long thread in which everyone argues semantics will
begin and sooner or later, the presence of the GIL will cause a Python civil
war, even though the GIL has nothing to do with anything related to this
conversation. Mark my words!

Python only passes by value if you use a non-standard definition of value:
and the moment you do that, a whole bunch of people will start making weird
assumptions of Python's object and scoping semantics and all kinds of
confusion will occur. Or holy wars on words shall come to pass.

Python does not have pointers, it is not passing a pointer, it is passing an
object. The moment you start talking about passing pointers, people start
expecting things to work as if they -were- pointers. Python objects don't.

Python has names, and objects. It passes objects. Those objects get a new
name as a result. If the object is mutable, changes will be seen by the
caller. If the object is not, changes won't (because you're re-binding a
name, not changing an object).

Any attempt to apply any other sort of words or labels besides names and
objects to the situation is just going to confuse people and make them
think Python-is-LanguageXor Python-works-like-LanguageY.

Let the argument begin! Again.

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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread Paul McGuire
On Feb 6, 1:36 pm, hzh...@gmail.com hzh...@gmail.com wrote:
 Hi,

 I am a fresh man with python. I know there is regular expressions in
 Python. What I need is that given a particular regular expression,
 output all the matches. For example, given “[1|2|3]{2}” as the regular
 expression, the program should output all 9 matches, i.e., 11 12 13
 21 22 23 31 32 33.

 Is there any well-written routine in Python or third-party program to
 do this? If there isn't, could somebody make some suggestions on how
 to write it myself?

 Thanks.

 Zhuo

Please check out this example on the pyparsing wiki, invRegex.py:
http://pyparsing.wikispaces.com/file/view/invRegex.py.  This code
implements a generator that returns successive matching strings for
the given regex.  Running it, I see that you actually have a typo in
your example.

 print list(invert([1|2|3]{2}))
['11', '1|', '12', '13', '|1', '||', '|2', '|3', '21', '2|', '22',
'23', '31', '3|', '32', '33']

I think you meant either [123]{2} or (1|2|3){2}.

 print list(invert([123]{2}))
['11', '12', '13', '21', '22', '23', '31', '32', '33']

 print list(invert((1|2|3){2}))
['11', '12', '13', '21', '22', '23', '31', '32', '33']

Of course, as other posters have pointed out, this inverter does not
accept regexen with unbounded multiple characters '+' or '*', but '?'
and {min,max} notation will work.  Even '.' is supported, although
this can generate a large number of return values.

Of course, you'll also have to install pyparsing to get this to work.

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


Re: Modifying Class Object

2010-02-07 Thread Steven D'Aprano
On Sun, 07 Feb 2010 22:03:06 -0500, Steve Holden wrote:

 Alf:
 
 This topic was discussed at great, nay interminable, length about a year
 ago. I'd appreciate it if you would search the archives and read what
 was said then rather than hashing the whole topic over again to nobody's
 real advantage.

Curse you Steve, I had just come up with a brilliant rebuttal of Alf's 
position. It was sheer genius, the sort of thing that would have James 
Gosling weeping with envy.

Oh well, into the bitbucket it goes...


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


Re: Modifying Class Object

2010-02-07 Thread alex23
Alf P. Steinbach al...@start.no wrote:
 Hm. While most everything I've seen at effbot.org has been clear and to the
 point, that particular article reads like a ton of obfuscation.

Must. Resist. Ad hominem.

 Python passes pointers by value, just as e.g. Java does.

 There, it needed just 10 words or so. :-)

10 words _plus_ an understanding of Java. Do you really think its
appropriate to discuss Python's behaviour purely in terms of other
languages?

Further, you've managed to define Python's behaviour as being somehow
_both_ of the major evaluation strategies - calling a reference by
value - so you're asking people to understand two totally irrelevant
models just to avoid describing one in its own terms. Rather than
arguing about whether you have a 'value' or a 'reference', it's a lot
easier to explain that you're passing mutable  immutable objects
around. The behaviour is thus defined in terms of the object and _not_
in the calling model, and is far more consistent with object
references throughout the language. It also doesn't require reference
to other languages simply to define Python's model in terms of what it
isn't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-07 Thread Alf P. Steinbach

* Steve Holden:

Alf P. Steinbach wrote:

* MRAB:

Alf P. Steinbach wrote:

* Chris Rebert:

On Sun, Feb 7, 2010 at 5:05 PM, T misceveryth...@gmail.com wrote:

Ok, just looking for a sanity check here, or maybe something I'm
missing.  I have a class Test, for example:

class Test:
   def __init__(self, param1, param2, param3):
   self.param1 = param1
   self.param2 = param2
   self.param3 = param3

Next, I have a dictionary mytest that contains instances of Test.  If
I want to modify one of the Test instances within my dictionary, I
have to rewrite the entire entry, correct (since Python passes by
value, not reference)?

Incorrect; Python uses neither. See
http://effbot.org/zone/call-by-object.htm for a excellent explanation
of what Python does use.

Hm. While most everything I've seen at effbot.org has been clear and
to the point, that particular article reads like a ton of obfuscation.

Python passes pointers by value, just as e.g. Java does.

There, it needed just 10 words or so. :-) Or perhaps some more words
to point out that in the Java language spec those reference values
are called pointers, but that this terminology isn't (apparently)
used for Python, and isn't even well known among Java programmers.
But that's just one extra little para.

One just has to be clear about exactly what it is that's passed by
value.

Not Python objects, but references (pointers) to them, the id(o) values.


A reference is not the same as a pointer.

Depends on your choice terminology. I referred to the Java (language
spec) terminology to make it clear.



A pointer tells you where something is; a reference doesn't.

Sorry, I don't know of any relevant terminology where that is the case.


Alf:

This topic was discussed at great, nay interminable, length about a year
ago. I'd appreciate it if you would search the archives and read what
was said then rather than hashing the whole topic over again to nobody's
real advantage.


Well that's my point, and thanks for backing me up on that :-): it's very 
simple, and as demonstrated can be expressed in 10 words or less (plus perhaps a 
terminology reference, as I did above), so all that discussion and in particular 
the lengthy article at effbot serves as obfuscation and nothing else.


By the way, most every programming language has some corner like that, something 
that is utterly simple but somehow has some kind of obfuscation-meme attached.


In C++ it's call and constructor. It doesn't help that the language's 
standard lays down the law on it, it doesn't help that the language's creator 
has laid down the law, it doesn't help that it's utterly and completely simple. 
Somehow newbies and even some experienced people manage to create their own 
terminological nightmare  and drawing conclusions about reality from that 
misguided obfuscated view, and then discussing it up and down and sideways.



Cheers  hth.,

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


C/C++ Import

2010-02-07 Thread 7H3LaughingMan
To make the background information short, I am trying to take a
program that uses Python for scripting and recompile it for Linux
since it originally was built to run on Win32. The program itself was
designed to be able to be compiled on Linux and someone made there on
release with source that added python scripting. After some issues I
got it to compile but now it is unable to import the files that it
needs.

The program is running the following code...
PyImport_Import( PyString_FromString(python.PlayerManager) );

This is meant to import the file PlayerManager.py inside of the python
folder. However it throws the following Python Error (Gotten through
PyErr_Print())
ImportError: No module named python.PlayerManager

I am using 2.6.4 so I can't call it by the filename, does anyone know
how to do a proper import?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-07 Thread Steven D'Aprano
On Mon, 08 Feb 2010 02:51:05 +0100, Alf P. Steinbach wrote:

 Python passes pointers by value, just as e.g. Java does.

How do I get a pointer in pure Python code (no ctypes)? I tried both 
Pascal and C syntax (^x and *x), but both give syntax errors.

For that matter, how do I get a pointer in Java code?

If Python doesn't have pointers, then why are you talking about Python 
passing pointers? It's a vacuous truth, like saying that Python passes 
dinosaurs by name.



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


Re: Modifying Class Object

2010-02-07 Thread T
Oops, this one was my fault - the object I was having the issues with
was actually a shelve file, not a dictionary..so just re-assigning the
variable isn't working, but re-writing the object to the shelve file
does.  So in this case, is there any way to just change a single
value, or am I stuck rewriting the entry?
-- 
http://mail.python.org/mailman/listinfo/python-list


Python 2.4 and list of dictionary issues

2010-02-07 Thread Chris Stevens
Hi all,

I'm a python newbie so please excuse me if I am missing something
simple here. I am writing a script which requires a list of
dictionaries (originally a dictionary of dictionaries, but I changed
it to a list to try and overcome the below problem).

Now my understanding is that you create the empty list, then append or
add entries to it. Correct?

Here is some code:

userInfo = []
...
userInfo.append( {
'username' : uidString[0],
...
'failedattempts' : int(0)
})

I'm not to sure on the bracketing here, but I have tried many
combinations. The issue here is that I get a IndexError: list index
out of range message on the line userInfo.append( {

I wrote this script on a box with Python 2.6 and it worked fine.
Moving it to a box with 2.4, and I get this error. I can't understand
why i'm getting a list index out of range error when trying to append
(not reference) a list?? I have also tried +=, and
userInfo(len(userInfo))=  just get the same error.

Could anyone shed some light on this?

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


Re: Modifying Class Object

2010-02-07 Thread Steven D'Aprano
On Mon, 08 Feb 2010 03:21:11 +0100, Alf P. Steinbach wrote:

 A pointer tells you where something is; a reference doesn't.
 
 Sorry, I don't know of any relevant terminology where that is the case.

Taken from Wikipedia:

A pointer is a simple, less abstracted implementation of the more 
abstracted reference data type (although it is not as directly usable as 
a C++ reference).

http://en.wikipedia.org/wiki/Pointer_(computing)

In other words, a pointer is a specific type of reference. A reference in 
turn is an opaque but low-level data type which refers to in some way 
to the data you actually care about. (C++ has a concrete reference type, 
which is not to be confused with abstract references.)

http://en.wikipedia.org/wiki/Reference_(computer_science)

Unless otherwise stated, references are opaque and coders need not care 
how the reference mechanism is implemented, see e.g.:

http://www.cocoabuilder.com/archive/cocoa/20777-opaque-reference.html

In Python you don't use references directly, there is no reference type 
or object. You can simulate the semantics of references (but not 
pointers) by putting your object in a list and passing the list around.



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


Re: Modifying Class Object

2010-02-07 Thread Alf P. Steinbach

* Steven D'Aprano:

On Mon, 08 Feb 2010 02:51:05 +0100, Alf P. Steinbach wrote:


Python passes pointers by value, just as e.g. Java does.


How do I get a pointer in pure Python code (no ctypes)? I tried both 
Pascal and C syntax (^x and *x), but both give syntax errors.


Well, I don't believe that you tried that. :-)

From one point of view it's extremely easy: just create some object, even just 
type 42 as an integer literal, and you can apply all of Python's pointer 
operations to the result  --  which isn't much, basically just checking for 
pointer equality via 'is' or applying 'id' to get a value that represents the 
pointer uniquely, or copying the pointer via assignment or parameter passing.


Whether you can obtain the bits of the internal pointer value, represented as 
e.g. an int, formally depends on the Python implementation.


In CPython the 'id' function provides the internal pointer value as an int.

I.e., with CPython you can do

  def foo( o ):
  print( id( o ) )# Shows the pointer value in decimal.

  whatever = 42
  print( id( whatever ) ) # Shows the pointer value in decimal.
  foo( whatever ) # Shows the exact *same* pointer value.

which at a slightly higher level of abstraction works just as well with any 
conceivable Python implementation, although you have no formal guarantee that 
the conceptual pointer values are actually the internally memory addresses.


But, in CPython they are, and you run into them all the time, for example (where 
the at tells you that it's a memory location specification, a pointer),


   import turtle
   turtle.forward
  function forward at 0x00DB7D20
  
   id( turtle.forward )
  14384416
   hex( id( turtle.forward ) )
  '0xdb7d20'
   _



For that matter, how do I get a pointer in Java code?


As with Python, from one point of view it's extremely easy, just 'new' some 
object, and then you can apply all of Java's pure pointer operations to the 
result  --  which isn't much, basically just checking for pointer equality and 
copying a pointer via assignment or parameter passing.


In Java it's a pointer by definition, namely the language spec's definition.

From another point of view, getting at the internal representation of the 
pointer is a bit harder in Java than in Python, at least as far as I know. It 
may not be practically possible. Disclaimer: I'm not a Java expert, and haven't 
used Java for years, and it just might be possible by using JNI (Java Native 
Interface), but that requires you to write a dynamic library in e.g. C or C++, 
and as I recall Java just creates a kind of fixed reference for the duration of 
a JNI call so the JNI side of things may not tell you anything about the Java 
side of things before or after the call.


But if it helps, just to learn about pointers in various languages you  --  or 
rather, some other reader, because I suspect that you know this already! :-) -- 
 might look at url: http://cslibrary.stanford.edu/106/.


It contains a simple pointers example expressed in four different languages, 
namely C, C++, Pascal and Java, in particular comparing C and Java.



If Python doesn't have pointers, then why are you talking about Python 
passing pointers? It's a vacuous truth, like saying that Python passes 
dinosaurs by name.


See above.


Cheers  hth.,

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


Re: How to print all expressions that match a regular expression

2010-02-07 Thread hzh...@gmail.com


 Please check out this example on the pyparsing wiki, 
 invRegex.py:http://pyparsing.wikispaces.com/file/view/invRegex.py.  This code
 implements a generator that returns successive matching strings for
 the given regex.  Running it, I see that you actually have a typo in
 your example.

  print list(invert([1|2|3]{2}))

 ['11', '1|', '12', '13', '|1', '||', '|2', '|3', '21', '2|', '22',
 '23', '31', '3|', '32', '33']

 I think you meant either [123]{2} or (1|2|3){2}.

  print list(invert([123]{2}))

 ['11', '12', '13', '21', '22', '23', '31', '32', '33']

  print list(invert((1|2|3){2}))

 ['11', '12', '13', '21', '22', '23', '31', '32', '33']

 Of course, as other posters have pointed out, this inverter does not
 accept regexen with unbounded multiple characters '+' or '*', but '?'
 and {min,max} notation will work.  Even '.' is supported, although
 this can generate a large number of return values.

 Of course, you'll also have to install pyparsing to get this to work.

 -- Paul


Hi Paul,

Thanks very much. This is exactly what I need now. I will check this
function.

Zhuo

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


Re: Modifying Class Object

2010-02-07 Thread Alf P. Steinbach

* Steven D'Aprano:

On Mon, 08 Feb 2010 03:21:11 +0100, Alf P. Steinbach wrote:


A pointer tells you where something is; a reference doesn't.

Sorry, I don't know of any relevant terminology where that is the case.


Taken from Wikipedia:

A pointer is a simple, less abstracted implementation of the more 
abstracted reference data type (although it is not as directly usable as 
a C++ reference).


http://en.wikipedia.org/wiki/Pointer_(computing)

In other words, a pointer is a specific type of reference. A reference in 
turn is an opaque but low-level data type which refers to in some way 
to the data you actually care about. (C++ has a concrete reference type, 
which is not to be confused with abstract references.)


http://en.wikipedia.org/wiki/Reference_(computer_science)

Unless otherwise stated, references are opaque and coders need not care 
how the reference mechanism is implemented, see e.g.:


http://www.cocoabuilder.com/archive/cocoa/20777-opaque-reference.html

In Python you don't use references directly, there is no reference type 
or object. You can simulate the semantics of references (but not 
pointers) by putting your object in a list and passing the list around.


Yes, sort of.

The last paragraph however confuses two different meanings of reference.

So when using terms such as reference it helps to refer :-) to some specific 
terminology, unless that's clearly understood from context.



Cheers,

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


Re: python admin abuse complaint

2010-02-07 Thread Aahz
In article mailman.2130.1265592763.28905.python-l...@python.org,
Jean-Michel Pichavant  jeanmic...@sequans.com wrote:

So guys, just ignore him if you don't like him. Mailers  news readers 
have plenty of feature to make it happen.

Unfortunately, unless you have a stable group of people with
self-control, that doesn't work.  Idiots like Xah will always get
responses.  (This opinion brought to you by two decades of experience
with BBS, mailing lists, and Usenet.)
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

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


Re: Python 2.4 and list of dictionary issues

2010-02-07 Thread Chris Rebert
On Sun, Feb 7, 2010 at 9:08 PM, Chris Stevens cjstev...@gmail.com wrote:
 Hi all,

 I'm a python newbie so please excuse me if I am missing something
 simple here. I am writing a script which requires a list of
 dictionaries (originally a dictionary of dictionaries, but I changed
 it to a list to try and overcome the below problem).

 Now my understanding is that you create the empty list, then append or
 add entries to it. Correct?

 Here is some code:

 userInfo = []
 ...
 userInfo.append( {
                                                'username' : uidString[0],
                                                ...
                                                'failedattempts' : int(0)
 })

 I'm not to sure on the bracketing here, but I have tried many
 combinations. The issue here is that I get a IndexError: list index
 out of range message on the line userInfo.append( {

Please include the full and exact error Traceback, and remember to do
so in the future.

 I wrote this script on a box with Python 2.6 and it worked fine.
 Moving it to a box with 2.4, and I get this error. I can't understand
 why i'm getting a list index out of range error when trying to append
 (not reference) a list?? I have also tried +=, and
 userInfo(len(userInfo))=  just get the same error.

 Could anyone shed some light on this?

I would guess that `uidString` is probably an empty string or list,
thus when you try to access the first character or item of it via
uidString[0], you get an error. However, as you didn't include a
Traceback, I can't be sure. I have no idea why the error only shows
itself for certain Python versions; the problem is probably in some
part of the code you're not showing us.

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


  1   2   >