Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-04 Thread Jussi Salmela
Robin Becker kirjoitti:
 
 Björn, in one of our projects we are sorting in javascript in several 
 languages English, German, Scandinavian languages, Japanese; from 
 somewhere (I cannot actually remember) we got this sort spelling 
 function for scandic languages
 
 a
 .replace(/\u00C4/g,'A~') //A umlaut
 .replace(/\u00e4/g,'a~') //a umlaut
 .replace(/\u00D6/g,'O~') //O umlaut
 .replace(/\u00f6/g,'o~') //o umlaut
 .replace(/\u00DC/g,'U~') //U umlaut
 .replace(/\u00fc/g,'u~') //u umlaut
 .replace(/\u00C5/g,'A~~') //A ring
 .replace(/\u00e5/g,'a~~'); //a ring
 
 does this actually make sense?

I think this order is not correct for Finnish, which is one of the 
Scandinavian languages. The Finnish alphabet in alphabetical order is:

a-z, å, ä, ö

If I understand correctly your replacements cause the order of the last 
3 characters to be

ä, å, ö

which is wrong.

HTH,
Jussi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to set docstrings for extensions supporting PyNumberMethods?

2007-03-04 Thread Ziga Seilnacht
Nick Alexander wrote:
 Hello,

 I am writing a python extension (compiled C code) that defines an
 extension type with PyNumberMethods.  Everything works swimmingly,
 except I can't deduce a clean way to set the docstring for tp_*
 methods.  That is, I always have

 type.__long__.__doc__ == 'x.__long__() == long(x)'

 which a quick glance at the Python 2.5 source shows is the default.

 I have found that I can use PyObject_GetAttr and PyWrapperDescrObject
 and set the descriptor objects d_base-doc to a char pointer... but I
 can't tell if this is safe.  Or the right way to do it.

 If I'm on the wrong list, please let me know!
 Thanks,
 Nick Alexander

I think that the right way is to add the methods to the tp_methods
slot and use METH_COEXIST in the PyMethodDef flags field. Example:

/* start of silly module */
#include Python.h

typedef struct {
PyObject_HEAD
double value;
} SillyNumber_Object;

/* Forward declarations */
static PyTypeObject SillyNumber_Type;

#define SillyNumber_Check(op) PyObject_TypeCheck(op,
SillyNumber_Type)

static PyObject *
new_SillyNumber(PyTypeObject *type, double value)
{
PyObject *self;

self = type-tp_alloc(type, 0);
if (self == NULL)
return NULL;

((SillyNumber_Object *)self)-value = value;
return self;
}

static PyObject *
SillyNumber_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
double value = 0.0;
static char *kwlist[] = {value, 0};

if (!PyArg_ParseTupleAndKeywords(args, kwds, |d:SillyNumber,
 kwlist, value))
return NULL;

return new_SillyNumber(type, value);
}

static PyObject *
SillyNumber_add(PyObject *left, PyObject *right)
{
double sum;

if (!SillyNumber_Check(left) || !SillyNumber_Check(right)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}

sum = (((SillyNumber_Object *)left)-value +
   ((SillyNumber_Object *)right)-value);

return new_SillyNumber(SillyNumber_Type, sum);
}

static PyObject *
SillyNumber_radd(PyObject *right, PyObject *left)
{
return SillyNumber_add(left, right);
}

static PyNumberMethods SillyNumber_as_number = {
SillyNumber_add,/* nb_add */
0,  /* nb_subtract */
0,  /* nb_multiply */
0,  /* nb_divide */
0,  /* nb_remainder */
0,  /* nb_divmod */
0,  /* nb_power */
0,  /* nb_negative */
0,  /* nb_positive */
0,  /* nb_absolute */
0,  /* nb_nonzero */
};

static PyMethodDef SillyNumber_methods[] = {
{__add__, SillyNumber_add, METH_O | METH_COEXIST,
Add two SillyNumbers.},
{__radd__, SillyNumber_radd, METH_O | METH_COEXIST,
Same as __add__.},
{NULL, NULL, 0, NULL}
};

static PyTypeObject SillyNumber_Type = {
PyObject_HEAD_INIT(NULL)
0,  /* ob_size */
silly.SillyNumber,/* tp_name */
sizeof(SillyNumber_Object), /* tp_basicsize */
0,  /* tp_itemsize */
0,  /* tp_dealloc */
0,  /* tp_print */
0,  /* tp_getattr */
0,  /* tp_setattr */
0,  /* tp_compare */
0,  /* tp_repr */
SillyNumber_as_number, /* tp_as_number */
0,  /* tp_as_sequence */
0,  /* tp_as_mapping */
0,  /* tp_hash */
0,  /* tp_call */
0,  /* tp_str */
0,  /* tp_getattro */
0,  /* tp_setattro */
0,  /* tp_as_buffer */
Py_TPFLAGS_DEFAULT |/* tp_flags */
Py_TPFLAGS_CHECKTYPES | /* PyNumberMethods do their own
coercion */
Py_TPFLAGS_BASETYPE,/* SillyNumber_Type allows subclassing
*/
Silly float numbers,  /* tp_doc */
0,  /* tp_traverse */
0,  /* tp_clear */
0,  /* tp_richcompare */
0,  /* tp_weaklistoffset */
0,  /* tp_iter */
0,  /* tp_iternext */
SillyNumber_methods,/* tp_methods */
0,  /* tp_members */
0,  /* tp_getset */
0,  /* tp_base */
0,  /* tp_dict */
0,  /* tp_descr_get */
0,  /* tp_descr_set */
0,  /* tp_dictoffset */
0,  /* tp_init */
0,  /* tp_alloc */
SillyNumber_new,/* tp_new */
0,  /* tp_free */
};

static 

Re: thread safe SMTP module

2007-03-04 Thread Gordon Messmer
Aahz wrote:
 
 That doesn't make any sense.  Blocking I/O generally releases the GIL,
 which is the whole reason Python doesn't totally suck for threading.

Nevertheless, among the caveats listed at 
http://docs.python.org/lib/module-thread.html is:

Not all built-in functions that may block waiting for I/O allow other 
threads to run. (The most popular ones (time.sleep(), file.read(), 
select.select()) work as expected.)

 There may be other thread problems, but I doubt that you have correctly
 analyzed their source.

I subclassed smtplib.SMTP and replaced only the lines of code that had 
to do with blocking IO (connect, send and receive operations). 
Beforehand, python would occasionally lock up. Having made those 
changes, python stopped locking up.  I think the problem was pretty well 
apparent.  I can't pin it down to which one of those three operations 
was at fault, and it may be that only one was.  However, when I use 
non-blocking IO, the application works.  When I used smtplib.SMTP, it 
didn't.

I'm open to other explanations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Yet another string interpolation function...

