Re: Writing byte stream as jpeg format to disk

2010-08-27 Thread Bryan
Robert Kern wrote:
> Please
> follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to
> make sure that you do not split on spurious b'\r\n\r\n' sequences inside the
> JPEG body. Do not decode the bytes.

Correct, and I'll add that this is a case where we might want to be
better than correct. BaseHTTPRequestHandler in the Python standard
library accommodates clients that incorrectly omit the '\r' and end
header lines with just '\n'. Such apps have been seen in the wild.
Since bare '\n' never appears in correctly formed HTTP headers,
interpreting it as equivalent to '\r\n' doesn't break anything.

The re module offers a split that does what we want.

  import re
  boundary_re = re.compile(br'\r?\n\r?\n')

then you can use:

  (headers, content) = boundary_re.split(rawdata, 1)

I like Robert's suggestion to use the HTTP server or wsgiref in the
Python library. There's significant arcane wisdom programmed in
already.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading the access attributes of directories in Windows

2010-08-27 Thread Rami Chowdhury
On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro
 wrote:
> In message , Nobody wrote:
>
>> Having this as a separate permission allows normal users to add entries to
>> log files but not to erase existing entries.
>
> Unix/Linux systems can do this already.

Ooh, I didn't know that -- what combination of permissions would I
have to use to get such an effect?

-- 
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading the access attributes of directories in Windows

2010-08-27 Thread Nobody
On Fri, 27 Aug 2010 13:28:46 +0600, Rami Chowdhury wrote:

>>> Having this as a separate permission allows normal users to add entries
>>> to log files but not to erase existing entries.
>>
>> Unix/Linux systems can do this already.
> 
> Ooh, I didn't know that -- what combination of permissions would I have to
> use to get such an effect?

You can't do it with permissions, you need to use ext2 attributes.
Specifically, "chattr +a " will set the "append" attribute,
which prevents the file being opened for write except in append mode.
Changing this attribute requires root privilege or the CAP_LINUX_IMMUTABLE
capability.

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


Re: Writing byte stream as jpeg format to disk

2010-08-27 Thread Nobody
On Thu, 26 Aug 2010 23:56:26 -0700, Bryan wrote:

>> follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1
>> argument to make sure that you do not split on spurious b'\r\n\r\n'
>> sequences inside the JPEG body. Do not decode the bytes.
> 
> Correct, and I'll add that this is a case where we might want to be better
> than correct. BaseHTTPRequestHandler in the Python standard library
> accommodates clients that incorrectly omit the '\r' and end header lines
> with just '\n'. Such apps have been seen in the wild. Since bare '\n'
> never appears in correctly formed HTTP headers, interpreting it as
> equivalent to '\r\n' doesn't break anything.

Yes it does. It breaks upstream filtering rules which are intended to
prohibit, remove or modify certain headers.

This class of attack is known as "HTTP request smuggling". By
appending a header preceded by a bare '\r' or '\n' to the end of
another header, the header can be "smuggled" past a filter which
parses headers using the correct syntax, but will still be treated as a
header by software which incorrectly parses headers using bare '\r' or
'\n' as separators.

The safest solution would be to simply reject any request (or response)
which contains bare '\r' or '\n' characters within headers, at least by
default. Force the programmer to read the documentation (where the risks
would be described) if they want the "fault tolerant" behaviour.

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


palindrome iteration

2010-08-27 Thread Baba
level: beginner

the following code looks ok to me but it doesn't work. I would like
some hints as to where my reasoning / thought goes wrong

def i_palindrome(pal):
 while len(pal)>1:
  if pal[0] == pal[-1]:
   pal=pal[1:-1]
 return True

print i_palindrome('annab')


