wrap exe with in another exe

2009-12-18 Thread prakash jp
Hi all,
I need to call an external executable from my "calling_exe.py" python
program.
Can we make a executable say->"Final.exe" from the "calling_exe.py" and the
"external.exe"
*"calling_exe.py" ->(calling)->  "external.exe"

||

---
(integrate using py2exe)  ||  how should the setup.py file look
like?
   \||/
\/
   "Final.exe"  *
*Regards*
*Prakash*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: share dictionary between processes

2009-12-18 Thread garabik-news-2005-05
blumenkraft  wrote:
> Hi,
> 
> I want to share dictionary between two distinct processes.
> 
...
> I have looked at POSH, but it requires master process that will fork
> childs. I want read-only sharing between completely unrelated
> processes.
> Is it possible?

Depends on your exact needs - dbm or shelve might be enough, especially for 
read only access.

-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: share dictionary between processes

2009-12-18 Thread Michele Simionato
On Dec 18, 8:48 am, blumenkraft  wrote:
> Hi,
>
> I want to share dictionary between two distinct processes.
>
> Something like this:
>
> first.py
> import magic_share_module
>
> def create_dictionary():
>     return {"a": 1}
>
> magic_share_module.share("shared_dictionary",
> creator.create_dictionary)
> while True:
>      pass
>
> second.py
> import magic_share_module
> d = magic_share_module.get_shared("shared_dictionary")
> print d["a"]
>
> And then run in command line:
> python first.py &
> sleep 1
> python second.py
>
> I have looked at POSH, but it requires master process that will fork
> childs. I want read-only sharing between completely unrelated
> processes.
> Is it possible?

Yes, see http://docs.python.org/library/multiprocessing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-18 Thread casevh
On Dec 17, 11:14 am, Joachim Dahl  wrote:
> In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a
> related bug:
>
> >>> foo(b='b')
>
> will set the value of a in the extension module to zero, thus clearing
> whatever
> default value it may have had.  In other words, the optional character
> arguments
> that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords().

The following code seems to work fine for me:

static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
{
int a=65, b=66;
char *kwlist[] = {"a", "b", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
&b))
return NULL;
return Py_BuildValue("(CC)", a, b);
}

The default values seem to remain as 'A' and 'B'.

>>> foo()
('A', 'B')
>>> foo(b='b')
('A', 'b')
>>> foo()
('A', 'B')
>>> foo('a')
('a', 'B')
>>> foo('a', b='b')
('a', 'b')
>>> foo()
('A', 'B')
>>>

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


Re: share dictionary between processes

2009-12-18 Thread News123
Hi Michael,

I'm new to the module multiprocessing, but at a first glance
it seems, that multiprocessing.Value can only be shared if
you create the second process from the first one.

Id like to start the first process from the command line and much later
the second process from the command line.

Is this possible?


thanks in advance and bye




N




Michele Simionato wrote:
> On Dec 18, 8:48 am, blumenkraft  wrote:
>> Hi,
>>
>> I want to share dictionary between two distinct processes.
>>
>> Something like this:
>>
>> first.py
>> import magic_share_module
>>
>> def create_dictionary():
>> return {"a": 1}
>>
>> magic_share_module.share("shared_dictionary",
>> creator.create_dictionary)
>> while True:
>>  pass
>>
>> second.py
>> import magic_share_module
>> d = magic_share_module.get_shared("shared_dictionary")
>> print d["a"]
>>
>> And then run in command line:
>> python first.py &
>> sleep 1
>> python second.py
>>
>> I have looked at POSH, but it requires master process that will fork
>> childs. I want read-only sharing between completely unrelated
>> processes.
>> Is it possible?
> 
> Yes, see http://docs.python.org/library/multiprocessing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't list comprehension be faster than for loops?

2009-12-18 Thread Carlos Grohmann

> Have you tried this with
>
>    dip1 = [dp - 0.01 if dp == 90 else dp for dp in dipList]
>

Yes that is better! many thanks!



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


Re: webscrapping ringcentral.com using mechanize

2009-12-18 Thread r0g
shrini wrote:
> Hi,
> 
> I am trying to scrap the website 'http://service.ringcentral.com'
> 
> It has a form with three input boxes.
> 
> When trying to get the form with mechanize, it is throwing the
> following error.
> 
> mechanize._mechanize.FormNotFoundError: no form matching name 'login'
> 
> but, the page has the form with name "login".
> 
> This form is submitted by javascript.
> 
> Need your help to fill the form and login to that site using python
> +mechanize.
> 
> My code is pasted here.
> 
> http://pastebin.com/f339461b4
> 
> Thanks.
> 
> Regards,
> Shrinivasan


You wouldn't be trying to crack their customers account logins would
you? Coz it would be highly illegal if you were.

Just sayin.


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


Fwd: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-18 Thread Emeka
static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
{
   int a=65, b=66;
   char *kwlist[] = {"a", "b", NULL};
I am yet to understand what kwlist pointer  does and why it is needed?

   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
&b))
   return NULL;
   return Py_BuildValue("(CC)", a, b);
}

Regards,
Emeka


The following code seems to work fine for me:

static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
{
   int a=65, b=66;
   char *kwlist[] = {"a", "b", NULL};
I am yet to understand what kwlist pointer  does and why it is needed?

   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
&b))
   return NULL;
   return Py_BuildValue("(CC)", a, b);
}

Regards,
Emeka


The default values seem to remain as 'A' and 'B'


On Fri, Dec 18, 2009 at 8:17 AM, casevh  wrote:

> On Dec 17, 11:14 am, Joachim Dahl  wrote:
> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a
> > related bug:
> >
> > >>> foo(b='b')
> >
> > will set the value of a in the extension module to zero, thus clearing
> > whatever
> > default value it may have had.  In other words, the optional character
> > arguments
> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords().
>
> The following code seems to work fine for me:
>
> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> {
> int a=65, b=66;
> char *kwlist[] = {"a", "b", NULL};
>if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
> &b))
>return NULL;
> return Py_BuildValue("(CC)", a, b);
> }
>
> The default values seem to remain as 'A' and 'B'.
>
> >>> foo()
> ('A', 'B')
> >>> foo(b='b')
> ('A', 'b')
> >>> foo()
> ('A', 'B')
> >>> foo('a')
> ('a', 'B')
> >>> foo('a', b='b')
> ('a', 'b')
> >>> foo()
> ('A', 'B')
> >>>
>
> casevh
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-18 Thread Emeka
   char *kwlist[] = {"a", "b", NULL};
   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
&b))
I am yet to understand what pointer kwlist[] does and why it is needed?

Regards,
Emeka

On Fri, Dec 18, 2009 at 8:17 AM, casevh  wrote:

> On Dec 17, 11:14 am, Joachim Dahl  wrote:
> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a
> > related bug:
> >
> > >>> foo(b='b')
> >
> > will set the value of a in the extension module to zero, thus clearing
> > whatever
> > default value it may have had.  In other words, the optional character
> > arguments
> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords().
>
> The following code seems to work fine for me:
>
> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> {
> int a=65, b=66;
> char *kwlist[] = {"a", "b", NULL};
>if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
> &b))
>return NULL;
> return Py_BuildValue("(CC)", a, b);
> }
>
> The default values seem to remain as 'A' and 'B'.
>
> >>> foo()
> ('A', 'B')
> >>> foo(b='b')
> ('A', 'b')
> >>> foo()
> ('A', 'B')
> >>> foo('a')
> ('a', 'B')
> >>> foo('a', b='b')
> ('a', 'b')
> >>> foo()
> ('A', 'B')
> >>>
>
> casevh
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Webpy and UnicodeDecodeError

2009-12-18 Thread Oscar Del Ben
So I'm trying to send a file through webpy and urllib2 but I can't get
around these UnicodeErrors. Here's the code:

# controller

x = web.input(video_original={})
params = {'foo': x['foo']}

files = (('video[original]', 'test', x['video_original'].file.read
()),)
client.upload(upload_url, params, files, access_token())

# client library