2007-03-04 Thread MonkeeSage
There are several string interpolation functions, as well as
string.Template. But here's yet another. This one emulates ruby's
inline interpolation syntax (using #{}), which interpolates strings as
well as expressions. NB. It uses eval(), so only use it in trusted
contexts!

import sys, re
def interp(string):
  locals  = sys._getframe(1).f_locals
  globals = sys._getframe(1).f_globals
  for item in re.findall(r'#\{([^{]*)\}', string):
string = string.replace('#{%s}' % item,
str(eval(item, globals, locals)))
  return string

test1 = 'example'
def tryit():
  test2 = 1
  # variable interpolation
  print interp('This is an #{test1} (and another #{test1}) and an int
(#{test2})')
  # expression interpolation
  print interp('This is an #{test1 +  (and another  + test1 + )}
and an int (#{test2})')
tryit()

Recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502257

Ok, now tell me all the things wrong with it! ;)

Regards,
Jordan

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


Re: pop method question

2007-03-04 Thread Hendrik van Rooyen
 Alex Martelli [EMAIL PROTECTED] wrote:

 Raymond Hettinger [EMAIL PROTECTED] wrote:
...
  The notion that pop is only defined for stack operations is somewhat
  pedantic.
 
 Worse: it's totally wrong.  It's also defined for eyes, as a musical
 genre, as a kind of soda, as an avant-garde artistic movement of the
 '50s, for baloons, as a parent of the male persuasion, for email
 reading, and moreover it's often used to refer to Persistent Organic
 Pollutants or Points Of Presence -- not forgetting weasels, either.
 
One should never forget the pawning of weasels.

Then there is the contrary meaning - instead of take out it can 
mean put in - Just pop it in the oven, there's a dear...

- Hendrik

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


Re: portable Python ifconfig

2007-03-04 Thread Bart Van Loon
It was Sun, 4 Mar 2007 02:38:58 +0500, when Bart Van Loon wrote:
 Hi all,

 I'm looking for a portable (FreeBSD and Linux) way of getting typical
 ifconfig information into Python.

After lots of trial and error (I'm proficient in C at all), I puzzled
togehter the following. It works (at least on FreeBSD and Linux), but is
still fairly rough, as it returns an empty string when given a non
existing or down interface.

I'll clean it up in due time. :-)

#include Python.h

#include sys/types.h
#include sys/socket.h
#include netdb.h
#include netinet/in.h
#include unistd.h
#include arpa/inet.h
#include stdio.h
#include ifaddrs.h
#include string.h

// parameters: string (interface name)
// output: string (ip address of interface in decimal notation)
PyObject * ipaddr(PyObject *self, PyObject *args) {

char ip[ 200 ];
char *itf;

if (! PyArg_ParseTuple(args, s, itf)) {
PyErr_SetString(PyExc_Exception, no interface given!);
return NULL;
}

  struct ifaddrs *ifa = NULL, *ifp = NULL;

  if (getifaddrs (ifp)  0)
{
  perror (getifaddrs);
  return NULL;
}

  for (ifa = ifp; ifa; ifa = ifa-ifa_next)
{
  socklen_t salen;

  if (ifa-ifa_addr-sa_family == AF_INET)
salen = sizeof (struct sockaddr_in);
  else if (ifa-ifa_addr-sa_family == AF_INET6)
salen = sizeof (struct sockaddr_in6);
  else
continue;

  if (strncmp(ifa-ifa_name, itf, sizeof(itf))) {
 continue;
  }

  if (getnameinfo (ifa-ifa_addr, salen,
   ip, sizeof (ip), NULL, 0, NI_NUMERICHOST)  0)
{
  perror (getnameinfo);
  continue;
}
break;

}

  freeifaddrs (ifp);

  return Py_BuildValue(s, ip);
}

static PyMethodDef ifconfig_methods[] = {
{ipaddr, (PyCFunction)ipaddr, METH_VARARGS, ipaddr(string)\n},
{NULL, NULL, 0, NULL}
};

DL_EXPORT(void) initifconfig(void)
{
Py_InitModule3(ifconfig, ifconfig_methods, Provides a function to get an 
ip address of a certain interface.\n);   
}

Inspiration came from and credit goes to the author of
http://www.hungry.com/~alves/local-ip-in-C.html

-- 
regards,
BBBart

   Hobbes : How is the diorama coming along?  
   Calvin : I'm almost finished.
   Hobbes : I don't see the roadrunner. Weren't you going to put one in?  
   Calvin : See the cotton balls I glued down?  
   Hobbes : Yeah?  
   Calvin : The roadrunner just ran out of the scene leaving behind clouds 
of dust!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: portable Python ifconfig

2007-03-04 Thread Bart Van Loon
It was Sun, 4 Mar 2007 14:09:20 +0500, when Bart Van Loon wrote:
 It was Sun, 4 Mar 2007 02:38:58 +0500, when Bart Van Loon wrote:
 Hi all,

 I'm looking for a portable (FreeBSD and Linux) way of getting typical
 ifconfig information into Python.

 After lots of trial and error (I'm proficient in C at all), I puzzled

err... I'm NOT proficient in c at all :-)

-- 
groetjes,
BBBart

   Hobbes : How is the diorama coming along?  
   Calvin : I'm almost finished.
   Hobbes : I don't see the roadrunner. Weren't you going to put one in?  
   Calvin : See the cotton balls I glued down?  
   Hobbes : Yeah?  
   Calvin : The roadrunner just ran out of the scene leaving behind clouds 
of dust!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python FTP server down

2007-03-04 Thread Christian Joergensen
John Nagle [EMAIL PROTECTED] writes:

 ftp://ftp.python.org/pub/; is returning Connection Refused today.

True.

 I need FTP access to download onto a colocated server.

Is HTTP firewalled? If you have SSH-access, you could just do the HTTP 
download at your workstation and scp/sftp it to the remote server.

-- 
Christian Joergensen | Linux, programming or web consultancy
http://www.razor.dk  | Visit us at: http://www.gmta.info
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pop method question

2007-03-04 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Nicholas
Parsons wrote:

 Just from my computer science background when I see pop(), I think of a
 stack data structure.

Then question your presumptions.  There are also many people thinking
`list` must be something with nodes and pointers when they see the
interface and usage of Python lists.

 But then again, there are other examples of ambiguity in the python
 language such as allowing operators like '+' to be overloaded.  Why not
 just have a add() method like Java?

Why does this remove ambiguity?  I even would expect different behaviour
from both.  I expect the ``+`` operator to return either an immutable or
entirely new object, while `add()` can be something on containers that
mutates the object.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Where I could find older python releases ?

2007-03-04 Thread 13
Hello list,

I have been searching the internet for python version 0.9.0 sources
which had been posted to alt.sources list, but without any luck. Maybe
someone has it available somewhere ?

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


multiple content-types break cgi.py

2007-03-04 Thread Janto Dreijer
Hi!

The Nokia Java SDK allows one to define multiple content-types in a
single HTTP header field. I'm not sure if it's standard, but it's
happening from some Java-enabled phones.

This breaks the FieldStorage class in cgi.py by not causing
self.read_urlencoded() to be called at object init. Specifically when
one gets a type value like 'text/plain, application/x-www-form-
urlencoded'.

Hacking one of the lines from:
if ctype == 'application/x-www-form-urlencoded':
self.read_urlencoded()
to
if 'application/x-www-form-urlencoded' in [s.strip() for s in
ctype.split(,)]:
self.read_urlencoded()
makes it work as expected.

The only reference to this bug I can find dates back to 1999:
http://tinyurl.com/3ahc3r

Regards
Janto

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


Re: multiple content-types break cgi.py

2007-03-04 Thread Jon Ribbens
In article [EMAIL PROTECTED], Janto Dreijer wrote:
 The Nokia Java SDK allows one to define multiple content-types in a
 single HTTP header field. I'm not sure if it's standard, but it's
 happening from some Java-enabled phones.
 
 The only reference to this bug I can find dates back to 1999:
 http://tinyurl.com/3ahc3r

It's not a bug - sending multiple content-types is just totally broken.
What would such a header even be supposed to mean? It's like saying
this is an apple orange.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST)

2007-03-04 Thread Aviroce
On Feb 24, 11:22 am, [EMAIL PROTECTED] wrote:
 Canada anti-terror law is struck downFrom the Associated Press

 February 24, 2007

 OTTAWA - Canada's Supreme Court on Friday unanimously declared it
 unconstitutional to detain foreign terrorism suspects indefinitely
 while the courts review their deportation orders.

 Five Arab Muslim men have been held for years under the security
 certificate program, which the Justice Department has said is a key
 tool in the fight against global terrorism and essential to Canada's
 security.

 The court found that the system violated the Charter of Rights and
 Freedoms, Canada's bill of rights. However, it suspended its ruling
 for a year to give Parliament time to rewrite the part of the
 Immigration and Refugee Protection Act that covers the certificate
 process.

 The security certificates were challenged by three men from Morocco,
 Syria and Algeria - all alleged by the Canadian Security Intelligence
 Service to have ties to terrorist networks.

 The men have spent years in jail while fighting deportation orders.

 They risk being labeled terrorists and sent back to their native
 countries, where they say they could face torture.

 The court said the treatment of the suspects was a violation of their
 rights.

 The overarching principle of fundamental justice that applies here is
 this: Before the state can detain people for significant periods of
 time, it must accord them a fair judicial process, Chief Justice
 Beverley McLachlin wrote in a ruling for all nine justices.

 The secrecy required by the scheme denies the person named in a
 certificate the opportunity to know the case put against him or her,
 and hence to challenge the government's case, she said.

 The challenged law allows sensitive intelligence to be heard behind
 closed doors by a federal judge, with only sketchy summaries given to
 defense attorneys.

 The court said the men and their lawyers should have a right to
 respond to the evidence used against them by intelligence agents.

 Stockwell Day, the minister of public safety, noted that because the
 ruling does not take effect for a year, the certificates would remain
 in place. He said the government would address the court's ruling in
 a timely and decisive fashion.

 Two of the men are out on bail and remain under house arrest. Three
 others are being held in a federal facility in Ontario.

The court said the treatment of the suspects was a
violation of their
rights.


The overarching principle of fundamental justice that applies here
is
this: Before the state can detain people for significant periods of
time, it must accord them a fair judicial process, Chief Justice
Beverley McLachlin wrote in a ruling for all nine justices.


The secrecy required by the scheme denies the person named in a
certificate the opportunity to know the case put against him or her,
and hence to challenge the government's case, she said.


THAT IS CALLED PROTECTING CIVIL RIGHTS.  IN THE UNITED STATES OF
AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE
NOT PROTECTED BY THE GENEVA CONVENTION.  DR. EVIL, V.P. CHENEY, AND
MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY
FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION.  THIS MEANS
ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO.
WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER.





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


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread Troy Melhase
[snip]

 So what's going on?  We've run into a conflict between an assumption of Python
 and of the Plesk control panel.  Plesk doesn't let the user create files
 in their own home directory.  This installer assumes it can.  Oops.
 (Plesk sets up a very locked down environment, which is a good thing on
 a web server.)

The installer used the options you gave it, or its defaults in their absence.

 Now it turns out that we have Python 2.4 in /usr/bin, and Python 2.5
 in /usr/local/bin.  That's where the installer put it.  So the CGI
 scripts are invoking the wrong version of Python.  The scripts had to
 be changed.

You could have fixed this with ./configure --prefix=/usr/local

 This kind of nonsense is why hosting companies don't want to support Python.
 Perl and PHP may be dumb, but they just work.  Java has a company behind it.
 Python just isn't ready.  Which is embarassing, ten years on.

Let's see...

You're trying to install a package without using the package
management tools provided by your system, you haven't read the docs
(or at least all of them), you show a general lack of understanding of
the different responsibilities in the free/open source software space
(development vs. packaging)... and after all that, then you come here
and complain?

Look, I'm sure lots of folks here would be glad to help you, but your
post comes across as whiny and confrontational.  I'm sure you've had a
frustrating experience, but please, don't blame python or the
python developers, because that blame would be misplaced.
-- 
http://mail.python.org/mailman/listinfo/python-list


SAMBA-PYTHON ???

2007-03-04 Thread WEBER Sébastien
Hello,

(I'm french and I speak english like a spanish cow : sorry.)

Does someone know how to use the samba-python tdb.so module ? I've been
looking for information about this on Google for 3 days and I've found not
a word. The only functions I can use are 'open()' and 'first_key()' : not
enough.

Thank's.

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


Re: multiple content-types break cgi.py

2007-03-04 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Jon Ribbens wrote:

 It's not a bug - sending multiple content-types is just totally broken.
 What would such a header even be supposed to mean? It's like saying
 this is an apple orange.

And the correct header for such a beast would be this is an iOrange of
course.  ;-)

SCNR,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST)

2007-03-04 Thread Aviroce
On Feb 24, 11:22 am, [EMAIL PROTECTED] wrote:
 Canada anti-terror law is struck downFrom the Associated Press

 February 24, 2007

 OTTAWA - Canada's Supreme Court on Friday unanimously declared it
 unconstitutional to detain foreign terrorism suspects indefinitely
 while the courts review their deportation orders.

 Five Arab Muslim men have been held for years under the security
 certificate program, which the Justice Department has said is a key
 tool in the fight against global terrorism and essential to Canada's
 security.

 The court found that the system violated the Charter of Rights and
 Freedoms, Canada's bill of rights. However, it suspended its ruling
 for a year to give Parliament time to rewrite the part of the
 Immigration and Refugee Protection Act that covers the certificate
 process.

 The security certificates were challenged by three men from Morocco,
 Syria and Algeria - all alleged by the Canadian Security Intelligence
 Service to have ties to terrorist networks.

 The men have spent years in jail while fighting deportation orders.

 They risk being labeled terrorists and sent back to their native
 countries, where they say they could face torture.

 The court said the treatment of the suspects was a violation of their
 rights.

 The overarching principle of fundamental justice that applies here is
 this: Before the state can detain people for significant periods of
 time, it must accord them a fair judicial process, Chief Justice
 Beverley McLachlin wrote in a ruling for all nine justices.

 The secrecy required by the scheme denies the person named in a
 certificate the opportunity to know the case put against him or her,
 and hence to challenge the government's case, she said.

 The challenged law allows sensitive intelligence to be heard behind
 closed doors by a federal judge, with only sketchy summaries given to
 defense attorneys.

 The court said the men and their lawyers should have a right to
 respond to the evidence used against them by intelligence agents.

 Stockwell Day, the minister of public safety, noted that because the
 ruling does not take effect for a year, the certificates would remain
 in place. He said the government would address the court's ruling in
 a timely and decisive fashion.

 Two of the men are out on bail and remain under house arrest. Three
 others are being held in a federal facility in Ontario.

The court said the treatment of the suspects was a
violation of their
rights.


The overarching principle of fundamental justice that applies here
is
this: Before the state can detain people for significant periods of
time, it must accord them a fair judicial process, Chief Justice
Beverley McLachlin wrote in a ruling for all nine justices.


The secrecy required by the scheme denies the person named in a
certificate the opportunity to know the case put against him or her,
and hence to challenge the government's case, she said.


THAT IS CALLED PROTECTING CIVIL RIGHTS.  IN THE UNITED STATES OF
AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE
NOT PROTECTED BY THE GENEVA CONVENTION.  DR. EVIL, V.P. CHENEY, AND
MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY
FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION.  THIS MEANS
ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO.
WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER.






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


RSS feed creator

2007-03-04 Thread Florian Lindner
Hello,
I'm looking for a python library that creates a RSS and/or Atom feed. E.g. I
give a list like that:
[
  [title1, short desc1, author1],
  [title2, short desc2, author2],
]

and the library creates a valid feed XML file. (return as a string)

Thanks,

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


Re: class attrdict

2007-03-04 Thread goodwolf
On Mar 3, 4:25 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
 Hallvard B Furuseth [EMAIL PROTECTED] wrote:

  Does this class need anything more?
  Is there any risk of a lookup loop?
  Seems to work...

  class attrdict(dict):
  Dict where d['foo'] also can be accessed as d.foo
  def __init__(self, *args, **kwargs):
  self.__dict__ = self
  dict.__init__(self, *args, **kwargs)
  def __repr__(self):
  return dict.__repr__(self).join((attrdict(, )))

 The problem is mostly that, given an instance a of attrdict, whether you
 can call (e.g.) a.update(foo) depends on whether you ever set
 a['update'], making the whole program extremely fragile -- a very high
 price to pay for some modest amount of syntax sugar.

 Alex

Then you will prefer something like this:

class Namespace(object):
def __init__(self, __ns={}, **kwargs):
if kwargs: __ns.update(kwargs)
self.__dict__ = __ns

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


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread Patrick Useldinger
http://www.serpentine.com/blog/2006/12/22/how-to-build-safe-clean-python-25-rpms-for-fedora-core-6/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread Jorge Godoy
Troy Melhase [EMAIL PROTECTED] writes:

 You're trying to install a package without using the package
 management tools provided by your system, you haven't read the docs
 (or at least all of them), you show a general lack of understanding of
 the different responsibilities in the free/open source software space
 (development vs. packaging)... and after all that, then you come here
 and complain?

Just to throw more on the fire: there are distributions that come with Python
2.5 packaged and working. ;-)

 Look, I'm sure lots of folks here would be glad to help you, but your
 post comes across as whiny and confrontational.  I'm sure you've had a
 frustrating experience, but please, don't blame python or the
 python developers, because that blame would be misplaced.

Anyway, if following the install after an error is true then some developer
should take a look at it.


-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html sql client

2007-03-04 Thread gert
http://sourceforge.net/projects/dfo/

Added some firefox2 ajax technologies to it and made it xhtml 1.1
valid :)




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


Re: SAMBA-PYTHON ???

2007-03-04 Thread Jorge Godoy
WEBER Sébastien [EMAIL PROTECTED] writes:

 (I'm french and I speak english like a spanish cow : sorry.)

(Shouldn't it be French cow?  Or you're more fluent in Spanish? ;-))

 Does someone know how to use the samba-python tdb.so module ? I've been
 looking for information about this on Google for 3 days and I've found not
 a word. The only functions I can use are 'open()' and 'first_key()' : not
 enough.

Did you get to run the examples supplied in the package?  I remember that I
had run these a while ago, but I don't remember if I had any problem (probably
not).  In the end I didn't use the package because the project changed
requirements and we adopted an alternative solution, but I got the examples to
run (or code very similar to them).

What are the errors that you're getting?  Send them to the group...

(BTW, I've used the samba-python package that comes with opensuse.) 

-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pop method question

2007-03-04 Thread Nicholas Parsons
Hi Jordan,

That is true what you say about pop() behavior with stack-like  
objects.  But the definition of pop() for a stack-like structure is  
stronger than that.  A stack is a LIFO data structure.  Therefore the  
pop() operation is defined to not only mutate the receiver and return  
the item popped but also ensure that the LAST item in the stack is  
removed.  This makes perfect sense for a list type in python since  
lists are mutable sequences that have a specified order.  But for  
dictionaries this does not hold since they are unordered sequences by  
definition.  So for dictionaries it would not make sense for a  
programmer to simulate a stack-like type.

While we're on the subject I'm also curious as to why the author of  
the built-in list class called the method append to add an element  
to the end of a list and not something like push.  But this is not  
really much of a problem if the programmer could create an alias for  
it.  Is it possible to do this in python?  I know you can do it in  
ruby and even override methods and attributes in an existing built-in  
class like String for instance.

--Nick




On Mar 3, 2007, at 10:40 PM, MonkeeSage wrote:

 Nick,

 In regards to stack-like objects, pop() implies mutation of the
 reciever and returning the item 'popped' off the stack. The same
 _semantic_ meaning can be used for pop() regarding dictionaries, even
 though the _implementation_ would be different: dict.pop(key) mutates
 the reciever and returns the value associated with the key.

 Regards,
 Jordan

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

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


Re: Python 3.0 unfit for serious work?

2007-03-04 Thread Jay Tee
Hey,

 Python 3.x.  I believe your fear is just a knee jerk reaction to the notion
 that there will be some stated incompatibilities between 2.x and 3.x without
 having done any investigation of the transition process.  Nobody is forcing
 you to do anything right now or completely abandon your code base.  Python
 2.x still has a long shelf life.  Hell, 3.0a1 isn't even out yet.  If you

Thanks to the pointer to PyCon, if there is anything relevant maybe
you can send me off a mail (or post here) with some links.  About the
above : it isn't fear, I'm just telling you what I suspect might
happen.  My own little piece of code in the giant picture will remain
in python, unless i am mandated to move it to something else : I
*like* python.

I threw in my few cents here just because I suspect the python
community does not intend to move itself into the realm of
interesting but not serious languages like Oberon did.  I could be
wrong, both in the sense that maybe that *is* the intention, or maybe
making a backwards-incompatible evolution of the language won't hurt
python or it's users.  We now return to your regularly scheduled
program.

  J back to the grind T

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


Re: pop method question

2007-03-04 Thread Nicholas Parsons

On Mar 4, 2007, at 4:38 AM, Marc 'BlackJack' Rintsch wrote:

 In [EMAIL PROTECTED], Nicholas
 Parsons wrote:

 Just from my computer science background when I see pop(), I think  
 of a
 stack data structure.

 Then question your presumptions.  There are also many people thinking
 `list` must be something with nodes and pointers when they see the
 interface and usage of Python lists.

Good point :).


 But then again, there are other examples of ambiguity in the python
 language such as allowing operators like '+' to be overloaded.   
 Why not
 just have a add() method like Java?

 Why does this remove ambiguity?  I even would expect different  
 behaviour
 from both.  I expect the ``+`` operator to return either an  
 immutable or
 entirely new object, while `add()` can be something on containers that
 mutates the object.


This is true.  As long as the language (be it Java, Python, X) itself  
remains consistent over time, then this should be fine.


 Ciao,
   Marc 'BlackJack' Rintsch
 -- 
 http://mail.python.org/mailman/listinfo/python-list

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


transfer data from one machine to another

2007-03-04 Thread bahoo
Hi,

I have ssh access to two linux machines (both WITHOUT root account),
and I'd like to copy data from one to another.
Since the directory structure is different, I want to specify in a
script (ideally in python, because that's what I want to learn) what
to copy over like this:

source: /home/john/folderA
destination: /home/smith/folderB

I'm a newbie on linux and ssh networking and python, so your
suggestions are welcome! A small working example would be appreciated!

bahoo

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


Re: transfer data from one machine to another

2007-03-04 Thread Bjoern Schliessmann
bahoo wrote:

 I have ssh access to two linux machines (both WITHOUT root
 account), and I'd like to copy data from one to another.
 Since the directory structure is different, I want to specify in a
 script (ideally in python, because that's what I want to learn)
 what to copy over like this:
 
 source: /home/john/folderA
 destination: /home/smith/folderB
 
 I'm a newbie on linux and ssh networking and python, so your
 suggestions are welcome! A small working example would be
 appreciated!

On example machine 10.0.0.1, logged in as john:

scp -r ~/folderA [EMAIL PROTECTED]:~/folderB

It's IMHO simpler and quicker than developing the same functionality
in Python. Or is there a simple module I overlooked?

Regards,


Björn

Fup2 comp.lang.python

P.S.: Please don't crosspost over hierarchies without setting
followup.

-- 
BOFH excuse #53:

Little hamster in running wheel had coronary; waiting for
replacement to be Fedexed from Wyoming

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


Re: class attrdict

2007-03-04 Thread goodwolf
On Mar 4, 1:03 pm, goodwolf [EMAIL PROTECTED] wrote:
 On Mar 3, 4:25 am, [EMAIL PROTECTED] (Alex Martelli) wrote:



  Hallvard B Furuseth [EMAIL PROTECTED] wrote:

   Does this class need anything more?
   Is there any risk of a lookup loop?
   Seems to work...

   class attrdict(dict):
   Dict where d['foo'] also can be accessed as d.foo
   def __init__(self, *args, **kwargs):
   self.__dict__ = self
   dict.__init__(self, *args, **kwargs)
   def __repr__(self):
   return dict.__repr__(self).join((attrdict(, )))

  The problem is mostly that, given an instance a of attrdict, whether you
  can call (e.g.) a.update(foo) depends on whether you ever set
  a['update'], making the whole program extremely fragile -- a very high
  price to pay for some modest amount of syntax sugar.

  Alex

 Then you will prefer something like this:

 class Namespace(object):
 def __init__(self, __ns={}, **kwargs):
 if kwargs: __ns.update(kwargs)
 self.__dict__ = __ns

oops, there is an error (empty dict is created once).
Here corrected one:

class Namespace(object):
def __init__(self, __ns=None, **kwargs):
if __ns is None:
self.__dict__ = kwargs
else:
assert len(kwargs) == 0
self.__dict__ = __ns

If you are familiar with JS then you can simulate JS Object:

class JSLikeObject(object):
def __init__(self, __ns={}, **kwargs):
if kwargs: __ns.update(kwargs)
self.__dict__ = __ns
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
setattr(self, name, value)
def __delitem__(self, name):
delattr(self, name)
def __iter__(self):
return iter(self.__dict__)
def __contains__(self, name):
return hasattr(self, name)

but I don't sagest to use it in real life.

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


Re: Converting a c array to python list

2007-03-04 Thread zefciu
Dennis Lee Bieber wrote:

   Written properly, all it returns is the address of that array data
 -- there is no massive copying of data..

I know :)  That's why I want to know how to write it properly.

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


Re: Where I could find older python releases ?

2007-03-04 Thread Adam
On Mar 4, 9:52 am, 13 [EMAIL PROTECTED] wrote:
 Hello list,

 I have been searching the internet for python version 0.9.0 sources
 which had been posted to alt.sources list, but without any luck. Maybe
 someone has it available somewhere ?

 Thanks,
 Martins

http://www.python.org/download/

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


Re: pop method question

2007-03-04 Thread Steven D'Aprano
On Sun, 04 Mar 2007 07:36:50 -0500, Nicholas Parsons wrote:

 Hi Jordan,
 
 That is true what you say about pop() behavior with stack-like  
 objects.  But the definition of pop() for a stack-like structure is  
 stronger than that.

That's okay, we're not talking about pop for stack-like structures, we're
talking about pop for dictionaries.


 A stack is a LIFO data structure.  Therefore the  
 pop() operation is defined to not only mutate the receiver and return  
 the item popped but also ensure that the LAST item in the stack is  
 removed.

Not so. Pop can also be defined to take an argument telling the data
structure (not necessarily a stack) which item to remove.

Pop can also operate on queues, in which case it removes the FIRST item in
the queue.

Pop can also be defined for dequeues (double-ended queue), in which case
it can remove from either the first or the last position.

Pop can also be defined for balloons, which is what they do when you stick
a pin in them.



 This makes perfect sense for a list type in python since  
 lists are mutable sequences that have a specified order.  But for  
 dictionaries this does not hold since they are unordered sequences by  
 definition.  

That's okay, since unordered sequences can define pop too. Obviously pop
for a dictionary has to be defined slightly differently, but the essential
characteristics -- remove an item and return it -- remain the same.


 So for dictionaries it would not make sense for a  
 programmer to simulate a stack-like type.

Dictionaries don't simulate stacks.

We can talk about pushing a value onto a stack, and about pushing a
value into a register, and yet registers are not stacks. We use the
same word, multiply, for both scalar multiplication (3*5=15), matrix
multiplication, and mixed scalar-to-matrix multiplication, even though
they are quite different. (For starters, XY = YX if X and Y are both
scalars, but not if they are matrices.)

We use concatenate to describe the different procedures of joining
linked lists, arrays and strings. We talk about inserting into linked
lists, B-trees, heaps, arrays and priority queues.

Why shouldn't we talk about popping a value from a dictionary?


 While we're on the subject I'm also curious as to why the author of  
 the built-in list class called the method append to add an element  
 to the end of a list and not something like push.

Well, gosh, I really don't know what they were thinking, using append as
the name of the method that, um, APPENDS an item to the end of a list. How
confusing is that?


 But this is not  
 really much of a problem if the programmer could create an alias for  
 it.

It isn't a problem at all.



-- 
Steven.

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


Re: Where I could find older python releases ?

2007-03-04 Thread Adam

Sorry jumped the gun a little there. Is this what you are looking for?
http://codespeak.net/download/py/py-0.9.0.zip

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


Hey! A VERY c00l feature of X and mplayer(could bind to PyQt4)

2007-03-04 Thread Marco
I found a Very c00l feature, that you can write your own MPlayer GUI.

The core is Xembed (http://www.freedesktop.org/wiki/Standards/xembed-spec)
And Of course MPlayer support it as its para: -wid

I hope you like it!

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


IDLE MySQLdb import error

2007-03-04 Thread Michael Boldin via alt email
I installed python 2.5 and used the win package for installing MySQLdb.  (I am 
running Windows XP)
Everything works as expected using python directly (Windows command shell) but 
using IDLE gives the import error below.
Same error with PythonWin as my IDE and everything works using python 2.4-- 
with IDLE and without, mySQLdb is loaded with out error.
Below is the IDLE screen capture

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on 
win32
Type copyright, credits or license() for more information.

Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.2  
 import MySQLdb
Traceback (most recent call last):
  File pyshell#1, line 1, in module
import MySQLdb
  File C:\Python25\lib\site-packages\MySQLdb\__init__.py, line 19, in module
import _mysql
ImportError: DLL load failed: The specified procedure could not be found.


It seems that when using IDLE the _mysql package can not be found although the 
path is the same as non-IDLE 
python and help('modules') shows _mysql is an available.

Is this an IDLE or MySQLdb bug or some incorrect settign on my side


 

Looking for earth-friendly autos? 
Browse Top Cars by Green Rating at Yahoo! Autos' Green Center.
http://autos.yahoo.com/green_center/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST)

2007-03-04 Thread Aviroce
On Feb 24, 11:22 am, [EMAIL PROTECTED] wrote:
 Canada anti-terror law is struck downFrom the Associated Press

 February 24, 2007

 OTTAWA - Canada's Supreme Court on Friday unanimously declared it
 unconstitutional to detain foreign terrorism suspects indefinitely
 while the courts review their deportation orders.

 Five Arab Muslim men have been held for years under the security
 certificate program, which the Justice Department has said is a key
 tool in the fight against global terrorism and essential to Canada's
 security.

 The court found that the system violated the Charter of Rights and
 Freedoms, Canada's bill of rights. However, it suspended its ruling
 for a year to give Parliament time to rewrite the part of the
 Immigration and Refugee Protection Act that covers the certificate
 process.

 The security certificates were challenged by three men from Morocco,
 Syria and Algeria - all alleged by the Canadian Security Intelligence
 Service to have ties to terrorist networks.

 The men have spent years in jail while fighting deportation orders.

 They risk being labeled terrorists and sent back to their native
 countries, where they say they could face torture.

 The court said the treatment of the suspects was a violation of their
 rights.

 The overarching principle of fundamental justice that applies here is
 this: Before the state can detain people for significant periods of
 time, it must accord them a fair judicial process, Chief Justice
 Beverley McLachlin wrote in a ruling for all nine justices.

 The secrecy required by the scheme denies the person named in a
 certificate the opportunity to know the case put against him or her,
 and hence to challenge the government's case, she said.

 The challenged law allows sensitive intelligence to be heard behind
 closed doors by a federal judge, with only sketchy summaries given to
 defense attorneys.

 The court said the men and their lawyers should have a right to
 respond to the evidence used against them by intelligence agents.

 Stockwell Day, the minister of public safety, noted that because the
 ruling does not take effect for a year, the certificates would remain
 in place. He said the government would address the court's ruling in
 a timely and decisive fashion.

 Two of the men are out on bail and remain under house arrest. Three
 others are being held in a federal facility in Ontario.

The court said the treatment of the suspects was a
violation of their
rights.


The overarching principle of fundamental justice that applies here
is
this: Before the state can detain people for significant periods of
time, it must accord them a fair judicial process, Chief Justice
Beverley McLachlin wrote in a ruling for all nine justices.


The secrecy required by the scheme denies the person named in a
certificate the opportunity to know the case put against him or her,
and hence to challenge the government's case, she said.


THAT IS CALLED PROTECTING CIVIL RIGHTS.  IN THE UNITED STATES OF
AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE
NOT PROTECTED BY THE GENEVA CONVENTION.  DR. EVIL, V.P. CHENEY, AND
MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY
FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION.  THIS MEANS
ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO.
WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER.







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


Re: Where I could find older python releases ?

2007-03-04 Thread Daniel Nogradi
 Sorry jumped the gun a little there. Is this what you are looking for?
 http://codespeak.net/download/py/py-0.9.0.zip

Probably not, the OP is looking for a python distribution, what you
are posting is a third party package *for* python and is actually a
part of the pypy project.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: transfer data from one machine to another

2007-03-04 Thread Rikishi 42
On Sunday 04 March 2007 13:56, bahoo wrote:

 I have ssh access to two linux machines (both WITHOUT root account),
 and I'd like to copy data from one to another.
 Since the directory structure is different, I want to specify in a
 script (ideally in python, because that's what I want to learn) what
 to copy over like this:
 
 source: /home/john/folderA
 destination: /home/smith/folderB
 
 I'm a newbie on linux and ssh networking and python, so your
 suggestions are welcome! A small working example would be appreciated!

Try rsync, if you need a second run, it will only copy what has been
modified in the source.

rsync -var -e ssh /home/john/folderA [EMAIL PROTECTED]:/home/smith/folderB

Should be enough.
Remove 'v' for less verbose operation.

-- 
Research is what I'm doing, when I don't know what I'm doing.
(von Braun)

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


Re: RSS feed creator

2007-03-04 Thread Jeff McNeil
What about this?

http://www.dalkescientific.com/Python/PyRSS2Gen.html



On 3/4/07, Florian Lindner [EMAIL PROTECTED] wrote:
 Hello,
 I'm looking for a python library that creates a RSS and/or Atom feed. E.g. I
 give a list like that:
 [
   [title1, short desc1, author1],
   [title2, short desc2, author2],
 ]

 and the library creates a valid feed XML file. (return as a string)

 Thanks,

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

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


Re: class attrdict

2007-03-04 Thread Alex Martelli
goodwolf [EMAIL PROTECTED] wrote:
   ...
 Then you will prefer something like this:
 
 class Namespace(object):
 def __init__(self, __ns={}, **kwargs):
 if kwargs: __ns.update(kwargs)
 self.__dict__ = __ns

I might, if it weren't for the redundant if and the horribly buggy
interference between separate instances -- which is why I wrote it,
almost six years ago and without the bugs, as
http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52308 .

Not much later, in the printed Cookbook, I also gave some other good
ways and explained (as I did in the current thread) why confusing
attributes and items, as proposed in most of this thread, is really a
bad idea.


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


Re: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST)

2007-03-04 Thread Aviroce
On Feb 24, 11:22 am, [EMAIL PROTECTED] wrote:
 Canada anti-terror law is struck downFrom the Associated Press

 February 24, 2007

 OTTAWA - Canada's Supreme Court on Friday unanimously declared it
 unconstitutional to detain foreign terrorism suspects indefinitely
 while the courts review their deportation orders.

 Five Arab Muslim men have been held for years under the security
 certificate program, which the Justice Department has said is a key
 tool in the fight against global terrorism and essential to Canada's
 security.

 The court found that the system violated the Charter of Rights and
 Freedoms, Canada's bill of rights. However, it suspended its ruling
 for a year to give Parliament time to rewrite the part of the
 Immigration and Refugee Protection Act that covers the certificate
 process.

 The security certificates were challenged by three men from Morocco,
 Syria and Algeria - all alleged by the Canadian Security Intelligence
 Service to have ties to terrorist networks.

 The men have spent years in jail while fighting deportation orders.

 They risk being labeled terrorists and sent back to their native
 countries, where they say they could face torture.

 The court said the treatment of the suspects was a violation of their
 rights.

 The overarching principle of fundamental justice that applies here is
 this: Before the state can detain people for significant periods of
 time, it must accord them a fair judicial process, Chief Justice
 Beverley McLachlin wrote in a ruling for all nine justices.

 The secrecy required by the scheme denies the person named in a
 certificate the opportunity to know the case put against him or her,
 and hence to challenge the government's case, she said.

 The challenged law allows sensitive intelligence to be heard behind
 closed doors by a federal judge, with only sketchy summaries given to
 defense attorneys.

 The court said the men and their lawyers should have a right to
 respond to the evidence used against them by intelligence agents.

 Stockwell Day, the minister of public safety, noted that because the
 ruling does not take effect for a year, the certificates would remain
 in place. He said the government would address the court's ruling in
 a timely and decisive fashion.

 Two of the men are out on bail and remain under house arrest. Three
 others are being held in a federal facility in Ontario.

The court said the treatment of the suspects was a
violation of their
rights.


The overarching principle of fundamental justice that applies here
is
this: Before the state can detain people for significant periods of
time, it must accord them a fair judicial process, Chief Justice
Beverley McLachlin wrote in a ruling for all nine justices.


The secrecy required by the scheme denies the person named in a
certificate the opportunity to know the case put against him or her,
and hence to challenge the government's case, she said.


THAT IS CALLED PROTECTING CIVIL RIGHTS.  IN THE UNITED STATES OF
AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE
NOT PROTECTED BY THE GENEVA CONVENTION.  DR. EVIL, V.P. CHENEY, AND
MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY
FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION.  THIS MEANS
ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO.
WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER.








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


Re: design question: no new attributes

2007-03-04 Thread Arnaud Delobelle
On Feb 26, 9:48 pm, Alan Isaac [EMAIL PROTECTED] wrote:
 I have a class whose instances should only receive attribute
 assignments for attributes that were created at inititialization.
 If slots are not appropriate, what is the Pythonic design for this?

Hi !

Even though a lot of people have argued against such a thing, I have
been thinking about this last night and I have the following hack.
Classes descending from SuspiciousObject below won't allow new
attributes to be added to their instances apart from within trusted
methods (i.e. methods decorated with @trustedmethod)

Note: this is probably not of great interest but I've decided to share
it since I did this as a result of reading this thread :)

class LockableDict(dict):
A dict where addition of new keys can be prevented by setting the
locked attribute
__slots__ = ('locked',)
def __init__(self, locked=False):
self.locked = locked
def force_setitem(self, key, value):
super(LockableDict, self).__setitem__(key, value)
def __setitem__(self, key, value):
if self.has_key(key) or not self.locked:
self.force_setitem(key, value)
else:
raise KeyError, key

def trustedmethod(f):
def pf(self, *args, **kwargs):
was_locked = self.__dict__.locked
self.__dict__.locked = False
try:
return f(self, *args, **kwargs)
finally:
self.__dict__.locked = was_locked
return pf

class SuspiciousObject(object):
def __new__(cls, *args, **kwargs):
self = object.__new__(cls)
super(SuspiciousObject, self).__setattr__('__dict__',
LockableDict(locked=True))
return self
def __setattr__(self, attr, value):
try:
self.__dict__[attr] = value
except KeyError:
raise AttributeError, '%s' object has no attribute '%s %
(type(self).__name__, attr)

# Instances of SuspiciousObject refuse anyone the right to create a
new attribute apart from methods marked with the decorator
@trustedmethod.
# Example:

class Foo(SuspiciousObject):
@trustedmethod
def __init__(self):
self.bar = 2
self.baz = 'Hello'
def foobar(self, v):
self.fubar = v
@trustedmethod
def force_setattr(self, attr, val=None):
setattr(self, attr, val)

This would give something like:

 foo=Foo()
 foo.bar
2
 foo.baz
'Hello'
 foo.baz=Bye # works as foo.baz exists
 foo.baz
'Bye'
 foo.fubar=4 # won't be trusted
...
AttributeError: 'Foo' object has no attribute 'fubar
 setattr(foo, 'fubar', 4) # won't work either
...
AttributeError: 'Foo' object has no attribute 'fubar
 foo.__dict__['fubar']=4 # Neither will this
...
KeyError: 'fubar'
 foo.foobar(4) # Neither will this as foo.foobar is not a trusted method
...
AttributeError: 'Foo' object has no attribute 'fubar
 foo.force_setattr('fubar', 4) # this will work as force_setattr is trusted
 foo.fubar
4
 # etc...

By creating a custom metaclass for SuspiciousObject, it would be easy
to make SuspiciousObjects trust their own methods by default instead
of having to declare which method are trusted.

--
Arnaud

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


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread John Nagle
Patrick Useldinger wrote:
 http://www.serpentine.com/blog/2006/12/22/how-to-build-safe-clean-python-25-rpms-for-fedora-core-6/

I've read that.  It's very funny. Now you’ll need to go into the SOURCES 
directory and frob a single file...

It does have something very useful in it - Python's
2.5's dependency list:

sudo yum install autoconf bzip2-devel db4-devel \
expat-devel findutils gcc-c++ gdbm-devel glibc-devel gmp-devel \
libGL-devel libX11-devel libtermcap-devel ncurses-devel \
openssl-devel pkgconfig readline-devel sqlite-devel tar \
tix-devel tk-devel zlib-devel

If a Python build needs all that, something in ./configure
should be checking for each of those.  After all, that's what
./configure is supposed to be for.  It looks like a Python
install will plow ahead without ncurses-devel, and install a
dud version.

(Why is make install doing compiles, anyway?  It should
just be copying.  make is supposed to do all the
compiles.)

This, though, illustrates exactly what I was talking about
  - there is no off the shelf way to install Python 2.5 on
Fedora Core 6.  Others have worked through this and documented
their pain and how to do it manually, but that's not the same
as fixing the packaging problem.

Debian tries to deal with this problem.   See

http://www.debian.org/doc/packaging-manuals/python-policy/index.html

But Fedora Core does not.

Perl, PHP, C, C++, and Java don't have this particular
problem.  Python stands alone, out in the cold.

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


How use XML parsing tools on this one specific URL?

2007-03-04 Thread [EMAIL PROTECTED]
I understand that the web is full of ill-formed XHTML web pages but
this is Microsoft:

http://moneycentral.msn.com/companyreport?Symbol=BBBY

I can't validate it and xml.minidom.dom.parseString won't work on it.

If this was just some teenager's web site I'd move on.  Is there any
hope avoiding regular expression hacks to extract the data from this
page?

Chris

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


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread skip

John If a Python build needs all that, something in ./configure should
John be checking for each of those.  After all, that's what ./configure
John is supposed to be for.  It looks like a Python install will plow
John ahead without ncurses-devel, and install a dud version.

As another person pointed out, you're conflating Python proper with a
specific Linux distribution's packaging techniques.  I run on a Mac and use
MacPorts.  There is no ncurses-devel package there, just ncurses and
ncursesw.  Building a Python interpreter doesn't require ncurses.  It's an
add-on module which happens to be distributed with Python.  The distutils
setup.py script checks for ncurses bits and indeed plows ahead if it's not
found.  Not all systems (Windows, in particular) have ncurses.

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


Re: How use XML parsing tools on this one specific URL?

2007-03-04 Thread skip

Chris http://moneycentral.msn.com/companyreport?Symbol=BBBY

Chris I can't validate it and xml.minidom.dom.parseString won't work on
Chris it.

Chris If this was just some teenager's web site I'd move on.  Is there
Chris any hope avoiding regular expression hacks to extract the data
Chris from this page?

Tidy it perhaps or use BeautifulSoup?  ElementTree can use tidy if it's
available.

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


Re: How use XML parsing tools on this one specific URL?

2007-03-04 Thread Jorge Godoy
[EMAIL PROTECTED] [EMAIL PROTECTED] writes:

 I understand that the web is full of ill-formed XHTML web pages but
 this is Microsoft:

Yes...  And Microsoft is responsible for a lot of the ill-formed pages on the
web be it on their website or made by their applications. 

 http://moneycentral.msn.com/companyreport?Symbol=BBBY

 I can't validate it and xml.minidom.dom.parseString won't work on it.

 If this was just some teenager's web site I'd move on.  Is there any
 hope avoiding regular expression hacks to extract the data from this
 page?

It all depends on what data you want.  Probably a non-validating parser would
be able to extract some things.  Another option is pass the page through some
validator that can fix the page, like tidy... 


-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Randomizing in Python

2007-03-04 Thread [EMAIL PROTECTED]
On Mar 3, 1:56 pm, Mark Nenadov [EMAIL PROTECTED] wrote:
 On Sat, 03 Mar 2007 08:46:09 -0800, [EMAIL PROTECTED] wrote:
   I want to randomize a certain calculation in Python but haven't
  figured it out yet. To explain what i mean, I' m going to use an
  example:
  I want to get the numbers to do a random
  experience database for a game. What would be necessary to do so?

 Look into the random module (http://docs.python.org/lib/module-random.html)

 random.choice selects a random item out of a sequence
 random.shuffle shuffles a sequence randomly
 random.random gives a random floating point number

 --
 Mark Nenadov - skype: marknenadov, web:http://www.marknenadov.com
 - Relying on the government to protect your privacy is like asking a
 peeping tom to install your window blinds. -- John Perry Barlow

Thanks a lot for the help

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


Re: Non Sequitur

2007-03-04 Thread Aahz
In article [EMAIL PROTECTED],
Ben Finney  [EMAIL PROTECTED] wrote:
Dennis Lee Bieber [EMAIL PROTECTED] writes:

 
  I before E
  Except after C
  Or when sounded as A
  As in Neighbor and Weigh
 

Yes, like the A sound in weird or ceiling.

http://jef.raskincenter.org/published/i_before_e.html
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

I disrespectfully agree.  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread John Nagle
[EMAIL PROTECTED] wrote:
  The distutils setup.py script checks for ncurses bits

No, it just plows on after compiler errors.

 As another person pointed out, you're conflating Python proper with a
 specific Linux distribution's packaging techniques. 

Exactly.  As I've pointed out before, Python doesn't play well with
others.  The Python developers pass the buck to the Linux packager, the
Linux packager passes the buck to the Python developers, and thus
the user experience sucks.

Debian seems to have struggled through this problem, but Red Hat
apparently just decided to give up keeping up with Python versions.

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


Re: class attrdict

2007-03-04 Thread goodwolf
class Namespace(object):
def __init__(self, __ns=None, **kwargs):
if __ns is None:#if no dictionary is given
self.__dict__ = kwargs  #then use kwargs without copying
or creating new dict
else:
assert len(kwargs) == 0
self.__dict__ = __ns#else use dictionary without
copyng

 #additional methods for JS like object (ONLY FOR DEMONSTRATION)
 def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
setattr(self, name, value)
def __delitem__(self, name):
delattr(self, name)
def __iter__(self):
return iter(self.__dict__)
def __contains__(self, name):
return hasattr(self, name)

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


Re: Where I could find older python releases ?

2007-03-04 Thread skip

Martins I have been searching the internet for python version 0.9.0
Martins sources which had been posted to alt.sources list, but without
Martins any luck. Maybe someone has it available somewhere ?

If you *really* want Python 0.9.0 and not PyPy 0.9.0, I think you're going
to have to deduce and check out the appropriate revision from the Subversion
repository.  Looking at the Misc/HISTORY file it appears that 0.9.0 was
released in February 1991.  Looking at the Subversion log I don't see any
specific comment pertaining to a release, but I see a lot of checkins on
1991-02-19, the last being r2314.  The next checkin after that is on
1991-03-06.  Since 0.9.1 was also released in February 1991, r2314 will
probably get you that version, or something very near to it.

Skip


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


doxygen

2007-03-04 Thread Jan Danielsson
Hello all,

   I guess I should really be asking in some doxygen mailing list, but
since I believe that I found doxygen through this group, I assume that
there are some people here who can answer.

   When I run doxygen on my python files, it does document classes, but
not standalone functions. I.e.:

---
## Foobar class
#
# This is a test class!
class Foobar:

   ## Init
   #
   # This is the init function.
   def __init__(self):
  pass
---

   ... is included, but:

---
## Test
#
# This is a test function
def TestFunction(foo=None):
   pass
---

   ..is not.

   Is this by design? Is it possible to get doxygen to include
standalone functions?


-- 
Kind regards,
Jan Danielsson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5, problems reading large ( 4Gbyes) files on win2k

2007-03-04 Thread Paul Duffy
Bill Tydeman wrote:
 Just curious, but since the file size limitation on NTFS is 4 GB, have 
 you confirmed that it isn't some other part of the interaction that is 
 causing the problem?   What FS is hosting the files?
I don't think that is correct.  Groovy version of app runs just fine.

 On 2 Mar 2007 10:09:15 -0800, [EMAIL PROTECTED] 
 mailto:[EMAIL PROTECTED]* [EMAIL PROTECTED] 
 mailto:[EMAIL PROTECTED] wrote:

 Folks,

 I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume).
 Reading a file of 13 GBytes, one line at a time.  It appears that,
 once the read line passes the 4 GByte boundary, I am getting
 occasional random line concatenations.  Input file is confirmed good
 via UltraEdit.  Groovy version of the same app runs fine.

 Any ideas?

 Cheers

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




 -- 
 There is no reason for any individual to have a computer in his home.
 Ken Olsen, President, Digital Equipment, 1977
 US computer engineer  industrialist (1926 - )

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


Re: thread safe SMTP module

2007-03-04 Thread Aahz
In article [EMAIL PROTECTED],
Gordon Messmer  [EMAIL PROTECTED] wrote:
Aahz wrote:
 
 That doesn't make any sense.  Blocking I/O generally releases the GIL,
 which is the whole reason Python doesn't totally suck for threading.

Nevertheless, among the caveats listed at 
http://docs.python.org/lib/module-thread.html is:

Not all built-in functions that may block waiting for I/O allow other 
threads to run. (The most popular ones (time.sleep(), file.read(), 
select.select()) work as expected.)

That's why I said generally.

 There may be other thread problems, but I doubt that you have correctly
 analyzed their source.

I subclassed smtplib.SMTP and replaced only the lines of code that had 
to do with blocking IO (connect, send and receive operations). 
Beforehand, python would occasionally lock up. Having made those 
changes, python stopped locking up.  I think the problem was pretty well 
apparent.  I can't pin it down to which one of those three operations 
was at fault, and it may be that only one was.  However, when I use 
non-blocking IO, the application works.  When I used smtplib.SMTP, it 
didn't.

I'm open to other explanations.

Assuming you have correctly tracked down the problem area, I would call
that a thread bug in Python.  But my experience is that you simply have
run into a problem with the socket.  I would suggest that using
socket.setdefaulttimeout() would work just as well.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

I disrespectfully agree.  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How use XML parsing tools on this one specific URL?

2007-03-04 Thread Nikita the Spider
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 I understand that the web is full of ill-formed XHTML web pages but
 this is Microsoft:
 
 http://moneycentral.msn.com/companyreport?Symbol=BBBY
 
 I can't validate it and xml.minidom.dom.parseString won't work on it.
 
 If this was just some teenager's web site I'd move on.  Is there any
 hope avoiding regular expression hacks to extract the data from this
 page?

Valid XHTML is scarcer than hen's teeth. Luckily, someone else has 
already written the ugly regex parsing hacks for you. Try Connelly 
Barnes' HTMLData: 
http://oregonstate.edu/~barnesc/htmldata/ 

Or BeautifulSoup as others have suggested.

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How use XML parsing tools on this one specific URL?

2007-03-04 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
 I understand that the web is full of ill-formed XHTML web pages but
 this is Microsoft:

 http://moneycentral.msn.com/companyreport?Symbol=BBBY

Yes, thank you Microsoft!

 I can't validate it and xml.minidom.dom.parseString won't work on it.

 If this was just some teenager's web site I'd move on.  Is there any
 hope avoiding regular expression hacks to extract the data from this
 page?

The standards adherence from Microsoft services is clearly at teenage
level, but here's a recipe:

import libxml2dom
import urllib
f = urllib.urlopen(http://moneycentral.msn.com/companyreport?
Symbol=BBBY)
d = libxml2dom.parse(f, html=1)
f.close()

You now have a document which contains a DOM providing libxml2's
interpretation of the HTML. Sadly, PyXML's HtmlLib doesn't seem to
work with the given document. Other tools may give acceptable results,
however.

Paul

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


looking for Java final/Ruby freeze functionality in Python

2007-03-04 Thread Antoine De Groote
Hello,

I've been googling for quite a while now but can't find anything about a 
function/keyword to make a list (or something else) immutable. Could 
anybody point me to docs about this matter or give me a reason why this 
(apparently) doesn't exist in Python?

Kind regards,
antoine
-- 
http://mail.python.org/mailman/listinfo/python-list


When will 2.5.1 be released?

2007-03-04 Thread Nile
This is not a big deal but I would like to use Tix with 2.5.  My
understanding is this bug will be fixed in the 2.5.1 release. Does
anyone know when this will be out ?  What is the best guess?

Thanks,

Nile

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


Re: looking for Java final/Ruby freeze functionality in Python

2007-03-04 Thread Bart Van Loon
It was Sun, 04 Mar 2007 20:38:16 +0100, when Antoine De Groote wrote:
 Hello,

 I've been googling for quite a while now but can't find anything about a 
 function/keyword to make a list (or something else) immutable. Could 
 anybody point me to docs about this matter or give me a reason why this 
 (apparently) doesn't exist in Python?

what about a tuple?

-- 
regards,
BBBart

   My family is dysfunctional and my parents won't empower me.  Consequently
I'm not self actualized.  -- Calvin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread MonkeeSage
On Mar 4, 12:03 pm, John Nagle [EMAIL PROTECTED] wrote:
 Exactly.  As I've pointed out before, Python doesn't play well with
 others.  The Python developers pass the buck to the Linux packager, the
 Linux packager passes the buck to the Python developers, and thus
 the user experience sucks.

The configure script checks for libraries and headers that are
required for a base build, and (according to the options passed to
configure, or using the defaults) optional components. There is NO WAY
for it to know which PACKAGES, on any of the 500 linux distributions,
provide those libs and headers. That is the job of the PACKAGER, or
(gasp) the end user if you use a distro without a package system or
trying to build from raw source. There is no passing the buck. If a
package is broken, the packager must fix it. If the source is broken,
the developer must fix it.

 Debian seems to have struggled through this problem, but Red Hat
 apparently just decided to give up keeping up with Python versions.

Anybody can make packages, not just the distro maintainers. Why not
search for them?

http://rpmseek.com/rpm-pl/python.html?hl=comcs=python%3APN%3A0%3A0%3A0%3A0%3A0qArStr=0qRtStr=1qDnStr=82

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


Re: looking for Java final/Ruby freeze functionality in Python

2007-03-04 Thread Arnaud Delobelle
On Mar 4, 7:38 pm, Antoine De Groote [EMAIL PROTECTED] wrote:
 Hello,

 I've been googling for quite a while now but can't find anything about a
 function/keyword to make a list (or something else) immutable. Could
 anybody point me to docs about this matter or give me a reason why this
 (apparently) doesn't exist in Python?

First result from google 'python freeze object':

http://www.python.org/dev/peps/pep-0351/

The PEP was rejected but the document contains a link to a discussion
about why there is no such thing in python:

http://mail.python.org/pipermail/python-dev/2006-February/060793.html

HTH

--
Arnaud

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


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread Paul Boddie
John Nagle wrote:
 I've been installing Python and its supporting packages on
 a dedicated server with Fedora Core 6 for about a day now.
 This is a standard dedicated rackmount server in a colocation
 facility, controlled via Plesk control panel, and turned over
 to me with Fedora Core 6 in an empty state.  This is the
 standard way you get a server in a colo today.

You have my commiserations, and I don't mean that to be a flippant
remark.

Bringing Python up in this completely clean environment is
 a huge hassle, and it doesn't really work.

Once upon a time, I used to manage an entire Python environment with
lots of modules, additional libraries, and so on. I don't have the
patience for that any more.

Fedora Core 6 ships with Python 2.4, which appears to be a
 good decision on someone's part.  Of course, there's no
 standard RPM for a Python 2.5 install on Linux.  Packaging is
 someone else's problem, according to the Python developers.

I managed to find a site which gives some kind of searchable index of
packages:

http://www.fedoratracker.org/

It's a bit like the Debian and Ubuntu package sites but seemingly
unofficial and a lot slower. Once upon a time there were some
contributed RPMs available from python.org, but I don't know what
happened to them.

[FTP server, GCC, configuration]

 But make install does some compiles, something install probably
 shouldn't be doing.

If the original build process didn't manage to compile everything,
make will revisit that part of the process. What should really happen
is that make should halt and not try and do anything else.

An aside on the subject of installing - something you may be aware of,
but worth repeating for others who have read this far. I guess that
make altinstall isn't necessary if you *don't* do something like
this when configuring:

./configure --prefix=/usr

The issue here is that if Fedora (or other distributions) has things
relying on /usr/bin/python, you have to make sure that you don't
overwrite it when installing. If you've been thinking that the new
version of Python should live alongside the others, you have to use
make altinstall to preserve the existing python program (the
python2.4 will survive, anyway) whilst installing python2.5 alongside
it.

Typically, the configure script behaves as if this were typed:

./configure --prefix=/usr/local

Thus, a make install will create /usr/local/bin/python and /usr/
local/bin/python2.5, hopefully not overwriting other things.

  Some of these compiles fail, with error messages
 like
 /var/www/vhosts/sitetruth.com/private/downloads/python/Python-2.5/Modules/_curses_panel.c:271:
 error: PyCursesPanelObject has no member named pan

This should stop the process, but as you note...

 But the install script plunges blindly on, presumably installing a broken
 Python 2.5.  Apparently Fedora Core 6 doesn't come with curses preinstalled,
 but the Python installer assumes it is there.  What's inexcusable is
 just plowing on after failed compiles, resulting in a broken install.

This might require a bug report.

 It's probably necessary to install something before building Python,
 but the README file is silent on this.

  OK.  Plunging onward, and not really needing the curses library,
 we try to install MySQLdb.  We get that with FTP,
 unpack it, go to the approprate directory, and run python setup.py.
 This fails because the MySQL headers aren't installed:

 _mysql.c:35:23: error: my_config.h: No such file or directory

 OK, looks like we need to install mysql-devel, so we do that,
 using yum.   This forces an update of OpenSSL, Kerberos, and
 e2fsprogs-dev.  Which means we should reboot at some point.

Perhaps the system wasn't up-to-date anyway.

 But now we can build MySQLdb.  So we build and install it.

 So then we try import MySQLdb in Python 2.5.  And we get this:

  /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.py:3:
   UserWarning: Module _mysql was already imported from 
  /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.pyc,
   but 
  /var/www/vhosts/sitetruth.com/private/downloads/MySQLdb/MySQL-python-1.2.2 
  is being added to sys.path
import sys, pkg_resources, imp
  Traceback (most recent call last):
File stdin, line 1, in module
File MySQLdb/__init__.py, line 19, in module
  import _mysql
File build/bdist.linux-i686/egg/_mysql.py, line 7, in module
File build/bdist.linux-i686/egg/_mysql.py, line 4, in __bootstrap__
File 
  /usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py,
   line 800, in resource_filename
File 
  /usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py,
   line 1228, in get_resource_filename
File 
  /usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py,
   line 1250, in _extract_resource
File 
  

Re: thread safe SMTP module

2007-03-04 Thread Gordon Messmer
Aahz wrote:
 
 Assuming you have correctly tracked down the problem area, I would call
 that a thread bug in Python.  But my experience is that you simply have
 run into a problem with the socket.  I would suggest that using
 socket.setdefaulttimeout() would work just as well.

I believe that solution, also would not work.  This note is included in 
the socket documentation, regarding timeout mode:

http://docs.python.org/lib/socket-objects.html
A consequence of this is that file objects returned by the makefile() 
method must only be used when the socket is in blocking mode; in timeout 
or non-blocking mode file operations that cannot be completed 
immediately will fail.

smtplib.SMTP uses file objects when reading SMTP responses.  If I used 
setdefaulttimeout(), then the socket would be in timeout mode and the 
above note would be applicable.

I am not at all above calling python's behavior a bug, except that it 
seemed like a known behavior given the note in the thread documentation 
regarding built-in functions that block on I/O.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple content-types break cgi.py

2007-03-04 Thread Janto Dreijer
On Mar 4, 12:29 pm, Jon Ribbens [EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED], Janto Dreijer wrote:
  The Nokia Java SDK allows one to define multiple content-types in a
  single HTTP header field. I'm not sure if it's standard, but it's
  happening from some Java-enabled phones.

  The only reference to this bug I can find dates back to 1999:
 http://tinyurl.com/3ahc3r

 It's not a bug - sending multiple content-types is just totally broken.
 What would such a header even be supposed to mean? It's like saying
 this is an apple orange.

Hmmm. Thanks! I suspected as much.

Rough inspection suggests that calling
connection.setRequestProperty(Content-Type, application/x-www-
form-urlencoded);
on the Nokia 6230 would actually cause the value to be *appended* and
not set.

Yuck! It looks like I'm going to have to keep a modified copy of
cgi.py if I want to support the phone. Or hack something on the Java
side.

Janto

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


Re: Perl and Python, a practical side-by-side example.

2007-03-04 Thread Bruno Desthuilliers
John Machin a écrit :
 On Mar 3, 12:36 pm, Bruno Desthuilliers 
 [snip]
 
 DATE = 5
 TARGET = 6
 
 [snip]
 
Now for the bad news: I'm afraid your algorithm is broken : here are my
test data and results:

input = [
 #ID  STATE ...  ...  ... TARG DATE
 aaa\tAAA\t...\t...\t...\tBBB\t20071212\n,
 
 [snip]
 
 Bruno, The worse news is that your test data is broken.

Re-reading the OP's specs, the bad news is that my only neuron left is 
broken. Shouldn't code at 2 o'clock in the morning :(
-- 
http://mail.python.org/mailman/listinfo/python-list


list-like behaviour of etree.Element

2007-03-04 Thread Daniel Nogradi
The etree.Element (or ElementTree.Element) supports a number of
list-like methods: append, insert, remove. Any special reason why it
doesn't support pop and extend (and maybe count)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Perl and Python, a practical side-by-side example.

2007-03-04 Thread Bruno Desthuilliers
Bjoern Schliessmann a écrit :
 Bruno Desthuilliers wrote:
 
Shawn Milo a écrit :
 
 
if recs.has_key(piid) is False:

'is' is the identity operator - practically, in CPython, it
compares memory addresses. You *dont* want to use it here.
 
 
 It's recommended to use is None; why not is False? Are there
 multiple False instances or is False generated somehow?

Once upon a time, Python didn't have a proper boolean type. It only 
had rules for boolean evaluation of a given object. According to these 
rules - that of course still apply -, empty strings, lists, tuples or 
dicts, numeric zeros and None are false in a boolean context. IOW, an 
expression can eval to false without actually being the False object 
itself. So the result of using the identity operator to test against 
such an expression, while being clearly defined, may not be exactly what 
you'd think.

To make a long story short:

if not []:
   print the empty list evals to false in a boolean context

if [] is False:
   print this python interpreter is broken

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


Re: looking for Java final/Ruby freeze functionality in Python

2007-03-04 Thread Antoine De Groote
yes thanks, that is quite what I was looking for.

Arnaud Delobelle wrote:
 On Mar 4, 7:38 pm, Antoine De Groote [EMAIL PROTECTED] wrote:
 Hello,

 I've been googling for quite a while now but can't find anything about a
 function/keyword to make a list (or something else) immutable. Could
 anybody point me to docs about this matter or give me a reason why this
 (apparently) doesn't exist in Python?
 
 First result from google 'python freeze object':
 
 http://www.python.org/dev/peps/pep-0351/
 
 The PEP was rejected but the document contains a link to a discussion
 about why there is no such thing in python:
 
 http://mail.python.org/pipermail/python-dev/2006-February/060793.html
 
 HTH
 
 --
 Arnaud
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Alternatives for Extracting EXIF and JPEG Data from Images

2007-03-04 Thread Roger
Does anybody have a pointer to a Python library/utility that will 
extract the chrominance and luminance quantization tables from JPG images? 

I have been using the _getexif method from PIL, which works fine, but 
doesn't extract the quantization data.  I am a bit fuzzy on the 
terminology, but the quantization data  seems to be JPEG data rather 
than EXIF data.  One utility that extracts the quantization tables is 
JPEGsnoop -- there is a link to download the utility here:
   http://www.impulseadventure.com/photo/jpeg-quantization.html

The source code for the above isn't available and may not be callable 
from a Python script even  if it were available.

Roger

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


Re: doxygen

2007-03-04 Thread Mike Kent
On Mar 4, 1:15 pm, Jan Danielsson [EMAIL PROTECTED] wrote:

When I run doxygen on my python files, it does document classes, but
 not standalone functions.

Look in the doxygen config file for your python project, named
'Doxyfile', for the config setting
'EXTRACT_ALL', and read the comments there.

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


Re: Perl and Python, a practical side-by-side example.

2007-03-04 Thread Bruno Desthuilliers
Shawn Milo a écrit :
(snip)
 The script reads a file from standard input and
 finds the best record for each unique ID (piid). The best is defined
 as follows: The newest expiration date (field 5) for the record with
 the state (field 1) which matches the desired state (field 6). If
 there is no record matching the desired state, then just take the
 newest expiration date.
 

Here's a fixed (wrt/ test data) version with a somewhat better (and 
faster) algorithm using Decorate/Sort/Undecorate (aka schwarzian transform):

import sys
output = sys.stdout

input = [
 #ID  STATE ...  ...  ...  DATE TARGET
 aaa\tAAA\t...\t...\t...\t20071212\tBBB\n,
 aaa\tAAA\t...\t...\t...\t20070120\tAAA\n,
 aaa\tAAA\t...\t...\t...\t20070101\tAAA\n,
 aaa\tAAA\t...\t...\t...\t20071010\tBBB\n,
 aaa\tAAA\t...\t...\t...\t2007\tBBB\n,
 ccc\tAAA\t...\t...\t...\t20071201\tBBB\n,
 ccc\tAAA\t...\t...\t...\t20070101\tAAA\n,
 ccc\tAAA\t...\t...\t...\t20071212\tBBB\n,
 ccc\tAAA\t...\t...\t...\t20071212\tAAA\n,
 bbb\tAAA\t...\t...\t...\t20070101\tBBB\n,
 bbb\tAAA\t...\t...\t...\t20070101\tBBB\n,
 bbb\tAAA\t...\t...\t...\t20071212\tBBB\n,
 bbb\tAAA\t...\t...\t...\t20070612\tBBB\n,
 bbb\tAAA\t...\t...\t...\t20071212\tBBB\n,
 ]

def find_best_match(input=input, output=output):
 PIID = 0
 STATE = 1
 EXP_DATE = 5
 DESIRED_STATE = 6

 recs = {}
 for line in input:
 line = line.rstrip('\n')
 row = line.split('\t')
 sort_key = (row[STATE] == row[DESIRED_STATE], row[EXP_DATE])
 recs.setdefault(row[PIID], []).append((sort_key, line))

 for decorated_lines in recs.itervalues():
 print  output, sorted(decorated_lines, reverse=True)[0][1]

Lines are sorted first on  whether the state matches the desired state, 
then on the expiration date. Since it's a reverse sort, we first have 
lines that match (if any) sorted by date descending, then the lines that 
dont match sorted by date descending. So in both cases, the 'best match' 
is the first item in the list. Then we just have to get rid of the sort 
key, et voilà !-)

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


identifying modules to be built and not

2007-03-04 Thread skip

The thread John Nagle started about building Python 2.5 on Fedora Core 6 led
me to implement a slight change to Python's setup.py.  You clearly can't
have the build stop if the bits needed to build a particular module aren't
found or if compiling a module fails, but it's fairly straightforward to
note which modules could be built and which can't be.  There's a patch for
setup.py on SourceForge you can try if you want:

http://python.org/sf/1673619

When setup.py is run it emits output like this after checking for modules it
knows how to build (this is from my Mac):

Located the necessary bits to build these modules:
_AE   _AH   _App   
_bisect   _bsddb_CarbonEvt 
_CF   _CG   _Cm
_codecs_cn_codecs_hk_codecs_iso2022
_codecs_jp_codecs_kr_codecs_tw 
_collections  _csv  _Ctl   
_ctypes   _ctypes_test  _curses
_curses_panel _Dlg  _Drag  
_elementtree  _Evt  _File  
_Fm   _Folder   _functools 
_hashlib  _heapq_Help  
_hotshot  _IBCarbon _Icn   
_Launch   _List _locale
_lsprof   _Menu _Mlte  
_multibytecodec   _OSA  _Qd
_Qdoffs   _Qt   _random
_Res  _Scrap_Snd   
_socket   _sqlite3  _ssl   
_struct   _TE   _testcapi  
_tkinter  _weakref  _Win   
array audioop   autoGIL
binascii  bsddb185  bz2
cmath ColorPicker   cPickle
crypt cStringIO datetime   
dbm   dlfcntl  
gestalt   grp   icglue 
imageop   itertools MacOS  
math  mmap  Nav
nis   operator  OSATerminology 
parserpwd   pyexpat
readline  resource  rgbimg 
selectstrop syslog 
termios   time  unicodedata

Failed to find the necessary bits to build these modules:
_elementtree  _md5  _sha   
_sha256   _sha512   gdbm   
linuxaudiodev ossaudiodev   spwd   

Feel free to add comments to the above patch page.  It will help the
development team decide whether or not it's a worthwhile addition.

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


Re: Perl and Python, a practical side-by-side example.

2007-03-04 Thread Peter Otten
Bruno Desthuilliers wrote:

  print  output, sorted(decorated_lines, reverse=True)[0][1]

Or just
   print  output, max(decorated_lines)[1]

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


Re: Perl and Python, a practical side-by-side example.

2007-03-04 Thread Bruno Desthuilliers
Peter Otten a écrit :
 Bruno Desthuilliers wrote:
 
 
 print  output, sorted(decorated_lines, reverse=True)[0][1]
 
 
 Or just
print  output, max(decorated_lines)[1]

Good point. More explicit, and a bit faster too. Thanks Peter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-04 Thread Paul Boddie
MonkeeSage wrote:

 The configure script checks for libraries and headers that are
 required for a base build, and (according to the options passed to
 configure, or using the defaults) optional components. There is NO WAY
 for it to know which PACKAGES, on any of the 500 linux distributions,
 provide those libs and headers.

True, but it would be nice to be able to do a configure --with-some-
library[=path] and have it give an error if that library isn't found.
A lot of tests for specific libraries and headers exist in the
autoconf universe, and it's also possible to write custom tests. Of
course, this may be academic since distutils has apparently taken over
a lot of the work concerning optional modules.

 That is the job of the PACKAGER, or
 (gasp) the end user if you use a distro without a package system or
 trying to build from raw source. There is no passing the buck. If a
 package is broken, the packager must fix it. If the source is broken,
 the developer must fix it.

I guess if you're building from source, you're the packager, yes.
These days when I can't find up-to-date packages for my aging
distribution, I actually seek out such packages for newer
distributions and backport them, mostly because the dependencies have
been worked out by someone else. In such circumstances, I'm the
packager but I'm using a package infrastructure, as opposed to having
to do a lot of the hard work myself.

Paul

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


Re: multiple content-types break cgi.py

2007-03-04 Thread Jon Ribbens
In article [EMAIL PROTECTED], Janto Dreijer wrote:
 It's not a bug - sending multiple content-types is just totally broken.
 What would such a header even be supposed to mean? It's like saying
 this is an apple orange.
 
 Hmmm. Thanks! I suspected as much.
 
 Rough inspection suggests that calling
 connection.setRequestProperty(Content-Type, application/x-www-
 form-urlencoded);
 on the Nokia 6230 would actually cause the value to be *appended* and
 not set.

If that method is inherited from java.net.URLConnection, then if the
phone is behaving as you suggest, its Java library is bugged and
behaving contrary to Sun's Java documentation.
-- 
http://mail.python.org/mailman/listinfo/python-list


MS SQL Database connection

2007-03-04 Thread Hitesh

Hi currently I am using DNS and ODBC to connect to MS SQL database.
Is there any other non-dns way to connect? If I want to run my script
from different server  I first have to create the DNS in win2k3.

Thank you,
hj

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


Snack -- Help

2007-03-04 Thread v.davis2
Is anyone out there knowledgeable about using the Snack tool under Windows? 
Once I try to get beyond the simple provided examples I run out of reference 
material.
Thanks, Vic 


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


Re: Alternatives for Extracting EXIF and JPEG Data from Images

2007-03-04 Thread Max Erickson
Roger [EMAIL PROTECTED] wrote:

 Does anybody have a pointer to a Python library/utility that will
 extract the chrominance and luminance quantization tables from
 JPG images? 
 
 I have been using the _getexif method from PIL, which works fine,
 but doesn't extract the quantization data.  I am a bit fuzzy on
 the terminology, but the quantization data  seems to be JPEG data
 rather than EXIF data.  One utility that extracts the
 quantization tables is JPEGsnoop -- there is a link to download
 the utility here: 
http://www.impulseadventure.com/photo/jpeg-quantization.html
 
 The source code for the above isn't available and may not be
 callable from a Python script even  if it were available.
 
 Roger
 

I don't know what the format is, etc, but jpegs I open with PIL have a 
quantization attribute, e.g:

 im.quantization
{0: array('b', [6, 4, 4, 5, 4, 4, 6, 5, 5, 5, 6, 6, 6, 7, 9, 14, 9, 9, 
8, 8, 9, 18, 13, 13, 10, 14, 21, 18, 22, 22, 21, 18, 20, 20, 23, 26, 
33, 28, 
snip a bunch more numbers


max

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


Project organization and import

2007-03-04 Thread Martin Unsal
I'm using Python for what is becoming a sizeable project and I'm
already running into problems organizing code and importing packages.
I feel like the Python package system, in particular the isomorphism
between filesystem and namespace, doesn't seem very well suited for
big projects. However, I might not really understand the Pythonic way.
I'm not sure if I have a specific question here, just a general plea
for advice.

1) Namespace. Python wants my namespace heirarchy to match my
filesystem heirarchy. I find that a well organized filesystem
heirarchy for a nontrivial project will be totally unwieldy as a
namespace. I'm either forced to use long namespace prefixes, or I'm
forced to use from foo import * and __all__, which has its own set
of problems.

1a) Module/class collision. I like to use the primary class in a file
as the name of the file. However this can lead to namespace collisions
between the module name and the class name. Also it means that I'm
going to be stuck with the odious and wasteful syntax foo.foo
everywhere, or forced to use from foo import *.

1b) The Pythonic way seems to be to put more stuff in one file, but I
believe this is categorically the wrong thing to do in large projects.
The moment you have more than one developer along with a revision
control system, you're going to want files to contain the smallest
practical functional blocks. I feel pretty confident saying that put
more stuff in one file is the wrong answer, even if it is the
Pythonic answer.

2) Importing and reloading. I want to be able to reload changes
without exiting the interpreter. This pretty much excludes from foo
import *, unless you resort to this sort of hack:

http://www.python.org/search/hypermail/python-1993/0448.html

Has anyone found a systematic way to solve the problem of reloading in
an interactive interpreter when using from foo import *?


I appreciate any advice I can get from the community.

Martin

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


Re: How to set docstrings for extensions supporting PyNumberMethods?

2007-03-04 Thread Nick Alexander
On Mar 4, 12:14 am, Ziga Seilnacht [EMAIL PROTECTED] wrote:
 NickAlexanderwrote:
  Hello,

  I am writing a python extension (compiled C code) that defines an
  extension type with PyNumberMethods.  Everything works swimmingly,
  except I can't deduce a clean way to set the docstring for tp_*
  methods.  That is, I always have

  type.__long__.__doc__ == 'x.__long__() == long(x)'

  which a quick glance at the Python 2.5 source shows is the default.

  I have found that I can use PyObject_GetAttr and PyWrapperDescrObject
  and set the descriptor objects d_base-doc to a char pointer... but I
  can't tell if this is safe.  Or the right way to do it.

  If I'm on the wrong list, please let me know!
  Thanks,
 NickAlexander

 I think that the right way is to add the methods to the tp_methods
 slot and use METH_COEXIST in the PyMethodDef flags field. Example:

Ziga, thanks for an extremely helpful reply.  I'll experiment and post
again if there are issues.

Cheers!
Nick

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


Re: Project organization and import

2007-03-04 Thread Nicholas Parsons




1a) Module/class collision. I like to use the primary class in a file
as the name of the file. However this can lead to namespace collisions
between the module name and the class name. Also it means that I'm
going to be stuck with the odious and wasteful syntax foo.foo
everywhere, or forced to use from foo import *.