my reasoning:
- i check the length of the string: if > 1 continue
- i check first and last char: if they are equal continue
- create a new, shorter string starting at index 1 and ending at
second last index (up to but not including index-1
-restart the while loop as long as length of string is > 1
- exiting this loop means all compared chars were identical hence it
is a palindrome and i return True

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


Re: palindrome iteration

2010-08-27 Thread Xavier Ho
One possible reason I can think of -
"- exiting this loop means all compared chars were identical hence it
is a palindrome and i return True"

is probably incorrect reasoning. Think again.

Also, you may consider posting your code in a way that preserves the
whitespace characters.

Cheers,
Xav

On 27 August 2010 18:53, Baba  wrote:

> level: beginner
>
> the following code looks ok to me but it doesn't work. I would like
> some hints as to where my reasoning / thought goes wrong
>
> def i_palindrome(pal):
>  while len(pal)>1:
>  if pal[0] == pal[-1]:
>   pal=pal[1:-1]
>  return True
>
> print i_palindrome('annab')
>
>
> my reasoning:
> - i check the length of the string: if > 1 continue
> - i check first and last char: if they are equal continue
> - create a new, shorter string starting at index 1 and ending at
> second last index (up to but not including index-1
> -restart the while loop as long as length of string is > 1
> - exiting this loop means all compared chars were identical hence it
> is a palindrome and i return True
>
> tnx
> Baba
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Peter Otten
Baba wrote:

> level: beginner
> 
> the following code looks ok to me but it doesn't work. I would like
> some hints as to where my reasoning / thought goes wrong
> 
> def i_palindrome(pal):
>  while len(pal)>1:
>   if pal[0] == pal[-1]:
>pal=pal[1:-1]
>  return True

Do yourself a favour and use 4-space indent. That makes the structure of 
your code more obvious.
 
> print i_palindrome('annab')
> 
> 
> my reasoning:
> - i check the length of the string: if > 1 continue
> - i check first and last char: if they are equal continue
> - create a new, shorter string starting at index 1 and ending at
> second last index (up to but not including index-1
> -restart the while loop as long as length of string is > 1
> - exiting this loop means all compared chars were identical hence it
> is a palindrome and i return True

If the test pal[0] == pal[-1] fails, i. e. the two compared characters 
differ, what happens?

More generally, if pal is not a palindrome, can your function ever return 
False? If not, at what point should it?

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


Re: palindrome iteration

2010-08-27 Thread Bruno Desthuilliers

Baba a écrit :

level: beginner

the following code looks ok to me but it doesn't work.


"doesn't work" is about the most useless description of a problem. 
Please specify what you expected and what actually happens.



I would like
some hints as to where my reasoning / thought goes wrong

def i_palindrome(pal):
 while len(pal)>1:
  if pal[0] == pal[-1]:
   pal=pal[1:-1]


Can you explain what happens if pal[0] != pal[-1] ? (answer below)


 return True



print i_palindrome('annab')


And then you go in an infinite loop !-)



my reasoning:
- i check the length of the string: if > 1 continue
- i check first and last char: if they are equal continue
- create a new, shorter string starting at index 1 and ending at
second last index (up to but not including index-1
-restart the while loop as long as length of string is > 1
- exiting this loop means all compared chars were identical hence it
is a palindrome and i return True


Your problem is that when first and last char are not equal, you don't 
exit the while loop. You need a "return False" somewhere here, ie:


def is_palindrom(pal):
  while len(pal)>1:
# NB : inverted the test here to make exit more obvious
if pal[0] != pal[-1]:
  return False
pal=pal[1:-1]
  return True


Now there is another solution. A palindrom is made of two symetric 
halves, with (odd len) or without (even len) a single char between the 
symetric halves, ie :


* odd : ABCBA ('AB' + 'C' + 'BA')
* even : ABCCBA ('ABC' + 'CBA')

So you just have to extract the symetric halves, reverse one, and 
compare both (case insensitive compare while we're at it). Here's a 
possible (and a bit tricky) Python 2.x implementation:


def is_palindrom(s):
s = s.lower()
slen = len(s)
until = slen / 2 # Python 2x integer division
offset = int(not(slen % 2))
runtil = until - offset
return s[0:until] == s[-1:runtil:-1]


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


Re: palindrome iteration

2010-08-27 Thread Richard Arts
> Now there is another solution. A palindrom is made of two symetric halves,
> with (odd len) or without (even len) a single char between the symetric
> halves, ie :
>
> * odd : ABCBA ('AB' + 'C' + 'BA')
> * even : ABCCBA ('ABC' + 'CBA')
>
> So you just have to extract the symetric halves, reverse one, and compare
> both (case insensitive compare while we're at it).

Yes, this is a correct observation, but it is not necessary to compare
the halves; Simply compare the complete string with its reverse. If
they match, it is a palindrome.

> Here's a possible (and a
> bit tricky) Python 2.x implementation:
>
> def is_palindrom(s):
>    s = s.lower()
>    slen = len(s)
>    until = slen / 2 # Python 2x integer division
>    offset = int(not(slen % 2))
>    runtil = until - offset
>    return s[0:until] == s[-1:runtil:-1]
>
>

At first glance this seems to be correct, but it is tricky indeed.
Particularly the assignment of the offset variable, casting a bool to
an integer of a negated expression. Given that Baba notes that this is
a beginners level query, it wouldn't have hurt to be a little bit more
verbose there.

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


Re: pil and reportlab: image compression

2010-08-27 Thread steph
On 26 Aug., 13:16, steph  wrote:
> Hi group,
>
> I've written a small application that puts images into a pdf document.
> It works ok, but my problem is that the pdf-files become quite huge,
> bigger than the original jpegs. The problem seems to arise because I
> use PIL to resize the pictures - and the images seem to get
> uncompressed in the process. Unfortunately I have not found a way to
> compress them again before rendering them to the pdf. Any clues?
>
> Thanks,
> Stephan

Solved this by writung to anonymous mmap. Works nicely :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Matteo Landi
> Yes, this is a correct observation, but it is not necessary to compare
> the halves; Simply compare the complete string with its reverse. If
> they match, it is a palindrome.

I've always used to implement the is_palindrome function as you
suggest, i.e. comparing the original string with the reverse one, but
while reading, I tought about a imho nicer version which prevent from
creating another string.

Here are both the recursive/iterative versions of the function:

def palindrome(str, i=0, j=-1):
try:
if str[i] == str[j]:
return palindrome(str, i + 1, j - 1)
return False
except IndexError:
return True

def palindrome(str, i=0, j=-1):
try:
while True:
if str[i] != str[j]:
return False
i, j = i + 1, j - 1
return True
except IndexError:
return True

Regards,
Matteo

>
>> Here's a possible (and a
>> bit tricky) Python 2.x implementation:
>>
>> def is_palindrom(s):
>>    s = s.lower()
>>    slen = len(s)
>>    until = slen / 2 # Python 2x integer division
>>    offset = int(not(slen % 2))
>>    runtil = until - offset
>>    return s[0:until] == s[-1:runtil:-1]
>>
>>
>
> At first glance this seems to be correct, but it is tricky indeed.
> Particularly the assignment of the offset variable, casting a bool to
> an integer of a negated expression. Given that Baba notes that this is
> a beginners level query, it wouldn't have hurt to be a little bit more
> verbose there.
>
> Richard
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Dave Angel



Bruno Desthuilliers wrote:
Baba a 
écrit :

level: beginner

the following code looks ok to me but it doesn't work.


"doesn't work" is about the most useless description of a problem. 
Please specify what you expected and what actually happens.



I would like
some hints as to where my reasoning / thought goes wrong

def i_palindrome(pal):
 while len(pal)>1:
  if pal[0] == pal[-1]:
   pal=pal[1:-1]


Can you explain what happens if pal[0] != pal[-1] ? (answer below)


 return True



print i_palindrome('annab')


And then you go in an infinite loop !-)



my reasoning:
- i check the length of the string: if > 1 continue
- i check first and last char: if they are equal continue
- create a new, shorter string starting at index 1 and ending at
second last index (up to but not including index-1
-restart the while loop as long as length of string is > 1
- exiting this loop means all compared chars were identical hence it
is a palindrome and i return True


Your problem is that when first and last char are not equal, you don't 
exit the while loop. You need a "return False" somewhere here, ie:


def is_palindrom(pal):
  while len(pal)>1:
# NB : inverted the test here to make exit more obvious
if pal[0] != pal[-1]:
  return False
pal=pal[1:-1]
  return True


Now there is another solution. A palindrom is made of two symetric 
halves, with (odd len) or without (even len) a single char between the 
symetric halves, ie :


* odd : ABCBA ('AB' + 'C' + 'BA')
* even : ABCCBA ('ABC' + 'CBA')

So you just have to extract the symetric halves, reverse one, and 
compare both (case insensitive compare while we're at it). Here's a 
possible (and a bit tricky) Python 2.x implementation:


def is_palindrom(s):
s = s.lower()
slen = len(s)
until = slen / 2 # Python 2x integer division
offset = int(not(slen % 2))
runtil = until - offset
return s[0:until] == s[-1:runtil:-1]



or  (untested)
def is_palindrom(s):
   s = s.lower()
   return s == s[::-1]

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


Re: Writing byte stream as jpeg format to disk

2010-08-27 Thread Bryan
Nobody wrote:
> Bryan wrote:
> > this is a case where we might want to be better
> > than correct. BaseHTTPRequestHandler in the Python standard library
> > accommodates clients that incorrectly omit the '\r' and end header lines
> > with just '\n'. Such apps have been seen in the wild. Since bare '\n'
> > never appears in correctly formed HTTP headers, interpreting it as
> > equivalent to '\r\n' doesn't break anything.
>
> Yes it does. It breaks upstream filtering rules which are intended to
> prohibit, remove or modify certain headers.
>
> This class of attack is known as "HTTP request smuggling". By
> appending a header preceded by a bare '\r' or '\n' to the end of
> another header, the header can be "smuggled" past a filter which
> parses headers using the correct syntax,

How does a bare '\r' or '\n' get past a filter which parses headers
using the correct syntax? I don't see where the correct syntax of the
HTTP protocol allows that.

> but will still be treated as a
> header by software which incorrectly parses headers using bare '\r' or
> '\n' as separators.

Why blame software that incorrectly accepts '\n' as a line break, and
not the filter that incorrectly accepted '\n' in the middle of a
header? Both are accepting incorrect syntax, but only the former has
good reason to do so.

> The safest solution would be to simply reject any request (or response)
> which contains bare '\r' or '\n' characters within headers, at least by
> default. Force the programmer to read the documentation (where the risks
> would be described) if they want the "fault tolerant" behaviour.

The Internet has a tradition of protocols above the transport level
being readable by eye and writable by hand. The result has been quick
development, but many mistakes that can induce unforeseen
consequences.

This case is somewhat subtle. Within a text entity-body, HTTP allows
any one of the three end-of-line delimiters. That's just the body; the
header portion is more rigid. In HTTP 1.0:

   "This flexibility regarding line breaks applies only to text
   media in the Entity-Body; a bare CR or LF should not be
   substituted for CRLF within any of the HTTP control
   structures (such as header fields and multipart boundaries)."
   -- RFC 1945

While in HTTP 1.1:

   "This flexibility regarding line breaks applies only to text
   media in the entity-body; a bare CR or LF MUST NOT be
   substituted for CRLF within any of the HTTP control
   structures (such as header fields and multipart boundaries)."
   -- RFC 2616

Note the change from "should not" to "MUST NOT". In reality our code
might be called upon to work with apps that botch the technically-
correct HTTP end-of-line marker. Rejecting bare '\n' may be safe from
a technical security perspective, but if our safe code breaks a
previously working system, then it will appear in a bug database and
not in production.

'Nobody' makes a fair point. I'd love to see Internet protocols
defined with mechanical rigor. Our discipline commonly specifies
programming language syntax formally, and Internet protocols are
syntactically simpler than programming languages. For now, HTTP is a
bit of a mess, so write it absolutely correctly but read it a bit
flexibly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Bruno Desthuilliers

Richard Arts a écrit :

Now there is another solution. A palindrom is made of two symetric halves,
with (odd len) or without (even len) a single char between the symetric
halves, ie :

* odd : ABCBA ('AB' + 'C' + 'BA')
* even : ABCCBA ('ABC' + 'CBA')

So you just have to extract the symetric halves, reverse one, and compare
both (case insensitive compare while we're at it).


Yes, this is a correct observation, but it is not necessary to compare
the halves; Simply compare the complete string with its reverse. If
they match, it is a palindrome.


Duh :(

I kinda feel stupid right now, thanks Richard :-/


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


Re: palindrome iteration

2010-08-27 Thread Bruno Desthuilliers

Dave Angel a écrit :
(snip)


or  (untested)
def is_palindrom(s):
   s = s.lower()
   return s == s[::-1]




Right, go on, make me feel a bit more stupid :-/
Who's next ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused: Newbie Function Calls

2010-08-27 Thread Aahz
In article <2dd74ab4-5ed6-40ac-aea7-705977b61...@g21g2000prn.googlegroups.com>,
fuglyducky   wrote:
>
>I am a complete newbie to Python (and programming in general) and I
>have no idea what I'm missing. Below is a script that I am trying to
>work with and I cannot get it to work. 

Side note: while it's fine to ask newbie questions on comp.lang.python,
you may want to use resources oriented more toward newbies, such as the
tutor list:

http://www.python.org/about/help/
http://www.python.org/mailman/listinfo/tutor
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box."  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread D'Arcy J.M. Cain
On Fri, 27 Aug 2010 11:49:42 -0400
"D'Arcy J.M. Cain"  wrote:
> is_palindrome = lambda x: x == x.lower()[::-1]

Oops.  Simple and wrong.

is_palindrome = lambda x: x.lower() == x.lower()[::-1]

-- 
D'Arcy J.M. Cain  |  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: palindrome iteration

2010-08-27 Thread Mark Lawrence

On 27/08/2010 15:43, Bruno Desthuilliers wrote:

Dave Angel a écrit :
(snip)


or (untested)
def is_palindrom(s):
s = s.lower()
return s == s[::-1]




Right, go on, make me feel a bit more stupid :-/
Who's next ?


It could be worse, try responding to issue 9702. :)

Cheers.

Mark Lawrence.

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


layer geld verdienen , leicht geldverdienen , wie kann ich onlinespiele geld gewinnen , geldgewinnspiele , zu geld machen , geld machen beim , pennergame geld verdienen , schnell geld vedienen , ohne

2010-08-27 Thread marianne rosen
layer geld verdienen , leicht geldverdienen , wie kann ich
onlinespiele geld gewinnen , geldgewinnspiele , zu geld machen , geld
machen beim , pennergame geld verdienen , schnell geld vedienen , ohne
geld online , geld mit online casino ,

*
*
*
+++ SOFORT GEWINN +++ REICH WERDEN +++
*
http://WWW.SOFORT-GEWINN-JETZT-1.NET
http://WWW.SOFORT-GEWINN-JETZT-1.NET
http://WWW.SOFORT-GEWINN-JETZT-1.NET
http://WWW.SOFORT-GEWINN-JETZT-1.NET
http://WWW.SOFORT-GEWINN-JETZT-1.NET
http://WWW.SOFORT-GEWINN-JETZT-1.NET
*
*
*






ich will bargeld gewinn leicht viel geld verdienen
wie kann ich online casino geld gewinnen wo kann ich geld am pc
verdienen
schnell geld verdienen im internet man mit dem internet geld
schnell geld verdienen ohne internet viel geld verdienen
drakensang geld machen uploads geld verdienen
internet noch geld geld im internet forum
geld verdienen durch internet ws schnell sofort geld gewinnen
shop geld verdienen wie kann ich geld gewinnen bei
mann schnell geld machen man leicht geld
texte schreiben geld verdienen mit internet geld machen
geld verdienen leicht gemacht wo kann ich geld gewinn spiel
eigenen fotos geld verdienen kann man geld gewinnen
pennergame geld machen einfach online geld verdienen
wo kann ich geld am pc verdienen ich schnelles geld machen
werbung internet geld geld verdienen im internet forum
kann man online geld verdienen gewinnspiel gewinnen jetzt sofort
mann geld machen schnell und legal geld verdienen
online um echtes geld spielen sofort geld gewonnen
wie kann ich geld gewinnen bei internet leicht geld
uploaded to geld verdienen leichtes geld verdienen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Ian

 On 27/08/2010 09:53, Baba wrote:

level: beginner

the following code looks ok to me but it doesn't work. I would like
some hints as to where my reasoning / thought goes wrong

def i_palindrome(pal):
  while len(pal)>1:
   if pal[0] == pal[-1]:
pal=pal[1:-1]
  return True

print i_palindrome('annab')


If you want to or must  do it recursively.
(Shown in pseudo code to make the logic clearer)

def isPalindrome(pal)
''' test pal (a list) is a palindrome '''
if length of pal = 1
return True # all one letter strings are palindromes.
if first equals last
# pal could be a palindrome
#  so test inner part
p = pal with first and last removed
return  isPalendrome(p)   #  and true - implied
else
return False # it can't be

Of course, the simpler way is to use the definition of a Palindrome as 
the same backwards and forwards.


def isPalindrome(pal)
return pal == pal.reverse



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


numpy is not installed with Python2.

2010-08-27 Thread justin
My university has a cluster computer, on which I want to run my python
program that uses numpy.
I am installing my Python2.7 locally separated from the main system,
and trying to install numpy, attach it with Python2.7.
I used many different versions of numpys to make it happen, but I got
stuck with the same following error on every trial,

"[...@login1 numpy]$ python2.7 setup.py install
Running from numpy source directory.Traceback (most recent call last):
  File "setup.py", line 210, in 
setup_package()
  File "setup.py", line 187, in setup_package
from numpy.distutils.core import setup
  File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in

from numpy.distutils.command import config, config_compiler, \
  File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py",
line 9, in 
from distutils.command.build_ext import build_ext as old_build_ext
  File "/users/hp6/apps/python27/lib/python2.7/distutils/command/
build_ext.py", line 13, in 
from site import USER_BASE, USER_SITE
ImportError: cannot import name USER_BASE"

It seems the error is related to the inability of Python2.7 to process
"from site import USER_BASE, USER_SITE",
since the machine I succeeded to install numpy with Python2.7 doesn't
prompt an error from this command,
whereas this machine in which I failed to do so cannot handle this.

My question is:
How can I make Python2.7 to process this, since the manual says this
package is the one that's automatically turned on in startup.

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


Re: palindrome iteration

2010-08-27 Thread D'Arcy J.M. Cain
On Fri, 27 Aug 2010 16:43:16 +0200
Bruno Desthuilliers  wrote:
> Dave Angel a écrit :
> > def is_palindrom(s):
> >s = s.lower()
> >return s == s[::-1]
> 
> 
> Right, go on, make me feel a bit more stupid :-/
> Who's next ?

How about a one-liner?

is_palindrome = lambda x: len(x)> 0 and x == x.lower()[::-1]

Note that the above assumes that single characters are palindromes but
empty strings are not.  I'm not 100% sure that that last is true.  If
not then this can be simplified.

is_palindrome = lambda x: x == x.lower()[::-1]

-- 
D'Arcy J.M. Cain  |  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: Queue cleanup

2010-08-27 Thread Aahz
In article ,
MRAB   wrote:
>
>An object will be available for garbage collection when nothing refers
>to it either directly or indirectly. If it's unreferenced then it will
>go away.

This isn't actually garbage collection as most people think of it.
Refcounting semantics mean that objects get reaped as soon as nothing
points at them.  OTOH, CPython does also have garbage collection to back
up refcounting so that when you have unreferenced object cycles they
don't stay around.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box."  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread MRAB

On 27/08/2010 17:20, Mark Lawrence wrote:

On 27/08/2010 15:43, Bruno Desthuilliers wrote:

Dave Angel a écrit :
(snip)


or (untested)
def is_palindrom(s):
s = s.lower()
return s == s[::-1]




Right, go on, make me feel a bit more stupid :-/
Who's next ?


It could be worse, try responding to issue 9702. :)


As a wise man once said: Ay caramba! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: numpy is not installed with Python2.

2010-08-27 Thread Robert Kern

On 8/27/10 11:40 AM, justin wrote:

My university has a cluster computer, on which I want to run my python
program that uses numpy.
I am installing my Python2.7 locally separated from the main system,
and trying to install numpy, attach it with Python2.7.
I used many different versions of numpys to make it happen, but I got
stuck with the same following error on every trial,

"[...@login1 numpy]$ python2.7 setup.py install
Running from numpy source directory.Traceback (most recent call last):
   File "setup.py", line 210, in
 setup_package()
   File "setup.py", line 187, in setup_package
 from numpy.distutils.core import setup
   File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in

 from numpy.distutils.command import config, config_compiler, \
   File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py",
line 9, in
 from distutils.command.build_ext import build_ext as old_build_ext
   File "/users/hp6/apps/python27/lib/python2.7/distutils/command/
build_ext.py", line 13, in
 from site import USER_BASE, USER_SITE
ImportError: cannot import name USER_BASE"

It seems the error is related to the inability of Python2.7 to process
"from site import USER_BASE, USER_SITE",
since the machine I succeeded to install numpy with Python2.7 doesn't
prompt an error from this command,
whereas this machine in which I failed to do so cannot handle this.


Your Python installation appears to be broken. Find the site.py module that you 
are actually importing. I.e. from the numpy source directory:


  $ python2.7 -c "import site; print site.__file__"

This will tell you the site.pyc file that actually gets imported. Find the 
associated site.py file (it should be in the same directory) and check to see if 
it has USER_BASE defined. The filename should be


  /users/hp6/apps/python27/lib/python2.7/site.pyc

If it isn't, that may be the source of your problem.

--
Robert Kern

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

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


Re: palindrome iteration

2010-08-27 Thread Mark Lawrence

On 27/08/2010 17:53, MRAB wrote:

On 27/08/2010 17:20, Mark Lawrence wrote:

On 27/08/2010 15:43, Bruno Desthuilliers wrote:

Dave Angel a écrit :
(snip)


or (untested)
def is_palindrom(s):
s = s.lower()
return s == s[::-1]




Right, go on, make me feel a bit more stupid :-/
Who's next ?


It could be worse, try responding to issue 9702. :)


As a wise man once said: Ay caramba! :-)


Isn't that a syntax error?  Shouldn't it be  ¡Ay caramba! :)

Cheers.

Mark Lawrence.

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


Re: palindrome iteration

2010-08-27 Thread Terry Reedy

On 8/27/2010 4:53 AM, Baba wrote:

level: beginner

the following code looks ok to me but it doesn't work. I would like
some hints as to where my reasoning / thought goes wrong

def i_palindrome(pal):
  while len(pal)>1:
   if pal[0] == pal[-1]:
pal=pal[1:-1]
  return True

print i_palindrome('annab')


General practical debugging procedurewhen logic inspection fails: insert 
print statements at key points.


In the case above, put "print pal" before the if statement and you 
should see the problem. And/or "print 'equal'" after the if.


--
Terry Jan Reedy

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


Re: palindrome iteration

2010-08-27 Thread MRAB

On 27/08/2010 18:28, Mark Lawrence wrote:

On 27/08/2010 17:53, MRAB wrote:

On 27/08/2010 17:20, Mark Lawrence wrote:

On 27/08/2010 15:43, Bruno Desthuilliers wrote:

Dave Angel a écrit :
(snip)


or (untested)
def is_palindrom(s):
s = s.lower()
return s == s[::-1]




Right, go on, make me feel a bit more stupid :-/
Who's next ?


It could be worse, try responding to issue 9702. :)