def __encodeMultipart(self, fields, files):
"""
fields is a sequence of (name, value) elements for regular
form fields.
files is a sequence of (name, filename, value) elements for
data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
boundary = mimetools.choose_boundary()
crlf = '\r\n'

l = []
for k, v in fields.iteritems():
l.append('--' + boundary)
l.append('Content-Disposition: form-data; name="%s"' % k)
l.append('')
l.append(v)
for (k, f, v) in files:
l.append('--' + boundary)
l.append('Content-Disposition: form-data; name="%s";
filename="%s"' % (k, f))
l.append('Content-Type: %s' % self.__getContentType(f))
l.append('')
l.append(v)
l.append('--' + boundary + '--')
l.append('')
body = crlf.join(l)

return boundary, body

def __getContentType(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-
stream'

def upload(self, path, post_params, files, token=None):

  if token:
token = oauth.OAuthToken.from_string(token)

  url = "http://%s%s"; % (self.authority, path)

  (boundary, body) = self.__encodeMultipart(post_params, files)

  headers = {'Content-Type': 'multipart/form-data; boundary=%s' %
boundary,
  'Content-Length': str(len(body))
  }

  request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
token,
http_method='POST',
http_url=url,
parameters=post_params
  )

  request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
self.consumer, token)

  request = urllib2.Request(request.http_url, postdata=body,
headers=headers)
  request.get_method = lambda: 'POST'

  return urllib2.urlopen(request)

Unfortunately I get two kinds of unicode error, the first one in the
crlf.join(l):

Traceback (most recent call last):
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 242, in process
return self.handle()
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 233, in handle
return self._delegate(fn, self.fvars, args)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 412, in _delegate
return handle_class(cls)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 387, in handle_class
return tocall(*args)
  File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in
POST
return simplejson.load(client.upload(upload_url, params, files,
access_token()))
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
131, in upload
(boundary, body) = self.__encodeMultipart(post_params, files)
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
111, in __encodeMultipart
body = crlf.join(l)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
42: ordinal not in range(128)


And here's another one:

Traceback (most recent call last):
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 242, in process
return self.handle()
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 233, in handle
return self._delegate(fn, self.fvars, args)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 412, in _delegate
return handle_class(cls)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 387, in handle_class
return tocall(*args)
  File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in
POST
return simplejson.load(client.upload(upload_url, params, files,
access_token()))
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
131, in upload
(boundary, body) = self.__encodeMultipart(post_params, files)
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
111, in __encodeMultipart
body = crlf.join(l)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
42: ordinal not in range(128)

Does anyone know why this errors happens and what I should do to
prevent them? Many thanks.

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


Re: ANN: withrestart 0.2.1

2009-12-18 Thread Neal Becker
I haven't tried it, but it sounds really cool.  I suppose I should expect a 
lot more overhead compared to try/except, since it's not built-in to python?

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


[ANN] pylint 0.19 / astng 0.19.2

2009-12-18 Thread Sylvain Thénault
Hi,

I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 release!

More information / download  on http://www.logilab.org/project/pylint/0.19.0.

This is a "community" release, including the work we've done during the pylint
bug day [1] and patches mostly from James Lingard and Vincent Ferotin.

Many thanks to James Lingard which provided two long waited features:

* check of function call arguments
* check string interpolation consistency


So, happy christmas, enjoy!

[1] http://www.logilab.org/blogentry/19260
-- 
Sylvain Thénault   LOGILAB, Paris (France)
Formations Python, Debian, Méth. Agiles: http://www.logilab.fr/formations
Développement logiciel sur mesure:   http://www.logilab.fr/services
CubicWeb, the semantic web framework:http://www.cubicweb.org

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


Re: ftplib timeout in Python 2.4

2009-12-18 Thread Nico Grubert

Try the timelimited function from this recipe





Works perfect! Thanks a lot, Jean!
--
http://mail.python.org/mailman/listinfo/python-list


Re: share dictionary between processes

2009-12-18 Thread r0g
blumenkraft wrote:
> Hi,
> 
> I want to share dictionary between two distinct processes.
> 
> 
> Something like this:
> 
> first.py
> import magic_share_module
> 
> def create_dictionary():
> return {"a": 1}
> 
> magic_share_module.share("shared_dictionary",
> creator.create_dictionary)
> while True:
>  pass
> 
> 
> second.py
> import magic_share_module
> d = magic_share_module.get_shared("shared_dictionary")
> print d["a"]
> 
> And then run in command line:
> python first.py &
> sleep 1
> python second.py
> 
> I have looked at POSH, but it requires master process that will fork
> childs. I want read-only sharing between completely unrelated
> processes.
> Is it possible?



Depends if you need to have access to the object itself or merely look
up values in it. If it's the latter you could start a thread in first.py
that offers dictionary lookups via a specific UDP socket. Any number of
subsequent progs and processes could then pitch up and lookup whatever
values they like whenever they like. ~10 lines of code in first.py,
maybe 5 in second.py

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


Re: share dictionary between processes

2009-12-18 Thread Wolodja Wentland
On Thu, Dec 17, 2009 at 23:48 -0800, blumenkraft wrote:
> I want to share dictionary between two distinct processes.
> Something like this:
> 
> first.py
> import magic_share_module
> def create_dictionary():
> return {"a": 1}
> 
> magic_share_module.share("shared_dictionary",
> creator.create_dictionary)
> while True:
>  pass

Have a look at multiprocessing.Manager() it provides (among other
things) proxies for dictionaries that can be used in different threads.
These are even accessible on different hosts if configures correctly.
-- 
  .''`. Wolodja Wentland 
 : :'  :
 `. `'` 4096R/CAF14EFC 
   `-   081C B7CD FF04 2BA9 94EA  36B2 8B7F 7D30 CAF1 4EFC


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Java-to-Python?

2009-12-18 Thread Virgil Stokes
I have a rather large Java package for the analysis of networks that I 
would like to convert to Python. Many of the classes in the Java package 
are "Serializable".


Any recommendations on Java-to-Python (2.6) would be appreciated.

--V



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


Re: Seek support for new slice syntax PEP.

2009-12-18 Thread Colin W.

On 17-Dec-09 20:00 PM, Nobody wrote:

On Mon, 14 Dec 2009 14:18:49 -0500, Terry Reedy wrote:


Many more people uses range objects (xrange in 2.x). A range object has
the same info as a slice object *plus* it is iterable.


This isn't quite true, as a range cannot have a stop value of None, i.e.
you can't represent [n:] or [:] etc as a range. Similarly for using
negative stop values for indices relative to the end of the sequence being
sliced.

Also, aside from the semantics of slice objects themselves, slice notation
isn't limited to a single slice object; it can also return a tuple of
slices and values, e.g.:

>  numpy.s_[1::2,...,3,4:5:6]
(slice(1, None, 2), Ellipsis, 3, slice(4, 5, 6))

For a single slice, enumerating over a slice with an unspecified stop
value would be equivalent to itertools.count(). Negative stop values won't
work.

For a multi-dimensional slice, with everything specified, you would
probably want to iterate over the cartesian product (i.e. N nested loops
for an N-dimensional slice). But this won't work if anything other than
the outermost loop has an unspecified stop value, or if you use an
ellipsis within a slice.

Oh, and being able to slice a slice could be quite useful, i.e.:

[10:90:10][2::2] == [30:90:20]

cf:
>  numpy.arange(100)[10:90:10][2::2]
array([30, 50, 70])
>  numpy.arange(100)[30:90:20]
array([30, 50, 70])


You don't say, but seem to imply that the slice components include None.

Section 5.3.3 of the Python doc for 2.6.4 has

The lower and upper bound expressions, if present, must evaluate to 
plain integers; defaults are zero and the sys.maxint, respectively. If 
either bound is negative, the sequence’s length is added to it. The 
slicing now selects all items with index k such that i <= k < j where i 
and j are the specified lower and upper bounds. This may be an empty 
sequence. It is not an error if i or j lie outside the range of valid 
indexes (such items don’t exist so they aren’t selected).


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


Re: Seek support for new slice syntax PEP.

2009-12-18 Thread Colin W.

On 17-Dec-09 20:00 PM, Nobody wrote:

On Mon, 14 Dec 2009 14:18:49 -0500, Terry Reedy wrote:


Many more people uses range objects (xrange in 2.x). A range object has
the same info as a slice object *plus* it is iterable.


This isn't quite true, as a range cannot have a stop value of None, i.e.
you can't represent [n:] or [:] etc as a range. Similarly for using
negative stop values for indices relative to the end of the sequence being
sliced.

Also, aside from the semantics of slice objects themselves, slice notation
isn't limited to a single slice object; it can also return a tuple of
slices and values, e.g.:

>  numpy.s_[1::2,...,3,4:5:6]
(slice(1, None, 2), Ellipsis, 3, slice(4, 5, 6))

For a single slice, enumerating over a slice with an unspecified stop
value would be equivalent to itertools.count(). Negative stop values won't
work.

For a multi-dimensional slice, with everything specified, you would
probably want to iterate over the cartesian product (i.e. N nested loops
for an N-dimensional slice). But this won't work if anything other than
the outermost loop has an unspecified stop value, or if you use an
ellipsis within a slice.

Oh, and being able to slice a slice could be quite useful, i.e.:

[10:90:10][2::2] == [30:90:20]

cf:
>  numpy.arange(100)[10:90:10][2::2]
array([30, 50, 70])
>  numpy.arange(100)[30:90:20]
array([30, 50, 70])


You don't say, but seem to imply that the slice components include None.

Section 5.3.3 of the Python doc for 2.6.4 has

The lower and upper bound expressions, if present, must evaluate to 
plain integers; defaults are zero and the sys.maxint, respectively. If 
either bound is negative, the sequence’s length is added to it. The 
slicing now selects all items with index k such that i <= k < j where i 
and j are the specified lower and upper bounds. This may be an empty 
sequence. It is not an error if i or j lie outside the range of valid 
indexes (such items don’t exist so they aren’t selected).


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


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-18 Thread Case Vanhorsen
On Fri, Dec 18, 2009 at 2:26 AM, Emeka  wrote:
>    char *kwlist[] = {"a", "b", NULL};
>    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
> &b))
> I am yet to understand what pointer kwlist[] does and why it is needed?
> Regards,
> Emeka

foo is designed to accept two arguments that can be specified by
either position or name. kwlist contains the legal keyword names. In
this example, the legal keywords are 'a' and 'b'. That they match the
names of the C variables is just a lucky coincidence. If you want to
change the keyword names to 'foo' and 'bar', you would just use char
*kwlist[]={"foo", "bar", NULL}.

casevh
>
> On Fri, Dec 18, 2009 at 8:17 AM, casevh  wrote:
>>
>> On Dec 17, 11:14 am, Joachim Dahl  wrote:
>> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a
>> > related bug:
>> >
>> > >>> foo(b='b')
>> >
>> > will set the value of a in the extension module to zero, thus clearing
>> > whatever
>> > default value it may have had.  In other words, the optional character
>> > arguments
>> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords().
>>
>> The following code seems to work fine for me:
>>
>> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
>> {
>>    int a=65, b=66;
>>    char *kwlist[] = {"a", "b", NULL};
>>    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
>> &b))
>>        return NULL;
>>    return Py_BuildValue("(CC)", a, b);
>> }
>>
>> The default values seem to remain as 'A' and 'B'.
>>
>> >>> foo()
>> ('A', 'B')
>> >>> foo(b='b')
>> ('A', 'b')
>> >>> foo()
>> ('A', 'B')
>> >>> foo('a')
>> ('a', 'B')
>> >>> foo('a', b='b')
>> ('a', 'b')
>> >>> foo()
>> ('A', 'B')
>> >>>
>>
>> casevh
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with invoking standard mail app in windows

2009-12-18 Thread Astan Chee

Hi,
I'm trying to launch standard mail app in windows and after looking 
around most look like this:


import urllib, webbrowser, win32api
def mailto_url(to=None,subject=None,body=None,cc=None):
   """
   encodes the content as a mailto link as described on
   http://www.faqs.org/rfcs/rfc2368.html
   """
   url = "mailto: " + urllib.quote(to.strip(),"@,")
   sep = "?"
   if cc:
   url+= sep + "cc=" + urllib.quote(cc,"@,")
   sep = "&"
   if subject:
   url+= sep + "subject=" + urllib.quote(subject,"")
   sep = "&"
   if body:
   # Also note that line breaks in the body of a message MUST be
   # encoded with "%0D%0A". (RFC 2368)
   body="\r\n".join(body.splitlines())
   url+= sep + "body=" + urllib.quote(body,"")
   sep = "&"
   return url

url = mailto_url(txtTo,txtSubject,body,txtCC)
# win32api.ShellExecute(0,'open',url,None,None,0)
webbrowser.open(url,new=1)
# os.startfile(url)

all of these are having "WindowsError : [Error 5] Access is denied" 
errors. I'm using windows xp and python 2.5. I have outlook 2007 
installed as a default mail client. Clicking on any mailto links in html 
brings up the normal write mail from the mail client. Any ideas why this 
is happening or how do I debug what access is being denied?

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


Eclipse Carriage Return Workaround

2009-12-18 Thread Steve Holden
I've written a Python 3 course that uses an Eclipse-based teaching
system. The school is telling me that their version of Eclipse/pydev
appears to have an input() function that appends a carriage return
character to the user's input. This makes several things go screwy, as
it's definitely not the way the standalone interpreter works, even on
Windows.

Can anyone think of a simple way work around this issue by overriding
__builtins__.input() with a function that calls input() and then returns
an rstrip()ped version of the input string? I though of setting a
PYTHONSTARTUP environment variable, but that only affects interactive
interpreter instances.

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

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


Line indexing in Python

2009-12-18 Thread seafoid

Hi Guys,

When python reads in a file, can lines be referred to via an index?

Example:

for line in file:
 if line[0] == '0':
 a.write(line)

This works, however, I am unsure if line[0] refers only to the first line or
the first character in all lines.

Is there an easy way to refer to a line with the first character being a
single letter that you know?

Thanks in advance,
Seafoid.
-- 
View this message in context: 
http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845253.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Webpy and UnicodeDecodeError

2009-12-18 Thread Dave Angel

Oscar Del Ben wrote:

So I'm trying to send a file through webpy and urllib2 but I can't get
around these UnicodeErrors. Here's the code:

# controller

x = web.input(video_original={})
params = {'foo': x['foo']}

files = (('video[original]', 'test', x['video_original'].file.read
()),)
client.upload(upload_url, params, files, access_token())

# client library

def __encodeMultipart(self, fields, files):
"""
fields is a sequence of (name, value) elements for regular
form fields.
files is a sequence of (name, filename, value) elements for
data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
boundary = mimetools.choose_boundary()
crlf = '\r\n'

l = []
for k, v in fields.iteritems():
l.append('--' + boundary)
l.append('Content-Disposition: form-data; name="%s"' % k)
l.append('')
l.append(v)
for (k, f, v) in files:
l.append('--' + boundary)
l.append('Content-Disposition: form-data; name="%s";
filename="%s"' % (k, f))
l.append('Content-Type: %s' % self.__getContentType(f))
l.append('')
l.append(v)
l.append('--' + boundary + '--')
l.append('')
body = crlf.join(l)

return boundary, body

def __getContentType(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-
stream'

def upload(self, path, post_params, files, token=None):

  if token:
token = oauth.OAuthToken.from_string(token)

  url = "http://%s%s"; % (self.authority, path)

  (boundary, body) = self.__encodeMultipart(post_params, files)

  headers = {'Content-Type': 'multipart/form-data; boundary=%s' %
boundary,
  'Content-Length': str(len(body))
  }

  request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
token,
http_method='POST',
http_url=url,
parameters=post_params
  )

  request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
self.consumer, token)

  request = urllib2.Request(request.http_url, postdata=body,
headers=headers)
  request.get_method = lambda: 'POST'

  return urllib2.urlopen(request)

Unfortunately I get two kinds of unicode error, the first one in the
crlf.join(l):

Traceback (most recent call last):
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 242, in process
return self.handle()
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 233, in handle
return self._delegate(fn, self.fvars, args)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 412, in _delegate
return handle_class(cls)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 387, in handle_class
return tocall(*args)
  File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in
POST
return simplejson.load(client.upload(upload_url, params, files,
access_token()))
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
131, in upload
(boundary, body) = self.__encodeMultipart(post_params, files)
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
111, in __encodeMultipart
body = crlf.join(l)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
42: ordinal not in range(128)


And here's another one:

Traceback (most recent call last):
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 242, in process
return self.handle()
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 233, in handle
return self._delegate(fn, self.fvars, args)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 412, in _delegate
return handle_class(cls)
  File "/Users/oscar/projects/work/whitelabel/web/application.py",
line 387, in handle_class
return tocall(*args)
  File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in
POST
return simplejson.load(client.upload(upload_url, params, files,
access_token()))
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
131, in upload
(boundary, body) = self.__encodeMultipart(post_params, files)
  File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
111, in __encodeMultipart
body = crlf.join(l)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
42: ordinal not in range(128)

Does anyone know why this errors happens and what I should do to
prevent them? Many thanks.

Oscar

  
I did a short test to demonstrate the likely problem, without all the 
other libraries and complexity.


lst = ["abc"]
lst.append("def")
lst.append(u"abc")
lst.append("g\x48\x82\x94i")
print lst
print "**".join(lst)


That fragment of code generates (in Python 2.6) the following output and 
traceback:


['abc', 'def', u'abc', 'gH\x82\x94i']
Traceback (most recent call last):
 

Setting Parameters inside of code

2009-12-18 Thread Jim Valenza
Hello All - I have a very novice question for any of you out there.  I need
to assign several parameters to a code in python. I have an example of a
code that was in DOS that I would need to set as parameters in my Python
script.

SetLocal EnableDelayedExpansion

SET OUTPUT=..\log
SET LOG=..\log
SET COMPLETED=..\Loaded
SET FAILED=..\Errors
SET REPORT=..\log\batch_projectdb.txt
SET SOURCE=..\InBox
SET BACKUP=..\Backup
SET SERVER=housdep01
SET INSTANCE=port:5151
SET DATASET=sde
SET /a LOADED=0
SET /a POSTED=0

 :: If the directories don't exist, later commands run into problems.

MD %OUTPUT%
MD %LOG%
MD %COMPLETED%
MD %FAILED%
MD %BACKUP%

I've been researching Parameters with the Python manuals and have not found
the help to be usefull as there is not much documentation for some reason. I
am new to the Python world so maybe I'm missing an important piece of vocab.

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


Re: Java-to-Python?

2009-12-18 Thread Tim Wintle
On Fri, 2009-12-18 at 15:44 +0100, Virgil Stokes wrote:
> I have a rather large Java package for the analysis of networks that I 
> would like to convert to Python. Many of the classes in the Java package 
> are "Serializable".
> 
> Any recommendations on Java-to-Python (2.6) would be appreciated.

I used java2python recently with quite a lot of success. I believe it
doesn't support newer java features though.

http://code.google.com/p/java2python/

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


Re: Line indexing in Python

