steps to solve bugs

2012-03-10 Thread ejjy
Hi,
 I am currently learning  python and I would like to solve some easy
bugs for my own practice. I am confused over following the steps
explained in the Python website, though I have the appropriate
software necessities. Kindly some one please tell me in a more
practical and easy way.
Thanks.
Regards,
 Ejaj
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyUSB available for current versions of Windows?

2012-03-10 Thread Dietmar Schwertberger

Am 09.03.2012 18:18, schrieb John Nagle:

I want to enumerate the available USB devices. All I really
need is the serial number of the USB devices available to PySerial.
(When you plug in a USB device on Windows, it's assigned the next
available COM port number. On a reboot, the numbers are reassigned.
So if you have multiple USB serial ports, there's a problem.)


You can get the required information using Windows Management
Instrumentation (WMI).

See e.g. here for serial port information:
http://www.activexperts.com/admin/scripts/wmi/python/0358/


I'm using code like this to find my USB CDC devices from the device
description:

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("SELECT Description,DeviceID FROM 
Win32_SerialPort")


COM_ports = []
for objItem in colItems:
print objItem.Description,objItem.DeviceID
if objItem.Description == "USB CDC Simple IO HC9S08JSxx":
COM_ports.append( objItem.DeviceID )


On some PCs the query took some seconds.


Regards,

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


Invalid syntax error

2012-03-10 Thread sl33k
I'm trying project euler problem 3 and I've hit the wall with this
error. What could be the problem here?

 l=[]
>>> num=600851475143
>>> i=1
>>> while i<=num:
... if num%i==0:
... l.append(i)
... i+=1
... print max(l)
  File "", line 5
print max(l)
^
SyntaxError: invalid syntax


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


Re: Invalid syntax error

2012-03-10 Thread Amit Sethi
Its an indentation error

-- 
A-M-I-T S|S
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invalid syntax error

2012-03-10 Thread Andrew Berg
On 3/10/2012 6:34 AM, sl33k wrote:
> I'm trying project euler problem 3 and I've hit the wall with this
> error. What could be the problem here?
> 
>  l=[]
 num=600851475143
 i=1
 while i<=num:
> ... if num%i==0:
> ... l.append(i)
> ... i+=1
> ... print max(l)
>   File "", line 5
> print max(l)
> ^
> SyntaxError: invalid syntax
> 
> 
You must be using Python 3. Along with many, many other changes, Python
3 uses a print function instead of a print statement. If you want to
follow along with the problems, use the version of Python it uses (2.7
is probably safe if there isn't a version specified).

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invalid syntax error

2012-03-10 Thread Vlastimil Brom
2012/3/10 sl33k :
> I'm trying project euler problem 3 and I've hit the wall with this
> error. What could be the problem here?
>
>  l=[]
 num=600851475143
 i=1
 while i<=num:
> ...     if num%i==0:
> ...         l.append(i)
> ...     i+=1
> ... print max(l)
>  File "", line 5
>    print max(l)
>        ^
> SyntaxError: invalid syntax
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list

Hi,
if you are using python 3, you'd (most likely) need to adapt the code
written for python 2.
see:
http://docs.python.org/py3k/whatsnew/3.0.html#print-is-a-function

hth,
 vbr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invalid syntax error

2012-03-10 Thread Ahsan
Just checked my version. Its showing 2.6.5.

>>> sys.version
'2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invalid syntax error

2012-03-10 Thread liuerfire Wang
在 2012年3月10日星期六UTC+8下午8时34分35秒,sl33k写道:
> I'm trying project euler problem 3 and I've hit the wall with this
> error. What could be the problem here?
> 
>  l=[]
> >>> num=600851475143
> >>> i=1
> >>> while i<=num:
> ... if num%i==0:
> ... l.append(i)
> ... i+=1
> ... print max(l)
>   File "", line 5
> print max(l)
> ^
> SyntaxError: invalid syntax

It is a indentation error. It should be like:

>>> while i<=num:
... if num%i==0:
... l.append(i)
... i+=1
...
>>> print max(l)
-- 
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2012-03-10 Thread Sam Sam
How to change the color of source browser in DrPython?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invalid syntax error

2012-03-10 Thread Günther Dietrich
In article 
<46758542-1bd6-43fe-8e80-bcf14b7d8...@pi6g2000pbc.googlegroups.com>,
 sl33k  wrote:

>I'm trying project euler problem 3 and I've hit the wall with this
>error. What could be the problem here?
>
> l=[]
 num=600851475143
 i=1
 while i<=num:
>... if num%i==0:
>... l.append(i)
>... i+=1
>... print max(l)
>  File "", line 5
>print max(l)
>^
>SyntaxError: invalid syntax

You have to insert an empty line after the end of the while loop (before 
the print command), so that the interpreter can run and finish the loop 
before it is to print the result.



Best regards,

Günther
-- 
http://mail.python.org/mailman/listinfo/python-list


nmea

2012-03-10 Thread Johannes Wagner

can any1 help me on how to get python to read nmea data?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't get around HTTP/401 response using SUDS [SOLVED]

2012-03-10 Thread Adam Tauno Williams
On Fri, 2012-03-09 at 00:03 +0100, Rafael Durán Castañeda wrote:
> El 08/03/12 16:44, Adam Tauno Williams escribió:
> > SUDS version 0.4 pn x86_64 Python 2.7
> > I'm having a bear of a time getting HTTP Basic Authentication to work
> > for a SOAP request via suds.  Also using an HTTP proxy server.
> > In WireShark I just see a request -
> > GET http://./services/services/JobService-0.0.1?wsdl HTTP/1.1
> > Accept-Encoding: identity
> > Host: ...
> > Connection: close
> > User-Agent: Python-urllib/2.7
> > This doesn't contain any authentication credentials so the response is
> > HTTP/401, and the client doesn't retry with credentials.  The response
> > does come from the remote as I can see there is a WWW-Authenticate
> > header and it is from an Apache Tomcat server - so it makes it through
> > the proxy server.
> > Code
> > 
> >   url = 'http://../services/services/JobService-0.0.1?wsdl'
> >   proxy = urllib2.ProxyHandler({'http': 'http://.:3128'})
> >   transport = suds.transport.http.HttpAuthenticated()
> >   transport.urlopener = urllib2.build_opener(proxy)
> >   client = suds.client.Client(url, transport=transport,
> > username='**', password='')
> > 
> > "/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/transport/http.py",
> >  line 64, in open
> >  raise TransportError(str(e), e.code, e.fp)
> > suds.transport.TransportError: HTTP Error 401: Unauthorized
> When I've got issues like yours, I usually try using a console client 
> (telnet/curl/wget,...) adding all needed headers/data manually so I'm 
> totally sure the request is OK, if everything goes Ok you know your 
> python code need to be reviewed but when you are under proxies you can 
> find a lot of not python related issues (bad gateways, using proxy when 
> it shouldn't or vice-versa, requests changed by proxy,).

Nope, proxy works perfectly [for hundreds of clients].

The problem turned out to be that SUDS uses the specified transport for
SOAP requests/operations.  When requesting the WSDL in order to built
the client interface it doesn't use the transport.

So either download the service description to a local file and use that
or just use urllib2 to retrieve the WSDL to a buffer (outside of SUDS).
Once the client is created the requests work with authentication and via
the proxy with no issues.

> wireshark can be very useful but in situations like this I usually 
> prefer tcpflow output, I think the request/response flow showed is 
> really useful, but that's a personal preference.

Wireshark does the same thing;  you just select a packet in the stream
and then select "follow conversation".

-- 
System & Network Administrator [ LPI & NCLA ]

OpenGroupware Developer 
Adam Tauno Williams

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


Re: nmea

2012-03-10 Thread Roy Smith
In article ,
 "Johannes Wagner"  wrote:

> can any1 help me on how to get python to read nmea data?

I assume you're talking about National Marine Electronics Association, 
i.e. the protocol GPSs use to talk to plotters and the like?  A quick 
google search for "nmea python" found a bunch of good hits.  This one 
looks like it's probably where you want to start.

http://blog.scaryclam.co.uk/2011/07/22/pynmea-a-python-nmea-library/
-- 
http://mail.python.org/mailman/listinfo/python-list


How to know that two pyc files contain the same code

2012-03-10 Thread Gelonida N
Hi,

I want to know whether two .pyc files are identical.

With identical I mean whether they contain the same byte code.

Unfortunately it seems, that .pyc files contain also something like the
time stamp of the related source file.

So though two pyc files contain the same byte code, they will not be
byte identical.

One option, that I found is to use
python -m unpyclib.application -d filename.pyc and check whether the
results are identical.


However even this will fail if the files were not compiled under the
same absolute path name as the source filename is contained twice  (at
least for my trivial example) in the disassemblers output.


Thanks a lot for any other idea.



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


How to know that two pyc files contain the same code

2012-03-10 Thread Gelonida N
Hi,

I want to know whether two .pyc files are identical.

With identical I mean whether they contain the same byte code.

Unfortunately it seems, that .pyc files contain also something like the
time stamp of the related source file.

So though two pyc files contain the same byte code, they will not be
byte identical.

One option, that I found is to use
python -m unpyclib.application -d filename.pyc and check whether the
results are identical.


However even this will fail if the files were not compiled under the
same absolute path name as the source filename is contained twice  (at
least for my trivial example) in the disassemblers output.


Thanks a lot for any other idea.



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


Re: How to know that two pyc files contain the same code

2012-03-10 Thread Bl0ckeduser

Gelonida N wrote:

Hi,

I want to know whether two .pyc files are identical.

With identical I mean whether they contain the same byte code.

Unfortunately it seems, that .pyc files contain also something like the
time stamp of the related source file.

So though two pyc files contain the same byte code, they will not be
byte identical.

One option, that I found is to use
python -m unpyclib.application -d filename.pyc and check whether the
results are identical.


However even this will fail if the files were not compiled under the
same absolute path name as the source filename is contained twice  (at
least for my trivial example) in the disassemblers output.


Thanks a lot for any other idea.



Try using the disassembler code here:

http://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html

and removing from it the parts which print out the timestamp and the 
absolute path. (Two different lines in the source). That seems to work 
for me.




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


Re: How to know that two pyc files contain the same code

2012-03-10 Thread Peter Otten
Gelonida N wrote:

> I want to know whether two .pyc files are identical.
> 
> With identical I mean whether they contain the same byte code.
> 
> Unfortunately it seems, that .pyc files contain also something like the
> time stamp of the related source file.
> 
> So though two pyc files contain the same byte code, they will not be
> byte identical.
> 
> One option, that I found is to use
> python -m unpyclib.application -d filename.pyc and check whether the
> results are identical.

Or you could just strip off the first 8 (may be version-dependent) bytes 
before you compare the file contents.
 
> However even this will fail if the files were not compiled under the
> same absolute path name as the source filename is contained twice  (at
> least for my trivial example) in the disassemblers output.

That's another problem. If you are OK with likelihood you can replace the 
filename of the old code with that of the new one before you compare.

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


Re: Invalid syntax error

2012-03-10 Thread Ian Kelly
On Sat, Mar 10, 2012 at 6:17 AM, Günther Dietrich
 wrote:
> In article
> <46758542-1bd6-43fe-8e80-bcf14b7d8...@pi6g2000pbc.googlegroups.com>,
>  sl33k  wrote:
>
>>I'm trying project euler problem 3 and I've hit the wall with this
>>error. What could be the problem here?
>>
>> l=[]
> num=600851475143
> i=1
> while i<=num:
>>...     if num%i==0:
>>...         l.append(i)
>>...     i+=1
>>... print max(l)
>>  File "", line 5
>>    print max(l)
>>        ^
>>SyntaxError: invalid syntax
>
> You have to insert an empty line after the end of the while loop (before
> the print command), so that the interpreter can run and finish the loop
> before it is to print the result.

Note that this only applies to the interactive interpreter, to help it
identify when to terminate the block and pass on to the compiler.
When running a script, the extra blank lines are unnecessary, and
indentation alone identifies the blocks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stackoverflow question

2012-03-10 Thread Ethan Furman

Terry Reedy wrote:

Thanks for the review, Terry!


On 3/9/2012 5:10 PM, Ethan Furman wrote:


http://stackoverflow.com/q/9638921/208880

If anyone here is willing to take a look at it and let me know if I did
not write it well, I would appreciate the feedback

Here's the question text:

I'm writing a metaclass to do some cool stuff, and part of its
processing is to check that certain attributes exist when the class is
created. Some of these are mutable, and would normally be set in
`__init__`, but since `__init__` isn't run until the instance is created
the metaclass won't know that the attribute *will* be created, and
raises an error.

>

a. Create an instance and see if it has the attribute. Then delete it.


If the class takes any arguments, I won't be able to create instances of it.


b. Put such tests in unit tests.


Always a good idea -- but this is the responsibility of the class author 
(who may not be me ;).



c. Check the code object to see if the attribute will be created.


I have no idea how to do this -- pointers?



I could do something like:

class Test(meta=Meta):
mutable = None
def __init__(self):
self.mutable = list()

But that isn't very elegant, and also violates DRY.


It works. It is a standard idiom for default values that are 
conditionally masked with an instance value.


What I need is some way to have:

class Test(metaclass=Meta):
mutable = list()

t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
t1.mutable # prints ['one']
t2.mutable # prints ['two']

Any ideas on how this can be accomplished?


Rewrite the __init__ code object ;-).


Ouch.  Can that be done in a cross-implementation way?  Any pointers?

Still, I'm not sure I'd want to go this route, anyway, as it makes it 
more difficult to get an actual class-wide mutable (rare though they are).


Thanks again for your feedback, I really appreciate it.

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


Re: newb __init__ inheritance

2012-03-10 Thread Colin J. Williams

On 08/03/2012 10:25 AM, hyperboogie wrote:

Hello everyone.

This is my first post in this group.
I started learning python a week ago from the "dive into python" e-
book and thus far all was clear.
However today while reading chapter 5 about objects and object
orientation I ran into something that confused me.
it says here:
http://www.diveintopython.net/object_oriented_framework/defining_classes.html#fileinfo.class.example

"__init__ methods are optional, but when you define one, you must
remember to explicitly call the ancestor's __init__ method (if it
defines one). This is more generally true: whenever a descendant wants
to extend the behavior of the ancestor, the descendant method must
explicitly call the ancestor method at the proper time, with the
proper arguments. "

However later on in the chapter:
http://www.diveintopython.net/object_oriented_framework/userdict.html

it says:
"Methods are defined solely by their name, and there can be only one
method per class with a given name. So if a descendant class has an
__init__ method, it always overrides the ancestor __init__ method,
even if the descendant defines it with a different argument list. And
the same rule applies to any other method. "

My question is if __init__ in the descendant class overrides __init__
in the parent class how can I call the parent's __init__ from the
descendant class - I just overrode it didn't I?

Am I missing something more fundamental here?
Thanks


The mro function [Method Resolution Order]is not too well advertised in 
the docs.  This should illustrate its usage:


#!/usr/bin/env python

class A():
  def __init__(self):
z= 1

  def ringA(self):
print ('aaa')

  def ringB(self):
print('bbb')

class B(A):
  def __init__(self):
z= 2

  def ringB(self):
print('BBB')

a= A()
b= B()
b.ringB()
b.ringA()
b.__class__.mro()[1].ringB(b)

z= 1
def main():
pass

if __name__ == '__main__':
main()
I'm not sure that the class initialization is required.

Good luck,

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


Re: stackoverflow question

2012-03-10 Thread Terry Reedy


On 3/10/2012 11:56 AM, Ethan Furman wrote:


I'm writing a metaclass to do some cool stuff, and part of its
processing is to check that certain attributes exist when the class is
created. Some of these are mutable, and would normally be set in
`__init__`, but since `__init__` isn't run until the instance is created
the metaclass won't know that the attribute *will* be created, and
raises an error.



c. Check the code object to see if the attribute will be created.


I have no idea how to do this -- pointers?


Capture output of dis.dis(targetclass.__init__) by temporarily setting 
sys.stdout to StringIO object. (There is tracker issue to make lines 
available to a program without doing this.)


>>> from dis import dis
>>> def f(self):
self.attr = 1

>>> dis(f)
  2   0 LOAD_CONST   1 (1)
  3 LOAD_FAST0 (self)
  6 STORE_ATTR   0 (attr)
  9 LOAD_CONST   0 (None)
 12 RETURN_VALUE

Look for STORE_ATTR line with target attribute name. If you want to 
check for wacko code that does setattr(self, 'attr', value), try it in 
'f' and dis again.


Anything to do with code objects (and dis module) is implementation and 
version specific


---
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list


Re: steps to solve bugs

2012-03-10 Thread Miki Tebeka
Greetings,

> I am confused over following the steps
> explained in the Python website,
Are you talking about http://docs.python.org/devguide/?

> Kindly some one please tell me in a more
> practical and easy way.
Can you tell in more details what are the problems you face?
This will help us help you more.

All the best,
--
Miki
-- 
http://mail.python.org/mailman/listinfo/python-list


How to re-implement the crypt.crypt function?

2012-03-10 Thread Cosmia Luna
I'm not searching for a full solution and only want to know how to use hashlib 
to create a equivalent string like 

crypt.crypt('123456', '$6$ds41p/9VMA.BHH0U') returns the string below. 

'$6$ds41p/9VMA.BHH0U$yv25s7jLxTRKLDNjIvT0Qc2jbcqdFRi5.PftO3cveTvjK49JhwCarIowOfrrNPD/PpYT3n6oNDIbjAONh8RXt1'

I tried:

from hashlib import sha512
from base64 import b64encode, b64decode

salt='ds41p/9VMA.BHH0U'
pwd='123456'

b64encode( sha512(pwd+salt).digest(), altchars='./' )
b64encode( sha512(salt+pwd).digest(), altchars='./' )
b64encode( sha512( pwd + b64decode(salt, altchars='./') ).digest(), 
altchars='./')
b64encode( sha512( b64decode(salt, altchars='./') + pwd ).digest(), 
altchars='./')

of course none of the four returns the value I want, 
'yv25s7jLxTRKLDNjIvT0Qc2jbcqdFRi5.PftO3cveTvjK49JhwCarIowOfrrNPD/PpYT3n6oNDIbjAONh8RXt1',
 how can I get the value? I can't use crypt.crypt because of the consideration 
of cross-platform.

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


Re: stackoverflow question

2012-03-10 Thread Owen Jacobson

On 2012-03-09 22:10:18 +, Ethan Furman said:


Hey all!

I posted a question/answer on SO earlier, but there seems to be some 
confusion around either the question or the answer (judging from the 
comments).


http://stackoverflow.com/q/9638921/208880

If anyone here is willing to take a look at it and let me know if I did 
not write it well, I would appreciate the feedback.



Here's the question text:

I'm writing a metaclass to do some cool stuff, and part of its 
processing is to check that certain attributes exist when the class is 
created.  Some of these are mutable, and would normally be set in 
`__init__`, but since `__init__` isn't run until the instance is 
created the metaclass won't know that the attribute *will* be created, 
and raises an error.  I could do something like:


 class Test(meta=Meta):
 mutable = None
 def __init__(self):
 self.mutable = list()

But that isn't very elegant, and also violates DRY.

What I need is some way to have:

 class Test(metaclass=Meta):
 mutable = list()

 t1 = Test()
 t2 = Test()
 t1.mutable.append('one')
 t2.mutable.append('two')
 t1.mutable  # prints ['one']
 t2.mutable  # prints ['two']

Any ideas on how this can be accomplished?

Also, the metaclass doing the checking doesn't care what type of object 
the attribute is, only that it is there.

---


Why check what you can ensure? The __init__ function your metaclass 
passes to type() doesn't have to be the __init__ method your metaclass 
received. Consider the following:



import functools as f

def make_init(real_init):
"""Define an __init__ method that ensures ``self.mutable`` is set. If the
passed ``real_init`` function later replaces ``self.mutable``, that value
is preserved; otherwise, ``self.mutable`` is set to a new, empty list.

Arguments to the generated ``__init__`` method are passed to the original
``real_init`` unchanged.
"""
def __init__(self, *args, **kwargs):
self.mutable = list()
if real_init is not None:
return real_init(self, *args, **kwargs)
if real_init is not None:
f.update_wrapper(__init__, real_init)
return __init__

class Meta(type):
def __new__(meta, name, parents, attributes):
attributes['__init__'] = make_init(attributes.get('__init__', None))
return type.__new__(Meta, name, parents, attributes)

class C(object):
__metaclass__ = Meta

a, b = C(), C()

a.mutable.append(3)
b.mutable.append(5)

a.mutable

[3]

b.mutable

[5]

All instances of classes whose metaclass is Meta will, guaranteed, have 
an instance field named 'mutable'. Its value is a list created at 
instance creation time, unless the instance's __init__ provides a 
different value.


What've I missed?

-o

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


Re: How to re-implement the crypt.crypt function?

2012-03-10 Thread Christian Heimes
Am 10.03.2012 20:33, schrieb Cosmia Luna:
> I'm not searching for a full solution and only want to know how to use 
> hashlib to create a equivalent string like 

If you chance your mind and choose to use a full solution, then I highly
recommend passlib [1]. It has an implementation of SHA-512 crypt as
indicated by the number 6 in the header of your string.

By the way "$6$ds41p/9VMA.BHH0U" is *not* the salt. Just
"ds41p/9VMA.BHH0U" is the salt, 6 is a hash identifier.

Christian

[1] http://packages.python.org/passlib/

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


Re: How to re-implement the crypt.crypt function?

2012-03-10 Thread Roy Smith
In article 
<28304124.1374.1331408016748.JavaMail.geo-discussion-forums@yncd8>,
 Cosmia Luna  wrote:

> I'm not searching for a full solution and only want to know how to use 
> hashlib to create a equivalent string like 
> 
> crypt.crypt('123456', '$6$ds41p/9VMA.BHH0U') returns the string below. 
> 
> '$6$ds41p/9VMA.BHH0U$yv25s7jLxTRKLDNjIvT0Qc2jbcqdFRi5.PftO3cveTvjK49JhwCarIowO
> frrNPD/PpYT3n6oNDIbjAONh8RXt1'
> [...]
> I can't use crypt.crypt because of the 
> consideration of cross-platform.

Just out of curiosity, why do you want to do this?  The python crypt 
module uses the crypt library supplied by the operating system (which is 
why it only works on unix).  The algorithm implemented is a modification 
of DES, i.e. a salt string is used to change some of the tables used in 
the DES computation.  It goes back to the ancient days of unix.

By today's standards, the algorithm isn't considered very strong.  The 
only place I'm aware that uses it is unix password files, and even there 
many (most?) systems have replaced it with something stronger such as 
SHA1.  Maybe Apache .htaccess files?

I don't know what your use case is, but unless you're doing something 
silly like trying to execute a dictionary attack against a unix password 
file, it's almost certain that you'd do better to just use SHA1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to re-implement the crypt.crypt function?

2012-03-10 Thread Christian Heimes
Am 10.03.2012 21:15, schrieb Roy Smith:
> By today's standards, the algorithm isn't considered very strong.  The 
> only place I'm aware that uses it is unix password files, and even there 
> many (most?) systems have replaced it with something stronger such as 
> SHA1.  Maybe Apache .htaccess files?

The algorithm with identifier 6 is a SHA-512 crypt algorithm with a
lengthy salt (IIRC up to 1024 bits) and 40,000 rounds of SHA-512. It's
the default algorithm on modern Linux machines and believed to be very
secure.

The large salt makes a rainbow table attack impossible and the 40,000
rounds require a lot of CPU time, even on modern systems.

Christian


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


Re: How to re-implement the crypt.crypt function?

2012-03-10 Thread Roy Smith
In article ,
 Christian Heimes  wrote:

> Am 10.03.2012 21:15, schrieb Roy Smith:
> > By today's standards, the algorithm isn't considered very strong.  The 
> > only place I'm aware that uses it is unix password files, and even there 
> > many (most?) systems have replaced it with something stronger such as 
> > SHA1.  Maybe Apache .htaccess files?
> 
> The algorithm with identifier 6 is a SHA-512 crypt algorithm with a
> lengthy salt (IIRC up to 1024 bits) and 40,000 rounds of SHA-512. It's
> the default algorithm on modern Linux machines and believed to be very
> secure.
> 
> The large salt makes a rainbow table attack impossible and the 40,000
> rounds require a lot of CPU time, even on modern systems.

But is that what crypt.crypt() does?  I though it implemented the 
old-style triple-DES.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to re-implement the crypt.crypt function?

2012-03-10 Thread Christian Heimes
Am 10.03.2012 21:41, schrieb Roy Smith:
> But is that what crypt.crypt() does?  I though it implemented the 
> old-style triple-DES.

Python's crypt module is an interface to the OS' crypt() function. On
some systems the crypt() function supports additional algorithms. You
can read it up in the notes section of crypt(3):
http://linux.die.net/man/3/crypt

Christian

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


Re: newb __init__ inheritance

2012-03-10 Thread Colin J. Williams

On 10/03/2012 12:58 PM, Colin J. Williams wrote:

On 08/03/2012 10:25 AM, hyperboogie wrote:

Hello everyone.


[snip]

main()
I'm not sure that the class initialization is required.

Good luck,

Colin W.

When I wrote earlier, I wondered about the need for initialization.

With Version 2, both __new__ and __init__ were required, not in the 
example below, using version 3.2:

#!/usr/bin/env python

class A():

  def ringA(self):
print ('aaa')

  def ringB(self):
print('bbb')

class B(A):
  def __init__(self:)
  def ringB(self):
print('BBB')

a= A()
b= B()
b.ringB()
b.ringA()
b.__class__.mro()[0].ringB(22)   #  22 is used for the ringB attribute
 #  Trial and error shows that any
 #  non-Null,including None for the
 #  argument gives the same result
z= 1
def main():
pass

if __name__ == '__main__':
main()

Colin W.


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


Re: How to know that two pyc files contain the same code

2012-03-10 Thread Steven D'Aprano
On Sat, 10 Mar 2012 15:48:48 +0100, Gelonida N wrote:

> Hi,
> 
> I want to know whether two .pyc files are identical.
> 
> With identical I mean whether they contain the same byte code.

Define "identical" and "the same".

If I compile these two files:


# file ham.py
x = 23
def func():
a = 23
return a + 19



# file = spam.py
def func():
return 42

tmp = 19
x = 4 + tmp
del tmp


do you expect spam.pyc and ham.pyc to count as "the same"?


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


Re: stackoverflow question

2012-03-10 Thread Ethan Furman

Owen Jacobson wrote:

On 2012-03-09 22:10:18 +, Ethan Furman said:


Hey all!

I posted a question/answer on SO earlier, but there seems to be some 
confusion around either the question or the answer (judging from the 
comments).


http://stackoverflow.com/q/9638921/208880

If anyone here is willing to take a look at it and let me know if I 
did not write it well, I would appreciate the feedback.



Here's the question text:

I'm writing a metaclass to do some cool stuff, and part of its 
processing is to check that certain attributes exist when the class is 
created.  Some of these are mutable, and would normally be set in 
`__init__`, but since `__init__` isn't run until the instance is 
created the metaclass won't know that the attribute *will* be created, 
and raises an error.  I could do something like:


 class Test(meta=Meta):
 mutable = None
 def __init__(self):
 self.mutable = list()

But that isn't very elegant, and also violates DRY.

What I need is some way to have:

 class Test(metaclass=Meta):
 mutable = list()

 t1 = Test()
 t2 = Test()
 t1.mutable.append('one')
 t2.mutable.append('two')
 t1.mutable  # prints ['one']
 t2.mutable  # prints ['two']

Any ideas on how this can be accomplished?

Also, the metaclass doing the checking doesn't care what type of 
object the attribute is, only that it is there.

---


Why check what you can ensure? The __init__ function your metaclass 
passes to type() doesn't have to be the __init__ method your metaclass 
received. Consider the following:



import functools as f

def make_init(real_init):
"""Define an __init__ method that ensures ``self.mutable`` is 
set. If the
passed ``real_init`` function later replaces ``self.mutable``, 
that value
is preserved; otherwise, ``self.mutable`` is set to a new, empty 
list.


Arguments to the generated ``__init__`` method are passed to the 
original

``real_init`` unchanged.
"""
def __init__(self, *args, **kwargs):
self.mutable = list()
if real_init is not None:
return real_init(self, *args, **kwargs)
if real_init is not None:
f.update_wrapper(__init__, real_init)
return __init__

class Meta(type):
def __new__(meta, name, parents, attributes):
attributes['__init__'] = 
make_init(attributes.get('__init__', None))

return type.__new__(Meta, name, parents, attributes)

class C(object):
__metaclass__ = Meta

a, b = C(), C()

a.mutable.append(3)
b.mutable.append(5)

a.mutable

[3]

b.mutable

[5]

All instances of classes whose metaclass is Meta will, guaranteed, have 
an instance field named 'mutable'. Its value is a list created at 
instance creation time, unless the instance's __init__ provides a 
different value.


The idea is good.  The devil is in the details, as usual.  How is the 
metaclass going to know:


  1) which attributes to replace
  2) what to replace them with?

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