As a wise man once said: Ay caramba! :-)


Isn't that a syntax error? Shouldn't it be ¡Ay caramba! :)


I stand (OK, sit) corrected.
--
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Jussi Piitulainen
Ian writes:

> If you want to or must  do it recursively.
> (Shown in pseudo code to make the logic clearer)
> 
> def isPalindrome(pal)
>  ''' test pal (a list) is a palindrome '''
>  if length of pal = 1
>  return True # all one letter strings are palindromes.
>  if first equals last
>  # pal could be a palindrome
>  #  so test inner part
>  p = pal with first and last removed
>  return  isPalendrome(p)   #  and true - implied
>  else
>  return False # it can't be

def palindromep(s): 
return ( s == "" or
 ( s[0] == s[-1] and
   palindromep(s[1:-1]) ) )

> Of course, the simpler way is to use the definition of a Palindrome
> as the same backwards and forwards.
> 
> def isPalindrome(pal)
>  return pal == pal.reverse

Agreed. But is there any nicer way to spell .reverse than [::-1] in
Python? There is .swapcase() but no .reverse(), right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mailbox.mbox not locking mbox properly

2010-08-27 Thread Chris Jewell
Even if you replace the python mbox code with something that uses
fcntl.flock() to protect against concurrent updating, you should also
understand that NFS does *not* provide full Unix filesystem semantics.
In particular, Unix flock(2) (which Python's fcntl.flock() wraps)
doesn't work over NFS.

That's why if you want to access mail over NFS, you should use maildir,
rather than mbox, no matter what your programming language.

-- 
Chris Jewell  chr...@puffin.com  PO Box 1396 Gualala CA USA 95445-1396
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy is not installed with Python2.

2010-08-27 Thread justin
On Aug 27, 12:10 pm, Robert Kern  wrote:
> On 8/27/10 11:40 AM, justin wrote:
>
>
>
>
>
> > My university has a cluster computer, on which I want to run my python
> > program that uses numpy.
> > I am installing my Python2.7 locally separated from the main system,
> > and trying to install numpy, attach it with Python2.7.
> > I used many different versions of numpys to make it happen, but I got
> > stuck with the same following error on every trial,
>
> > "[...@login1 numpy]$ python2.7 setup.py install
> > Running from numpy source directory.Traceback (most recent call last):
> >    File "setup.py", line 210, in
> >      setup_package()
> >    File "setup.py", line 187, in setup_package
> >      from numpy.distutils.core import setup
> >    File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in
> > 
> >      from numpy.distutils.command import config, config_compiler, \
> >    File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py",
> > line 9, in
> >      from distutils.command.build_ext import build_ext as old_build_ext
> >    File "/users/hp6/apps/python27/lib/python2.7/distutils/command/
> > build_ext.py", line 13, in
> >      from site import USER_BASE, USER_SITE
> > ImportError: cannot import name USER_BASE"
>
> > It seems the error is related to the inability of Python2.7 to process
> > "from site import USER_BASE, USER_SITE",
> > since the machine I succeeded to install numpy with Python2.7 doesn't
> > prompt an error from this command,
> > whereas this machine in which I failed to do so cannot handle this.
>
> Your Python installation appears to be broken. Find the site.py module that 
> you
> are actually importing. I.e. from the numpy source directory:
>
>    $ python2.7 -c "import site; print site.__file__"
>
> This will tell you the site.pyc file that actually gets imported. Find the
> associated site.py file (it should be in the same directory) and check to see 
> if
> it has USER_BASE defined. The filename should be
>
>    /users/hp6/apps/python27/lib/python2.7/site.pyc
>
> If it isn't, that may be the source of your problem.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>    -- Umberto Eco

Dear Kern,

Thanks a lot.
Your quick and detailed comment saves me a lot of time and effort
now.

It seems the file path links are out of order as you diagnosed.
Like you said, there is a site.py on /users/hp6/apps/python27/lib/
python2.7/.
But when I typed in "$ python2.7 -c "import site; print
site.__file__", it refers to another place:
"/opt/apps/gurobi/3.0.0/linux64/lib/python2.5/site.pyc", and it
doesn't have USER_BASE!

So I changed the value of PYTHONPATH accordingly.

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


Re: palindrome iteration

2010-08-27 Thread Dave Angel



Jussi Piitulainen wrote:

Ian writes:

  

If you want to or must  do it recursively.
(Shown in pseudo code to make the logic clearer)

def isPalindrome(pal)
 ''' test pal (a list) is a palindrome '''
 if length of pal = 1
 return True # all one letter strings are palindromes.
 if first equals last
 # pal could be a palindrome
 #  so test inner part
 p = pal with first and last removed
 return  isPalendrome(p)   #  and true - implied
 else
 return False # it can't be



def palindromep(s): 
return ( s == "" or

 ( s[0] == s[-1] and
   palindromep(s[1:-1]) ) )

  

Of course, the simpler way is to use the definition of a Palindrome
as the same backwards and forwards.

def isPalindrome(pal)
 return pal == pal.reverse



Agreed. But is there any nicer way to spell .reverse than [::-1] in
Python? There is .swapcase() but no .reverse(), right?

  
There can't be a .reverse() method on string, because it's immutable.  
You could use


   "".join(reversed(pal))

but I'd prefer  pal[::-1]  as I said earlier.

DaveA

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


Re: numpy is not installed with Python2.

2010-08-27 Thread Robert Kern

On 8/27/10 1:38 PM, justin wrote:

On Aug 27, 12:10 pm, Robert Kern  wrote:

On 8/27/10 11:40 AM, justin wrote:






My university has a cluster computer, on which I want to run my python
program that uses numpy.
I am installing my Python2.7 locally separated from the main system,
and trying to install numpy, attach it with Python2.7.
I used many different versions of numpys to make it happen, but I got
stuck with the same following error on every trial,



"[...@login1 numpy]$ python2.7 setup.py install
Running from numpy source directory.Traceback (most recent call last):
File "setup.py", line 210, in
  setup_package()
File "setup.py", line 187, in setup_package
  from numpy.distutils.core import setup
File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in

  from numpy.distutils.command import config, config_compiler, \
File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py",
line 9, in
  from distutils.command.build_ext import build_ext as old_build_ext
File "/users/hp6/apps/python27/lib/python2.7/distutils/command/
build_ext.py", line 13, in
  from site import USER_BASE, USER_SITE
ImportError: cannot import name USER_BASE"



It seems the error is related to the inability of Python2.7 to process
"from site import USER_BASE, USER_SITE",
since the machine I succeeded to install numpy with Python2.7 doesn't
prompt an error from this command,
whereas this machine in which I failed to do so cannot handle this.


Your Python installation appears to be broken. Find the site.py module that you
are actually importing. I.e. from the numpy source directory:

$ python2.7 -c "import site; print site.__file__"

This will tell you the site.pyc file that actually gets imported. Find the
associated site.py file (it should be in the same directory) and check to see if
it has USER_BASE defined. The filename should be

/users/hp6/apps/python27/lib/python2.7/site.pyc

If it isn't, that may be the source of your problem.

--
Robert Kern

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


Dear Kern,

Thanks a lot.
Your quick and detailed comment saves me a lot of time and effort
now.

It seems the file path links are out of order as you diagnosed.
Like you said, there is a site.py on /users/hp6/apps/python27/lib/
python2.7/.
But when I typed in "$ python2.7 -c "import site; print
site.__file__", it refers to another place:
"/opt/apps/gurobi/3.0.0/linux64/lib/python2.5/site.pyc", and it
doesn't have USER_BASE!

So I changed the value of PYTHONPATH accordingly.


You should not set PYTHONPATH to those directories ever. The correct one will 
already be on the sys.path. In a multiple-Python environment, you simply 
shouldn't use PYTHONPATH at all since all of the interpreters will try to use it.


--
Robert Kern

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

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


Re: palindrome iteration

2010-08-27 Thread D'Arcy J.M. Cain
On Fri, 27 Aug 2010 12:02:39 -0400
"D'Arcy J.M. Cain"  wrote:
> On Fri, 27 Aug 2010 11:49:42 -0400
> "D'Arcy J.M. Cain"  wrote:
> > is_palindrome = lambda x: x == x.lower()[::-1]
> 
> Oops.  Simple and wrong.
> 
> is_palindrome = lambda x: x.lower() == x.lower()[::-1]

slightly more efficient I think.

is_palindrome = lambda y: (lambda x: x == x[::-1])(y.lower())

-- 
D'Arcy J.M. Cain  |  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: palindrome iteration

2010-08-27 Thread Jussi Piitulainen
Dave Angel writes:

> Jussi Piitulainen wrote:
>> Ian writes:
>>> Of course, the simpler way is to use the definition of a
>>> Palindrome as the same backwards and forwards.
>>>
>>> def isPalindrome(pal)
>>>  return pal == pal.reverse
>>
>> Agreed. But is there any nicer way to spell .reverse than [::-1] in
>> Python? There is .swapcase() but no .reverse(), right?
>>
> There can't be a .reverse() method on string, because it's
> immutable. You could use
> 
> "".join(reversed(pal))
> 
> but I'd prefer  pal[::-1]  as I said earlier.

There could easily be a .reverse() method on strings. It would return
the reversed string, like .swapcase() returns the swapcased string.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-27 Thread John Nagle

On 8/11/2010 1:26 PM, EW wrote:

On Aug 11, 2:52 pm, Paul Rubin  wrote:

EW  writes:

Well I cared because I thought garbage collection would only happen
when the script ended - the entire script.  Since I plan on running
this as a service it'll run for months at a time without ending.  So I
thought I was going to have heaps of Queues hanging out in memory,
unreferenced and unloved.  It seemed like bad practice so I wanted to
get out ahead of it.


Even if GC worked that way it wouldn't matter, if you use just one queue
per type of task.  That number should be a small constant so the memory
consumption is small.


Well I can't really explain it but 1 Queue per task for what I'm
designing just doesn't feel right to me.  It feels like it will lack
future flexibility.  I like having 1 Queue per producer thread object
and the person instantiating that object can do whatever he wants with
that Queue.  I can't prove I'll need that level of flexibility but I
don't see why it' bad to have.  It's still a small number of Queues,
it's just a small, variable, number of Queues.


That's backwards.  Usually, you want one queue per unique consumer.
That is, if you have a queue that contains one kind of request,
there's one thread reading the queue, blocked until some other
thread puts something on the queue.  No polling is needed.

One consumer reading multiple queues is difficult to implement
well.

Note, by the way, that CPython isn't really concurrent.  Only
one thread runs at a time, due to an archaic implementation.  So
if your threads are compute-bound, even on a multicore CPU threading
will not help.

There's a "multiprocessing module" which allows spreading work
over several processes instead of threads.  That can be helpful
as a workaround.

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


Re: palindrome iteration

2010-08-27 Thread MRAB

On 27/08/2010 20:43, Jussi Piitulainen wrote:

Dave Angel writes:


Jussi Piitulainen wrote:

Ian writes:

Of course, the simpler way is to use the definition of a
Palindrome as the same backwards and forwards.

def isPalindrome(pal)
  return pal == pal.reverse


Agreed. But is there any nicer way to spell .reverse than [::-1] in
Python? There is .swapcase() but no .reverse(), right?


There can't be a .reverse() method on string, because it's
immutable. You could use

 "".join(reversed(pal))

but I'd prefer  pal[::-1]  as I said earlier.


There could easily be a .reverse() method on strings. It would return
the reversed string, like .swapcase() returns the swapcased string.


Lists have a .reverse method, but it's an in-place reversal. In order
to reduce confusion, a string method which returned the string reversed
would be better called .reversed().
--
http://mail.python.org/mailman/listinfo/python-list


Re: mailbox.mbox not locking mbox properly

2010-08-27 Thread John Nagle

On 8/10/2010 2:25 AM, Chris Rebert wrote:

On Tue, Aug 10, 2010 at 2:01 AM,  wrote:

Tim Roberts  wrote:

tinn...@isbd.co.uk wrote:


I'm using the python mailbox class in a script that processes incoming
mail and delivers it to various mbox format mailboxes.  It appears
that, although I am calling the lock method on the destination before
writing to the mbox and calling unlock afterwards the locking isn't
working correctly.
...
So it seems that python's mailbox class locking isn't playing nicely
with mutt's mailbox locking whereas postfix's locking does work
correctly.


Correct.  The "dest.flush()" method creates a temporary file, copies the
entire modified mailbox into it, removed the original file, and renames the
temp file into place.


Yes, I just took a look at the mailbox.py code and it does exactly
that which of course screws up just about any normal MUA looking at
the mbox.  Grr!



The Postfix MDA, like most MDAs, just opens the existing file and appends
the new data to it.


Has anyone seen this problem before, and/or do I need to anything more
than the following for the locking to work correctly:-


It's not the locking.  It's the flush mechanism.  The mbox class doesn't
know that the ONLY thing you did was an append.  You might have modified
other messages in the middle.  If you want to do an append, you'll need to
write your own subclass of mbox.


OK, thanks.  In reality I can probably just use straightforward file
reading and writing as the *only* thing I will ever be doing is to
append a message to a mailbox file.

I think there should be a big warning in the mailbox documentation to
this effect as doing it the way that Python's mailbox class does it
will break all sorts of things.  There should maybe be a specific
'append' method.


File a documentation and/or library bug:
http://bugs.python.org/

Cheers,
Chris


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


Re: palindrome iteration

2010-08-27 Thread Jussi Piitulainen
MRAB writes:
> On 27/08/2010 20:43, Jussi Piitulainen wrote:
>> Dave Angel writes:
>>> Jussi Piitulainen wrote:
 Agreed. But is there any nicer way to spell .reverse than [::-1]
 in Python? There is .swapcase() but no .reverse(), right?

>>> There can't be a .reverse() method on string, because it's
>>> immutable. You could use
>>>
>>>  "".join(reversed(pal))
>>>
>>> but I'd prefer  pal[::-1]  as I said earlier.
>>
>> There could easily be a .reverse() method on strings. It would
>> return the reversed string, like .swapcase() returns the swapcased
>> string.
> 
> Lists have a .reverse method, but it's an in-place reversal. In
> order to reduce confusion, a string method which returned the string
> reversed would be better called .reversed().

Yes, agreed.

Meanwhile, I have decided to prefer this:

def palindromep(s):
def reversed(s):
return s[::-1]
return s == reversed(s)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Terry Reedy

On 8/27/2010 3:43 PM, Jussi Piitulainen wrote:

Dave Angel writes:



There could easily be a .reverse() method on strings. It would return
the reversed string, like .swapcase() returns the swapcased string.


Could be, but the main use case seems to be for palindrome testing ;-)
Given that slicing and reversed() can do the same thing, the need is thin.