2009-12-18 Thread Richard Thomas
On Dec 18, 3:42 pm, seafoid  wrote:
> Hi Guys,
>
> When python reads in a file, can lines be referred to via an index?
>
> Example:
>
> for line in file:
>      if line[0] == '0':
>          a.write(line)
>
> This works, however, I am unsure if line[0] refers only to the first line or
> the first character in all lines.
>
> Is there an easy way to refer to a line with the first character being a
> single letter that you know?
>
> Thanks in advance,
> Seafoid.
> --
> View this message in 
> context:http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845253.html
> Sent from the Python - python-list mailing list archive at Nabble.com.

'for line in file' goes through the lines of the file. 'line[0]' is
then the first character of that line. You'll need to index them
manually, for which you should use a dictionary:

index = {}
for line in file:
index[line[0]] = line
a.write(index['0'])

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


Re: Webpy and UnicodeDecodeError

2009-12-18 Thread Oscar Del Ben
On Dec 18, 4:43 pm, Dave Angel  wrote:
> Oscar Del Ben wrote:
> > So I'm trying to send a file through webpy and urllib2 but I can't get
> > around these UnicodeErrors. Here's the code:
>
> > # controller
>
> > x = web.input(video_original={})
> > params = {'foo': x['foo']}
>
> > files = (('video[original]', 'test', x['video_original'].file.read
> > ()),)
> > client.upload(upload_url, params, files, access_token())
>
> > # client library
>
> > def __encodeMultipart(self, fields, files):
> >         """
> >         fields is a sequence of (name, value) elements for regular
> > form fields.
> >         files is a sequence of (name, filename, value) elements for
> > data to be uploaded as files
> >         Return (content_type, body) ready for httplib.HTTP instance
> >         """
> >         boundary = mimetools.choose_boundary()
> >         crlf = '\r\n'
>
> >         l = []
> >         for k, v in fields.iteritems():
> >             l.append('--' + boundary)
> >             l.append('Content-Disposition: form-data; name="%s"' % k)
> >             l.append('')
> >             l.append(v)
> >         for (k, f, v) in files:
> >             l.append('--' + boundary)
> >             l.append('Content-Disposition: form-data; name="%s";
> > filename="%s"' % (k, f))
> >             l.append('Content-Type: %s' % self.__getContentType(f))
> >             l.append('')
> >             l.append(v)
> >         l.append('--' + boundary + '--')
> >         l.append('')
> >         body = crlf.join(l)
>
> >         return boundary, body
>
> >     def __getContentType(self, filename):
> >         return mimetypes.guess_type(filename)[0] or 'application/octet-
> > stream'
>
> >     def upload(self, path, post_params, files, token=None):
>
> >       if token:
> >         token = oauth.OAuthToken.from_string(token)
>
> >       url = "http://%s%s"; % (self.authority, path)
>
> >       (boundary, body) = self.__encodeMultipart(post_params, files)
>
> >       headers = {'Content-Type': 'multipart/form-data; boundary=%s' %
> > boundary,
> >           'Content-Length': str(len(body))
> >           }
>
> >       request = oauth.OAuthRequest.from_consumer_and_token(
> >         self.consumer,
> >         token,
> >         http_method='POST',
> >         http_url=url,
> >         parameters=post_params
> >       )
>
> >       request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
> > self.consumer, token)
>
> >       request = urllib2.Request(request.http_url, postdata=body,
> > headers=headers)
> >       request.get_method = lambda: 'POST'
>
> >       return urllib2.urlopen(request)
>
> > Unfortunately I get two kinds of unicode error, the first one in the
> > crlf.join(l):
>
> > Traceback (most recent call last):
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 242, in process
> >     return self.handle()
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 233, in handle
> >     return self._delegate(fn, self.fvars, args)
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 412, in _delegate
> >     return handle_class(cls)
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 387, in handle_class
> >     return tocall(*args)
> >   File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in
> > POST
> >     return simplejson.load(client.upload(upload_url, params, files,
> > access_token()))
> >   File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
> > 131, in upload
> >     (boundary, body) = self.__encodeMultipart(post_params, files)
> >   File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
> > 111, in __encodeMultipart
> >     body = crlf.join(l)
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
> > 42: ordinal not in range(128)
>
> > And here's another one:
>
> > Traceback (most recent call last):
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 242, in process
> >     return self.handle()
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 233, in handle
> >     return self._delegate(fn, self.fvars, args)
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 412, in _delegate
> >     return handle_class(cls)
> >   File "/Users/oscar/projects/work/whitelabel/web/application.py",
> > line 387, in handle_class
> >     return tocall(*args)
> >   File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in
> > POST
> >     return simplejson.load(client.upload(upload_url, params, files,
> > access_token()))
> >   File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
> > 131, in upload
> >     (boundary, body) = self.__encodeMultipart(post_params, files)
> >   File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line
> > 111, in __encodeMultipart
> >     body = crlf.join(l)
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
> 

Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-18 Thread Emeka
Case,

Thanks so much! However, I am still confused. This is what I understood;

foo (a = "a", b = "b") so function , foo,  has default values which are "a"
and "b". pointer kwlist[] is a way of specifying default values .

Regards,
Emeka

On Fri, Dec 18, 2009 at 3:02 PM, Case Vanhorsen  wrote:

> On Fri, Dec 18, 2009 at 2:26 AM, Emeka  wrote:
> >char *kwlist[] = {"a", "b", NULL};
> >if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
> > &b))
> > I am yet to understand what pointer kwlist[] does and why it is needed?
> > Regards,
> > Emeka
>
> foo is designed to accept two arguments that can be specified by
> either position or name. kwlist contains the legal keyword names. In
> this example, the legal keywords are 'a' and 'b'. That they match the
> names of the C variables is just a lucky coincidence. If you want to
> change the keyword names to 'foo' and 'bar', you would just use char
> *kwlist[]={"foo", "bar", NULL}.
>
> casevh
> >
> > On Fri, Dec 18, 2009 at 8:17 AM, casevh  wrote:
> >>
> >> On Dec 17, 11:14 am, Joachim Dahl  wrote:
> >> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a
> >> > related bug:
> >> >
> >> > >>> foo(b='b')
> >> >
> >> > will set the value of a in the extension module to zero, thus clearing
> >> > whatever
> >> > default value it may have had.  In other words, the optional character
> >> > arguments
> >> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords().
> >>
> >> The following code seems to work fine for me:
> >>
> >> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> >> {
> >>int a=65, b=66;
> >>char *kwlist[] = {"a", "b", NULL};
> >>if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
> >> &b))
> >>return NULL;
> >>return Py_BuildValue("(CC)", a, b);
> >> }
> >>
> >> The default values seem to remain as 'A' and 'B'.
> >>
> >> >>> foo()
> >> ('A', 'B')
> >> >>> foo(b='b')
> >> ('A', 'b')
> >> >>> foo()
> >> ('A', 'B')
> >> >>> foo('a')
> >> ('a', 'B')
> >> >>> foo('a', b='b')
> >> ('a', 'b')
> >> >>> foo()
> >> ('A', 'B')
> >> >>>
> >>
> >> casevh
> >> --
> >> http://mail.python.org/mailman/listinfo/python-list
> >
> >
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line indexing in Python

2009-12-18 Thread Steve Holden
seafoid wrote:
> Hi Guys,
> 
> When python reads in a file, can lines be referred to via an index?
> 
> Example:
> 
> for line in file:
>  if line[0] == '0':
>  a.write(line)
> 
> This works, however, I am unsure if line[0] refers only to the first line or
> the first character in all lines.
> 
Each time around the loop the variable "line" contains the current line
from the file. Thus line[0] is the first character of the current line.

If your intent is to print all lines beginning with "0" then your code
will work.

> Is there an easy way to refer to a line with the first character being a
> single letter that you know?
> 
You might express it more readably as

for line in file:
if line.startswith("0"):
a.write(line)

This seems to express the intent of your code somewhat more directly.

regards
 Steve

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

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


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-18 Thread Case Vanhorsen
On Fri, Dec 18, 2009 at 7:57 AM, Emeka  wrote:
> Case,
> Thanks so much! However, I am still confused. This is what I understood;
> foo (a = "a", b = "b") so function , foo,  has default values which are "a"
> and "b". pointer kwlist[] is a way of specifying default values .
> Regards,
> Emeka
kwlist just specifies the names. The default values are specified by
"int a=65, b=66;". 65 is equivalent to 'A' and 66 is equivalent to
'B'.

casevh
>
> On Fri, Dec 18, 2009 at 3:02 PM, Case Vanhorsen  wrote:
>>
>> On Fri, Dec 18, 2009 at 2:26 AM, Emeka  wrote:
>> >    char *kwlist[] = {"a", "b", NULL};
>> >    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
>> > &b))
>> > I am yet to understand what pointer kwlist[] does and why it is needed?
>> > Regards,
>> > Emeka
>>
>> foo is designed to accept two arguments that can be specified by
>> either position or name. kwlist contains the legal keyword names. In
>> this example, the legal keywords are 'a' and 'b'. That they match the
>> names of the C variables is just a lucky coincidence. If you want to
>> change the keyword names to 'foo' and 'bar', you would just use char
>> *kwlist[]={"foo", "bar", NULL}.
>>
>> casevh
>> >
>> > On Fri, Dec 18, 2009 at 8:17 AM, casevh  wrote:
>> >>
>> >> On Dec 17, 11:14 am, Joachim Dahl  wrote:
>> >> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's
>> >> > a
>> >> > related bug:
>> >> >
>> >> > >>> foo(b='b')
>> >> >
>> >> > will set the value of a in the extension module to zero, thus
>> >> > clearing
>> >> > whatever
>> >> > default value it may have had.  In other words, the optional
>> >> > character
>> >> > arguments
>> >> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords().
>> >>
>> >> The following code seems to work fine for me:
>> >>
>> >> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
>> >> {
>> >>    int a=65, b=66;
>> >>    char *kwlist[] = {"a", "b", NULL};
>> >>    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
>> >> &b))
>> >>        return NULL;
>> >>    return Py_BuildValue("(CC)", a, b);
>> >> }
>> >>
>> >> The default values seem to remain as 'A' and 'B'.
>> >>
>> >> >>> foo()
>> >> ('A', 'B')
>> >> >>> foo(b='b')
>> >> ('A', 'b')
>> >> >>> foo()
>> >> ('A', 'B')
>> >> >>> foo('a')
>> >> ('a', 'B')
>> >> >>> foo('a', b='b')
>> >> ('a', 'b')
>> >> >>> foo()
>> >> ('A', 'B')
>> >> >>>
>> >>
>> >> casevh
>> >> --
>> >> http://mail.python.org/mailman/listinfo/python-list
>> >
>> >
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line indexing in Python

2009-12-18 Thread seafoid

Thanks for that Richard and Steve.

I have another question.

fname = raw_input('Please enter the name of the file: ')

# create file objects

blah = open(fname, 'r')
a = open('rubbish', 'w')

for line in blah:
if line.startswith("0"):
a.write(line)
elif line.endswith("0"):
lists_a = line.strip().split() 
print lists_a
elif line.startswith("0"):
lists_b = line.strip().split()
print lists_b

Essentially, I wish to take input from a file and based on the location of
zero, assign lines to lists.

Any suggestions?

Seafoid.

-- 
View this message in context: 
http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845949.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Java-to-Python?

2009-12-18 Thread Luis M . González
On Dec 18, 11:44 am, Virgil Stokes  wrote:
> I have a rather large Java package for the analysis of networks that I
> would like to convert to Python. Many of the classes in the Java package
> are "Serializable".
>
> Any recommendations on Java-to-Python (2.6) would be appreciated.
>
> --V

Have you considered using this package with Jython?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line indexing in Python

2009-12-18 Thread seafoid

Thanks for that Richard and Steve!

Below is my full code so far:

for line in file:
if line.startswith("1"):
a.write(line)
elif line.endswith("0"):
lists_a = line.strip().split()
print lists_a
elif line.startswith("2"):
lists_b = line.strip().split()
print list_a

Essentially, I want to read in a file and depending on location of 0, 1, 2,
write to another file or create lists.

The above passes without error warning but does nothing (semantic error?).

Any Suggestions?

Thanks in advance,
Seafoid.
-- 
View this message in context: 
http://old.nabble.com/Line-indexing-in-Python-tp26845253p26846049.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Design question about pretree classifier

2009-12-18 Thread Julian
Hello,

I've got a design problem for a classifier. To make it short: it maps
strings on strings.

Some strings have exactly one classification, some none and some more
than one.

There's a method classify(self, word) wich classifies a word. For the
first case there's no problem:

- one classification: return the value (it's a string)

But:

- none classification: return an exception or None? I think None is
better, hence its not an exception that there is no classification but
a defined state. What do you think?
- many classifications: what to do? retun a sequence of strings? raise
an exception and implement another method wich returns than the
classifications? what should I do here?

thanks for your answers!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: imports in __init__.py

2009-12-18 Thread sKeeZe
I wrote my last message late last night. When I said "I am unable to
import a module from the package without an import error.", I did mean
the 'modulename' module.

However, I just set up a Debian VM with Python 2.5.2 and what I was
trying to do works. So it is either something that changed with Python
3.1.1, or a problem with Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: imports in __init__.py

2009-12-18 Thread Phil
I wrote my last message late last night. When I said "I am unable to
import a module from the package without an import error.", I did mean
the 'modulename' module.

However, I just set up a Debian VM with Python 2.5.2 and what I was
trying to do works. So it is either something that changed with Python
3.1.1, or a problem with Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line indexing in Python

2009-12-18 Thread Lie Ryan

On 12/19/2009 3:27 AM, seafoid wrote:


Thanks for that Richard and Steve.

I have another question.


What's the question?


fname = raw_input('Please enter the name of the file: ')

# create file objects

blah = open(fname, 'r')
a = open('rubbish', 'w')

for line in blah:
 if line.startswith("0"):
 a.write(line)
 elif line.endswith("0"):
 lists_a = line.strip().split()
 print lists_a


The following block is a dead code; the block will never be executed 
since if line.startswith("0") is true, the control will fall to the 
a.write(line) block and this block is skipped.

 elif line.startswith("0"):
 lists_b = line.strip().split()
 print lists_b

Essentially, I wish to take input from a file and based on the location of
zero, assign lines to lists.

Any suggestions?

Seafoid.



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


Re: iterators and views of lists

2009-12-18 Thread Anh Hai Trinh
On Dec 18, 3:07 am, Brendan Miller  wrote:

> Well, it doesn't really need to be any slower than a normal list. You
> only need to use index and do extra additions because it's in python.
> However, if listagent were written in C, you would just have a pointer
> into the contents of the original list, and the length, which is all
> that list itself has.

You're right, I was thinking in Python instead of C. So the
translations in that case is really straight forward, using just
pointer arithmetic.

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


Re: Raw string substitution problem

2009-12-18 Thread Sion Arrowsmith
Gregory Ewing   wrote:
>MRAB wrote:
>> Regular expressions and replacement strings have their own escaping
>> mechanism, which also uses backslashes.
>This seems like a misfeature to me. It makes sense for
>a regular expression to give special meanings to backslash
>sequences, because it's a sublanguage with its own syntax.
>But I can't see any earthly reason to do that with the
>*replacement* string, which is just data.

>>> re.sub('a(.)c', r'\1', "123abcdefg")
'123bdefg'

Still think the replacement string is "just data"?

-- 
\S

   under construction

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


Re: Raw string substitution problem

2009-12-18 Thread MRAB

Gregory Ewing wrote:

MRAB wrote:


Regular expressions and replacement strings have their own escaping
mechanism, which also uses backslashes.


This seems like a misfeature to me. It makes sense for a regular
expression to give special meanings to backslash sequences, because
it's a sublanguage with its own syntax. But I can't see any earthly
reason to do that with the *replacement* string, which is just data.

It looks like a feature that's been blindly copied over from Perl
without thinking about whether it makes sense in Python.


In simple cases you might be replacing with the same string every time,
but other cases you might want the replacement to contain substrings
captured by the regex.

For example, swapping pairs of words:


re.sub(r'(\w+) (\w+)', r'\2 \1', r'first second third fourth')

'second first fourth third'


Python also allows you to provide a function that returns the
replacement string, but that seems a bit long-winded for those cases
when a simple replacement template would suffice.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] pylint 0.19 / astng 0.19.2

2009-12-18 Thread Jean-Michel Pichavant

Sylvain Thénault wrote:

Hi,

I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 release!

More information / download  on http://www.logilab.org/project/pylint/0.19.0.

This is a "community" release, including the work we've done during the pylint
bug day [1] and patches mostly from James Lingard and Vincent Ferotin.

Many thanks to James Lingard which provided two long waited features:

* check of function call arguments
* check string interpolation consistency


So, happy christmas, enjoy!

[1] http://www.logilab.org/blogentry/19260
  

I have troubles after updating pylint:

easy_install pylint -U --install-dir 
/opt/tools/python/python2.3/site-packages


> pylint

 File 
"/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py", 
line 28, in 
   from logilab.astng._nodes import Proxy_, List, Tuple, Function, If, 
TryExcept

ImportError: No module named _nodes

There is no _nodes.py file within the egg. Has anyone experienced the 
same issue ?


Jean-Michel

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


Re: share dictionary between processes

2009-12-18 Thread Steve Holden
blumenkraft wrote:
> Hi,
> 
> I want to share dictionary between two distinct processes.
> 
> 
> Something like this:
> 
> first.py
> import magic_share_module
> 
> def create_dictionary():
> return {"a": 1}
> 
> magic_share_module.share("shared_dictionary",
> creator.create_dictionary)
> while True:
>  pass
> 
> 
> second.py
> import magic_share_module
> d = magic_share_module.get_shared("shared_dictionary")
> print d["a"]
> 
> And then run in command line:
> python first.py &
> sleep 1
> python second.py
> 
> I have looked at POSH, but it requires master process that will fork
> childs. I want read-only sharing between completely unrelated
> processes.
> Is it possible?

Take a look at pyro, though it may be overkill for your needs.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] pylint 0.19 / astng 0.19.2

2009-12-18 Thread Jerry Hill
On Fri, Dec 18, 2009 at 12:24 PM, Jean-Michel Pichavant >  File
> "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py",
> line 28, in 
>   from logilab.astng._nodes import Proxy_, List, Tuple, Function, If,
> TryExcept
> ImportError: No module named _nodes

You're installing the wrong version of logilab.  That's the python 2.5
version, judging by the name of the egg.  I'm not sure how
easy_install decides which version of python to install for, but it's
definitely picking the wrong one here.

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


Re: Line indexing in Python

2009-12-18 Thread seafoid

Thanks for that Lie.

I had to have a think about what you meant when you referred to control
going to a.write(line).

Have you any suggestions how I may render this code undead or should I scrap
it and create something new?