The normal convention is to use a initial uppercase letter when  
defining a class and using all lowercase letters for naming a file/ 
module.


For example you might have a file called foo.py with the following:

class Foo:
  pass

Now no namespace collision will result when you import the foo file/ 
module.




1b) The Pythonic way seems to be to put more stuff in one file, but I
believe this is categorically the wrong thing to do in large projects.
The moment you have more than one developer along with a revision
control system, you're going to want files to contain the smallest
practical functional blocks. I feel pretty confident saying that put
more stuff in one file is the wrong answer, even if it is the
Pythonic answer.


Each file is considered a module in python.  You usually don't want  
to throw everything into one module, especially for big projects.   
Breaking your code down into meaningful modules that can be reused in  
other modules.  There is no general rule to follow here as far as  
length of a file/module is concerned.  Use your judgment here.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Questions about app design - OOP with python classes

2007-03-04 Thread greg
Paul Rubin wrote:

 Maybe we can concoct a cross between Python and Haskell, and call it
 Paskell after the philosopher Blaise ;-).

No, we name it after Pascall's confectionery:

   http://www.homesick-kiwi.com/productpage.php?id=51

Lots of syntactic sugar. :-)

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


wxPython import error...

2007-03-04 Thread king kikapu
Hi,

i am just completed installing Python/Pydev/Eclipse/wxPython on an
Ubuntu system and all are running fine except program that contains
references to wx