--
Terry Jan Reedy

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


Re: palindrome iteration

2010-08-27 Thread Richard Arts
On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen
 wrote:
> MRAB writes:
>> On 27/08/2010 20:43, Jussi Piitulainen wrote:
>>> Dave Angel writes:
 Jussi Piitulainen wrote:
> Agreed. But is there any nicer way to spell .reverse than [::-1]
> in Python? There is .swapcase() but no .reverse(), right?
>
 There can't be a .reverse() method on string, because it's
 immutable. You could use

      "".join(reversed(pal))

 but I'd prefer  pal[::-1]  as I said earlier.
>>>
>>> There could easily be a .reverse() method on strings. It would
>>> return the reversed string, like .swapcase() returns the swapcased
>>> string.
>>
>> Lists have a .reverse method, but it's an in-place reversal. In
>> order to reduce confusion, a string method which returned the string
>> reversed would be better called .reversed().
>
> Yes, agreed.
>
> Meanwhile, I have decided to prefer this:
>
> def palindromep(s):
>    def reversed(s):
>        return s[::-1]
>    return s == reversed(s)
> --
> http://mail.python.org/mailman/listinfo/python-list
>

That seems like a bit of overkill... Why would you want to define a
function in a function for something trivial like this? Just

def palindrome(s):
return s[::-1]