My confusion and ineptitude is perhaps explained by my being a biologist :-(

Thanks,
Seafoid.
-- 
View this message in context: 
http://old.nabble.com/Line-indexing-in-Python-tp26845253p26846854.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: imports in __init__.py

2009-12-18 Thread Peter Otten
Phil wrote:

> I wrote my last message late last night. When I said "I am unable to
> import a module from the package without an import error.", I did mean
> the 'modulename' module.
> 
> However, I just set up a Debian VM with Python 2.5.2 and what I was
> trying to do works. So it is either something that changed with Python
> 3.1.1, or a problem with Windows.

In Python 3.x absolute import is on by default. Change

from application import *

to

from .application import *

to indicate that the application module is located within the current 
package.

Peter

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


Re: [ANN] pylint 0.19 / astng 0.19.2

2009-12-18 Thread Jean-Michel Pichavant

Jerry Hill wrote:

On Fri, Dec 18, 2009 at 12:24 PM, Jean-Michel Pichavant >  File
  

"/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py",
line 28, in 
  from logilab.astng._nodes import Proxy_, List, Tuple, Function, If,
TryExcept
ImportError: No module named _nodes



You're installing the wrong version of logilab.  That's the python 2.5
version, judging by the name of the egg.  I'm not sure how
easy_install decides which version of python to install for, but it's
definitely picking the wrong one here.

  

well, according this mail title, astng 0.19.2 is the correct one.

I should have mentioned /opt/tools/python/python2.3/ is a network drive 
where we install 3rd party modules. It is still named python2.3 but this 
is in fact totally irrelevant (we're the kind of lazy guys).

Python 2.5 is the one installed on my system so easy_install guess is right.

Or maybe you suggested that pylint is no more compatible with python2.5 ?

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


Help with invoking standard mail app in windows

2009-12-18 Thread Astan Chee

Hi,
I don't know if my last mail made it or not but here it is again.
I'm trying to launch standard mail app in windows and after looking 
around most look like this:


import urllib, webbrowser, win32api
def mailto_url(to=None,subject=None,body=None,cc=None):
   """
   encodes the content as a mailto link as described on
   http://www.faqs.org/rfcs/rfc2368.html
   """
   url = "mailto: " + urllib.quote(to.strip(),"@,")
   sep = "?"
   if cc:
   url+= sep + "cc=" + urllib.quote(cc,"@,")
   sep = "&"
   if subject:
   url+= sep + "subject=" + urllib.quote(subject,"")
   sep = "&"
   if body:
   # Also note that line breaks in the body of a message MUST be
   # encoded with "%0D%0A". (RFC 2368)
   body="\r\n".join(body.splitlines())
   url+= sep + "body=" + urllib.quote(body,"")
   sep = "&"
   return url

url = mailto_url(txtTo,txtSubject,body,txtCC)
# win32api.ShellExecute(0,'open',url,None,None,0)
webbrowser.open(url,new=1)
# os.startfile(url)

all of these are having "WindowsError : [Error 5] Access is denied" 
errors. I'm using windows xp and python 2.5. I have outlook 2007 
installed as a default mail client. Clicking on any mailto links in html 
brings up the normal write mail from the mail client. Any ideas why this 
is happening or how do I debug what access is being denied?

Thanks for any help
Astan

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


Re: [ANN] pylint 0.19 / astng 0.19.2

2009-12-18 Thread Sylvain Thénault
On 18 décembre 18:24, Jean-Michel Pichavant wrote:
> Sylvain Thénault wrote:
> >Hi,
> >
> >I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 
> >release!
> >
> >More information / download  on http://www.logilab.org/project/pylint/0.19.0.
> >
> >This is a "community" release, including the work we've done during the 
> >pylint
> >bug day [1] and patches mostly from James Lingard and Vincent Ferotin.
> >
> >Many thanks to James Lingard which provided two long waited features:
> >
> >* check of function call arguments
> >* check string interpolation consistency
> >
> >
> >So, happy christmas, enjoy!
> >
> >[1] http://www.logilab.org/blogentry/19260
> I have troubles after updating pylint:
> 
> easy_install pylint -U --install-dir
> /opt/tools/python/python2.3/site-packages
> 
> > pylint
> 
>  File 
> "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py",
> line 28, in 
>from logilab.astng._nodes import Proxy_, List, Tuple, Function,
> If, TryExcept
> ImportError: No module named _nodes
> 
> There is no _nodes.py file within the egg. Has anyone experienced
> the same issue ?

yep someone else on the list have the same pb. I think I've identified it:

  python setup.py register sdist upload

*doesn't* regenerate MANIFEST if one is found... So packages uploaded to pypi 
had some missing files. Should be fixed now, sorry for this pb.
-- 
Sylvain Thénault   LOGILAB, Paris (France)
Formations Python, Debian, Méth. Agiles: http://www.logilab.fr/formations
Développement logiciel sur mesure:   http://www.logilab.fr/services
CubicWeb, the semantic web framework:http://www.cubicweb.org

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


Re: Raw string substitution problem

2009-12-18 Thread Alan G Isaac

On 12/17/2009 7:59 PM, Rhodri James wrote:

"re.compile('a\\nc')" passes a sequence of four characters to
re.compile: 'a', '\', 'n' and 'c'.  re.compile() then does it's own
interpretation: 'a' passes through as is, '\' flags an escape which
combined with 'n' produces the newline character (0x0a), and 'c' passes
through as is.



I got that from MRAB's posts. (Thanks.)
What I'm not getting is why the replacement string
gets this particular interpretation.  What is the payoff?
(Contrast e.g. Vim's substitution syntax.)

Thanks,
Alan

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


Re: Raw string substitution problem

2009-12-18 Thread Alan G Isaac

On 12/18/2009 12:17 PM, MRAB wrote:

In simple cases you might be replacing with the same string every time,
but other cases you might want the replacement to contain substrings
captured by the regex.



Of course that "conversion" is needed in the replacement.
But e.g. Vim substitutions handle this fine without the
odd (to non perlers) handling of backslashes in replacement.

Alan Isaac

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


Re: Design question about pretree classifier

2009-12-18 Thread Steve Holden
Julian wrote:
> Hello,
> 
> I've got a design problem for a classifier. To make it short: it maps
> strings on strings.
> 
> Some strings have exactly one classification, some none and some more
> than one.
> 
> There's a method classify(self, word) wich classifies a word. For the
> first case there's no problem:
> 
> - one classification: return the value (it's a string)
> 
> But:
> 
> - none classification: return an exception or None? I think None is
> better, hence its not an exception that there is no classification but
> a defined state. What do you think?
> - many classifications: what to do? retun a sequence of strings? raise
> an exception and implement another method wich returns than the
> classifications? what should I do here?
> 
> thanks for your answers!

Always return a list or tuple. For no classifications it should be
empty, for one classification it should have one element, ... , for N
classifications it should have N elements.

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

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


Re: [ANN] pylint 0.19 / astng 0.19.2

2009-12-18 Thread David Robinow
On Fri, Dec 18, 2009 at 12:49 PM, Jean-Michel Pichavant
 wrote:
> Jerry Hill wrote:
>>
>> On Fri, Dec 18, 2009 at 12:24 PM, Jean-Michel Pichavant >  File
>>> "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py",
>>> line 28, in 
>>>  from logilab.astng._nodes import Proxy_, List, Tuple, Function, If,
>>> TryExcept
>>> ImportError: No module named _nodes
>>>

It works for me (but I'm running cygwin)
You should have a file
/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/_nodes.py

Does it exist? If not, reinstall logilab_astng-0.19.2
-- 
http://mail.python.org/mailman/listinfo/python-list


Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments

2009-12-18 Thread Alf P. Steinbach

I finally finished (draft), I believe!, chapter 2...

Chapter 1 gets the reader up & running, i.e. it's "Hello, world!", basic tool 
usage, without discussing anything about programming really. One reaction to 
this chapter, based on the two example programs in it, was that it wasn't 
gradual and slow enough; hey, those examples are far too advanced, and 
unexplained! But that reader misunderstood: the progression is actually *slower* 
than one might expect. This chapter is only about tool usage. I.e., it's about 
getting those programs running, for the reader who can't rely on teachers or 
fellow students or, as Kernighan & Ritchie put it, "your local guru" (IIRC).


Chapter 2 is about Basic Concepts (of programming). It's the usual: variables, 
basic types and arrays, loops, decision, routines, classes, events, although not 
presented in that order. I make heavy use of complete, concrete examples, many 
of them graphical, and everything is in support of what's actually needed for 
such concrete examples. The intent is to enable the reader to experiment and try 
things out  --  since the only way to really learn is by doing! As best I could 
I've labored to apply this minimalism also to the Python language, using only a 
"minimal" subset (to the degree of not even introducing boolean ops :-) ).


Chapter 3 will, by my current plan, delve into the Python language and such 
things as how integers and floating point works on the inside, and that includes 
those in chapter 2 not even mentioned boolean operations. One important issue, 
introducing exceptions, and in support of that, type hierarchies. After chapter 
3 I have only much vaguer notions about what to introduce in what order, but a 
main issue, assuming that I go on with this writing, will be to apply and teach 
methodology all the way, integrated into the examples and text.


A table of contents + chapters 1 and 2 is available in PDF format at Google 
Docs, at

  http://tinyurl.com/programmingbookP3>

Comments are very welcome!

Re comments: there are two deviations from current Python practice in chapter 2. 
First, that I use spaces inside argument parentheses, which makes the code more 
readable when one gets used/trained to it because it gives the eye more direct 
information (with some training visual structure can be processed unconsciously 
& effortlessly, but purely logical structure has to be processed analytically). 
The second deviation is that since most names are constants, I do not follow PEP 
8's recommendation to use uppercase names of constants. In fact almost no Python 
code does, but then it seems that people are not aware of how many of their 
names are constants and think that they're uppercasing constants when in fact 
they're not. E.g. routine arguments and in particular routine names are usually 
constants, absolutely not meant to be modified, but it would be silly to UC...


So both these two deviations from Python practice are /intentional/, since this 
is a book about programming, not about Python the language & how to conform to 
idiosyncratic language-specific conventions.


But, if there are other deviations from Python practice I'd be very glad to hear 
of it! I'm very hopeful that any such convention deviations can be fixed. :-)



Cheers,

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


Re: Another MySQL Problem

2009-12-18 Thread John Nagle

MRAB wrote:

Victor Subervi wrote:

Hi;

mysql> truncate tem126072414516;
Query OK, 0 rows affected (0.00 sec)

Then I run a script:

  if whatDo == 'insert':
try:
  sql = 'insert into %s (ProdID, Quantity) values ("%s", "%s");' % 
(tmpTable, prodid, quantity)

  print sql
  cursor.execute(sql)


 Don't put values into an SQL statement using the "%" operator.  It doesn't
do SQL escapes and allows SQL injection attacks.

 Try something more like this (assuming that tmpTable does NOT come
from external input, which would be very risky).

cursor = db.cursor()## create cursor
sql = 'insert into ' + tmpTable + ' (ProdID, Quantity) values (%s,%s);'
values = (prodid, quantity) ## values to insert
print sql
cursor.execute(sql, values) ## let SQL do the substitution
db.commit() ## commit transaction



1. The table names look different.
2. Did you commit the changes?


That, too.

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


Re: Line indexing in Python

2009-12-18 Thread Lie Ryan

On 12/19/2009 4:33 AM, seafoid wrote:


Thanks for that Lie.

I had to have a think about what you meant when you referred to control
going to a.write(line).


and if-elif-elif-... chain is executed sequentially and when a match is 
found, the rest of the chain is skipped. Your code:


if line.startswith("0"):
# BLOCK 1 #
elif line.endswith("0"):
# BLOCK 2 #
elif line.startswith("0"):
# BLOCK 3 #

BLOCK 3 never gets executed, since if line.startswith("0") is true, your 
BLOCK 1 is executed and the rest of the if-elif chain is skipped.




Have you any suggestions how I may render this code undead or should I scrap
it and create something new?


I still don't get what you want to do with the code, but to make it not 
dead you can either:


for line in blah:
if line.startswith("0"):
a.write(line)
lists_b = line.strip().split()
print lists_b
elif line.endswith("0"):
lists_a = line.strip().split()
print lists_a

or this:

for line in blah:
if line.startswith("0"):
a.write(line)
if line.endswith("0"):
lists_a = line.strip().split()
print lists_a
elif line.startswith("0"):
lists_b = line.strip().split()
print lists_b

depending on which one seems more readable to you.


My confusion and ineptitude is perhaps explained by my being a biologist :-(

Thanks,
Seafoid.


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


Re: Line indexing in Python

2009-12-18 Thread seafoid

Hi Guys,

It has been point out that it is difficult for anyone to provide suggestions
if I do not outline more clearly my input file and an example of what I wish
to do with it (Thanks Rory!).

I mentioned it in this thread (Is creating different threads bad etiquette?
If so, lesson learned!):

http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html

Hope you guys may have some suggestions as I am stumped!

Thanks,
Seafoid :-)

seafoid wrote:
> 
> Hi Guys,
> 
> When python reads in a file, can lines be referred to via an index?
> 
> Example:
> 
> for line in file:
>  if line[0] == '0':
>  a.write(line)
> 
> This works, however, I am unsure if line[0] refers only to the first line
> or the first character in all lines.
> 
> Is there an easy way to refer to a line with the first character being a
> single letter that you know?
> 
> Thanks in advance,
> Seafoid.
> 

-- 
View this message in context: 
http://old.nabble.com/Line-indexing-in-Python-tp26845253p26847598.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Using PyImport_ExtendInittab with package

2009-12-18 Thread Julien Danjou
Hi,

I'm trying to embed Python and therefore use PyImport_ExtendInittab() to
register modules.
My current problem is that, if it works well with a simple module
"hello", naming a module "hello.foobar" in the inittab struct does not
seems to work.
imp.find_module("hello.foobar") returns correctly that the module is
found, but import hello.foobar fails badly.

Is . notation supported in inittab? Am I doing something wrong?

-- 
Julien Danjou
// ᐰhttp://julien.danjou.info
// 9A0D 5FD9 EB42 22F6 8974  C95C A462 B51E C2FE E5CD
// Don't give up.


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Raw string substitution problem

2009-12-18 Thread Lie Ryan

On 12/19/2009 4:59 AM, Alan G Isaac wrote:

On 12/18/2009 12:17 PM, MRAB wrote:

In simple cases you might be replacing with the same string every time,
but other cases you might want the replacement to contain substrings
captured by the regex.



Of course that "conversion" is needed in the replacement.
But e.g. Vim substitutions handle this fine without the
odd (to non perlers) handling of backslashes in replacement.

Alan Isaac


Short answer: Python is not Perl, Python's re.sub is not Vim's :s.

Slightly longer answer: Different environments have different need; 
vim-ers more often needs to escape with just a plain text. All in all, 
the decision for default behaviors are often made so that less backslash 
will be needed for the more common case in the particular environment.

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


Re: Line indexing in Python

2009-12-18 Thread Rory Campbell-Lange
On 18/12/09, seafoid (fitzp...@tcd.ie) wrote:
> Have you any suggestions how I may render this code undead or should I scrap
> it and create something new?

It might be easier for us to help you if you give us an example of your
input file and a clearer description of what you are trying to do with
the output from your programme.

-- 
Rory Campbell-Lange
r...@campbell-lange.net

Campbell-Lange Workshop
www.campbell-lange.net
0207 6311 555
3 Tottenham Street London W1T 2AF
Registered in England No. 04551928
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterators and views of lists

2009-12-18 Thread Carl Banks
On Dec 17, 10:00 pm, Brendan Miller  wrote:
> On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano
>
>  wrote:
> > On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote:
>
> >> I was thinking it would be cool to make python more usable in
> >> programming competitions by giving it its own port of the STL's
> >> algorithm library, which needs something along the lines of C++'s more
> >> powerful iterators.
>
> > For the benefit of those of us who aren't C++ programmers, what do its
> > iterators do that Python's don't?
>
> Python iterators basically only have one operation:
>
> next(), which returns the next element or throws StopIteration.
>
> In C++ terminology this is a Input iterator. It is good for writing
> "for each" loops or map reduce operations.

Hmm.  I guess the main thing that's bothering me about this whole
thread is that the true power of Python iterators is being overlooked
here, and I don't think you're being fair to call Python iterators
"weak" (as you did in another thread) or say that they are only good
for for-else type loops.

The fact is, Python iterators have a whole range of powers that C++
iterators do not.  C++ iterators, at least the ones that come in STL,
are limited to iterating over pre-existing data structures.  Python
iterators don't have this limation--the data being "iterated" over can
be virtual data like an infinite list, or data generated on the fly.
This can be very powerful.

Here's a cool slideshow on what can be done with iterators in Python
(generators specifically):

http://www.dabeaz.com/generators/

It is true that Python iterators can't be used to mutate the
underlying structure--if there is actual underlying data structure--
but it doesn't mean they are weak or limited.  Python and C++
iterators are similar in their most basic usage, but grow more
powerful in different directions.



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


Re: How to create a docstring for a module?

2009-12-18 Thread Albert van der Horst
In article ,
alex23   wrote:
>"Phillip M. Feldman"  wrote:
>> It does seem as though IPython could be a bit more clever about this. =A0
>
>I disagree. I _like_ that IPython is only reporting on the current
>state of the interpreter and not trying to second guess what I meant.
>
>> If the user asks for documentation on xyz via "?xyz" and xyz is not
>> defined, then I'd like to see IPython check for a module named "xyz" and
>> if it exists, extract and display the docstring.
>
>How would you recommend IPython distinguish between which "xyz" you
>meant: the one in site-packages, the one in some package on the python
>path, or the one in the folder you're running IPython from?

Alternatively, it could state that "xyz" is not loaded, but could be
loaded from one of the places you summarize.
(Kind of what Ubuntu does: hack?, I have no "hack" but such command
could be installed from BSD classical games. )

Groetjes Albert.

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: shouldn't list comprehension be faster than for loops?

2009-12-18 Thread sturlamolden
On 17 Des, 18:37, Carlos Grohmann  wrote:

> Tenting the time spent by each approach (using time.clock()), with a
> file with about 100,000 entries, I get 0.03s for the loop and 0.05s
> for the listcomp.
>
> thoughts?

Anything else being equal, list comprehensions will be the faster
becuase they incur fewer name and attribute lookups. It will be the
same as the difference between a for loop and a call to map. A list
comprehension is basically an enhancement of map.





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


Re: shouldn't list comprehension be faster than for loops?

2009-12-18 Thread sturlamolden
On 17 Des, 18:42, "Alf P. Steinbach"  wrote:

> Have you tried this with
>
>    dip1 = [dp - 0.01 if dp == 90 else dp for dp in dipList]

And for comparison with map:

map(lambda dp: dp - 0.01 if dp == 90 else dp, dipList)

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


Re: shouldn't list comprehension be faster than for loops?

2009-12-18 Thread Carl Banks
On Dec 17, 9:37 am, Carlos Grohmann  wrote:
> Tenting the time spent by each approach (using time.clock()), with a
> file with about 100,000 entries, I get 0.03s for the loop and 0.05s
> for the listcomp.
>
> thoughts?

You shouldn't trust your intuition in things like this.  Some features
were added to Python to make writing easier, not to make it run
faster.  This time your intuition was correct.  Next time, who knows?


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


How Do I...?

2009-12-18 Thread Victor Subervi
Hi;
I have this code:

i = 0
nameNos = []
nos = []
for option in ourOptions():
  nameNos.append('optionNo%d' % i)
  nos.append(i)
  i += 1

The idea is that through every iteration of option, I can create a new
variable such as 'optionNo0', 'optionNo1' etc and assign values such as '0',
'1' etc to them. Of course that code doesn't work. What would?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't list comprehension be faster than for loops?

2009-12-18 Thread sturlamolden
On 17 Des, 18:37, Carlos Grohmann  wrote:

> Tenting the time spent by each approach (using time.clock()), with a
> file with about 100,000 entries, I get 0.03s for the loop and 0.05s
> for the listcomp.
>
> thoughts?

Let me ask a retoric question:

- How much do you really value 20 ms of CPU time?






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


Re: subprocess.Popen and ordering writes to stdout and stderr

2009-12-18 Thread Lie Ryan

On 12/18/2009 8:15 AM, Chris Withers wrote:


the order of the writes isn't preserved.
How can I get this to be the case?



You'll need to flush the std{out|err} or set them unbuffered; or you can 
just forget about relying on std{out|err} being ordered per write-order.

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


Re: iterators and views of lists

2009-12-18 Thread Alf P. Steinbach

* Carl Banks:

On Dec 17, 10:00 pm, Brendan Miller  wrote:

On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano

 wrote:

On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote:

I was thinking it would be cool to make python more usable in
programming competitions by giving it its own port of the STL's
algorithm library, which needs something along the lines of C++'s more
powerful iterators.

For the benefit of those of us who aren't C++ programmers, what do its
iterators do that Python's don't?

Python iterators basically only have one operation:

next(), which returns the next element or throws StopIteration.

In C++ terminology this is a Input iterator. It is good for writing
"for each" loops or map reduce operations.


Hmm.  I guess the main thing that's bothering me about this whole
thread is that the true power of Python iterators is being overlooked
here, and I don't think you're being fair to call Python iterators
"weak" (as you did in another thread) or say that they are only good
for for-else type loops.

The fact is, Python iterators have a whole range of powers that C++
iterators do not.  C++ iterators, at least the ones that come in STL,
are limited to iterating over pre-existing data structures.  Python
iterators don't have this limation--the data being "iterated" over can
be virtual data like an infinite list, or data generated on the fly.
This can be very powerful.


It's good that Python iterators can do things.

However, it's not the case that C++ iterators can't do those things.

C++ iterators very much routinely do such things.

However, C++ iterators are flawed in a way that Python iterators are not.

You might say, in an analogy with control structures, that this flaw gives C++ 
iterators the power of "goto" but also with all the negative baggage...


I'm too lazy to Google, but you might search for Alexandrescu and "ranges", and 
possibly throw in "iterators" among the search terms.



Cheers & hth.,

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


Re: Help with invoking standard mail app in windows

2009-12-18 Thread Kev Dwyer
On Sat, 19 Dec 2009 04:56:34 +1100, Astan Chee wrote:

> Hi,
> I don't know if my last mail made it or not but here it is again. I'm
> trying to launch standard mail app in windows and after looking around
> most look like this:
> 
> import urllib, webbrowser, win32api
> def mailto_url(to=None,subject=None,body=None,cc=None):
> """
> encodes the content as a mailto link as described on
> http://www.faqs.org/rfcs/rfc2368.html """
> url = "mailto: " + urllib.quote(to.strip(),"@,") sep = "?"
> if cc:
> url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&"
> if subject:
> url+= sep + "subject=" + urllib.quote(subject,"") sep = "&"
> if body:
> # Also note that line breaks in the body of a message MUST be #
> encoded with "%0D%0A". (RFC 2368)
> body="\r\n".join(body.splitlines())
> url+= sep + "body=" + urllib.quote(body,"") sep = "&"
> return url
> 
> url = mailto_url(txtTo,txtSubject,body,txtCC) #
> win32api.ShellExecute(0,'open',url,None,None,0)
> webbrowser.open(url,new=1)
> # os.startfile(url)
> 
> all of these are having "WindowsError : [Error 5] Access is denied"
> errors. I'm using windows xp and python 2.5. I have outlook 2007
> installed as a default mail client. Clicking on any mailto links in html
> brings up the normal write mail from the mail client. Any ideas why this
> is happening or how do I debug what access is being denied? Thanks for
> any help
> Astan

Hello Astan,

Your code executes without error for me on Win98 (!) with Python 2.5 or 
XP with Python 2.6.  

It would help people to help you if you could provide the *exact* console 
output from when you try to execute the code, *including* the traceback.  
That way we can work out which line of code is hitting the exception.

Cheers,

Kev

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


Creating Classes

2009-12-18 Thread seafoid

Hey Guys,

I have started to read over classes as a brief respite from my parsing
problem.

When a class is defined, how does the class access the data upon which the
class should act?

Example:

class Seq:

def __init__(self, data, alphabet = Alphabet.generic_alphabet):
self.data = data 
self.alphabet = alphabet

def tostring(self):   
return self.data  

def tomutable(self):
return MutableSeq(self.data, self.alphabet)

def count(self, item):
return len([x for x in self.data if x == item])

I know what it should do, but have no idea how to feed it the data.

Methinks I need to invest in actual computing books as learning from
biologists is hazy!

Kind regards,
Seafoid.
  
-- 
View this message in context: 
http://old.nabble.com/Creating-Classes-tp26848375p26848375.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: iterators and views of lists

2009-12-18 Thread Lie Ryan

On 12/18/2009 7:07 AM, Brendan Miller wrote:

As for copying pointers not taking much time... that depends on how
long the list is. if you are working with small sets of data, you can
do almost anything and it will be efficient. However, if you have
megabytes or gigabytes of data (say you are working with images or
video), than the difference between an O(1) or an O(n) operation is a
big deal.


A 1-million member list takes ~130 msec, 10 million 1.3s. In many cases 
the algorithm would easily dwarf the copying itself.

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


Re: Design question about pretree classifier

2009-12-18 Thread Julian
On 18 Dez., 18:59, Steve Holden  wrote:
> Julian wrote:
> > Hello,
>
> > I've got a design problem for a classifier. To make it short: it maps
> > strings on strings.
>
> > Some strings have exactly one classification, some none and some more
> > than one.
>
> > There's a method classify(self, word) wich classifies a word. For the
> > first case there's no problem:
>
> > - one classification: return the value (it's a string)
>
> > But:
>
> > - none classification: return an exception or None? I think None is
> > better, hence its not an exception that there is no classification but
> > a defined state. What do you think?
> > - many classifications: what to do? retun a sequence of strings? raise
> > an exception and implement another method wich returns than the
> > classifications? what should I do here?
>
> > thanks for your answers!
>
> Always return a list or tuple. For no classifications it should be
> empty, for one classification it should have one element, ... , for N
> classifications it should have N elements.
>

thanks, sounds simple and good!

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

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


Re: iterators and views of lists

2009-12-18 Thread Carl Banks
On Dec 18, 11:08 am, "Alf P. Steinbach"  wrote:
> * Carl Banks:
>
>
>
> > On Dec 17, 10:00 pm, Brendan Miller  wrote:
> >> On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano
>
> >>  wrote:
> >>> On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote:
>  I was thinking it would be cool to make python more usable in
>  programming competitions by giving it its own port of the STL's
>  algorithm library, which needs something along the lines of C++'s more
>  powerful iterators.
> >>> For the benefit of those of us who aren't C++ programmers, what do its
> >>> iterators do that Python's don't?
> >> Python iterators basically only have one operation:
>
> >> next(), which returns the next element or throws StopIteration.
>
> >> In C++ terminology this is a Input iterator. It is good for writing
> >> "for each" loops or map reduce operations.
>
> > Hmm.  I guess the main thing that's bothering me about this whole
> > thread is that the true power of Python iterators is being overlooked
> > here, and I don't think you're being fair to call Python iterators
> > "weak" (as you did in another thread) or say that they are only good
> > for for-else type loops.
>
> > The fact is, Python iterators have a whole range of powers that C++
> > iterators do not.  C++ iterators, at least the ones that come in STL,
> > are limited to iterating over pre-existing data structures.  Python
> > iterators don't have this limation--the data being "iterated" over can
> > be virtual data like an infinite list, or data generated on the fly.
> > This can be very powerful.
>
> It's good that Python iterators can do things.
>
> However, it's not the case that C++ iterators can't do those things.
>
> C++ iterators very much routinely do such things.

STL Iterators?  No.  Maybe if you're talking about boost or homemade
iterators or something I could buy it, though I'd still bs suspicious
of "routinely".


> However, C++ iterators are flawed in a way that Python iterators are not.
>
> You might say, in an analogy with control structures, that this flaw gives C++
> iterators the power of "goto" but also with all the negative baggage...

That too.


> I'm too lazy to Google, but you might search for Alexandrescu and "ranges", 
> and
> possibly throw in "iterators" among the search terms.


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


Re: Help with invoking standard mail app in windows

2009-12-18 Thread Astan Chee

Kev Dwyer wrote:

Hello Astan,

Your code executes without error for me on Win98 (!) with Python 2.5 or 
XP with Python 2.6.  

It would help people to help you if you could provide the *exact* console 
output from when you try to execute the code, *including* the traceback.  
That way we can work out which line of code is hitting the exception.


Cheers,

Kev

  

Hi,
My mistake. The length of body is over 1400 characters. Here is my 
updated code and result:


import urllib, webbrowser, win32api
def mailto_url(to=None,subject=None,body=None,cc=None):
   """
   encodes the content as a mailto link as described on
   http://www.faqs.org/rfcs/rfc2368.html """
   url = "mailto: " + urllib.quote(to.strip(),"@,")
   sep = "?"
   if cc:
   url+= sep + "cc=" + urllib.quote(cc,"@,")
   sep = "&"
   if subject:
   url+= sep + "subject=" + urllib.quote(subject,"")
   sep = "&"
   if body:
   # Also note that line breaks in the body of a message MUST be
   # encoded with "%0D%0A". (RFC 2368)
   body="\r\n".join(body.splitlines())
   url+= sep + "body=" + urllib.quote(body,"")
   sep = "&"
   return url

txtTo = "t...@com.com"
txtSubject = "Test Subject"
body = "Test body"
for t in range(278):
   body+="test "
txtCC = "cc_t...@com.com"

url = mailto_url(txtTo,txtSubject,body,txtCC)
#win32api.ShellExecute(0,'open',url,None,None,0)
webbrowser.open(url,new=1)
# os.startfile(url)

result:

Traceback (most recent call last):
 File "C:/stanc_home/python/mail_test.py", line 32, in 
   webbrowser.open(url,new=1)
 File "C:\Python25\lib\webbrowser.py", line 61, in open
   if browser.open(url, new, autoraise):
 File "C:\Python25\lib\webbrowser.py", line 518, in open
   os.startfile(url)
WindowsError: [Error 5] Access is denied: 'mailto: 
t...@com.com?cc=cc_test@com.com&subject=Test%20Subject&body=Test%20bodytest%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20te

st%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test
%20test%20test%20test%20test%20test%20'

Is there some sort of limitation here? If I shorten the string, it works 
fine. You're right, but I'm wondering if there is a way to go around 
this limitation.

Thanks again
Cheers
Astan

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


Re: How Do I...?

2009-12-18 Thread Rami Chowdhury
On Fri, Dec 18, 2009 at 10:55, Victor Subervi  wrote:
> Hi;
> I have this code:
>
>     i = 0
>     nameNos = []
>     nos = []
>     for option in ourOptions():
>   nameNos.append('optionNo%d' % i)
>   nos.append(i)
>   i += 1
>
> The idea is that through every iteration of option, I can create a new
> variable such as 'optionNo0', 'optionNo1' etc and assign values such as '0',
> '1' etc to them.

What are you expecting to do with those variables and values later?



-- 
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: How Do I...?

2009-12-18 Thread Victor Subervi
On Fri, Dec 18, 2009 at 3:46 PM, Rami Chowdhury wrote:

> On Fri, Dec 18, 2009 at 10:55, Victor Subervi 
> wrote:
> > Hi;
> > I have this code:
> >
> > i = 0
> > nameNos = []
> > nos = []
> > for option in ourOptions():
> >   nameNos.append('optionNo%d' % i)
> >   nos.append(i)
> >   i += 1
> >
> > The idea is that through every iteration of option, I can create a new
> > variable such as 'optionNo0', 'optionNo1' etc and assign values such as
> '0',
> > '1' etc to them.
>
> What are you expecting to do with those variables and values later?
>

:-} I discovered after I wrote this that all I had to do was use the length
of ourOptions. But it's an interesting academic question for future
reference ;/
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Do I...?

2009-12-18 Thread Tim Chase

Victor Subervi wrote:

How do I...?


Well, you start by reading a book on how to program.  You would 
then learn that what you want (in all likelihood) is a 
dictionary/map structure for dynamically created key/value pairs. 
Once you have progressed from your current apprenticeship and 
achieved the rank of third-degree journeyman programmer, the ways 
of dynamic variable creation will avail themselves.



i = 0
nameNos = []
nos = []
for option in ourOptions():
  nameNos.append('optionNo%d' % i)
  nos.append(i)
  i += 1

The idea is that through every iteration of option, I can create a new
variable such as 'optionNo0', 'optionNo1' etc and assign values such as '0',
'1' etc to them. Of course that code doesn't work. What would?


As stated above, you want a dictionary where your keys are

  'optionNo%d' % i

and your values are "i".  You can also use the more idiomatic

  for i, option in enumerate(ourOptions()):
...

and skip the manual initialization and incrementation of "i".  Or 
even more succinctly, you could pass the above as a generator to 
the dict() initialization.  But that's a level-2 apprentice bit 
of code.  Patience grasshopper.


And as additional weirdness, you don't actually make use of 
"option" in your for-loop...


-tkc



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


Re: Help with invoking standard mail app in windows

2009-12-18 Thread Kev Dwyer
On Sat, 19 Dec 2009 06:36:32 +1100, Astan Chee wrote:

> Kev Dwyer wrote:
>> Hello Astan,
>>
>> Your code executes without error for me on Win98 (!) with Python 2.5 or
>> XP with Python 2.6.
>>
>> It would help people to help you if you could provide the *exact*
>> console output from when you try to execute the code, *including* the
>> traceback. That way we can work out which line of code is hitting the
>> exception.
>>
>> Cheers,
>>
>> Kev
>>
>>
> Hi,
> My mistake. The length of body is over 1400 characters. Here is my
> updated code and result:
> 
> import urllib, webbrowser, win32api
> def mailto_url(to=None,subject=None,body=None,cc=None):
> """
> encodes the content as a mailto link as described on
> http://www.faqs.org/rfcs/rfc2368.html """ url = "mailto: " +
> urllib.quote(to.strip(),"@,") sep = "?"
> if cc:
> url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&"
> if subject:
> url+= sep + "subject=" + urllib.quote(subject,"") sep = "&"
> if body:
> # Also note that line breaks in the body of a message MUST be #
> encoded with "%0D%0A". (RFC 2368)
> body="\r\n".join(body.splitlines())
> url+= sep + "body=" + urllib.quote(body,"") sep = "&"
> return url
> 
> txtTo = "t...@com.com"
> txtSubject = "Test Subject"
> body = "Test body"
> for t in range(278):
> body+="test "
> txtCC = "cc_t...@com.com"
> 
> url = mailto_url(txtTo,txtSubject,body,txtCC)
> #win32api.ShellExecute(0,'open',url,None,None,0)
> webbrowser.open(url,new=1)
> # os.startfile(url)
> 
> result:
> 
> Traceback (most recent call last):
>   File "C:/stanc_home/python/mail_test.py", line 32, in 
> webbrowser.open(url,new=1)
>   File "C:\Python25\lib\webbrowser.py", line 61, in open
> if browser.open(url, new, autoraise):
>   File "C:\Python25\lib\webbrowser.py", line 518, in open
> os.startfile(url)
> WindowsError: [Error 5] Access is denied: 'mailto:
> t...@com.com?cc=cc_test@com.com&subject=Test%20Subject&body=Test%
20bodytest%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20t
>  est%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20te
>  st%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20tes
>  t%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test
%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%
20test%20test%20test%20test%20test%20test%20test
>  %20test%20test%20test%20test%20test%20'
> 
> Is there some sort of limitation here? If I shorten the string, it works
> fine. You're right, but I'm wondering if there is a way to go around
> this limitation.
> Thanks again
> Cheers
> Astan

Hmmm.

For me, body < 1400 opens an outlook message form, body > 1400 opens IE7.

No time to look into this right now, but perhaps this is a windows thing.

Don't know why you get windowserror, perhaps permissions???

I'll try and look again later/tomorrow.

Cheers,

Kev

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


Re: iterators and views of lists

2009-12-18 Thread Alf P. Steinbach

* Carl Banks:

On Dec 18, 11:08 am, "Alf P. Steinbach"  wrote:

* Carl Banks:




On Dec 17, 10:00 pm, Brendan Miller  wrote:

On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano
 wrote:

On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote:

I was thinking it would be cool to make python more usable in
programming competitions by giving it its own port of the STL's
algorithm library, which needs something along the lines of C++'s more
powerful iterators.

For the benefit of those of us who aren't C++ programmers, what do its
iterators do that Python's don't?

Python iterators basically only have one operation:
next(), which returns the next element or throws StopIteration.
In C++ terminology this is a Input iterator. It is good for writing
"for each" loops or map reduce operations.

Hmm.  I guess the main thing that's bothering me about this whole
thread is that the true power of Python iterators is being overlooked
here, and I don't think you're being fair to call Python iterators
"weak" (as you did in another thread) or say that they are only good
for for-else type loops.
The fact is, Python iterators have a whole range of powers that C++
iterators do not.  C++ iterators, at least the ones that come in STL,
are limited to iterating over pre-existing data structures.  Python
iterators don't have this limation--the data being "iterated" over can
be virtual data like an infinite list, or data generated on the fly.
This can be very powerful.

It's good that Python iterators can do things.

However, it's not the case that C++ iterators can't do those things.

C++ iterators very much routinely do such things.


STL Iterators?  No.  Maybe if you're talking about boost or homemade
iterators or something I could buy it, though I'd still bs suspicious
of "routinely".


The intersection of STL and the C++ standard library is of nearly the same size 
as the STL, but I don't understand why you're limiting yourself to the STL.


After all, the STL was first developed for the Ada language, IIRC.

Using the standard C++ library, per the 1998 first (and current!) C++ standard, 
below is an idiomatic "copy Carl Banks to output" C++ program where, you might 
note, the "ostream_iterator" has a sister "istream_iterator" that definitely 
does not only iterat over a "pre-existing data structure", as you wrote.


Of course, mostly one defines iterators in the source code or by using Boost or 
similar libraries; that's how C++ works.


There's no special language support for iterators in C++; it's wholly a library 
and application defined concept.




#include 
#include 
#include 
#include 

int main()
{
using namespace std;
static char const* constwords[] =
{ "Carl", "Banks", "is", "wrong", "on", "the", "Internet", "!" };

copy(
words, words + sizeof(words)/sizeof(*words),
ostream_iterator( cout, "\n" )
);
}



Cheers & hth.,

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


Re: shouldn't list comprehension be faster than for loops?

2009-12-18 Thread Brian J Mingus
On Fri, Dec 18, 2009 at 11:55 AM, sturlamolden wrote:

> On 17 Des, 18:37, Carlos Grohmann  wrote:
>
> > Tenting the time spent by each approach (using time.clock()), with a
> > file with about 100,000 entries, I get 0.03s for the loop and 0.05s
> > for the listcomp.
> >
> > thoughts?
>
> Let me ask a retoric question:
>
> - How much do you really value 20 ms of CPU time?
>

If it takes 1 nanosecond to execute a single instruction then 20
milliseconds represents 20 million instructions. Therefore I value 20ms of
CPU time very much indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating Classes

2009-12-18 Thread Steve Holden
seafoid wrote:
> Hey Guys,
> 
> I have started to read over classes as a brief respite from my parsing
> problem.
> 
> When a class is defined, how does the class access the data upon which the
> class should act?
> 
> Example:
> 
> class Seq:
> 
> def __init__(self, data, alphabet = Alphabet.generic_alphabet):
> self.data = data 
> self.alphabet = alphabet
> 
> def tostring(self):   
> return self.data  
> 
> def tomutable(self):
> return MutableSeq(self.data, self.alphabet)
> 
> def count(self, item):
> return len([x for x in self.data if x == item])
> 
> I know what it should do, but have no idea how to feed it the data.
> 
> Methinks I need to invest in actual computing books as learning from
> biologists is hazy!
> 
> Kind regards,
> Seafoid.
> 

Supposing you create an instance of your Seq class

seq = Seq("aggadgaga")

When you call (let's say) the tostring() method of the *instance* the
interpreter automatically provides that as the first (self) argument to
the method call.

So in fact

   seq.tostring()

is exactly the same as

   Seq.tostring(seq)

but considerably shorter and easier to understand. Try asking the
interpreter what Seq.tostring and seq.tostring are, and you will find
one is an
unbound method", the other is a "bound method" (which means "bound to a
given instance" - in other words, it "knows" which instance it's a
method *of*.

Does this clarify it or make it more obscure?

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

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


Re: iterators and views of lists

2009-12-18 Thread Brendan Miller
On Fri, Dec 18, 2009 at 10:39 AM, Carl Banks  wrote:
> On Dec 17, 10:00 pm, Brendan Miller  wrote:
>> On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano
>>
>>  wrote:
>> > On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote:
>>
>> >> I was thinking it would be cool to make python more usable in
>> >> programming competitions by giving it its own port of the STL's
>> >> algorithm library, which needs something along the lines of C++'s more
>> >> powerful iterators.
>>
>> > For the benefit of those of us who aren't C++ programmers, what do its
>> > iterators do that Python's don't?
>>
>> Python iterators basically only have one operation:
>>
>> next(), which returns the next element or throws StopIteration.
>>
>> In C++ terminology this is a Input iterator. It is good for writing
>> "for each" loops or map reduce operations.
>
> Hmm.  I guess the main thing that's bothering me about this whole
> thread is that the true power of Python iterators is being overlooked
> here, and I don't think you're being fair to call Python iterators
> "weak" (as you did in another thread) or say that they are only good
> for for-else type loops.
>
> The fact is, Python iterators have a whole range of powers that C++
> iterators do not.  C++ iterators, at least the ones that come in STL,
> are limited to iterating over pre-existing data structures.  Python
> iterators don't have this limation--the data being "iterated" over can
> be virtual data like an infinite list, or data generated on the fly.
> This can be very powerful.
>
> Here's a cool slideshow on what can be done with iterators in Python
> (generators specifically):
>
> http://www.dabeaz.com/generators/
>
> It is true that Python iterators can't be used to mutate the
> underlying structure--if there is actual underlying data structure--
> but it doesn't mean they are weak or limited.  Python and C++
> iterators are similar in their most basic usage, but grow more
> powerful in different directions.
>

When I said they are "weak" I meant it in sense that the algorithms
writeable against an InputerIterator interface (which is what python's
iterator protocol provides) is a proper subset of the algorithms that
can be written against a RandomAccessIterator interface. The class of
algorithms expressible against a python iterator is indeed limited to
those that can be expressed with a for each loop or map/reduce
operation.

Yes, python iterators can indeed iterate over infinite lists. All that
you need to do is have the next() operation never throw. The same
thing can be done in c++, or any other language that has iterators.

Generators provide a convenient way to write input iterators; however,
the same thing can be done in any language. It just requires more
boilerplate code to keep track of the iteration state.

Of course, that's not to say generators aren't important. They make it
that much easier to write your own iterators, so in a practical sense,
people are more likely to write their own iterators in python than in
C++.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating Classes

2009-12-18 Thread seafoid

Steve, that has indeed clarified matters!

Thanks!

-- 
View this message in context: 
http://old.nabble.com/Creating-Classes-tp26848375p26849864.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Line indexing in Python

2009-12-18 Thread Rory Campbell-Lange
On 18/12/09, seafoid (fitzp...@tcd.ie) wrote:
> http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html

Your specification is confusing. However I suggest you break it down
the code so that the steps in your programme are logical. Good luck.

# example psuedocode
headers = {}
header_clauses = {}
current_header = None

def header_parser (input):
split input into parts
make unique header desciptor
check not in headers else abort with error (?)
add descriptor to headers hash
# eg descriptor 1 = [attrib1, attrib2, attrib3]
return descriptor

def clause_parser (input, current_header):
if current_header is None: abort
split clause into parts
store in array in header_clauses [current_header]
# this will make a data structure like this:
# header_clauses = {
#   descriptor1 = {[ clause parts ], [ clause parts ], ... }
#   descriptor2 = {[ clause parts ], [ clause parts ], ... }

def comment_parser (input)
pass

# now run over the file
for l in lines:
if l[0] == 'c':
comment_parser(l)
elif l[0] == 'p':
current_header = header_parser(l)
else:
clause_parser(l, current_header)

# now that we have stored everything, check the data
for h in headers:
attrib1, attrib2, attrib3  = headers[h]
for c in header_clauses:
iterate over the arrays of clause parts either adding them
up or comparing them to the header attributes

-- 
Rory Campbell-Lange
Director
r...@campbell-lange.net

Campbell-Lange Workshop
www.campbell-lange.net
0207 6311 555
3 Tottenham Street London W1T 2AF
Registered in England No. 04551928
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line indexing in Python

2009-12-18 Thread seafoid

Hey folks,

Is it possible to assign a list within a nested list to a variable?

Example:

l = [['1', '2', '3'], ['4', '5', '6']]

for i in l:
if i[0][1] == '1':
m = i

Indeed, I generally do not understand how to assign variables within a loop!

Is there an easy way to 'flatten' a nested list and assign the lists to
variables?

Thanks,
Seafoid.
-- 
View this message in context: 
http://old.nabble.com/Line-indexing-in-Python-tp26845253p26849921.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Line indexing in Python

2009-12-18 Thread seafoid

Rory,

You are a gentleman!

Thank you very much for your suggestion!

Kind Regards,
Seafoid.


Rory Campbell-Lange wrote:
> 
> On 18/12/09, seafoid (fitzp...@tcd.ie) wrote:
>> http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html
> 
> Your specification is confusing. However I suggest you break it down
> the code so that the steps in your programme are logical. Good luck.
> 
> # example psuedocode
> headers = {}
> header_clauses = {}
> current_header = None
> 
> def header_parser (input):
> split input into parts
> make unique header desciptor
> check not in headers else abort with error (?)
> add descriptor to headers hash
> # eg descriptor 1 = [attrib1, attrib2, attrib3]
> return descriptor
> 
> def clause_parser (input, current_header):
> if current_header is None: abort
> split clause into parts
> store in array in header_clauses [current_header]
> # this will make a data structure like this:
> # header_clauses = {
> #   descriptor1 = {[ clause parts ], [ clause parts ], ... }
> #   descriptor2 = {[ clause parts ], [ clause parts ], ... }
> 
> def comment_parser (input)
> pass
> 
> # now run over the file
> for l in lines:
> if l[0] == 'c':
> comment_parser(l)
> elif l[0] == 'p':
> current_header = header_parser(l)
> else:
> clause_parser(l, current_header)
> 
> # now that we have stored everything, check the data
> for h in headers:
> attrib1, attrib2, attrib3  = headers[h]
> for c in header_clauses:
> iterate over the arrays of clause parts either adding them
> up or comparing them to the header attributes
> 
> -- 
> Rory Campbell-Lange
> Director
> r...@campbell-lange.net
> 
> Campbell-Lange Workshop
> www.campbell-lange.net
> 0207 6311 555
> 3 Tottenham Street London W1T 2AF
> Registered in England No. 04551928
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Line-indexing-in-Python-tp26845253p26849944.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-18 Thread casevh
On Dec 18, 10:28 am, Joachim Dahl  wrote:
> My mistake seems to be that I declared
>
> char a, b;
>
> instead of
>
> int a, b;
>
> Thank you for sorting this out.
>
> Joachim

I think you need to initialize them, too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterators and views of lists

2009-12-18 Thread Terry Reedy

On 12/18/2009 1:00 AM, Brendan Miller wrote:


For the benefit of those of us who aren't C++ programmers, what do its
iterators do that Python's don't?


It depends on what one means by 'iterator'. Python iterators do not fit 
in the STL hierarchy. On the other hand, Python indexes are a form of 
random access iterator, the top of the hierarchy.



Python iterators basically only have one operation:



next(), which returns the next element or throws StopIteration.

In C++ terminology this is a Input iterator. It is good for writing
"for each" loops or map reduce operations.

An input iterator can't mutate the data it points to.


For that, Python uses indexes. Random access 'iterators' are a 
generalization of sequence indexes.



C++ also has progressively stronger iterators:
http://www.sgi.com/tech/stl/Iterators.html

InputIterator<- read only, one direction, single pass
ForwardIterator<- read/write, one direction, multi pass
BidirectionalIterator<- read/write, can move in either direction
RandomAccessIterator<- read/write, can move in either direction by an
arbitrary amount in constant time (as powerful as a pointer)


An index can be incremented or decremented an arbitrary amount. Note 
that Python indexes are object pointers, not memory byte pointers, so 
that index + 1 points to the next object, not the next byte of memory in 
possibly the same object. They are, however, much safer than pointers in 
that x[i] can only retrieve objects of x and never, surprise, surprise, 
of some other collection.



Each only adds extra operations over the one before. So a
RandomAccessIterator can be used anywhere a InputIterator can, but not
vice versa.

Also, this is a duck typing relationship, not a formal class
inheritance. Anything that quacks like a RandomAccessIterator is a
RandomAccessIterator, but there is no actual RandomAccessIterator
class.

So, for instance stl sort function takes pair of random access
iterator delimiting a range, and can sort any datastructure that can
provide that powerful of an iterator (arrays, vectors, deques).


Python, traditionally, only came with one mutable builtin sequence type, 
so the sort function was made a method of that type. There is also the 
importable array module. Apparently, there has been little demand for a 
generic array.sort method as there is none. One could easily write a 
function that took an array or other seqeunce and two indexes as args.


The generic reversed() builtin function by default uses sequence indexes 
in the obvious manner to return a reversed version of *any* sequence, 
mutable or not.



http://www.sgi.com/tech/stl/sort.html

MyCollection stuff;
// put some stuff in stuff

sort(stuff.begin(), stuff.end());

Where begin() and end() by convention return iterators pointing to the
beginning and end of the sequence.


start,stop = 0, len(seq)

Terry Jan Reedy


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


Re: Setting Parameters inside of code

2009-12-18 Thread Terry Reedy

On 12/18/2009 10:46 AM, Jim Valenza wrote:

Hello All - I have a very novice question for any of you out there.  I
need to assign several parameters to a code in python.


In Python, a 'parameter' is a function local name defined in the header 
of the function and bound to an argument when the function is called.


 I have an example

of a code that was in DOS that I would need to set as parameters in my
Python script.
SetLocal EnableDelayedExpansion

SET OUTPUT=..\log


OUTPUT = '../log/


SET LOG=..\log
SET COMPLETED=..\Loaded
SET FAILED=..\Errors
SET REPORT=..\log\batch_projectdb.txt
SET SOURCE=..\InBox
SET BACKUP=..\Backup
SET SERVER=housdep01
SET INSTANCE=port:5151
SET DATASET=sde
SET /a LOADED=0
SET /a POSTED=0
  :: If the directories don't exist, later commands run into problems.

MD %OUTPUT%


MD = make directory. Look for this in the os or os.path modules.
Do read the tutorial.

Terry Jan Reedy



MD %LOG%
MD %COMPLETED%
MD %FAILED%
MD %BACKUP%
I've been researching Parameters with the Python manuals and have not
found the help to be usefull as there is not much documentation for some
reason. I am new to the Python world so maybe I'm missing an important
piece of vocab.
Thanks A lot
Jim




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


Re: Setting Parameters inside of code

2009-12-18 Thread David Robinow
On Fri, Dec 18, 2009 at 10:46 AM, Jim Valenza  wrote:
> Hello All - I have a very novice question for any of you out there.  I need
> to assign several parameters to a code in python. I have an example of a
> code that was in DOS that I would need to set as parameters in my Python
> script.
>
> SetLocal EnableDelayedExpansion
> SET OUTPUT=..\log
> SET LOG=..\log
> SET COMPLETED=..\Loaded

You have an unusual use of the word "parameter". What you are doing is
setting environment variables. You can read these values in Python

import os
outvar = os.getenv("OUTPUT")
logvar = os.getenv("LOG")
completevar = os.getenv("COMPLETED")

# etc
print outvar
print logvar
print completevar

--
You may also want to pass arguments (I think 'argument' is what you
called 'parameter') to your script:
   myScript.py firstArg secondArg thirdArg

hunt for sys.argv in the documentation.


For more sophisticated argument passing you may want to look at the
'optparse' module
-- 
http://mail.python.org/mailman/listinfo/python-list


Sort the values of a dict

2009-12-18 Thread mattia
Hi all, I have a dictionary that uses dates and a tuples ad key, value 
pairs. I need to sort the values of the dict and insert everything in a 
tuple. The additional problem is that I need to sort the values looking 
at the i-th element of the list. I'm not that good at python (v3.1), but 
this is my solution:

>>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)}
>>> t = [x for x in d.values()]
>>> def third(mls):
... return mls[2]
...
>>> s = sorted(t, key=third)
>>> pres = []
>>> for x in s:
... for k in d.keys():
... if d[k] == x:
... pres.append(k)
... break
...
>>> res = []
>>> for x in pres:
... res.append((x, d[x]))
...
>>> res
[(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))]
>>>

Can you provide me a much pythonic solution (with comments if possible, 
so I can actually learn something)?

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


Re: Sort the values of a dict

2009-12-18 Thread Chris Kaynor
I'd write it as:
s = sorted(d.iteritems(), key=lambda i: i[1][2])

If using python 3, it should be d.items() instead of d.iteritems().

d.iteritems() is a generator yielding tuples of (key, value) from
the dictionary 'd'.
lambda i: i[1][2] is the same as:
def sort_(i):
return i[1][2]
but in-line.

Chris


On Fri, Dec 18, 2009 at 2:34 PM, mattia  wrote:

> Hi all, I have a dictionary that uses dates and a tuples ad key, value
> pairs. I need to sort the values of the dict and insert everything in a
> tuple. The additional problem is that I need to sort the values looking
> at the i-th element of the list. I'm not that good at python (v3.1), but
> this is my solution:
>
> >>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)}
> >>> t = [x for x in d.values()]
> >>> def third(mls):
> ... return mls[2]
> ...
> >>> s = sorted(t, key=third)
> >>> pres = []
> >>> for x in s:
> ... for k in d.keys():
> ... if d[k] == x:
> ... pres.append(k)
> ... break
> ...
> >>> res = []
> >>> for x in pres:
> ... res.append((x, d[x]))
> ...
> >>> res
> [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))]
> >>>
>
> Can you provide me a much pythonic solution (with comments if possible,
> so I can actually learn something)?
>
> Thanks, Mattia
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort the values of a dict