Re: How to know that two pyc files contain the same code

2012-03-10 Thread Chris Angelico
On Sun, Mar 11, 2012 at 9:52 AM, Steven D'Aprano
 wrote:
> On Sat, 10 Mar 2012 15:48:48 +0100, Gelonida N wrote:
> Define "identical" and "the same".
>
> If I compile these two files:
>
>
> # file ham.py
> x = 23
> def func():
>    a = 23
>    return a + 19
>
>
>
> # file = spam.py
> def func():
>    return 42
>
> tmp = 19
> x = 4 + tmp
> del tmp
>
>
> do you expect spam.pyc and ham.pyc to count as "the same"?

They do not contain the same code. They may contain code which has the
same effect, but it is not the same code.

I don't think Python has the level of aggressive optimization that
would make these compile to the same bytecode, but if it did, then
they would _become identical_ per the OP's description - that they
contain identical bytecode. In fact, I think the OP defined it quite
clearly.

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


Re: Porting the 2-3 heap data-structure library from C to Python

2012-03-10 Thread Hrvoje Niksic
Stefan Behnel  writes:

>> which is the standard way of extending Python with high-performance
>> (and/or system-specific) C code.
>
> Well, it's *one* way.  Certainly not the easiest way, neither the most
> portable and you'll have a hard time making it the fastest.