It gives me:
ImportError: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-unicode/wx/
_core_.so: undefined symbol: PyUnicodeUCS4_FromEncodedObject

I installed the wx packages the way the wx web site says, especially
for Ubuntu.

Can anyone help with this as i have been searching the net for this
with no luck...

Thanks for any help

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


Re: Questions about app design - OOP with python classes

2007-03-04 Thread greg
John Nagle wrote:

 The Pascal/Ada/Modula family of languages all had type systems
 with restrictions on conversion.  Unlike C, types in Pascal
 are not simply abbreviations of the type; they're unique types.

Ada is the only one of those that would let you
define things like a new kind of integer that
is not compatible with other integers.

Pascal and Modula just had a fixed set of numeric
types with various predefined compatibility
rules, not much different from C.

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


Re: Project organization and import

2007-03-04 Thread Jorge Godoy
Martin Unsal [EMAIL PROTECTED] writes:

 1) Namespace. Python wants my namespace heirarchy to match my filesystem
 heirarchy. I find that a well organized filesystem heirarchy for a
 nontrivial project will be totally unwieldy as a namespace. I'm either
 forced to use long namespace prefixes, or I'm forced to use from foo import
 * and __all__, which has its own set of problems.

I find it nice.  You have the idea of where is something just from the import
and you don't have to search for it everywhere.  Isn't, e.g., Java like that?
(It's been so long since I last worried with Java that I don't remember if
this is mandatory or just a convention...)