will do fine.

Of course, you can stick the inner function in a library somewhere if you like.

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


Re: palindrome iteration

2010-08-27 Thread Richard Arts
On Fri, Aug 27, 2010 at 11:47 PM, Richard Arts  wrote:
> On Fri, Aug 27, 2010 at 10:51 PM, Jussi Piitulainen
>  wrote:
>> MRAB writes:
>>> On 27/08/2010 20:43, Jussi Piitulainen wrote:
 Dave Angel writes:
> Jussi Piitulainen wrote:
>> Agreed. But is there any nicer way to spell .reverse than [::-1]
>> in Python? There is .swapcase() but no .reverse(), right?
>>
> There can't be a .reverse() method on string, because it's
> immutable. You could use
>
>      "".join(reversed(pal))
>
> but I'd prefer  pal[::-1]  as I said earlier.

 There could easily be a .reverse() method on strings. It would
 return the reversed string, like .swapcase() returns the swapcased
 string.
>>>
>>> Lists have a .reverse method, but it's an in-place reversal. In
>>> order to reduce confusion, a string method which returned the string
>>> reversed would be better called .reversed().
>>
>> Yes, agreed.
>>
>> Meanwhile, I have decided to prefer this:
>>
>> def palindromep(s):
>>    def reversed(s):
>>        return s[::-1]
>>    return s == reversed(s)
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
> That seems like a bit of overkill... Why would you want to define a
> function in a function for something trivial like this? Just
>
> def palindrome(s):
>    return s[::-1]
>
> will do fine.
>
> Of course, you can stick the inner function in a library somewhere if you 
> like.
>
> Regards,
> Richard
>