I didn't say it was easy, but standard, in the sense of documented in
Python documentation.  Python/C is as portable as Python itself, and as
fast as the platform allows.  I understand your desire to promote
Cython, but please stop resorting to FUD in doing so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Porting the 2-3 heap data-structure library from C to Python

2012-03-10 Thread Terry Reedy

On 3/10/2012 8:03 PM, Hrvoje Niksic wrote:

Stefan Behnel  writes:


which is the standard way of extending Python with high-performance
(and/or system-specific) C code.


Well, it's *one* way.  Certainly not the easiest way, neither the most
portable and you'll have a hard time making it the fastest.


I didn't say it was easy, but standard, in the sense of documented in
Python documentation.  Python/C is as portable as Python itself, and as


Python is portable because a *lot* of work has gone and continues to go 
into making it so. And because it sticks with the lowest common 
denominator of C89. There is much system or compiler specific code in 
#ifdefs. There are over 60 buildbots for testing patches on various 
hardware-os-compiler-(python)version combinations. Perhaps once a week 
something does not work on one of them. The patch gets revised. It 
happened just today.


Apple is changing compilers for the Mac; Python initially did not build 
with the new compiler. Some people had to do some work so there would 
continue to be Python on the Mac. So I can imagine that Cython *might* 
shield one from some of the very real portability problems.