2009-12-18 Thread mattia
Actually, in order to use duplicate values I need something like:

>>> import copy
>>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8), 3:('u', 9, 8) }
>>> dc = copy.deepcopy(d)
>>> t = [x for x in d.values()]
>>> def third(mls):
... return mls[2]
...
>>> s = sorted(t, key=third)
>>> pres = []
>>> for x in s:
... for k in d.keys():
... if d[k] == x:
... pres.append(k)
... del d[k] # speedup and use duplicate values
... break
...
>>> res = []
>>> for x in pres:
... res.append((x, dc[x]))
...
>>> res
[(2, ('u', 9, 8)), (3, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 
12))]
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterators and views of lists

2009-12-18 Thread Bearophile
Brendan Miller:
> I agree though, it doesn't matter to everyone and anyone. The reason I
> was interested was because i was trying to solve some specific
> problems in an elegant way. I was thinking it would be cool to make
> python more usable in programming competitions by giving it its own
> port of the STL's algorithm library, which needs something along the
> lines of C++'s more powerful iterators.

It seems you have missed my post, so here it is, more explicitly:

http://www.boostcon.com/site-media/var/sphene/sphwiki/attachment/2009/05/08/iterators-must-go.pdf

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


Re: Sort the values of a dict

2009-12-18 Thread David Robinow
On Fri, Dec 18, 2009 at 5:34 PM, mattia  wrote:
> Hi all, I have a dictionary that uses dates and a tuples ad key, value
> pairs. I need to sort the values of the dict and insert everything in a
> tuple. The additional problem is that I need to sort the values looking
> at the i-th element of the list. I'm not that good at python (v3.1), but
> this is my solution:
>
 d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)}
 t = [x for x in d.values()]
 def third(mls):