You might get bitten with that when moving files from one OS to another,
specially if one of them disconsider the case and the other is strict with
it. 

 1a) Module/class collision. I like to use the primary class in a file as the
 name of the file. However this can lead to namespace collisions between the
 module name and the class name. Also it means that I'm going to be stuck
 with the odious and wasteful syntax foo.foo everywhere, or forced to use
 from foo import *.

Your classes should be CamelCased and start with an uppercase letter.  So
you'd have foo.Foo, being foo the package and Foo the class inside of it.

 1b) The Pythonic way seems to be to put more stuff in one file, but I
 believe this is categorically the wrong thing to do in large projects.  The
 moment you have more than one developer along with a revision control
 system, you're going to want files to contain the smallest practical
 functional blocks. I feel pretty confident saying that put more stuff in
 one file is the wrong answer, even if it is the Pythonic answer.

Why?  RCS systems can merge changes.  A RCS system is not a substitute for
design or programmers communication.  You'll only have a problem if two people
change the same line of code and if they are doing that (and worse: doing that
often) then you have a bigger problem than just the contents of the file. 

Unit tests help being sure that one change doesn't break the project as a
whole and for a big project you're surely going to have a lot of those tests.

If one change breaks another, then there is a disagreement on the application
design and more communication is needed between developers or a better
documentation of the API they're implementing / using. 

 2) Importing and reloading. I want to be able to reload changes without
 exiting the interpreter. This pretty much excludes from foo import *,
 unless you resort to this sort of hack:

 http://www.python.org/search/hypermail/python-1993/0448.html

 Has anyone found a systematic way to solve the problem of reloading in an
 interactive interpreter when using from foo import *?