fast as the platform allows.  I understand your desire to promote
Cython, but please stop resorting to FUD in doing so.


You admitted it might be easier. Portability is plausible. So I think 
that a bit harsh.


--
Terry Jan Reedy

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


[RFC] PEP 3143: supplementary group list concerns

2012-03-10 Thread Jan Pokorný

Hello,

in the light of a recent spot in Python Paste [1], I've come across
the python-daemon [2] implementation and found it also lacks support
for supplementary groups.

First, I just wanted to post a patch to the author, but realized
the broader context of PEP 3143 that would probably deserve
revisiting at the first place.  As the target Python version
seems not to be decided yet, I see a space for it.

If the spirit of solution [2] was to be followed (i.e., initialize
this list with all groups of which user derived from `uid` is
a member + group derived from `gid` (regardless if `uid`/`gid`
is explicit), no change of the PEP would be necessary.
This fact of intented handling of supplementary groups under the hood
still could be mentioned so the users and authors of compatible
interfaces are aware of this "detail".

Another way (in the spirit of systemd [3]) is to extend the interface
with an option (named, e.g., supplementary_groups) for optional
specification of supplemental groups.  The default would be something
as in the previous paragraph.

To be honest, I am not sure how consistently is the concept of
supplementary groups used across various *nixes.
POSIX seems to admit variances, e.g. (via [4]):
v
The System Interfaces volume of IEEE Std 1003.1-2001 does not specify
whether the effective group ID of a process is included in its
supplementary group list.
^

But I believe this should be addressed before the PEP in question is
brought into effect.

[2] 
http://groups.google.com/group/paste-users/browse_thread/thread/2aa651ba331c2471
[3] http://0pointer.de/public/systemd-man/systemd.exec.html
[4] http://pubs.opengroup.org/onlinepubs/95399/utilities/newgrp.html

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


Re: How to know that two pyc files contain the same code

2012-03-10 Thread Gelonida N
Hi Steven,

On 03/10/2012 11:52 PM, Steven D'Aprano wrote:
> > On Sat, 10 Mar 2012 15:48:48 +0100, Gelonida N wrote:
> >
>> >> Hi,
>> >>
>> >> I want to know whether two .pyc files are identical.
>> >>
>> >> With identical I mean whether they contain the same byte code.
> >
> > Define "identical" and "the same".
Indeed! Identical is not that simple to define and depends on the context.

One definition of identical, that would suit me at the moment would be:

If I have two .pyc files, which were the result of a compilation of
two identical .py files, then I would like to treat these two .pyc files
as identical,
even if they were compiled at different times (absolutely necessary)
and with a different absolute path (would be nice)

Above definition of identical byte code would also mean, that any error
message about errors in a given line number would be identical for both
.pyc files

> >
> > If I compile these two files:
> >
> >
> > # file ham.py
> > x = 23
> > def func():
> > a = 23
> > return a + 19
> >
> >
> >
> > # file = spam.py
> > def func():
> > return 42
> >
> > tmp = 19
> > x = 4 + tmp
> > del tmp
> >
> >
> > do you expect spam.pyc and ham.pyc to count as "the same"?
> >
For most pythons I would not expect, that ham.py and spam.py would
result in the same byte code and would thus not even have the same
performance,

I agree, though that an efficient compiler might generate the same byte
code, though I wonder if an optimizing compiler would/should be allowed
to optimize away the global variable tmp, as it would be visible (though
only for a short time) in a multithreading environment.

If the byte code were different in two .pyc files. then I would
like to have them treated as different .pyc files.

If by coincidence, the generated btye code were the same, then I
wouldn't mind, if they were treated as identical,  but I wouldn't insist.

Up to my knowledge Python (or at least C-python) stores line numbers in
the .pyc files, so that it can report exact line numbers refering to the
originating source code in case of an exception or for back traces

So there is the choice to say, that two pyc files with exactly the same
byte code would be treated identical if white spaces / line numbers of
their sources were different or the choice to say, that they are
different.

Being conservative I'd treat them as different.

Ideally I'd like to be able depending on my use case to distinguish
following cases.
a) .pyc files with identical byte code
b) .pyc files with identical byte code AND source code line numbers
c) same as b) AND identical source file names.






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