Duh, of course I mean

def palindrome(s):
   return s == s[::-1]

I'm sorry.

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


Re: Writing byte stream as jpeg format to disk

2010-08-27 Thread Lawrence D'Oliveiro
In message
, Navkirat Singh wrote:

> I receive a jpeg file with the POST method.The file (.jpeg) is encoded in
> bytes, I parse the bytes by decoding them to a string. I wanted to know
> how i could write the file (now a string) as a jpeg image on disk.

I assume the JPEG data is received along with other field values in the 
POST. You’ll be saving those other fields in a database, right? So why not 
save the JPEG image there as well?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing byte stream as jpeg format to disk

2010-08-27 Thread Lawrence D'Oliveiro
In message , Navkirat 
Singh wrote:

> The image bytes are a part of a HTTP header content ( not the message body
> ).

In which case, won’t they be in some encoding like Base-64? I don’t think 
you’re allowed arbitrary binary bytes in an HTTP header.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading the access attributes of directories in Windows

2010-08-27 Thread Lawrence D'Oliveiro
In message , Rami 
Chowdhury wrote:

> On Wed, Aug 25, 2010 at 05:04, Lawrence D'Oliveiro
>  wrote:
>
>> In message , Nobody wrote:
>>
>>> Having this as a separate permission allows normal users to add entries
>>> to log files but not to erase existing entries.
>>
>> Unix/Linux systems can do this already.
> 
> Ooh, I didn't know that -- what combination of permissions would I
> have to use to get such an effect?

No special permissions needed at all—just use the syslog(3) functions.

And the nice thing is, you don’t have to know whether the system logs are 
kept on the local machine or on a remote machine, or how different 
categories of messages are divided up into different files, how log rotation 
is done, or anything like that—it’s all transparent.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing byte stream as jpeg format to disk

2010-08-27 Thread Robert Kern

On 8/27/10 5:58 PM, Lawrence D'Oliveiro wrote:

In message
, Navkirat Singh wrote:


I receive a jpeg file with the POST method.The file (.jpeg) is encoded in
bytes, I parse the bytes by decoding them to a string. I wanted to know
how i could write the file (now a string) as a jpeg image on disk.


I assume the JPEG data is received along with other field values in the
POST. You’ll be saving those other fields in a database, right? So why not
save the JPEG image there as well?


No, the only thing in the body of the POST are the bytes of the JPEG. He was 
incorrect in thinking that the JPEG data was arriving in the header. See the 
later posts in the thread for complete answers to his problem.


--
Robert Kern

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

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


ANN: ActivePython 2.6.6.15 is now available

2010-08-27 Thread Sridhar Ratnakumar
ActiveState is pleased to announce ActivePython 2.6.6.15, a complete, 
ready-to-install binary distribution of Python 2.6.6.


http://www.activestate.com/activepython

What's New in ActivePython-2.6.6.15
===

*Release date: 25-Aug-2010*

New Features & Upgrades
---

- Upgrade to Python 2.6.6 (`release notes 
`__)

- Security upgrade to openssl-0.9.8o
- [MacOSX] 64-bit support (PPC and 10.4 are no longer supported)
- Upgrade to PyPM 1.1.1; noteworthy changes:

  - Custom config file support w/ new repository settings (-R free,be 
instead of

-L)
  - Support for installing a local package, eg: ``pypm install
/path/to/foo.pypm``
  - Bug #87687: Prevent partial downloading of repo index cache

- Upgraded the following packages:

  - Distribute-0.6.14
  - pip-0.8
  - SQLAlchemy-0.6.3

Noteworthy Changes & Bug Fixes
--

- [MacOSX] Fix Help index on Snow Leopard (10.6) - Bug #87290
- [Windows] Add file extension to Tools\scripts\2to3.py - Bug #87465


What's New in ActivePython-2.6.5.14
===

*Release date: 07-Jul-2010*

New Features & Upgrades
---

- Upgrade to PyPM 1.0.2

  - 'pypm search' now also shows if a package is installed and upgradeable
  - 'pypm info' now prints a concise representation by default
  - 'pypm list --short' will show only packages names; for scripting 