I don't reload...  When my investigative tests gets bigger I write a script
and run it with the interpreter.  It is easy since my text editor can call
Python on a buffer (I use Emacs). 

 I appreciate any advice I can get from the community.

This is just how I deal with it...  My bigger project has several modules
now each with its own namespace and package.  The API is very documented and
took the most work to get done.

Using setuptools, entrypoints, etc. helps a lot as well. 


The thing is that for big projects your design is the most important part.
Get it right and you won't have problems with namespaces and filenames.  If
you don't dedicate enough time on this task you'll find yourself in trouble
really soon. 

-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedded and extending python 2.5: trouble with __main__ in PyRun_SimpleFileExFlags?

2007-03-04 Thread Carl Douglas
I am going to answer this question myself, but perhaps this will be
useful for someone else.  My original C++ code was fine, the
PyRun_SimpleFile was failing due to errors in my python code.  To get
a console and display the python interpreter errors I allocated a
console, and redirected stdout and stderr:

BOOL APIENTRY DllMain( HMODULE hModule,
   DWORD  ul_reason_for_call,
   LPVOID lpReserved
 )
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
AllocConsole();
fpStdOut = freopen( CONOUT$, wt, stdout);
fpStdErr = freopen( CONOUT$, wt, stderr);
fprintf(stdout, Console opened\n);
Py_Initialize();
init_mymodule(); // SWIG generated method
break;
case DLL_PROCESS_DETACH:
fclose(fpStdErr);
fclose(fpStdOut);
FreeConsole();
Py_Finalize();
break;
//case DLL_THREAD_ATTACH:
//case DLL_THREAD_DETACH:
}
return TRUE;
}