> ...     return mls[2]
> ...
 s = sorted(t, key=third)
 pres = []
 for x in s:
> ...     for k in d.keys():
> ...         if d[k] == x:
> ...             pres.append(k)
> ...             break
> ...
 res = []
 for x in pres:
> ...     res.append((x, d[x]))
> ...
 res
> [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))]

>
> Can you provide me a much pythonic solution (with comments if possible,
> so I can actually learn something)?
>
> Thanks, Mattia
> --
> http://mail.python.org/mailman/listinfo/python-list
>
I won't engage in any arguments about pythonicity but it seems simpler
if you convert to a list of tuples right away.

d = {1:('a', 1, 12), 5:('r',21,10), 2:('u',9,8)}
l = [(x, d[x]) for x in d.keys()]
def third(q):
return q[1][2]

s = sorted(l, key=third)
print s
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort the values of a dict

2009-12-18 Thread mattia
Il Fri, 18 Dec 2009 18:00:42 -0500, David Robinow ha scritto:

> On Fri, Dec 18, 2009 at 5:34 PM, mattia  wrote:
>> Hi all, I have a dictionary that uses dates and a tuples ad key, value
>> pairs. I need to sort the values of the dict and insert everything in a
>> tuple. The additional problem is that I need to sort the values looking
>> at the i-th element of the list. I'm not that good at python (v3.1),
>> but this is my solution:
>>
> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} t = [x for x in
> d.values()]
> def third(mls):
>> ...     return mls[2]
>> ...
> s = sorted(t, key=third)
> pres = []
> for x in s:
>> ...     for k in d.keys():
>> ...         if d[k] == x:
>> ...             pres.append(k)
>> ...             break
>> ...
> res = []
> for x in pres:
>> ...     res.append((x, d[x]))
>> ...
> res
>> [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))]
>
>
>> Can you provide me a much pythonic solution (with comments if possible,
>> so I can actually learn something)?
>>
>> Thanks, Mattia
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> I won't engage in any arguments about pythonicity but it seems simpler
> if you convert to a list of tuples right away.
> 
> d = {1:('a', 1, 12), 5:('r',21,10), 2:('u',9,8)} l = [(x, d[x]) for x in
> d.keys()]
> def third(q):
> return q[1][2]
> 
> s = sorted(l, key=third)
> print s