Re: stackoverflow question

2012-03-10 Thread Owen Jacobson

On 2012-03-10 22:21:55 +, Ethan Furman said:


Owen Jacobson wrote:

On 2012-03-09 22:10:18 +, Ethan Furman said:


Hey all!

I posted a question/answer on SO earlier, but there seems to be some 
confusion around either the question or the answer (judging from the 
comments).


http://stackoverflow.com/q/9638921/208880

If anyone here is willing to take a look at it and let me know if I did 
not write it well, I would appreciate the feedback.



Here's the question text:

I'm writing a metaclass to do some cool stuff, and part of its 
processing is to check that certain attributes exist when the class is 
created.  Some of these are mutable, and would normally be set in 
`__init__`, but since `__init__` isn't run until the instance is 
created the metaclass won't know that the attribute *will* be created, 
and raises an error.  I could do something like:


class Test(meta=Meta):
mutable = None
def __init__(self):
self.mutable = list()

But that isn't very elegant, and also violates DRY.

What I need is some way to have:

class Test(metaclass=Meta):
mutable = list()

t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
t1.mutable  # prints ['one']
t2.mutable  # prints ['two']

Any ideas on how this can be accomplished?

Also, the metaclass doing the checking doesn't care what type of object 
the attribute is, only that it is there.