Then, I can show the Python interpreter errors in the console using
PyErr_Print() in my C++ code:

// Display the Open dialog box.
if (GetOpenFileName(ofn)==TRUE)
{
// Thank you:  http://www.ragestorm.net/tutorial?id=21#8
PyObject* PyFileObject = PyFile_FromString(ofn.lpstrFile, r);
if (PyFileObject == NULL)
{
PyErr_Print();
PyErr_Clear();
return false; // Let the user know the error.
}

if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), 
ofn.lpstrFile) == -1)
{
PyErr_Print();
PyErr_Clear();
}

Py_DECREF(PyFileObject);
}



On 2/19/07, Carl Douglas [EMAIL PROTECTED] wrote:
 Hi Python fans,

 I am developing a DLL that is loaded by a host application on windows.
  I'm using python 2.5.

 My DLL uses an embedded python interpreter which can access the host
 application through an API which I have exposed using SWIG 1.3.31.

 Therefore I have both extended and embedded Python at once: the SWIG
 generated code is statically linked into my DLL, and one of the
 functions in my DLL executes PyRun_SimpleFile.

 Using python25_d.dll, I stepped through some python code to understand
 what is happening, and it appears that PyRun_SimpleFile is returning
 -1 because python cannot create the module __main__.

 Here's the code from pythonrun.c:

 int
 PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
 PyCompilerFlags *flags)
 {
 PyObject *m, *d, *v;
 const char *ext;

 m = PyImport_AddModule(__main__);
 if (m == NULL)
 return -1;
 .
 .
 .
 }

 BTW, PyImport_AddModule fails because deeper down a dictionary check fails:

 if (!PyDict_Check(op))
 return NULL;


 Can someone suggest what I need to do to get this to work?

 Here are the relevant lines from my code:

 if (GetOpenFileName(ofn)==TRUE)
 {
 Py_Initialize();
 init_mymodule(); // SWIG generated method

 PyObject* PyFileObject = PyFile_FromString(ofn.lpstrFile, 
 r);

 if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), 
 ofn.lpstrFile)==-1)
 {
 MessageBox(NULL, error running script, Python, 
 MB_ICONERROR);
 }

 Py_DECREF(PyFileObject);

 Py_Finalize();
 }

 Thanks.

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


Re: Alternatives for Extracting EXIF and JPEG Data from Images

2007-03-04 Thread Roger
Max Erickson wrote:
 Roger [EMAIL PROTECTED] wrote:
 
 Does anybody have a pointer to a Python library/utility that will
 extract the chrominance and luminance quantization tables from
 JPG images? 

 I have been using the _getexif method from PIL, which works fine,
 but doesn't extract the quantization data.  I am a bit fuzzy on
 the terminology, but the quantization data  seems to be JPEG data
 rather than EXIF data.  One utility that extracts the
 quantization tables is JPEGsnoop -- there is a link to download
 the utility here: 