Thanks, I'm not yet aware of all the wonderful conversions python can do, 
amazing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments

2009-12-18 Thread Mensanator
> The second deviation is that since most names are constants,

Really? Does that mean you don't use literals, to save the time
required to convert them to integers? Isn't that done at compile
time?

So, instead of doing the Collatz Conjecture as

while a>1:
  f = gmpy.scan1(a,0)
  if f>0:
a = a >> f
  else:
a = a*3 + 1

You would do this?

zed = 0
one = 1
two = 2
twe = 3
while a>one:
  f = gmpy.scan1(a,zed)
  if f>zed:
a = a >> f
  else:
a = a*twe + one

Does this really save any time?

Now, it's a different story if you're using the gmpy module.
You DON'T want to use literals in loops involving gmpy, because
they would have to be coerced to .mpz's on every pass through the
loop.

In that case, you DO want to use constants as opposed to literals:

ZED = gmpy.mpz(0)
ONE = gmpy.mpz(1)
TWO = gmpy.mpz(2)
TWE = gmpy.mpz(3)
while a>ONE:
  f = gmpy.scan1(a,0) # int used here, so it can be a literal
  if f>ZED:
a = a >> f
  else:
a = a*TWE + ONE

And yes, the time savings can be tremendous, especially when 'a'
has over 50,000 decimal digits.

. I do not follow PEP
> 8's recommendation to use uppercase names of constants. In fact almost no 
> Python
> code does,

Mine does when I use gmpy. Otherwise, the notion that "most names
are constants" is generally false.
-- 
http://mail.python.org/mailman/listinfo/python-list


Acceesing python httplib2 over a network share in windows 7

2009-12-18 Thread aj
I am trying to run python from a network share on windows 7.
The network share is T:

>t:\python-2.6.1\python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> import httplib2
httplib2\__init__.py:29: DeprecationWarning: the md5 module is
deprecated; use hashlib instead
import md5
Traceback (most recent call last):
File "", line 1, in 
File "T:\python-2.6.1\lib\python2.6\site-packages
\httplib2\__init__.py", line 36, in 
import httplib
File "T:\python-2.6.1\lib\httplib.py", line 77, in 
import mimetools
File "T:\python-2.6.1\lib\mimetools.py", line 6, in 
import tempfile
File "T:\python-2.6.1\lib\tempfile.py", line 34, in 
from random import Random as _Random
File "T:\python-2.6.1\lib\random.py", line 871, in 
_inst = Random()
File "T:\python-2.6.1\lib\random.py", line 96, in __init__
self.seed(x)
File "T:\python-2.6.1\lib\random.py", line 110, in seed
a = long(_hexlify(_urandom(16)), 16)
WindowsError: [Error 127] The specified procedure could not be
found


When I copy python-2.6.1 to my local drive it works fine. It also
works fine on my windows XP machine using the same network share.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort the values of a dict

2009-12-18 Thread Rory Campbell-Lange
On 18/12/09, mattia (ger...@gmail.com) wrote:
> Hi all, I have a dictionary that uses dates and a tuples ad key, value 
> pairs. I need to sort the values of the dict and insert everything in a 
> tuple. The additional problem is that I need to sort the values looking 
> at the i-th element of the list. I'm not that good at python (v3.1), but 
> this is my solution:
> 
> >>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)}
> >>> t = [x for x in d.values()]
> >>> def third(mls):
> ... return mls[2]
> ...
> >>> s = sorted(t, key=third)
> >>> pres = []
> >>> for x in s:
> ... for k in d.keys():
> ... if d[k] == x:
> ... pres.append(k)
> ... break
> ...
> >>> res = []
> >>> for x in pres:
> ... res.append((x, d[x]))
> ...
> >>> res
> [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))]

How about 

>>> mylist = [z for z in zip(list(d), list(d.values()))]

and then sort on your sort criteria, either i[0], i[0][1], i[0][2] or
i[0][3].

Rory



-- 
Rory Campbell-Lange
Director
r...@campbell-lange.net

Campbell-Lange Workshop
www.campbell-lange.net
0207 6311 555
3 Tottenham Street London W1T 2AF
Registered in England No. 04551928
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Raw string substitution problem

2009-12-18 Thread Gregory Ewing

MRAB wrote:


In simple cases you might be replacing with the same string every time,
but other cases you might want the replacement to contain substrings
captured by the regex.


But you can give it a function that has access to the
match object and can produce whatever replacement string
it wants.

You already have a complete programming language at
your disposal. There's no need to invent yet another
mini-language for the replacement string.

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


  1   2   >