---


Why check what you can ensure? The __init__ function your metaclass 
passes to type() doesn't have to be the __init__ method your metaclass 
received.


[… __init__-generation technique elided …]

All instances of classes whose metaclass is Meta will, guaranteed, have 
an instance field named 'mutable'. Its value is a list created at 
instance creation time, unless the instance's __init__ provides a 
different value.


The idea is good.  The devil is in the details, as usual.  How is the 
metaclass going to know:


   1) which attributes to replace
   2) what to replace them with?


I can think of at least three techniques; others are certainly possible:

1. As with the example code, the list is hard-coded in the metaclass's 
source code.
2. The list (or, rather, a dictionary) is drawn from a class attribute 
of the class being created:


class Foo(object):
mandatory_fields = {'mutable': list, 'more_stuff': str}
__metaclass__ = IntrospectingMetaclass

3. A metaclass-returning factory produces new metaclasses on demand, 
each of which has a dict of mandatory fields baked into it. (This is a 
hybrid of the two approaches, and can easily have some messy side 
effects on your app's type ecology if used carelessly.)


Of course, you can also treat this the other way around: instead of 
enforcing that instances have specific fields, you could have users of 
those instances be aware that the field might not exist, and wrap 
access to the field in a try/except NameError block or use getattr to 
read the attribute.


What's appropriate really depends on how you plan to use this 
metaclass, and on the nature of the higher-level problem to which "I 
know, I'll use metaclasses" is your answer. How about telling us a 
slightly broader story about your problem?


-o

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


Re: "Decoding unicode is not supported" in unusual situation

2012-03-10 Thread John Nagle

On 3/9/2012 4:57 PM, Steven D'Aprano wrote:

On Fri, 09 Mar 2012 10:11:58 -0800, John Nagle wrote:
This demonstrates a gross confusion about both Unicode and Python. John,
I honestly don't mean to be rude here, but if you actually believe that
(rather than merely expressing yourself poorly), then it seems to me that
you are desperately misinformed about Unicode and are working on the
basis of some serious misapprehensions about the nature of strings.

In Python 2.6/2.7, there is no ambiguity between str/bytes. The two names
are aliases for each other. The older name, "str", is a misnomer, since
it *actually* refers to bytes (and always has, all the way back to the
earliest days of Python). At best, it could be read as "byte string" or
"8-bit string", but the emphasis should always be on the *bytes*.


   There's an inherent ambiguity in that "bytes" and "str" are really
the same type in Python 2.6/2.7.  That's a hack for backwards
compatibility, and it goes away in 3.x.  The notes for PEP 358
admit this.

   It's implicit in allowing

unicode(s)

with no encoding, on type "str", that there is an implicit
assumption that s is ASCII.  Arguably, "unicode()" should
have required an encoding in all cases.

Or "str" and "bytes" should have been made separate types in
Python 2.7, in which case unicode() of a str would be a safe
ASCII to Unicode translation, and unicode() of a bytes object
would require an encoding.  But that would break too much old code.
So we have an ambiguity and a hack.

"While Python 2 also has a unicode string type, the fundamental 
ambiguity of the core string type, coupled with Python 2's default 
behavior of supporting automatic coercion from 8-bit strings to unicode 
objects when the two are combined, often leads to UnicodeErrors"

- PEP 404

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


Re: How to know that two pyc files contain the same code

2012-03-10 Thread Steven D'Aprano
On Sun, 11 Mar 2012 12:15:11 +1100, Chris Angelico wrote:

> On Sun, Mar 11, 2012 at 9:52 AM, Steven D'Aprano
>  wrote:
>> On Sat, 10 Mar 2012 15:48:48 +0100, Gelonida N wrote: Define
>> "identical" and "the same".
>>
>> If I compile these two files:
>>
>>
>> # file ham.py
>> x = 23
>> def func():
>>    a = 23
>>    return a + 19
>>
>>
>>
>> # file = spam.py
>> def func():
>>    return 42
>>
>> tmp = 19
>> x = 4 + tmp
>> del tmp
>>
>>
>> do you expect spam.pyc and ham.pyc to count as "the same"?
> 
> They do not contain the same code. They may contain code which has the
> same effect, but it is not the same code.

To me, they do: they contain a function "func" which takes no arguments 
and returns 42, and a global "x" initialised to 23. Everything else is an 
implementation detail.

I'm not being facetious. One should be asking what is the *purpose* of 
this question -- is it to detect when two pyc files contain the same 
*interface*, or to determine if they were generated from identical source 
code files (and if the later, do comments and whitespace matter)?

What if one merely changed the order of definition? Instead of:

def foo(): pass
def bar(): pass

one had this?

def bar(): pass
def foo(): pass

It depends on why the OP cares if they are "identical". I can imagine use-
cases where the right solution is to forget ideas about identical code, 
and just checksum the files (ignoring any timestamps).


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


Re: Porting the 2-3 heap data-structure library from C to Python

2012-03-10 Thread Stefan Behnel
Hrvoje Niksic, 11.03.2012 02:03:
> Stefan Behnel writes:
>>> which is the standard way of extending Python with high-performance
>>> (and/or system-specific) C code.
>>
>> Well, it's *one* way.  Certainly not the easiest way, neither the most
>> portable and you'll have a hard time making it the fastest.
> 
> I didn't say it was easy, but standard, in the sense of documented in
> Python documentation.  Python/C is as portable as Python itself, and as
> fast as the platform allows.

Only if you know how to do it right and have the discipline to do a lot of
cross-platform testing, benchmarking and tuning. Not everyone wants to
invest that much time into details that are unrelated to the problem at
hand. And why should they, when other people (who have gained some
experience in it) have already done if for them and continue to do that, so
that they don't need to care and can get it for free?


> I understand your desire to promote
> Cython, but please stop resorting to FUD in doing so.

I can't see it being FUD (although arguably promotion) to tell people that
"we write C so you don't have to". It's certainly not FUD that it's easier
(and IMHO also more fun) to write good Python code than good C code. Quite
the contrary, telling new users to go straight for writing C code and using
CPython's C-API natively is like asking them why (the heck!) they are using
Python in the first place, when they can just dive into the beautiful world
of C. I don't think that's the ideal attitude for this list.

Stefan

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