http://www.impulseadventure.com/photo/jpeg-quantization.html

 The source code for the above isn't available and may not be
 callable from a Python script even  if it were available.

 Roger

 
 I don't know what the format is, etc, but jpegs I open with PIL have a 
 quantization attribute, e.g:
 
 im.quantization
 {0: array('b', [6, 4, 4, 5, 4, 4, 6, 5, 5, 5, 6, 6, 6, 7, 9, 14, 9, 9, 
 8, 8, 9, 18, 13, 13, 10, 14, 21, 18, 22, 22, 21, 18, 20, 20, 23, 26, 
 33, 28, 
 snip a bunch more numbers
 
 
 max
 

Thank you, I wasn't aware of the quantization method.  I was unable to 
find any documentation for it.

The 0: array() output would appear to be the luminance 8x8 array and the 
1: array() to be the chrominance 8x8 array.  A curiosity is the values 
disagree with the output of the JPEGsnoop utility.  For my Canon 
Powershot S2 IS set to fine, im.quantization yields (after formatting):

{0: array('b', [
1, 1, 1, 2, 1, 1, 2, 2,
2, 2, 3, 2, 2, 3, 3, 6,
4, 3, 3, 3, 3, 7, 5, 8,
4, 6, 8, 8, 10, 9, 8, 7,
11, 8, 10, 14, 13, 11, 10, 10,
12, 10, 8, 8, 11, 16, 12, 12,
13, 15, 15, 15, 15, 9, 11, 16,
17, 15, 14, 17, 13, 14, 14, 14
]),

1: array('b', [
4, 4, 4, 5, 4, 5, 9, 5,
5, 9, 15, 10, 8, 10, 15, 26,
19, 9, 9, 19, 26, 26, 26, 26,
13, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26])}

The JPEGsnoop output for the same jpg file is (pardon the line wrap):

   Precision=0 bits
   Destination ID=0 (Luminance)
 DQT, Row #0:   1   1   1   2   3   6   8  10  AnnexRatio:  16.0 
11.0  10.0   8.0   8.0   6.7   6.4   6.1
 DQT, Row #1:   1   1   2   3   4   8   9   8  AnnexRatio:  12.0 
12.0   7.0   6.3   6.5   7.3   6.7   6.9
 DQT, Row #2:   2   2   2   3   6   8  10   8  AnnexRatio:   7.0 
6.5   8.0   8.0   6.7   7.1   6.9   7.0
 DQT, Row #3:   2   2   3   4   7  12  11   9  AnnexRatio:   7.0 
8.5   7.3   7.3   7.3   7.3   7.3   6.9
 DQT, Row #4:   3   3   8  11  10  16  15  11  AnnexRatio:   6.0 
7.3   4.6   5.1   6.8   6.8   6.9   7.0
 DQT, Row #5:   3   5   8  10  12  15  16  13  AnnexRatio:   8.0 
7.0   6.9   6.4   6.8   6.9   7.1   7.1
 DQT, Row #6:   7  10  11  12  15  17  17  14  AnnexRatio:   7.0 
6.4   7.1   7.3   6.9   7.1   7.1   7.2
 DQT, Row #7:  14  13  13  15  15  14  14  14  AnnexRatio:   5.1 
7.1   7.3   6.5   7.5   7.1   7.4   7.1
 Approx quality factor = 92.96 (scaling=14.08 variance=5.28)
   
   Precision=0 bits
   Destination ID=1 (Chrominance)
 DQT, Row #0:   4   4   5   9  15  26  26  26  AnnexRatio:   4.3 
4.5   4.8   5.2   6.6   3.8   3.8   3.8
 DQT, Row #1:   4   4   5  10  19  26  26  26  AnnexRatio:   4.5 
5.3   5.2   6.6   5.2   3.8   3.8   3.8
 DQT, Row #2:   5   5   8   9  26  26  26  26  AnnexRatio:   4.8 
5.2   7.0  11.0   3.8   3.8   3.8   3.8
 DQT, Row #3:   9  10   9  13  26  26  26  26  AnnexRatio:   5.2 
6.6  11.0   7.6   3.8   3.8   3.8   3.8
 DQT, Row #4:  15  19  26  26  26  26  26  26  AnnexRatio:   6.6 
5.2   3.8   3.8   3.8   3.8   3.8   3.8
 DQT, Row #5:  26  26  26  26  26  26  26  26  AnnexRatio:   3.8 
3.8   3.8   3.8   3.8   3.8   3.8   3.8
 DQT, Row #6:  26  26  26  26  26  26  26  26  AnnexRatio:   3.8 
3.8   3.8   3.8   3.8   3.8   3.8   3.8
 DQT, Row #7:  26  26  26  26  26  26  26  26  AnnexRatio:   3.8 
3.8   3.8   3.8   3.8   3.8   3.8   3.8
 Approx quality factor = 88.24 (scaling=23.52 variance=21.42)

I don't understand the AnnexRatio data JPEGsnoop is adding to each 
row.  Anyone have an explanation on how to translate the im.quantization 
values to the JPEGsnoop values?  Or am I looking at two different types 
of quantization tables?

Roger

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


Re: How use XML parsing tools on this one specific URL?

2007-03-04 Thread Paul McGuire
On Mar 4, 11:42 am, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 I understand that the web is full of ill-formed XHTML web pages but
 this is Microsoft:

 http://moneycentral.msn.com/companyreport?Symbol=BBBY

 I can't validate it and xml.minidom.dom.parseString won't work on it.

 If this was just some teenager's web site I'd move on.  Is there any
 hope avoiding regular expression hacks to extract the data from this
 page?

 Chris

How about a pyparsing hack instead?  With English-readable expression
names and a few comments, I think this is fairly easy to follow.  Also
note the sample statement at then end showing how to use the results
names to access the individual data fields (much easier than indexing
into a 20-element list!).

(You should also verify you are not running afoul of any terms of
service related to the content of this page.)

-- Paul

===
from pyparsing import *
import urllib

# define matching elements
integer = Word(nums).setParseAction(lambda t:int(t[0]))
real = Combine(Word(nums) + Word(.,nums)).setParseAction(lambda
t:float(t[0]))
pct = real + Suppress(%)
date = Combine(Word(nums) + '/' + Word(nums))
tdStart,tdEnd = map(Suppress,makeHTMLTags(td))
dollarUnits = oneOf(Mil Bil)

# stats are one of two patterns - single value or double value stat,
wrapped in HTML td tags
# also, attach parse action to make sure each matches only once
def statPattern(name,label,statExpr=real):
if (isinstance(statExpr,And)):
statExpr.exprs[0] = statExpr.exprs[0].setResultsName(name)
else:
statExpr = statExpr.setResultsName(name)
expr = tdStart + Suppress(label) + tdEnd + tdStart + statExpr +
tdEnd
return expr.setParseAction(OnlyOnce(lambda t:None))

def bistatPattern(name,label,statExpr1=real,statExpr2=real):
expr = (tdStart + Suppress(label) + tdEnd +
tdStart + statExpr1 + tdEnd +
tdStart + statExpr2 + tdEnd).setResultsName(name)
return expr.setParseAction(OnlyOnce(lambda t:None))

stats = [
statPattern(last,Last Price),
statPattern(hi,52 Week High),
statPattern(lo,52 Week Low),
statPattern(vol,Volume, real + Suppress(dollarUnits)),
statPattern(aveDailyVol_13wk,Average Daily Volume (13wk), real
+ Suppress(dollarUnits)),
statPattern(movingAve_50day,50 Day Moving Average),
statPattern(movingAve_200day,200 Day Moving Average),
statPattern(volatility,Volatility (beta)),
bistatPattern(relStrength_last3,Last 3 Months, pct, integer),
bistatPattern(relStrength_last6,Last 6 Months, pct, integer),
bistatPattern(relStrength_last12,Last 12 Months, pct,
integer),
bistatPattern(sales,Sales, real+Suppress(dollarUnits), pct),
bistatPattern(income,Income, real+Suppress(dollarUnits), pct),
bistatPattern(divRate,Dividend Rate, real, pct | NA),
bistatPattern(divYield,Dividend Yield, pct, pct),
statPattern(curQtrEPSest,Qtr(+date+) EPS Estimate),
statPattern(curFyEPSest,FY(+date+) EPS Estimate),
statPattern(curPE,Current P/E),
statPattern(fwdEPSest,FY(+date+) EPS Estimate),
statPattern(fwdPE,Forward P/E),
]

# create overall search pattern - things move faster if we verify that
we are positioned
# at a td tag before going through the MatchFirst group
statSearchPattern = FollowedBy(tdStart) + MatchFirst(stats)

# SETUP IS DONE - now get the HTML source
# read in web page
pg = urllib.urlopen(http://moneycentral.msn.com/companyreport?
Symbol=BBBY)
stockHTML = pg.read()
pg.close()

# extract and merge statistics
ticker =
sum( statSearchPattern.searchString(stockHTML),ParseResults([]) )

# print them out
print ticker.dump()
print ticker.last, ticker.hi,ticker.lo,ticker.vol,ticker.volatility

---
prints:
[39.547, 43.32, 30.922, 2.3599,
2.7402, 40.922, 37.657,
0.72998, 1.5, 55, 15.5, 69, 9.8007, 62,
6.2998, 19.399, 586.25,
27.199, 0.0, 'NA', 0.0, 0.0, 0.78003,
2.1499, 19.399, 2.3901,
18.399]
- aveDailyVol_13wk: 2.74
- curFyEPSest: 2.15
- curPE: 19.4
- curQtrEPSest: 0.78
- divRate: [0.0, 'NA']
- divYield: [0.0, 0.0]
- fwdEPSest: 2.39
- fwdPE: 18.4
- hi: 43.32
- income: [586.25, 27.199]
- last: 39.55
- lo: 30.92
- movingAve_200day: 37.66
- movingAve_50day: 40.92
- relStrength_last12: [9.8007, 62]
- relStrength_last3: [1.5, 55]
- relStrength_last6: [15.5, 69]
- sales: [6.2998, 19.399]
- vol: 2.36
- volatility: 0.73
39.55 43.32 30.92 2.36 0.73

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


Re: How use XML parsing tools on this one specific URL?

2007-03-04 Thread Paul McGuire
P.S. Please send me 1% of all the money you make from your automated-
stock speculation program.  On the other hand, if you lose money with
your program, don't bother sending me a bill.

-- Paul

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


Platform-specific compile flags in setup.py?

2007-03-04 Thread Nikita the Spider
Hi all,
I'm a newbie when it comes to distributing C-based Python modules. I'm 
just now sharing my first with the rest of the world (it's actually V. 
Marangozov's shared memory module for IPC) and I've learned that the 
module needs a different set of compile flags for Linux than for my Mac. 
My question is this: is there a convention or standard that says where 
platform-specific compile flags should reside? I could put them in 
setup.py, OTOH I know that within the .C file I can add something like 
this:
#ifdef __FreeBSD__
#include machine/param.h  /* for system definition of PAGE_SIZE */
#endif

That works, but for maximum Python programmer-friendliness I should 
perhaps put the complexity in setup.py rather than in a .C file.

Opinions appreciated.

PS - The module in question is here; Linux users must remove the tuple 
('HAVE_UNION_SEMUN', None) from setup.py:
http://NikitaTheSpider.com/python/shm/

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Platform-specific compile flags in setup.py?

2007-03-04 Thread Alex Martelli
Nikita the Spider [EMAIL PROTECTED] wrote:

 Hi all,
 I'm a newbie when it comes to distributing C-based Python modules. I'm
 just now sharing my first with the rest of the world (it's actually V.
 Marangozov's shared memory module for IPC) and I've learned that the 
 module needs a different set of compile flags for Linux than for my Mac.
 My question is this: is there a convention or standard that says where
 platform-specific compile flags should reside? I could put them in 
 setup.py,

If you need, specifically, *compile-flags*, then setup.py is a good
place for them (also linker-flags c).


 OTOH I know that within the .C file I can add something like 
 this:
 #ifdef __FreeBSD__
 #include machine/param.h  /* for system definition of PAGE_SIZE */
 #endif

This is NOT a compile-flag -- it's a reasonable C technique, though.


 That works, but for maximum Python programmer-friendliness I should 
 perhaps put the complexity in setup.py rather than in a .C file.
 
 Opinions appreciated.

My opinion: flags in setup.py, conditional includes (c) in the .c or .h
file[s].

If you can do something either way: if you know platform X will ALWAYS
want that something, hard-code it in the .c or .h; if you want to make
it easier to change for Python programmers, then put it in the setup.py.


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


Re: Alternatives for Extracting EXIF and JPEG Data from Images

2007-03-04 Thread Terry Reedy

Roger [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| Max Erickson wrote:
|  I don't know what the format is, etc, but jpegs I open with PIL have a
|  quantization attribute, e.g:
| 
|  im.quantization

| Thank you, I wasn't aware of the quantization method.  I was unable to
| find any documentation for it.

The builtin dir(ob) function returns a list of attributes of ob.  Great for 
discovering things that are not documented.

tjr



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


Re: list-like behaviour of etree.Element

2007-03-04 Thread Terry Reedy

Daniel Nogradi [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| The etree.Element (or ElementTree.Element) supports a number of
| list-like methods: append, insert, remove. Any special reason why it
| doesn't support pop and extend (and maybe count)?

I think you should turn the question around: why should such be added?
I imagine that the author wrote the methods he and his users thought 
necessary.
Anything more has various costs.

tjr



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


Python stock market analysis tools?

2007-03-04 Thread Mudcat
I have done a bit of searching and can't seem to find a stock market
tool written in Python that is active. Anybody know of any? I'm trying
not to re-create the wheel here.

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


Re: Python stock market analysis tools?

2007-03-04 Thread Raymond Hettinger
On Mar 4, 7:52 pm, Mudcat [EMAIL PROTECTED] wrote:
 I have done a bit of searching and can't seem to find a stock market
 tool written in Python that is active. Anybody know of any? I'm trying
 not to re-create the wheel here.

What kind of tool do you want?  Getting quotes is the easy part:

import urllib
symbols = 'ibm jpm msft nok'.split()
quotes = urllib.urlopen( 'http://finance.yahoo.com/d/quotes.csv?s=' +
 '+'.join(symbols) + 'f=l1e=.csv').read().split()
print dict(zip(symbols, quotes))

The hard part is raising capital and deciding what to buy, sell, or
hold.


Raymond

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


Squisher -- a lightweight, self-contained alternative to eggs?

2007-03-04 Thread Adam Atlas
I wrote this little program called Squisher that takes a ZIP file
containing Python modules and generates a totally self-contained .pyc
file that imports a specified module therein. (Conveniently, Python's
bytecode parser ignores anything after an end marker, and the
zipimport mechanism skips any non-ZIP data at the beginning of a
file!) For example, say you have a directory called 'foo', which
contains an __init__.py, which contains print 'hello'; x = 123, and
a thing.py, which contains y = 456. If you make a ZIP archive of
this and run it through Squisher, you'll get a single .pyc file which
can be imported by any Python installation anywhere just like any
other module, without requiring users to install any supporting
mechanisms (like setuptools), and giving all the flexibility and
stability of zipimport. In other words, you can do this simply by
dropping the foo.pyc file into a directory:

 import foo
hello
 foo.x
123
 from foo.thing import y
 y
456

Of course, this is a stupid and useless example, but you can do it
with any package you could use as an egg, yet without requiring people
to install setuptools (or any other external glue) to use it. I've
tested it with several large packages, including SQLAlchemy.

Right now I'm just testing and polishing up the code... in the
meantime, any comments?

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


package_data question

2007-03-04 Thread bytecolor
I have a simple package. I'm trying to add an examples subdirectory
with distutils. I'm using Python 2.4 on Linux. My file layout and
setup.py can be found here:

http://www.deadbeefbabe.org/paste/3870

I've tried using data_files as well, with the same result; examples/
fig2.3.apt is not added to the tarball.

--
bytecolor

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


Descriptor/Decorator challenge

2007-03-04 Thread Raymond Hettinger
I had an idea but no time to think it through.
Perhaps the under-under name mangling trick
can be replaced (in Py3.0) with a suitably designed decorator.
Your challenge is to write the decorator.
Any trick in the book (metaclasses, descriptors, etc) is fair game.


Raymond

 how we currently localize method access with name mangling
--
class A:
def __m(self):
print 'A.__m'
def am(self):
self.__m()

class B(A):
def __m(self):
print 'B.__m'
def bm(self):
self.__m()

m = B()
m.am() # prints 'A.__m'
m.bm() # prints 'B.__m'


 how I would like to localize method access with a decorator
--
class A:
@localmethod
def m(self):
print 'A.m'
def am(self):
self.m()

class B(A):
@localmethod
def m(self):
print 'B.m'
def bm(self):
self.m()

m = B()
m.am() # prints 'A.m'
m.bm() # prints 'B.m'

-

P.S. Here's a link to the descriptor how-to:
http://users.rcn.com/python/download/Descriptor.htm

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


  1   2   >