purposes

  - Respect distutils install schemes (purelib, scripts)


Noteworthy Changes & Bug Fixes
--

- [MacOSX] Fix /usr/local/bin symlinks to not use the 'Current' symlink
- [MacOSX] Fix uninstall on Snow Leopard (10.6)
- [Windows] Include IDLE in the Start Menu shortcut, instead of PythonWin


See the release notes for full details:

http://docs.activestate.com/activepython/2.6/relnotes.html#changes


What is ActivePython?
=

ActivePython is ActiveState's binary distribution of Python. Builds for 
Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and 
AIX builds, and access to older versions are available in ActivePython 
Business, Enterprise and OEM editions:


http://www.activestate.com/python

ActivePython includes the Python core and the many core extensions: zlib 
and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite 
(sqlite3) database libraries, OpenSSL bindings for HTTPS support, the 
Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on 
supported platforms) for low-level library access, and others. The 
Windows distribution ships with PyWin32 -- a suite of Windows tools 
developed by Mark Hammond, including bindings to the Win32 API and 
Windows COM.


ActivePython 2.6 and 2.7 also include a binary package manager for 
Python (PyPM) that can be used to install packages much easily. For example:


  C:\>pypm install mysql-python
  [...]

  C:\>python
  >>> import MySQLdb
  >>>

See this page for full details:

http://docs.activestate.com/activepython/2.6/whatsincluded.html

As well, ActivePython ships with a wealth of documentation for both new 
and experienced Python programmers. In addition to the core Python docs, 
ActivePython includes the "What's New in Python" series, "Dive into 
Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals 
(PEPs).


An online version of the docs can be found here:

http://docs.activestate.com/activepython/2.6/

We would welcome any and all feedback to:

activepython-feedb...@activestate.com

Please file bugs against ActivePython at:

http://bugs.activestate.com/enter_bug.cgi?product=ActivePython

Supported Platforms
===

ActivePython is available for the following platforms:

- Windows/x86   (32-bit)
- Windows/x64   (64-bit) (aka "AMD64")
- Mac OS X
- Linux/x86 (32-bit)
- Linux/x86_64  (64-bit) (aka "AMD64")

- Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition 
only)
- Solaris/x86   (32-bit)(Business, Enterprise or OEM edition 
only)
- HP-UX/PA-RISC (32-bit)(Business, Enterprise or OEM edition 
only)

- HP-UX/IA-64   (32-bit and 64-bit) (Enterprise or OEM edition only)
- AIX/PowerPC   (32-bit and 64-bit) (Business, Enterprise or OEM edition 
only)


More information about the Business Edition can be found here:

http://www.activestate.com/business-edition

Custom builds are available in the Enterprise Edition:

http://www.activestate.com/enterprise-edition

Thanks, and enjoy!

The Python Team

--
Sridhar Ratnakumar
sridharr at activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


ANN: ActivePython 2.7.0.2 is now available

2010-08-27 Thread Sridhar Ratnakumar
ActiveState is pleased to announce ActivePython 2.7.0.2, a complete, 
ready-to-install binary distribution of Python 2.7.


http://www.activestate.com/activepython

What's New in ActivePython-2.7.0.2
==

*Release date: 25-Aug-2010*

New Features & Upgrades
---

- Security upgrade to openssl-0.9.8o
- Upgrade to PyPM 1.1.1; noteworthy changes:

  - Custom config file support w/ new repository settings (-R free,be 
instead of

-L)
  - Support for installing a local package, eg: ``pypm install
/path/to/foo.pypm``
  - Bug #87687: Prevent partial downloading of repo index cache

- Upgraded the following packages:

  - Distribute-0.6.14
  - pip-0.8
  - SQLAlchemy-0.6.3


Noteworthy Changes & Bug Fixes
--

- [MacOSX] Fix Help index on Snow Leopard (10.6) - Bug #87290
- [Windows] Add file extension to Tools\scripts\2to3.py - Bug #87465


What is ActivePython?
=

ActivePython is ActiveState's binary distribution of Python. Builds for 
Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and 
AIX builds, and access to older versions are available in ActivePython 
Business, Enterprise and OEM editions:


http://www.activestate.com/python

ActivePython includes the Python core and the many core extensions: zlib 
and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite 
(sqlite3) database libraries, OpenSSL bindings for HTTPS support, the 
Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on 
supported platforms) for low-level library access, and others. The 
Windows distribution ships with PyWin32 -- a suite of Windows tools 
developed by Mark Hammond, including bindings to the Win32 API and 
Windows COM.


ActivePython 2.6 and 2.7 also include a binary package manager for 
Python (PyPM) that can be used to install packages much easily. For example:


  C:\>pypm install mysql-python
  [...]

  C:\>python
  >>> import MySQLdb
  >>>

See this page for full details:

http://docs.activestate.com/activepython/2.7/whatsincluded.html

As well, ActivePython ships with a wealth of documentation for both new 
and experienced Python programmers. In addition to the core Python docs, 
ActivePython includes the "What's New in Python" series, "Dive into 
Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals 
(PEPs).


An online version of the docs can be found here:

http://docs.activestate.com/activepython/2.7/

We would welcome any and all feedback to:

activepython-feedb...@activestate.com

Please file bugs against ActivePython at:

http://bugs.activestate.com/enter_bug.cgi?product=ActivePython

Supported Platforms
===

ActivePython is available for the following platforms:

- Windows/x86   (32-bit)
- Windows/x64   (64-bit) (aka "AMD64")
- Mac OS X
- Linux/x86 (32-bit)
- Linux/x86_64  (64-bit) (aka "AMD64")

- Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition 
only)
- Solaris/x86   (32-bit)(Business, Enterprise or OEM edition 
only)
- HP-UX/PA-RISC (32-bit)(Business, Enterprise or OEM edition 
only)

- HP-UX/IA-64   (32-bit and 64-bit) (Enterprise or OEM edition only)
- AIX/PowerPC   (32-bit and 64-bit) (Business, Enterprise or OEM edition 
only)


More information about the Business Edition can be found here:

http://www.activestate.com/business-edition

Custom builds are available in the Enterprise Edition:

http://www.activestate.com/enterprise-edition

Thanks, and enjoy!

The Python Team

--
Sridhar Ratnakumar
sridharr at activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: ftplib limitations?

2010-08-27 Thread Lawrence D'Oliveiro
In message <4c74e604.6090...@sschwarzer.net>, Stefan Schwarzer wrote:

> Now it may be that the data connection, after having started
> the transfer, works as it should, but the control connection
> times out because the duration of the transfer is too long.

It might not be the fault of the FTP server. If you’re going through a 
router doing NAT, that could be where the timeout is happening.

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


How to convert (unicode) text to image?

2010-08-27 Thread kj


Hi!  Does anyone know of an easy way to convert a Unicode string into an image 
file (either jpg or png)?

TIA!

~k


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


Re: Overload print

2010-08-27 Thread genxtech
On Aug 25, 5:18 pm, Ross Williamson 
wrote:
> Hi All
>
> Is there anyway in a class to overload the print function?
>
> >> class foo_class():
> >>      pass
> >> cc = foo_class()
> >> print cc
>
> Gives:
>
> <__main__.foo_class instance at >
>
> Can I do something like:
>
> >> class foo_class():
> >>     def __print__(self):
> >>           print "hello"
> >> cc = foo_class()
> >> print cc
>
> Gives:
>
> hello
>
> I'm looking at finding nice way to print variables in a class just by
> asking to print it
>
> Cheers
>
> Ross
>
> --
> Ross Williamson
> University of Chicago
> Department of Astronomy & Astrophysics
> 773-834-9785 (office)
> 312-504-3051 (Cell)

Are you talking about overriding print(), kind of like overloading the
<< operator in c++ so that you can determine how the foo_class gets
printed?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-27 Thread Steven D'Aprano
On Fri, 27 Aug 2010 09:16:52 -0700, Aahz wrote:

> In article , MRAB 
>  wrote:
>>
>>An object will be available for garbage collection when nothing refers
>>to it either directly or indirectly. If it's unreferenced then it will
>>go away.
> 
> This isn't actually garbage collection as most people think of it.
> Refcounting semantics mean that objects get reaped as soon as nothing
> points at them.  OTOH, CPython does also have garbage collection to back
> up refcounting so that when you have unreferenced object cycles they
> don't stay around.


I've repeatedly asked, both here and elsewhere, why reference counting 
isn't "real" garbage collection. Nobody has been able to give me a 
satisfactory answer. As far as I can tell, it's a bit of pretentiousness 
with no basis in objective fact.

http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)
http://en.wikipedia.org/wiki/Reference_counting

Reference counting is one specific kind of garbage collection, and like 
all gc strategies, it has strengths as well as weaknesses. It is *simple* 
to implement (which may be why a certain class of programmer likes to 
think it isn't "real" gc). When it runs is deterministic, and is 
immediate upon the resource being freed. The overhead is very light (a 
plus) and continuous (which can be both a plus and a minus). It is better 
suited to managing scarce resources like open files than are tracing 
garbage collectors. It avoids the "embarrassing pause" of tracing 
collectors. It doesn't deal well with reference cycles, and (at least 
with Python's implementation of ref counting) it causes performance 
issues with threaded applications.

http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)
http://en.wikipedia.org/wiki/Reference_counting

So CPython has two garbage collectors -- a reference counting 
implementation, and a tracing implementation. Jython and IronPython use 
the native garbage collectors from Java and .Net. Other Pythons may use 
something else.


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


Re: How to convert (unicode) text to image?

2010-08-27 Thread Benjamin Kaplan
On Fri, Aug 27, 2010 at 8:01 PM, kj  wrote:
>
>
> Hi!  Does anyone know of an easy way to convert a Unicode string into an 
> image file (either jpg or png)?
>

Do you mean you have some text and you want an image containing that
text? PIL's ImageDraw module can do that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-27 Thread Paul Rubin
Steven D'Aprano  writes:
> I've repeatedly asked, both here and elsewhere, why reference counting 
> isn't "real" garbage collection. Nobody has been able to give me a 
> satisfactory answer. As far as I can tell, it's a bit of pretentiousness 
> with no basis in objective fact.

Well, it's a bit of a subjective matter.  I'd say it's not real gc
because 1) it's unsound (misses reference cycles), and 2) it requires
constant attention from the mutator to incr and decr the reference
counts.  So developing modules for the CPython API means endlessly
finding and fixing refcount bugs that lead to either crashes/security
failures, or memory leaks.  If you program the Java JNI or a typical
Lisp FFI, you'll find that real gc is a lot simpler to use since you
avoid all the refcount maintenance hassles.  You allocate memory and
shut your eyes, and the gc takes care of freeing it when it figures out
that you are done.  Refcounting is basically a form of manual memory
management, while gc is automatic.  

Someone said here recently that as a program gets larger, saying "this
will work as long as we do X every time without fail" becomes equal to
saying "this won't work".  Substitute "properly maintain all ref counts"
for X and you can see the problem.  I've seen released "production"
"tested" Python C modules with subtle refcount bugs on more than one
occasion.  In gc'd systems there are fewer places for the code to go
wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


comp.lang.python

2010-08-27 Thread roshini begum
www.127760.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


love me

2010-08-27 Thread love me
1st step
like me on facbook at this link 
http://www.facebook.com/pages/loveme/145529285481739
2nd step
   visit this link http://www.kqzyfj.com/click-3778203-10786395
-- 
http://mail.python.org/mailman/listinfo/python-list


Walking deeply nested lists

2010-08-27 Thread donn
This is all about walking trees, recursion and generators. None of which 
fit my brain at all!


From an XML tree (an SVG file) I build a bunch of Tag objects.

[I use lxml, but I am combining multiple svg files into a 'forest' of 
trees, so I can't use the lxml walking methods because they all stop at 
the 'end' of a branch where there is actually a 'link' over to another 
tree.]


Each Tag has a flatwalk() method. The return from that is a list which 
can be deeply nested. As an example, something like this:

L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ]

(The numbers in the example would actually be Tag Instances.)

Aim 1
---
I'm trying to write a generator around such lists so that I can 'walk' them:

for parent, child in mystery_generator(L):
 print level, item

Right now, I am running a 'flatten' function on the entire list (which I 
don't savvy, I found it online) and then I iterate over that flattened 
list. This doesn't feel right to me. (Code at end.)


Aim 2
---
The Objects that represent the svg tags use that flatwalk() method to 
build the nested list, I'd far prefer flatwalk() to be directly useable 
in something like this way:


for container, child in some_tag.flatwalk():
 print container, child

The flatwalk() function is (and this is another puzzle see *) kind of 
recursive. "For each of my children, tell that child to go flatwalk()".

(Code at end.)
I am not sure how to turn such a thing into a generator.

I keep wondering how os.walk() does its thing. My hierarchy of Tag 
objects can be thought of as directories (tags:g, symbol, svg), files 
(path, circle, etc.) and soft-links (use tags).


* If an Instance calls a method on *another* Instance of the *same* 
class, is this still recursion? And how does this 'stack up'? I mean, 
literally, on the stack. Does each instance get its own stack, or does 
all the push, call, pop stuff happen in one main stack?

(I worry about recursion depth limits because svg trees can get quite deep.)


The walking code so far:

## Found code.
def flatten(input):
 output = []
 stack = []
 stack.extend(reversed(input))
 while stack:
  top = stack.pop()
  if isinstance(top, list):
   stack.extend(reversed(top))
  else:
   output.append(top)
 return output

## My walker
def test_walk(e): #lxml Element comes in
 obj = ebag_get(e)['obj'] #get a tag object
 l=obj.flatwalk()
 ll= flatten(l)
 #No current solution to get 'parent' in this iterator
 #ie. for parent, child in ...
 for tag in ll:
  print tag

Here's one of my Tag objects:

class Brancher(object):
  def __init__(self, elem):
self.elem = elem
self.children = []

  def flatwalk(self):
l=[self]
for child in self.children:
  l.append( child.flatwalk() ) #recur(ish)ion here
return l

class G( Brancher ): #Object for  tags.
  pass

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


Re: Reading the access attributes of directories in Windows

2010-08-27 Thread Lawrence D'Oliveiro
In message , Tim Golden 
wrote:

> Can you run Python from within a Run-As-Administrator command
> prompt?

Kind of worrying, isn’t it, when the answer to “my program won’t work” is 
“give it more privileges”? Defeats the point of having such a complex 
security system, doesn’t it, when people are no longer able to understand 
its ramifications, and have to resort to bypassing it to get work done?
-- 
http://mail.python.org/mailman/listinfo/python-list


rfile.readline()

2010-08-27 Thread sarah
i want to know that what this function returns???

and what does this function do??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Jussi Piitulainen
Terry Reedy writes:
> On 8/27/2010 3:43 PM, Jussi Piitulainen wrote:
> > Dave Angel writes:
> 
> > There could easily be a .reverse() method on strings. It would return
> > the reversed string, like .swapcase() returns the swapcased string.
> 
> Could be, but the main use case seems to be for palindrome testing ;-)
> Given that slicing and reversed() can do the same thing, the need is thin.

The need is quite thin, but immutability of strings is not an issue,
just like there can be .swapcase() though strings are immutable. That
is all I am saying above.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Walking deeply nested lists

2010-08-27 Thread Peter Otten
donn wrote:

> * If an Instance calls a method on another Instance of the same
> class, is this still recursion? And how does this 'stack up'? I mean,
> literally, on the stack. Does each instance get its own stack, or does
> all the push, call, pop stuff happen in one main stack?
> (I worry about recursion depth limits because svg trees can get quite
> deep.)

If you call functions within functions (or methods, it doesn't matter) they 
consume stack space, e. g: 

>>> def alpha():
... return beta()
...
>>> def beta():
... return gamma()
...
>>> import random
>>> def gamma():
... return random.choice([alpha, beta, gamma])()
...
>>> import sys
>>> sys.setrecursionlimit(10)
>>> alpha()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in alpha
  File "", line 2, in beta
  File "", line 2, in gamma
  File "", line 2, in gamma
  File "", line 2, in alpha
  File "", line 2, in beta
  File "", line 2, in gamma
  File "", line 2, in beta
  File "", line 2, in gamma
RuntimeError: maximum recursion depth exceeded

The normal recursion limit is 1000, I'm reducing it to give you a smaller 
traceback.

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