Re: A critique of cgi.escape

2006-09-27 Thread Georg Brandl
Anthony Baxter wrote:
>> I would really rather this were a discussion than an argument. You will
>> now no doubt reply telling me I wouldn't.
>>
>> My posting was issued as a response to the irritation engendered by your
>> argumentative style of debate. Your latest response simply proves that
>> there is indeed no remark, however irrelevant, that you will allow to go
>> unanswered.
> 
> The Complaints department is down the hall...

Though some discussion participants seemingly want to stay for more
being-hit-on-the-head lessons ;)

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


Re: does anybody earn a living programming in python?

2006-09-27 Thread wesley chun
> From: "OKB (not okblacke)" <[EMAIL PROTECTED]>
> Date: Wed, 27 Sep 2006 04:04:02 GMT
>
>> - at yahoo, we developed yahoo!mail in python (and some C++)
>> - at synarc, i wrote software for doctors in python (and some C)
>> - at ironport, most everything is in python (and some C, PyRex)
>
>   This is interesting to me in that all these jobs also involve C.
> I'm not the original poster, but I'd be interested to hear about people
> who make a living programming Python WITHOUT knowing C.


you make a good point, however, when you have to write an extension
(performance, protect source code, library interface, etc.), you must
write it in the natively-supported language in which the
implementation of Python you're using is compiled in. for (C)Python,
it's C/C++, Java for Jython, and C#/VB.NET for IronPython.

if you have been successful at building projects completely in pure
Python, that's great, but you're limited in that you won't be able to
take advantage of the benefits of extensions or necessarily be able to
hook up to native libraries that don't already have a Python adapter
written for them. for the past employment i listed, the primary use of
C was either an extension or a library adapter. of course, i never
claimed above to have written any of that C code. ;-)

my final thought is that you cannot truly appreciate a tool like
Python until you've been in the trenches with C and done all that
stuff that is now a "waste of time."

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Makin search on the other site and getting data and writing in xml

2006-09-27 Thread Ben Finney
Steve Holden <[EMAIL PROTECTED]> writes:

> Lawrence D'Oliveiro wrote:
> > Steve Holden wrote:
> >>The fact remains that Google can chop your searching ability off
> >>at the knees ...
> > No they can't. They can only chop off your ability to use Google.
> > 
> [sigh]. Right, Lawrence, sorry I wasn't quite explicit enough for you.

Seems like a fairly important distinction. Google has the power to
"chop your searching ability off at the knees" only to the extent that
you grant them that power.

-- 
 \  "[...] a Microsoft Certified System Engineer is to information |
  `\ technology as a McDonalds Certified Food Specialist is to the |
_o__)culinary arts."  -- Michael Bacarella |
Ben Finney

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


Python Lead / Developers required for a Telecom Company, Hyderabad

2006-09-27 Thread hrnetindia
World's No:1 Telecom Product Development (Billing Settlement) 
company urgently requires the following:

Position: Team Lead / Software Engineer

Skills:
Essential: Python
Other: Perl / XML / J2ME

Experinece: 2-5 years of experience using Python. 

Location: Hyderabad, India

Please mail the CV to [EMAIL PROTECTED]

Thanks
HR Net Consultants Pvt .Ltd.
# 405 Amough Plaza ,Beside ITC Kakatiya Hotel
Begumpet,Hyderabad 500016,AP,India 
Tel :91+40-66756565 ( 4 lines)
www.hrnetindia.com





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


Re: One program in different GUI Toolkits

2006-09-27 Thread Franz Steinhaeusler
On Wed, 20 Sep 2006 08:27:30 +0200 (CEST), Franz Steinhaeusler
<[EMAIL PROTECTED]> wrote:

>Hello NG,
>
>I have a suggestion.
>
>For simplifying learning or switching between different GUI
>Toolkits, I could imagine to have one short clearly presented
>program in different GUI Toolkits.
>
>What about for example wxProject?
>
>http://wiki.wxpython.org/index.cgi/WxProject 
>or some other suggestion to take as base program.
>(could contain menus, buttons, listboxes, dialogs, ...)
>
>I would be very interested how it would looks in:
>wxPython
>pyGtk
>pyQt
>TkInter
>
>
>Maybe in:
>Wax
>PythonCard
>PyFLTK
>...
>
>
>Anybody is interested in implementing in one other GUI?
>We could put in on one Python wiki page for example.
>
>Many thanks in advance!

Hello all,

thank you for your replies.

Hmm, ideally the program is short and a little useful,
to that I agree.

What about a small text editor using the scintilla control?
It should be available for Pythoncard, wxPython, pygtk and pyQt
(qtscintilla).
With a small find dialog, open, save should be enough for the beginning.

Other suggestions?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critique of cgi.escape

2006-09-27 Thread Ben Finney
Georg Brandl <[EMAIL PROTECTED]> writes:

> Anthony Baxter wrote:
> >> I would really rather this were a discussion than an
> >> argument. You will now no doubt reply telling me I wouldn't.
> > The Complaints department is down the hall...
>
> Though some discussion participants seemingly want to stay for more
> being-hit-on-the-head lessons ;)

No no, hold your head like this, and then go "waaagh". Try it again.

-- 
 \   "It is seldom that liberty of any kind is lost all at once."  |
  `\ -- David Hume |
_o__)  |
Ben Finney

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


Battlefield Weapon Popularity Trend (was: Computer Language Popularity Trend)

2006-09-27 Thread Mirco Wahab
Thus spoke Xah Lee (on 2006-09-27 05:03):

> This page gives a visual report of computer languages's 
> popularity, as indicated by their traffic level in newsgroups. 
> ...
> http://xahlee.org/lang_traf/index.html

When the Samurai of medieval Japan were confronted
with new 'battlefield language', e.g. early Shotguns,
they resisted because one could push any peasant
behind a gun -- thus nullifying the result of
the Samurai Art of Warfare that required a life
full of learning - in the end wiping out a
complete culture.

Same trend here - the reason is: 'cost' ;-)


Regards & scnr

Mirco

f'up: clpm, clp


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


Python website bug: Wrong URL in http://www.python.org/download/releases/2.5/highlights/

2006-09-27 Thread Anand
The URL which links to "Whats New in Python 2.5" in the following text
is wrong.

"Here are some of the (subjective) highlights of Python 2.5. More
detail on almost all of the new features can be found in the document
What's New In Python 2.5"

It links to http://docs.python.org/dev/whatsnew/ whereas it should
point to http://docs.python.org/whatsnew/whatsnew25.html instead.

I tried to report the bug in python.org using
http://wiki.python.org/moin/PythonWebsiteCreatingNewTickets but since I
dont have a Trac login there, I am reporting it here. Python.org
webmaster, please consider this a bug report.

Thanks

-Anand

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


Re: QuoteSQL

2006-09-27 Thread Duncan Booth
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

> def EscapeSQLWild(Str) :
> """escapes MySQL pattern wildcards in Str."""
> Result = []
> for Ch in str(Str) :
> if Ch == "%" or Ch == "_" :
> Result.append("\\")
> #end if
> Result.append(Ch)
> #end for
> return "".join(Result)
> #end EscapeSQLWild

That doesn't quite work. If you want to stop wildcards being interpreted as 
such in a string used as a parameter to a query, then you have to escape 
the escape character as well. In a LIKE clause, backslash percent matches a 
percent character, but double backslash matches a single backslash and 
double backslash percent matches a backslash followed by anything.

I think this version should work, (or rewrite it as a 'for' loop if you 
prefer, though I think the replace version is clearer as well as being 
between 3 and 222 times faster on the inputs I tried):

def EscapeSQLWild(s):
   s = s.replace('\\', '')
   s = s.replace('%', '\\%')
   s = s.replace('_', '\\_')
   return s

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


RE: Starting Win32 Service

2006-09-27 Thread Tim Golden
[placid]
| Using Tim Golden's wmi module you can get the service names
| 
| import wmi
| c = wmi.WMI ()
| stopped_services = c.Win32_Service (StartMode="Auto", State="Stopped")
| if stopped_services:
|   for s in stopped_services:
| print s.Caption, "service is not running"
| else:
|   print "No auto services stopped"
|
| but how do i start services that are stopped?


import wmi
c = wmi.WMI ()
for method in c.Win32_Service._methods:
  print method

#
#... includes StartService
#

print c.Win32_Service.StartService

#  (ReturnValue)>

#
# Therefore, to start all non-running auto services (!)
#
for service in c.Win32_Service (StartMode="Auto", State="Stopped"):
  print service.Caption
  service.StartService ()



TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: AN Intorduction to Tkinter

2006-09-27 Thread Mikael Olofsson
The following is the answer I gave on [EMAIL PROTECTED] Perhaps Fredrik can 
elaborate on the status of different versions of his excellent publication.


Tanner Ruschman wrote about "An Introduction to Tkinter" by Fredrik Lundh:

> > When I saw that it was written 
> > (actually, copyrighted) in 1999, I figured that a new(er) version of 
> > Tkinter had come out since then, changing how some of the code examples 
> > work.
> >
> > Does anybody know of a guide as comprehensive as this, but written for 
> > one of the more recent Tkinter modules?
>   

You probably mean

http://www.pythonware.com/library/tkinter/introduction/

which is copyrighted 1999. There is also

http://effbot.org/tkinterbook/

which I think is the most recent version of it. It states that it is 
last updated in November 2005.

HTH
/Mikael Olofsson

Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: A critique of cgi.escape

2006-09-27 Thread Brian Quinlan
John Bokma wrote:
>> Why cgi.escape should NOT be changed:
>> o it is current used in lots of code and changing it will almost
>>certainly break some of it, test suites at minimum e.g.
>>assert my_template_system("{foo}", foo='"') == '"'
> 
> You must be kidding.

Nope. How do you write your templating system unit tests?

>> o escaping attribute values is less common than escaping element
>>text
> 
> Again, you must be kidding: href="/search.cgi?query=3&results=10"
> 

Actually, I wasn't kidding. I was basing this belief on greping through 
the Python standard library where only the quote=None form is ever used. 
It also matches my experience. But I don't have a large enough sample to 
make any claim either way.

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


Re: Running Python script from C++ code(.NET)

2006-09-27 Thread Gerard Flanagan

volcano wrote:

> volcano wrote:
> > Hello, folks!
> > A trivial question - I have a working Python script that I have to
> > invoke from C++ code. No fancy stuff - just run the whole script with
> > its parameters. No callbacks, no signalling - nada, just
> > stupid,primitive, straightforward call.
> >
> > And while there is a lot of help on embedding, I could not find out how
> > to run script as a whole.SOS
>
> Thanks a lot to all of you who cared to answer! Eventually it was
> "::CreateProcess", and it works!
>

I used to find http://pinvoke.net a good resource when I was doing
Active Directory stuff.  Just for interest's sake, cutting and pasting
from the CreateProcess page, the following arcana will start Python (
again from C#, but here you can see the internals at least):

using System;
using System.Runtime.InteropServices;

class Class1
{
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct STARTUPINFO
{
Int32 cb;
string lpReserved;
string lpDesktop;
string lpTitle;
Int32 dwX;
Int32 dwY;
Int32 dwXSize;
Int32 dwYSize;
Int32 dwXCountChars;
Int32 dwYCountChars;
Int32 dwFillAttribute;
Int32 dwFlags;
Int16 wShowWindow;
Int16 cbReserved2;
IntPtr lpReserved2;
IntPtr hStdInput;
IntPtr hStdOutput;
IntPtr hStdError;
}

[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}

[DllImport("kernel32.dll")]
public static extern bool CreateProcess(string lpApplicationName,
string lpCommandLine, ref SECURITY_ATTRIBUTES 
lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool 
bInheritHandles,
uint dwCreationFlags, IntPtr lpEnvironment, string
lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);

[STAThread]
static void Main(string[] args)
{
const uint NORMAL_PRIORITY_CLASS = 0x0020;

bool retValue;
string Application = @"c:\python\python24\python.exe";
string CommandLine = "";
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
pSec.nLength = Marshal.SizeOf(pSec);
tSec.nLength = Marshal.SizeOf(tSec);

retValue = CreateProcess(Application,CommandLine,
ref pSec,ref tSec,false,NORMAL_PRIORITY_CLASS,
IntPtr.Zero,null,ref sInfo,out pInfo);

}
}

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


Re: ruby %w equivalent

2006-09-27 Thread Nick Craig-Wood
MonkeeSage <[EMAIL PROTECTED]> wrote:
>  In ruby there are several special literal notations, just like python.
>  In ruby it goes like this:
> 
>  %{blah} / %Q{blah} # same as "blah" but igornes " and '
>  %q{blah} # same as 'blah' but no interpolation
>  %w{blah blah} # same as "blah blah".split
>  %r{blah} # same as /blah/
>  %x{ls} # same as `ls`

These are snatched straight from perl.  In perl they are spelt
slightly differently

  q{blah}   r"""blah""" # not identical but similar
  qq{blah}  """blah"""  # no interpolation in python so no direct concept
  qw{blah blah} "blah blah".split()
  qr{blah}  re.compile(r"blah")
  qx{ls}commands.getoutput("ls")

In perl (and maybe in ruby I don't know) the { } can be replaced with
any two identical chars, or the matching pair if bracketty, so q/blah/
or q(blah).

As a perl refugee, the only one I miss at all is qw{}, ie %w{} in ruby
the subject of this post.

In python when making __slots__ or module.__all__ you end up typing
lists of objects or methods and they turn out like this which is quite
a lot of extra typing

  __slots__ = ["method1", "method2", "method3", "method4", "method5"]

You can of course write it like this

  __slots__ = "method1 method2 method3 method4 method5".split()

which is nearly as neat as qw//, but not quite since the split() bit
comes at the end so it doesn't notify you that you have an array of
strings rather than a string.

I don't expect a replacement for %w{}, qw// to ever be added to
python, it is not the python way.  And the python way is why I am now
a python programmer not a perl programmer!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's up with site.Quitter?

2006-09-27 Thread Georg Brandl
James Stroud wrote:
> Hello All,
> 
> Still jubilantly configuring my work environment for python 2.5, I came 
> accross a curiosity when writing an automatic vim syntax file creator 
> (so I can automatically update my syntax coloring with future python 
> releases).
> 
> It seems I can find a reference to just about every type except those 
> for "exit" and "quit" in the standard library somewhere. E.g.:
> 
> py> type(__builtins__.Ellipsis) is types.EllipsisType
> True
> 
> However, in an appearant break with consistency, this can not be done 
> for "exit" and "quit" because site.Quitter is nested inside of the 
> setquit() function in the site.py module.
> 
> Would moving this class definition to module level be something that 
> would meet with great resistance?

Not really, but what would you do with it? It's an internal object used
for only exit() and quit(), and of no real use elsewhere.

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


Re: Running Python script from C++ code(.NET)

2006-09-27 Thread Gerard Flanagan

volcano wrote:

> volcano wrote:
> > Hello, folks!
> > A trivial question - I have a working Python script that I have to
> > invoke from C++ code. No fancy stuff - just run the whole script with
> > its parameters. No callbacks, no signalling - nada, just
> > stupid,primitive, straightforward call.
> >
> > And while there is a lot of help on embedding, I could not find out how
> > to run script as a whole.SOS
>
> Thanks a lot to all of you who cared to answer! Eventually it was
> "::CreateProcess", and it works!
>

I used to find http://pinvoke.net a good resource when I was doing
Active Directory stuff.  Just for interest's sake, cutting and pasting
from the CreateProcess page, the following arcana will start Python (
again from C#, but here you can see the internals at least):

using System;
using System.Runtime.InteropServices;

class Class1
{
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct STARTUPINFO
{
Int32 cb;
string lpReserved;
string lpDesktop;
string lpTitle;
Int32 dwX;
Int32 dwY;
Int32 dwXSize;
Int32 dwYSize;
Int32 dwXCountChars;
Int32 dwYCountChars;
Int32 dwFillAttribute;
Int32 dwFlags;
Int16 wShowWindow;
Int16 cbReserved2;
IntPtr lpReserved2;
IntPtr hStdInput;
IntPtr hStdOutput;
IntPtr hStdError;
}

[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}

[DllImport("kernel32.dll")]
public static extern bool CreateProcess(string lpApplicationName,
string lpCommandLine, ref SECURITY_ATTRIBUTES 
lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool 
bInheritHandles,
uint dwCreationFlags, IntPtr lpEnvironment, string
lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);

[STAThread]
static void Main(string[] args)
{
const uint NORMAL_PRIORITY_CLASS = 0x0020;

bool retValue;
string Application = @"c:\python\python24\python.exe";
string CommandLine = "";
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
pSec.nLength = Marshal.SizeOf(pSec);
tSec.nLength = Marshal.SizeOf(tSec);

retValue = CreateProcess(Application,CommandLine,
ref pSec,ref tSec,false,NORMAL_PRIORITY_CLASS,
IntPtr.Zero,null,ref sInfo,out pInfo);

}
}

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


What's the best way to communicate between processes?

2006-09-27 Thread awmcclain . nospam
Here's my situation:

I'm writing a simple reminder bot which will IM me based on input from
a web server. Right now, I have a simple AIM bot written using twisted
2 words. It logs into AIM and can send/receive messages. There's part
1.

I have a django server running under mod_python through apache, which
is my web server. Part 2.

How do I get part 2 to talk to part 1?? Ideally I'd like to fire off a
(signal/message/data) from mod_python to a separate process running the
twisted AIM bot, so that the mod_python thread(s) can just forget about
the whole thing and let someone else deal with talking with AIM.

I can't really just include the twisted AIM bot from django, because
mod_python (as I understand it) runs different requests on different
threads, and I don't want to spawn a bot and log into IM each request.
I can't run the whole thing through twisted, either.

I'm thinking about coding some sort of 'local notify server' in twisted
(basically just listening to a socket and then passing the information
to the IM bot), then connecting to it via a python socket in django and
passing some serialized/pickled data. I worry about two requests
connecting to the 'notify server' at once, though, because i *cannot*
hang my web server.

Thoughts? Is there a better solution? Is there a simpler way to do this
(a way with built-in serialization?)

Thanks for any help.

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


Re: odbc DbiDate date conversion

2006-09-27 Thread Frank Millman

flupke wrote:
> Frank Millman schreef:
> 
>
> > Well waddyaknow - I get exactly the same, for dates earlier than
> > 1970-01-02. Thanks for finding a bug that would have bitten me sooner
> > or later.
> >
> > I will do some investigation. If I find an answer I will post it here,
> > unless some kind soul saves me the trouble and beats me to it.
> >
> > Frank
> >
>
> Thanks for investigating it so far Frank.
>
> Is there a workaround to parse that date and get the date info that i want?
>

Not that I know of. The results of my investigations so far seem to
indicate that we have a problem :-(

Here is a link to an article dated 1998 -
https://svn.python.org/www/trunk/pydotorg/windows/OdbcHints.html

Among other interesting stuff, it states -

"Notice that result values are converted to Python objects. Dates in
particular are returned as dbiDate objects. This can be a serious
limitation, because dbiDate can not represent dates prior to the UNIX
epoch (1 Jan 1970 00:00:00 GMT). If you try to retrieve earlier dates,
you'll get garbage and may even provoke a crash."

I contacted Mark Hammond, author of the win32 extensions, to ask if
there was a solution and particularly to suggest a modification to
return a datetime.datetime object. This was his reply -

"I'd be happy with an option to use the datetime module - maybe it
could even be on the cursor?  However, I wont have time to do this in
the short term.
You could consider using ADO via win32com too..."

It looks as if we will have to use ADO for now. There is an 'adodbapi'
module available which is DB-API 2.0 compliant -
adodbapi.sourceforge.net. I will give it a try.

Frank

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


Re: Python website bug: Wrong URL in http://www.python.org/download/releases/2.5/highlights/

2006-09-27 Thread Steve Holden
Anand wrote:
> The URL which links to "Whats New in Python 2.5" in the following text
> is wrong.
> 
> "Here are some of the (subjective) highlights of Python 2.5. More
> detail on almost all of the new features can be found in the document
> What's New In Python 2.5"
> 
> It links to http://docs.python.org/dev/whatsnew/ whereas it should
> point to http://docs.python.org/whatsnew/whatsnew25.html instead.
> 
> I tried to report the bug in python.org using
> http://wiki.python.org/moin/PythonWebsiteCreatingNewTickets but since I
> dont have a Trac login there, I am reporting it here. Python.org
> webmaster, please consider this a bug report.
> 
See the Cc: address on this post? That's probably a much more effective 
way to communicate with the python.org webmasters. Relying on them to 
read a hgh-noise newsgroup like c.l.py is asking to be ignored.

Thanks for taking the time to try and keep the web site up to date.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Antoon Pardon wrote:

> I need this Top value in
> a context where it can be used as a start or stop value
> in a slice.

But the only valid values allowed for indices are 0 up to the length of the
array inclusive. Larger integers are not allowed, so why should Top be
allowed?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Makin search on the other site and getting data and writing in xml

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Ben Finney
wrote:

> Steve Holden <[EMAIL PROTECTED]> writes:
> 
>> Lawrence D'Oliveiro wrote:
>> > Steve Holden wrote:
>> >>The fact remains that Google can chop your searching ability off
>> >>at the knees ...
>> > No they can't. They can only chop off your ability to use Google.
>> > 
>> [sigh]. Right, Lawrence, sorry I wasn't quite explicit enough for you.
> 
> Seems like a fairly important distinction. Google has the power to
> "chop your searching ability off at the knees" only to the extent that
> you grant them that power.

Saying "search" when you mean "Google" is like saying "using a PC" when you
mean "using Microsoft Windows".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: QuoteSQL

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Duncan Booth wrote:

> Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> 
>> def EscapeSQLWild(Str) :
>> """escapes MySQL pattern wildcards in Str."""
>> Result = []
>> for Ch in str(Str) :
>> if Ch == "%" or Ch == "_" :
>> Result.append("\\")
>> #end if
>> Result.append(Ch)
>> #end for
>> return "".join(Result)
>> #end EscapeSQLWild
> 
> That doesn't quite work. If you want to stop wildcards being interpreted
> as such in a string used as a parameter to a query, then you have to
> escape the escape character as well.

That's part of the separation of function. Note that the above function does
not generate a MySQL string literal: you must still put it through the
previously-defined SQLString routine, which will automatically escape all
the specials added by EscapeSQLWild.

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


Re: ruby %w equivalent

2006-09-27 Thread Duncan Booth
Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

> In python when making __slots__ or module.__all__ you end up typing
> lists of objects or methods and they turn out like this which is quite
> a lot of extra typing
> 
>   __slots__ = ["method1", "method2", "method3", "method4", "method5"]
> 
> 

For __all__ you can use a decorator to avoid retyping the function name at 
all. e.g.

def public(f):
all = f.func_globals.setdefault('__all__', [])
all.append(f.__name__)
return f

@public
def foo(): pass

I don't use __slots__ much at all, and if you'd said "attribute1" etc. I'd 
have understood, but I'm really curious why would you be listing any 
methods in __slots__?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Battlefield Weapon Popularity Trend (was: Computer Language Popularity Trend)

2006-09-27 Thread Ramon Diaz-Uriarte
On 9/27/06, Mirco Wahab <[EMAIL PROTECTED]> wrote:
> Thus spoke Xah Lee (on 2006-09-27 05:03):
>
> > This page gives a visual report of computer languages's
> > popularity, as indicated by their traffic level in newsgroups.
> > ...
> > http://xahlee.org/lang_traf/index.html
>
> When the Samurai of medieval Japan were confronted
> with new 'battlefield language', e.g. early Shotguns,
> they resisted because one could push any peasant

shouldn't this be "they [the Samurai] did not resist"?

> behind a gun -- thus nullifying the result of
> the Samurai Art of Warfare that required a life
> full of learning - in the end wiping out a
> complete culture.
>
> Same trend here - the reason is: 'cost' ;-)
>
>
> Regards & scnr
>
> Mirco
>
> f'up: clpm, clp
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Ramon Diaz-Uriarte
Bioinformatics Unit
Spanish National Cancer Centre (CNIO)
http://ligarto.org/rdiaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: does anybody earn a living programming in python?

2006-09-27 Thread Simon Brunning
On 26 Sep 2006 13:43:24 -0700, Fuzzyman <[EMAIL PROTECTED]> wrote:
> Simon Brunning is a Pythonista in his spare time but uses
> Java at work. He has got Jython fairly deeply embedded though.

Sure do. We also use Python for a lot of internal tools, the most
complex probably being a fairly extensive code generator. (If you
think you need to generate Python, you are almost certainly taking the
wrong approach, but Java is repetitive, static, verbose and just plain
hideous enough that code generation can be a good solution.)

-- 
Cheers,
Simon B,
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread John Machin

Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Antoon Pardon wrote:
>
> > I need this Top value in
> > a context where it can be used as a start or stop value
> > in a slice.
>
> But the only valid values allowed for indices are 0 up to the length of the
> array inclusive. Larger integers are not allowed, so why should Top be
> allowed?

Larger integers are not allowed as subscripts, but slicing is more
tolerant:

| >>> array = ['a', 'b', 'c']
| >>> array[:1]
| ['a']
| >>> array[:2]
| ['a', 'b']
| >>> array[:3]
| ['a', 'b', 'c']
| >>> array[:4]
| ['a', 'b', 'c']
| >>> array[:987654321]
| ['a', 'b', 'c']

BTW, negative subscripts are allowed, too; see e.g.
http://docs.python.org/tut/node5.html#SECTION00514

HTH,
John

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


Re: R.S.I. solutions?

2006-09-27 Thread Eric S. Johansson
Nick Craig-Wood wrote:
> This is excellent advice... I was diagnosed with tendonitis over 5
> years ago now.  I found the medical people generally hopeless, but the
> physios really know their stuff (this is in the UK also).

some know their stuff but a vast majority of them are humming because 
they don't know the words.

12 years ago, I went through a whole bunch of doctors including 
physiotherapist etc. and they all just kind of said "sucks to be you". 
Now, after having been stable for 10 years, the pain is getting worse 
again.  This time the nerve conduction studies show compression and it's 
off to the neurologist I go.  I expect a second round of "sucks to be you"

Now the list of things he suggested are basically sound but only work 
for a small proportion of people injured.  This is the real big 
indicator that the medics don't know what they're doing or even have a 
vague understanding of the problem.  We would get just as good a result 
if we gave people tonics and told them to stay out of the miasmic vapors 
of the lowlands.



> 2) Get your workplace right! chair height, screen height, distance to
> keyboard etc.  The physio can advise here.

it is exceptionally difficult to do this yourself even if you are 
well-educated.  The reason being is that you need somebody else from the 
outside to look at how you are sitting.  You also need someone to visit 
and evaluate your workspace.
> 
> 3) The physio recommended a rolled up towel as a wrist rest - for me
> that is just the thing.  It is large and soft.

my problem is a different one.  Most keyboards are to narrow for me.  If 
you have the classic IT profile (i.e. spare tire), your elbows will be 
pushed out and your hands will want to form a / \ position to the 
keyboard and as a result, you will twist your wrists outward to make 
them parallel so you can easily get the keys.

I have seen even normal weight large men have problems with keyboard 
width.  The only people who haven't had problems are typically women 
under 130 pounds.  It would be really nice to find a keyboard with a 
wide center space and no keypad.

The other thing to pay attention to are the keys themselves.  Many 
keyboards today are garbage.  Cheap ( but not necessarily inexpensive) 
keyboards including the Microsoft natural, have sticky keys that make 
you use too much pressure in order to get a keystroke and then 
frequently you will bottom out with a sharp shock.  At any one time, out 
of a selection of 30 or 40 different keyboards I might find one with 
acceptable keys.

What's really strange is that most people think laptop keyboards are 
horrible but I absolutely love the ones I've had from Dell and Acer 
laptops.  the Acer one is truly remarkable because the keyboard is 
arranged in a smiling face which accommodates my greater width without 
being obnoxiously wide.  If only they would put that on a desktop 
keyboard, I would be very happy.  In terms of key pressure, that's also 
wonderful.  It's lightweight and I barely have to touch them.  IMO, it's 
a win.

> 4) I swapped my mouse usage to the left hand (my right hand was
> worse).  It took a few months to get used to but it feels totally
> natural now.  I can now mouse with both hands just fine.

I'm currently using a trackball although the best input device for me 
has been a tablet with pen.  I do wish the pen was fatter and cushier 
but that's something you can do to using some foam if there's some way 
to keep the pen side buttons available.  see wacom for the 4 x 6 
tablets.  Be aware however that a pen costs almost half a tablet and are 
only available over the mat so that when a pen breaks, it is frequently 
cheaper/easier to throw a tablet away and buy a new one than it is to 
replace the pen.

> RSI is a complicated disease - there are lots of different forms of it
> all caused by different things.  You'll need some professional advice
> to sort it out.

and lots of whom don't know what they are doing.  you will be pushed in 
different directions and the only thing I will say to stay away from is 
surgery.  Especially for ulnar nerve transposition.  I do not know a 
single person that that has helped investing lots of people with scars 
all over their arms and neck from surgeons mucking about with nerves 
like they were Dr. Frankenstein creating new life.

the rule of thumb is: try anything you want but stay away from anything 
you can't go back and get seconds.

which reminds me.  It's incredibly easy to gain weight at the best of 
time for geeks like us.  If you are hurting, in lots of pain, and 
feeling very isolated, it's really easy to gain even more weight if you 
seek solace in food.  It's hard but try to resist.  Gaining weight will 
make the symptoms worse but losing the weight afterwards won't always 
make you feel better.

Do what you can with the parts of your body that aren't hurting.  Go 
walking, put together the money for a recumbent bicycle (under seat 
steering is a godsend if you like 

Status of Router on webpage

2006-09-27 Thread Hostílio Thumbo




Hi,

Anyone can help me to create this small system.
I have more than 50 Cisco Routers on my network, and I am trying to
display the status of them on a webpage.
I want to display the status of the router on the following link
http://www.x.com/test.html

1. When the serial is "up", "with line protocol
up"does not display anything on webpage.

2. When the serial is "up" with "line protocol
down", must display on webpage:

__
ipofrouter (nameofrouter)

Serial x is up, line protocol is down   |   
descriptionoftherouter   |   Failed:  timeoffailed  dateoffailed
__

eg.
_
192.168.10.4 (FR-Brazil)
--
Serial 2/4:3 is up, line protocol is down   |  
BRAZIL_ATM_CA158587894_128k  |   Failed: 06:30 2006-09-08
_

3. When the serial is "up"
with "line protocol down -looped-", must display on webpage:

__
ipofrouter (nameofrouter)
--
Serial x is up, line protocol is down  -looped-   |   
descriptionoftherouter   |   Failed:  timeoffailed  dateoffailed
__


4. When the serial is  "down" with "line protocol
down",must display on webpage: 

_
ipofrouter (nameofrouter)

Serial x is down, line protocol is down    |   
descriptionoftherouter   |   Failed:  timeoffailed  dateoffailed
_



Regards.


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

a query on sorting

2006-09-27 Thread Satya Upadhya
Dear Friends,I am having a few issues with respect to sorting using python. I am usingPython 2.4.3 Win32 (IDLE 1.1.3).>>> x = [2,6,4]>>> x.sort()>>> x[2, 4, 6]>>> x = [2,6,4]>>> y = []>>> y = x.sort()>>> y>>> print yNoneSo the problem essentially is that i am unable to store the sortedelements of list x into an empty list y in a straightforward manner. I canget around this, of course, using the following:>>> x = [2,6,4]>>> x.sort()>>> x[2, 4, 6]>>> y = []>>> for i in x:y.append(i)>>> y[2, 4, 6]But this seems a little less succinct then one would expect from python.Also, consider the sorting of the indices of a sorted list. Consider thefollowing code:>>> x = [2,6,4]>>> import operator>>> sortedindices = sorted(range(len(x)), key = x.__getitem__)>>> print sortedindices[0, 2, 1]>>> x.sort()>>> x[2, 4, 6]>>>x (x = [2,6,4] originally) is the original list, and its indices are0,1,2. If you sort x, then x becomes [2,4,6] and the the list of thesorted
 indices becomes [0,2,1] since the 4 (which originally correspondsto index 2) has now shifted to a position corresponding to index 1 andlikewise for element 6.The equivalent matlab code for getting the sorted indices is much simpler:if x is a list (array) of values, then just write:[y,i] = sort(x);and y will be a list containing the sorted elements of x and i will be alist containing the sorted indices.Am i missing a trick here?Thanking you,Satya 
	

	
		 
Find out what India is talking about on  - Yahoo! Answers India  
Send FREE SMS to your friend's mobile from Yahoo! Messenger Version 8. Get it NOW-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Makin search on the other site and getting data and writing in xml

2006-09-27 Thread Steve Holden
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Ben Finney
> wrote:
> 
> 
>>Steve Holden <[EMAIL PROTECTED]> writes:
>>
>>
>>>Lawrence D'Oliveiro wrote:
>>>
Steve Holden wrote:

>The fact remains that Google can chop your searching ability off
>at the knees ...

No they can't. They can only chop off your ability to use Google.

>>>
>>>[sigh]. Right, Lawrence, sorry I wasn't quite explicit enough for you.
>>
>>Seems like a fairly important distinction. Google has the power to
>>"chop your searching ability off at the knees" only to the extent that
>>you grant them that power.
> 
> 
> Saying "search" when you mean "Google" is like saying "using a PC" when you
> mean "using Microsoft Windows".

Well, I thought it was self-evident that since I was referring to Google 
I wasn't talking about Alta Vista searching. If I said "Microsoft have 
the ability to terminate your license" presumably you'd chastise me by 
pointing out that they wouldn't be able to revoke my *Linux* license. 
Whatever.

"There's none as thick as them that wants to be."

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Starting Win32 Service

2006-09-27 Thread Gabriel Genellina

At Wednesday 27/9/2006 01:39, placid wrote:


Using Tim Golden's wmi module you can get the service names
but how do i start services that are stopped?


Surely there are fancier ways:
>net start servicename



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: A critique of cgi.escape

2006-09-27 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, Gabriel G wrote:
> By example, I do not validate a "page". I validate that all methods 
> that make up pieces of a page, build them the way they should - these 
> are our "unit tests". Then, it's up to the templating library to join 
> all the pieces into the final html page.

That sounds sensible to me - and also likely to be the sort of tests
that are not going to get broken by changes to cgi.escape ;-)

> I validated the original html against the corresponding dtd some time 
> ago (using the w3c validator), and ocasionally when things "looks 
> wrong" on a browser, but most of the time the html generated pages 
> are not validated nor checked as a whole.

That's possibly a mistake, but obviously that depends on details of
how your overall methodology works that I have no information about.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to communicate between processes?

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> I'm thinking about coding some sort of 'local notify server' in twisted
> (basically just listening to a socket and then passing the information
> to the IM bot), then connecting to it via a python socket in django and
> passing some serialized/pickled data.

That sounds like the right sort of thing. I've done this sort of thing
myself, though I've been careful not to use any language-specific
communication formats.

> I worry about two requests 
> connecting to the 'notify server' at once, though, because i *cannot*
> hang my web server.

Your Web server won't hang. The particular Web server thread/process waiting
for the request to be serviced will be held up, and so of course will the
particular user sitting in front of the browser waiting for a response from
that thread/process, but nobody else will notice anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re.compile().split(): why it produces empty string as a first element of the list

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, alf wrote:

> Fredrik Lundh wrote:
>> alf wrote:
>> 
>>> Let's run following:
>>>
>>>  >>> re.compile('(\[.*?\])').split('[aa]bb[11]22')
>>> ['', '[aa]', 'bb', '[11]', '22']
>>>
>>> Why does it return '' as a first element of the list?
>> 
>> 
>> because the string starts with a separator.
>> 
>> 
>> 
> so is it safe to say that the index of separator in the list is always
> an odd number?

Hard to see why not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Computer Language Popularity Trend

2006-09-27 Thread [EMAIL PROTECTED]

Xah Lee wrote:
> Computer Language Popularity Trend
>
> This page gives a visual report of computer languages's popularity, as
> indicated by their traffic level in newsgroups. This is not a
> comprehensive or fair survey, but does give some indications of
> popularity trends.
>
> http://xahlee.org/lang_traf/index.html

Careful there with the sweeping generalizations and quick judgments
about languages :)

Furthermore, it's nice to conclude that Lisp is getting more popular,
but we also have to take into account global trends (maybe more people
are using usenet in general? maybe the total number of programmers in
the world is increasing?).

Still, it's nice to see trends plotted out like that, thanks for the
work :)

mfh

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


Re: Computer Language Popularity Trend

2006-09-27 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote:
>> http://xahlee.org/lang_traf/index.html
> 
> Careful there with the sweeping generalizations and quick judgments
> about languages :)

I just read "PHP as a language is rather dry and business-like",
and fell off my chair.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critique of cgi.escape

2006-09-27 Thread Duncan Booth
Brian Quinlan <[EMAIL PROTECTED]> wrote:

> Actually, I wasn't kidding. I was basing this belief on greping through 
> the Python standard library where only the quote=None form is ever used. 
> It also matches my experience. But I don't have a large enough sample to 
> make any claim either way.
> 

A better sample might be to grep the Zope sources. There are a lot of calls 
to escape and the vast majority don't set the quote parameter, but most use 
of escape is actually hidden by the templating system. The TAL engine uses 
escape(s,1) for attribute values and escape(text) for content, so you get 
the best of both worlds: you don't have to think about which form of escape 
you need (or even that you need to escape strings at all), and you don't 
get quotes escaped when they don't have to be.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: QuoteSQL

2006-09-27 Thread Duncan Booth
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

> In message <[EMAIL PROTECTED]>, Duncan Booth
> wrote: 
> 
>> Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
>> 
>>> def EscapeSQLWild(Str) :
>>> """escapes MySQL pattern wildcards in Str."""
>>> Result = []
>>> for Ch in str(Str) :
>>> if Ch == "%" or Ch == "_" :
>>> Result.append("\\")
>>> #end if
>>> Result.append(Ch)
>>> #end for
>>> return "".join(Result)
>>> #end EscapeSQLWild
>> 
>> That doesn't quite work. If you want to stop wildcards being
>> interpreted as such in a string used as a parameter to a query, then
>> you have to escape the escape character as well.
> 
> That's part of the separation of function. Note that the above
> function does not generate a MySQL string literal: you must still put
> it through the previously-defined SQLString routine, which will
> automatically escape all the specials added by EscapeSQLWild.
> 
You are still missing the point. I'm not talking about generating a MySQL 
string literal, I'm talking about preventing wildcards characters having 
their special meaning when using the string as a parameter in 
cursor.execute. You still have to escape the escape character, and you have 
to do that before or at the same time as you escape the wildcards. No 
string literals are involved anywhere.

Calling the SQLString routine in this situation would be wrong because it 
would escape characters such as newline which must not be escaped.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Makin search on the other site and getting data and writing in xml

2006-09-27 Thread altemurbugra
ok i close this discussion
i understand everybody no problem

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


Re: QuoteSQL

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Duncan Booth wrote:

> Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> 
>> In message <[EMAIL PROTECTED]>, Duncan Booth
>> wrote:
>> 
>>> Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
>>> 
 def EscapeSQLWild(Str) :
 """escapes MySQL pattern wildcards in Str."""
 Result = []
 for Ch in str(Str) :
 if Ch == "%" or Ch == "_" :
 Result.append("\\")
 #end if
 Result.append(Ch)
 #end for
 return "".join(Result)
 #end EscapeSQLWild
>>> 
>>> That doesn't quite work. If you want to stop wildcards being
>>> interpreted as such in a string used as a parameter to a query, then
>>> you have to escape the escape character as well.
>> 
>> That's part of the separation of function. Note that the above
>> function does not generate a MySQL string literal: you must still put
>> it through the previously-defined SQLString routine, which will
>> automatically escape all the specials added by EscapeSQLWild.
>> 
> You are still missing the point. I'm not talking about generating a MySQL
> string literal, I'm talking about preventing wildcards characters having
> their special meaning when using the string as a parameter in
> cursor.execute.

But that's what cursor.execute will do if you use its parameter-substitution
mechanism--generate a string literal.

> You still have to escape the escape character...

Which will be done by cursor.execute if you use its parameter-substitution
mechanism.

> Calling the SQLString routine in this situation would be wrong because it
> would escape characters such as newline which must not be escaped.

SQLString will convert newlines into the \n sequence in the generated string
literal, which MySQL will interpret as a newline. cursor.execute's
parameter-substitution mechanism would do exactly the same thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/MySQL problem on Windows

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Eric Smith wrote:

> I could have sworn that I got the use of connection() from published
> sample code, but I must be mistaken.

If all else fails, read the documentation
,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: does anybody earn a living programming in python?

2006-09-27 Thread Magnus Lycka
walterbyrd wrote:
> If so, I doubt there are many. 

Depends on what you compare with. I'm pretty sure there are thousands
of people working as Python programmers, and many more using it as a
smaller tool in their work. Of course this is small compared to Java
or C++.

In the US, it seems a lot of companies in the animation industry, such
as Dreamworks and Industrial Light & Magic regularly look for Python
skilled people.

In my vicinity, Göteborg with surroundings in Sweden, I know of
several places where people work with Python. I'm sure the amount of
C++,  Java or VB programmers are magnitudes bigger, but there are also
a lot more people eager to fill those positions.

My employer, Jeppesen Systems AB, has dozens of Python programmers,
and we train our customers to use Python for customization and 
integration etc. So, we know that a significant number of the world's
largest air lines and some significant railroad companies have trained
Python developers (we trained them) and use Python for customizing our
products, and for e.g. integration with legacy systems.

Just a few hundred meters from us, there is AB Strakt, which was more
or less a pure Python company last time I looked. The pharmaceuticals
company Astra Zeneca uses Python in some of their research, and I've
seen people from other companies in the vicinity asking Python questions
on various mailing lists etc. Python is certainly used in Chalmers, the
technical University here. This is in a region with way less than one
million inhabitants. I'm pretty sure we have >1 Python programmer per
10 000 inhabitants. Let's say that's above Swedish average. I still
think there is at least 300 Python programmers among the 9 million
people here. Although we're just 0.15% of the worlds populations, my
experience is that we make and use something like 1% of the high tech
stuff in the world, so my standard extrapolation technique would yield
3 python programmers globally.

> I wonder why that is?

Well, it takes time to change things, and many decision makers aren't
very well informed. Maybe they are more likely to choose something
which is marketed and supported by some large commercial entity. The
rise of Linux and open source is changing that, but it takes time.
If you look at languages introduced the last 15 years or so, I think
Python is one of the more popular. The languages I can think of right
now, that have appeared since 1990 or so, and received a significant
mindshare are C#, Java, JavaScript, Perl, PHP, Python, Ruby and Visual
Basic.

Of these, C#, Java and Visual Basic have serious commercial backing
which promoted them heavily for certain applications, and provided a
lot of convenient tools. Those languages are also closely modeled
syntactically on a predecessor, C++ for Java, Java for C#, and VB is
just a new BASIC dialect, which makes the transition to start using
them easier, at the expense of retaining stupid aspect of old languages
that we'd rather get rid of. I.e. getting started seems more important
than getting it right. That should help in the short run, but be less
good in the long run.

Perl and CGI was the best available tool when the big web boost
happened, and PHP has taken over that role. They are very popular in
a particular niche (but Perl seems to be in decline) but like
JavaScript, they are niche tools.

Ruby is the language most like Python I guess, and it's nowhere near
Python in popularity, even if RoR has given it a boost. As people have
noticed, Python is often used together with C or C++, and it seems to
me that Java programmer might prefer Ruby to Python. This might be
because Java and Ruby are both purely OO, and might fit people who think
OO is everything, while Python and C++ are multi paradigm programmers
that share a different mindset.

So, to summarize, Python is probably the most popular general purpose
programming language invented since 1990 which didn't have multi
billion dollar backing. Now, it has more backing, with Google investing
in it, for instance by hiring the creator and other important Python
developers. Python 2.5 has advanced it even further, and it seems to
me that Python 3.0 will be a much smoother ride than Perl 6 turned out
to be for the Perl community. IronPython and PyPy are also very
interesting projects.

Python is a generic programming language, so I don't think we need some
kind of killer application like RoR. On the other hand, I think a really
smooth IDE with a convenient GUI builder could help making it more
widely spread "among the masses".

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


Re: I need some tips to begin a simple project

2006-09-27 Thread Magnus Lycka
dutche wrote:
> Hi, I'm new in Python and I'm learning with "Learning Python" oreilly's
> book which is very good written and explanatory.

You're not saying how new you are to programming (particularly
GUI programming) in general. Python itself is probably not the
tricky part here.

> And I can use some other graphical interface, like OpenGL? Or with
> PyGame I can do an animattion like zooming the icon image when hover?

It seems to me that PyGame might be a candidate for the kind of stuff
you want to do, although I'm no expert in that. I'd download it and
play with it. There are some PyGame tutorials and example code to
get you started.

Good Luck!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb and mod_python issue (Steve Holden)

2006-09-27 Thread Alvin Delagon
Thanks for the reply. Fixing it seems a tedious task. I opted in rewriting the application to a HTTPServer and is working now. I've noticed this problem on CentOS 4 I might as well report to them the possible version conflict.

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

Re: QuoteSQL

2006-09-27 Thread Ben

Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Duncan Booth wrote:
>
> > Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> >
> >> In message <[EMAIL PROTECTED]>, Duncan Booth
> >> wrote:
> >>
> >>> Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> >>>
>  def EscapeSQLWild(Str) :
>  """escapes MySQL pattern wildcards in Str."""
>  Result = []
>  for Ch in str(Str) :
>  if Ch == "%" or Ch == "_" :
>  Result.append("\\")
>  #end if
>  Result.append(Ch)
>  #end for
>  return "".join(Result)
>  #end EscapeSQLWild
> >>>
> >>> That doesn't quite work. If you want to stop wildcards being
> >>> interpreted as such in a string used as a parameter to a query, then
> >>> you have to escape the escape character as well.
> >>
> >> That's part of the separation of function. Note that the above
> >> function does not generate a MySQL string literal: you must still put
> >> it through the previously-defined SQLString routine, which will
> >> automatically escape all the specials added by EscapeSQLWild.
> >>
> > You are still missing the point. I'm not talking about generating a MySQL
> > string literal, I'm talking about preventing wildcards characters having
> > their special meaning when using the string as a parameter in
> > cursor.execute.
>
> But that's what cursor.execute will do if you use its parameter-substitution
> mechanism--generate a string literal.
>
> > You still have to escape the escape character...
>
> Which will be done by cursor.execute if you use its parameter-substitution
> mechanism.
>
> > Calling the SQLString routine in this situation would be wrong because it
> > would escape characters such as newline which must not be escaped.
>
> SQLString will convert newlines into the \n sequence in the generated string
> literal, which MySQL will interpret as a newline. cursor.execute's
> parameter-substitution mechanism would do exactly the same thing.

But cursor.execute does not necessarily do parameter-substitution. It
can send the data directly to the database with no escaping. In this
case, doing it yourself is a massive pessimization, and you're more
likely to get it wrong than the driver writers

Ben

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


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread Peter Otten
Antoon Pardon wrote:

> I had written my own module, which works similarly but
> is somewhat extended. Here is an example of how it can
> be used and how I would like to use it but get stuck.
> 
> from extreme import Top
 Top
> Top
 Top + 1
> Top
 Top - 30
> Top
 Top > 1e99
> True
 lst = range(10)
 lst[:Top]
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: slice indices must be integers or None
> 
> So this is where I am stuck. I need this Top value in
> a context where it can be used as a start or stop value
> in a slice. My idea was that since a stop value greater
> than the length of lst in this context would simply return
> a copy of lst, using Top in such a way should behave so
> too. However I don't see a way of doing that.
> 
> So can someone provide ideas to get this behaviour?

>>> import sys
>>> class Top(object):
... def __index__(self):
... return sys.maxint
...
>>> Top = Top()
>>> range(5)[:Top]
[0, 1, 2, 3, 4]

This can of course fail in many interesting ways...

Peter


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


Re: What's up with site.Quitter?

2006-09-27 Thread James Stroud
Fredrik Lundh wrote:
> James Stroud wrote:
> 
>> Yes, but I was speaking more consistency than convenience (see above 
>> for what I mean by consistency).
> 
> why would having access to a type object for exit/quit help you do 
> proper syntax coloring, btw?  if you want to generate a syntax table, 
> wouldn't it be better to use things like
> 
> issubclass(obj, Exception)
> 
> and
> 
> callable(obj)
> 
> etc. ?

Actually, my code has the first test and the second is a consequence of 
my checking for types.BuiltinFunctionType. Perhaps the way you suggest 
is less cumbersome. Food for thought.

> (__builtins__ is an implementation detail, btw;

OK. I assumed that __builtins__ are somehow sacred regarding what would 
be reserved. Perhaps not. However, I used __builtins__ to generate a 
list of reserved words and used types for syntax checking.

 > if you want a list of
 > the builtins, import __builtin__ (no plural) and do dir on that).
 >
 > 

cPython, at least, gives this equivalence:

py> import __builtin__
py> __builtins__ is __builtin__
True

I assume, as you suggest, that one may not depend on this equivalence 
for all implementations.

Thank you for your suggestions,
James
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Battlefield Weapon Popularity Trend

2006-09-27 Thread Mirco Wahab
Thus spoke Ramon Diaz-Uriarte (on 2006-09-27 11:01):

>> When the Samurai of medieval Japan were confronted
>> with new 'battlefield language', e.g. early Shotguns,
>> they resisted because one could push any peasant
> 
> shouldn't this be "they [the Samurai] did not resist"?

The "resisted" believing all the buzz,
e.g.: "armies made of dudes with guns" ...

(and tried to preserve their Art,
which did not work in the end -
"the Art of Killing" was replaced
by "mass production of deaths" on
the battlefield ...)

Regards,

M.

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


Re: What's up with site.Quitter?

2006-09-27 Thread skip

Georg> Not really, but what would you do with it?  It's an internal
Georg> object used for only exit() and quit(), and of no real use
Georg> elsewhere.

In fact, I would argue that objects placed in builtins as a convenience in
inteactive mode shouldn't be colorized at all (dir, help, exit, quit,
copyright, credits, license, maybe vars).  They shouldn't be considered
special in code written to be used in non-interactive contexts.

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


Re: What's up with site.Quitter?

2006-09-27 Thread James Stroud
Georg Brandl wrote:
> James Stroud wrote:
>> Hello All,
>>
>> Still jubilantly configuring my work environment for python 2.5, I 
>> came accross a curiosity when writing an automatic vim syntax file 
>> creator (so I can automatically update my syntax coloring with future 
>> python releases).
>>
>> It seems I can find a reference to just about every type except those 
>> for "exit" and "quit" in the standard library somewhere. E.g.:
>>
>> py> type(__builtins__.Ellipsis) is types.EllipsisType
>> True
>>
>> However, in an appearant break with consistency, this can not be done 
>> for "exit" and "quit" because site.Quitter is nested inside of the 
>> setquit() function in the site.py module.
>>
>> Would moving this class definition to module level be something that 
>> would meet with great resistance?
> 
> Not really, but what would you do with it? It's an internal object used
> for only exit() and quit(), and of no real use elsewhere.
> 
> Georg

Outside of my type checking against it for syntax coloring, I have no 
idea. I just get a funny feeling with computers when exceptions to a 
general pattern come along. But then again, maybe the consistency I 
perceive for the rest of __builtins__ is more or less illusory. This 
might have been the point of Fredrik's question.

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


Re: One program in different GUI Toolkits

2006-09-27 Thread Paul Boddie
Franz Steinhaeusler wrote:
>
> What about a small text editor using the scintilla control?
> It should be available for Pythoncard, wxPython, pygtk and pyQt
> (qtscintilla).
> With a small find dialog, open, save should be enough for the beginning.

You might be interested in this page:

http://wiki.python.org/moin/GuiProgrammingShootout

Other people have suggested similar projects before, and you might be
able to get the ball rolling with the above suggestion.

Paul

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


Re: Battlefield Weapon Popularity Trend

2006-09-27 Thread Ramon Diaz-Uriarte
On 9/27/06, Mirco Wahab <[EMAIL PROTECTED]> wrote:
> Thus spoke Ramon Diaz-Uriarte (on 2006-09-27 11:01):
>
> >> When the Samurai of medieval Japan were confronted
> >> with new 'battlefield language', e.g. early Shotguns,
> >> they resisted because one could push any peasant
> >
> > shouldn't this be "they [the Samurai] did not resist"?
>
> The "resisted" believing all the buzz,
> e.g.: "armies made of dudes with guns" ...
>

OK, I think I see it.

> (and tried to preserve their Art,
> which did not work in the end -
> "the Art of Killing" was replaced
> by "mass production of deaths" on
> the battlefield ...)

Yeap, that I saw.

Thansk,

R.

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


-- 
Ramon Diaz-Uriarte
Bioinformatics Unit
Spanish National Cancer Centre (CNIO)
http://ligarto.org/rdiaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: does anybody earn a living programming in python?

2006-09-27 Thread Jeff Hagen
I do... but then I'm a grad student so I'm not sure what extent you 
would call it "a living"

I know that Python is used __extensively__ in academia for running 
experiments where speed is not important.

-Jeff

Magnus Lycka wrote:
> walterbyrd wrote:
>> If so, I doubt there are many
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ruby %w equivalent

2006-09-27 Thread Piet van Oostrum
> hg <[EMAIL PROTECTED]> (A) wrote:

>A> Antoine De Groote wrote:
>>> Hi everybody,
>>> 
>>> is there a python equivalent for the ruby %w operator?
>>> %w{a b c} creates an array with strings "a", "b", and "c" in ruby...
>>> 
>>> Thanks a lot
>>> Regards,
>>> antoine

>A> Why would they want to make such an obscure API ? ... didn't they have
>A> Python to learn from (I am truly amazed - nothing cynical ...just ...
>A> why ?)

I think it is modeled after Perl.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's up with site.Quitter?

2006-09-27 Thread skip

James> But then again, maybe the consistency I perceive for the rest of
James> __builtins__ is more or less illusory. This might have been the
James> point of Fredrik's question.

As I implied in my note, there is a difference between fundamental builtins
like open and Exception, and convenience builtins like exit and license.  If
you make that distinction and only really worry about consistency within the
fundamental builtins I think you'll be on more solid ground.

Skip

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


Re: QuoteSQL

2006-09-27 Thread Duncan Booth
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

>> You are still missing the point. I'm not talking about generating a
>> MySQL string literal, I'm talking about preventing wildcards
>> characters having their special meaning when using the string as a
>> parameter in cursor.execute.
> 
> But that's what cursor.execute will do if you use its
> parameter-substitution mechanism--generate a string literal.

The current implementation of the MySQL database adapter will do that. 
Other database adaptors may handle parameters without generating string 
literals.

> 
>> You still have to escape the escape character...
> 
> Which will be done by cursor.execute if you use its
> parameter-substitution mechanism.

Too late and not enough. Too late, because if you want to search for the 
literal "\\%" (single backslash percent) you need to escape the backslash 
before you escape the percent. Not enough because at the point MySQLdb 
finally converts it to a string literal a literal backslash to be used in a 
context where wildcards are allowed needs to be spelled with 4 backslashes. 
i.e. it needs to be escaped twice, once for the string literal and once to 
stop it being interpreted as an escape within the wildcard string.

> 
>> Calling the SQLString routine in this situation would be wrong
>> because it would escape characters such as newline which must not be
>> escaped. 
> 
> SQLString will convert newlines into the \n sequence in the generated
> string literal, which MySQL will interpret as a newline.
> cursor.execute's parameter-substitution mechanism would do exactly the
> same thing. 
> 
Correct: they both do the same thing. So you have to use either SQLString 
or the parameter substitution. You cannot use both. Calling SQLString on a 
string to be passed in to the parameter substitution mechanism will not 
work correctly.

May I suggest that the way for you to progress would be if you wrote some 
unit tests? So, create a simple table containing a few strings with special 
characters and do a few wildcard searches looking for %, newline etc. That 
way you can post not just a function, but some runnable code which either 
demonstrates that your function does what you say, or lets people suggest a 
new test which demonstrates that it fails to handle some particular edge 
case.

Here, I'll even give you a start. Run the code below (you might need to 
create a database called 'test' if you don't already have one), and then 
explain why test_escapebackslashwild fails, and either why you think the 
test is broken or how you would fix your code? All the other tests should 
pass.


 mysqltest.py ---
import unittest
import MySQLdb

def EscapeSQLWild(Str) :
"""escapes MySQL pattern wildcards in Str."""
Result = []
for Ch in str(Str) :
if Ch == "%" or Ch == "_" :
Result.append("\\")
#end if
Result.append(Ch)
#end for
return "".join(Result)
#end EscapeSQLWild

class Tests(unittest.TestCase):
values = "x%x", "xnx", "x\nx", "x\\nx", "x\\%x"
def setUp(self):
db = self.db = MySQLdb.connect("", "", "", "test")
cursor = self.cursor = db.cursor()
cursor.execute('''create temporary table pythontest
(id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
name VARCHAR(30))''')
cursor.executemany(
"insert into pythontest(name) values(%s)",
self.values)

def tearDown(self):
self.cursor.execute("drop table pythontest")

def test_wildcard(self):
n = self.cursor.execute(
"select name from pythontest where name like %s",
"x%x")
self.assertEqual(n, 5)

def test_nonwildcard(self):
self.cursor.execute(
"select name from pythontest where name like %s",
"x\\%x")
expected = (('x%x',),)
self.assertEqual(expected, self.cursor.fetchall())

def test_newline(self):
self.cursor.execute(
"select name from pythontest where name like %s",
"x\nx")
expected = (('x\nx',),)
self.assertEqual(expected, self.cursor.fetchall())

def test_backslashn(self):
self.cursor.execute(
"select name from pythontest where name like %s",
"xnx")
expected = (('x\\nx',),)
self.assertEqual(expected, self.cursor.fetchall())

def test_backslashpercent(self):
self.cursor.execute(
"select name from pythontest where name like %s",
"x\\%x")
expected = (('x\\%x',),)
self.assertEqual(expected, self.cursor.fetchall())

def test_escapewild(self):
self.cursor.execute(
"select name from pythontest where name like %s",
EscapeSQLWild("x%x"))
expected = (('x%x',),)
self.assertEqual(expected, self.cursor.fetchall())

def test_escapebackslashwild(self):
self.cursor.execute(
"se

Re: Computer Language Popularity Trend

2006-09-27 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Xah Lee wrote:
>> Computer Language Popularity Trend
>>
>> This page gives a visual report of computer languages's popularity, as
>> indicated by their traffic level in newsgroups. This is not a
>> comprehensive or fair survey, but does give some indications of
>> popularity trends.
>>
>> http://xahlee.org/lang_traf/index.html
> 
> Careful there with the sweeping generalizations and quick judgments
> about languages :)
> 
> Furthermore, it's nice to conclude that Lisp is getting more popular,
> but we also have to take into account global trends (maybe more people
> are using usenet in general? maybe the total number of programmers in
> the world is increasing?).
> 
> Still, it's nice to see trends plotted out like that, thanks for the
> work :)
> 
> mfh
> 

Finally, a contribution of substance from lambda. Who woulda thunk it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's up with site.Quitter?

2006-09-27 Thread James Stroud
[EMAIL PROTECTED] wrote:
> James> But then again, maybe the consistency I perceive for the rest of
> James> __builtins__ is more or less illusory. This might have been the
> James> point of Fredrik's question.
> 
> As I implied in my note, there is a difference between fundamental builtins
> like open and Exception, and convenience builtins like exit and license.  If
> you make that distinction and only really worry about consistency within the
> fundamental builtins I think you'll be on more solid ground.
> 
> Skip
> 

Thank you. I'm glad I'm learning something from what originally felt 
like a silly distraction (writing the syntax colorer generator).

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


Re: Replace single character at given position

2006-09-27 Thread Magnus Lycka
Larry Bates wrote:
>> How do I replace a single character in a string at a given position?

You can't. Strings can't be mutated in Python how ever hard you try.
The string type is immutable. (Of course, I suspect you can write a
horrible C extension that would help you cheat. Yuk!)

You need to create a *new* string object with the properties you like.
This is what you do below. As soon as you use "s1=...", you are
rebinding "s1" to a (typically) different string object than it was
bound to before.

If you think about this, it will probably also answer the "does Python
use call by reference or call by value" questions that will eventually
pop up in your head if you come from C.

>> From programming languages like C I expect something like that:

What you need to realize is that objects and assignments are
different in Python and in C. In C, "a=x" basically means "put
the value identified by x in the location defined by a". In
Python, "a=x" basically means "bind the name a to the object
identified by x". See http://pyref.infogami.com/naming-and-binding

> You can do this:
> 
> s1=s1.replace('x','y', 1) # Only replace the first x with y
> 
> or
> 
> s1l=list(s1)
> s1l[1]='y'
> s1=''.join(s1l)

Both these examples creates new string objects and rebind the
name s1 to these new objects. In other words, if you had "s2=s1"
on a previous line, the expression "s1==s2" will be false after
the code above has been executed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One program in different GUI Toolkits

2006-09-27 Thread Franz Steinhaeusler
On 27 Sep 2006 03:42:17 -0700, "Paul Boddie" <[EMAIL PROTECTED]> wrote:

>Franz Steinhaeusler wrote:
>>
>> What about a small text editor using the scintilla control?
>> It should be available for Pythoncard, wxPython, pygtk and pyQt
>> (qtscintilla).
>> With a small find dialog, open, save should be enough for the beginning.
>
>You might be interested in this page:
>
>http://wiki.python.org/moin/GuiProgrammingShootout
>
>Other people have suggested similar projects before, and you might be
>able to get the ball rolling with the above suggestion.
>
>Paul

Thank you for your information!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterator question

2006-09-27 Thread Neal Becker
George Sakkis wrote:

> [EMAIL PROTECTED] wrote:
> 
>> def transform(seq, size):
>> i = 0
>> while i < len(seq):
>> yield tuple(seq[i:i+size])
>> i += size
> 
> Or for arbitrary iterables, not just sequences:
> 
> from itertools import islice
> def transform(iterable, size):
>  it = iter(iterable)
>  while True:
>  window = tuple(islice(it,size))
>  if not window:
> break
>  yield window
> 
> George
> 

Thanks guys!

This one above is my personal favorite.


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


Re: QuoteSQL

2006-09-27 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Duncan Booth wrote:

> Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> 
>>> You are still missing the point. I'm not talking about generating a
>>> MySQL string literal, I'm talking about preventing wildcards
>>> characters having their special meaning when using the string as a
>>> parameter in cursor.execute.
>> 
>> But that's what cursor.execute will do if you use its
>> parameter-substitution mechanism--generate a string literal.
> 
> The current implementation of the MySQL database adapter will do that.
> Other database adaptors may handle parameters without generating string
> literals.

Doesn't matter what other implementations of parametrization might or might
not do. The syntax I generate is valid for MySQL, therefore it will work
with the MySQL database adapter regardless of what else the adaptor might
do.

>>> You still have to escape the escape character...
>> 
>> Which will be done by cursor.execute if you use its
>> parameter-substitution mechanism.
> 
> Too late and not enough. Too late, because if you want to search for the
> literal "\\%" (single backslash percent) you need to escape the backslash
> before you escape the percent. Not enough because at the point MySQLdb
> finally converts it to a string literal a literal backslash to be used in
> a context where wildcards are allowed needs to be spelled with 4
> backslashes. i.e. it needs to be escaped twice, once for the string
> literal and once to stop it being interpreted as an escape within the
> wildcard string.

I'm assuming you mean, how would you get from a Python expression to a MySQL
clause that looks like

name like "%%%"

(wildcard % followed by literal backslash \\ followed by literal percent \%
followed by wildcard %.) That's easy:

EscapeSQLWild(r"\%") => r"\\%"
SQLString(r"\\%") => r'"%"'

So the Python expression

"name like %s" % SQLString("%" + EscapeSQLWild(r"\%") + "%")

gives you what you want.

> Correct: they both do the same thing. So you have to use either SQLString
> or the parameter substitution. You cannot use both. Calling SQLString on a
> string to be passed in to the parameter substitution mechanism will not
> work correctly.

I thought I had made that clear already.

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


Re: What's the best way to communicate between processes?

2006-09-27 Thread grahamd
[EMAIL PROTECTED] wrote:
> I'm thinking about coding some sort of 'local notify server' in twisted
> (basically just listening to a socket and then passing the information
> to the IM bot), then connecting to it via a python socket in django and
> passing some serialized/pickled data.

Use the XML-RPC server gateway from Twisted on the server side. In
the Django web pages then use xmlrpclib module to initiate XML-RPC
requests to the server.

Graham

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


Re: a query on sorting

2006-09-27 Thread Steve Holden
Satya Upadhya wrote:
> Dear Friends,
> I am having a few issues with respect to sorting using python. I am using
> Python 2.4.3 Win32 (IDLE 1.1.3).
> 
 x = [2,6,4]
 x.sort()
 x
> [2, 4, 6]
 x = [2,6,4]
 y = []
 y = x.sort()
 y
 print y
> None
> 
> So the problem essentially is that i am unable to store the sorted
> elements of list x into an empty list y in a straightforward manner. I can
> get around this, of course, using the following:
 x = [2,6,4]
 x.sort()
> 
>  >>> x
> [2, 4, 6]
 y = []
 for i in x:
> y.append(i)
> 
> 
 y
> [2, 4, 6]
> 
> But this seems a little less succinct then one would expect from python.
> 
Not only that, but you've also modified the original list, which seems 
to conflict with your requirements.

> Also, consider the sorting of the indices of a sorted list. Consider the
> following code:
 x = [2,6,4]
 import operator
 sortedindices = sorted(range(len(x)), key = x.__getitem__)
 print sortedindices
> [0, 2, 1]
 x.sort()
 x
> [2, 4, 6]

> 
> x (x = [2,6,4] originally) is the original list, and its indice
>  s are
> 0,1,2. If you sort x, then x becomes [2,4,6] and the the list of the
> sorted
>  indices becomes [0,2,1] since the 4 (which originally corresponds
> to index 2) has now shifted to a position corresponding to index 1 and
> likewise for element 6.
> 
> The equivalent matlab code for getting the sorted indices is much simpler:
> if x is a list (array) of values, then just write:
> 
> [y,i] = sort(x);
> and y will be a list containing the sorted elements of x and i will be a
> list containing the sorted indices.
> 
> Am i missing a trick here?
> 
> Thanking you,
> Satya
> 
  >>> sorted

  >>> a = [9,4,3,5,2,6,7,1,2]
  >>> b = sorted(a)
  >>> a
[9, 4, 3, 5, 2, 6, 7, 1, 2]
  >>> b
[1, 2, 2, 3, 4, 5, 6, 7, 9]
  >>>

Remember that sort() was specifically designed top operate on a list 
in-place, so it always returns None.

If you want the indexes as well you need to become a bit tricky. 
Remember that enumerate() will produced two-element tuples with the 
index value associated with the list value.

  >>> [x for x in enumerate(a)]
[(0, 9), (1, 4), (2, 3), (3, 5), (4, 2), (5, 6), (6, 7), (7, 1), (8, 2)]

But you really want the index second, so the sort works on the list 
values not the index values. Combining all this we get

  >>> sorted((x[1], x[0]) for x in enumerate(a))
[(1, 7), (2, 4), (2, 8), (3, 2), (4, 1), (5, 3), (6, 5), (7, 6), (9, 0)]

Tadaaa!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: QuoteSQL

2006-09-27 Thread Duncan Booth
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

> I'm assuming you mean, how would you get from a Python expression to a
> MySQL clause that looks like
> 
> name like "%%%"
> 
> (wildcard % followed by literal backslash \\ followed by literal
> percent \% followed by wildcard %.) That's easy:
> 
> EscapeSQLWild(r"\%") => r"\\%"
> SQLString(r"\\%") => r'"%"'
> 
> So the Python expression
> 
> "name like %s" % SQLString("%" + EscapeSQLWild(r"\%") + "%")
> 
> gives you what you want.
> 
Deary me. Did you actually test out that bit of code before you posted it? 
No, I thought not. I even gave you a test harness to make it easy for you 
to check the quality of your code before posting.

All you had to do was to add another test:

def test_escapebackslashwild2(self):
self.cursor.execute(
("select name from pythontest where name like %s" %
SQLString("%" + EscapeSQLWild(r"\%") + "%")))
expected = (('x\\%x',),)
self.assertEqual(expected, self.cursor.fetchall())

and the output is:
==
FAIL: test_escapebackslashwild2 (__main__.Tests)
--
Traceback (most recent call last):
  File "mysqltest.py", line 111, in test_escapebackslashwild2
self.assertEqual(expected, self.cursor.fetchall())
AssertionError: (('x\\%x',),) != (('x\\nx',), ('x\\%x',))

--

as I said before, your escaping is too late and not enough. You've got a 
search for a literal backslash in there sure enough, but you haven't 
managed to escape the percent character.

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


Re: odbc DbiDate date conversion

2006-09-27 Thread flupke
Frank Millman schreef:


> Not that I know of. The results of my investigations so far seem to
> indicate that we have a problem :-(
> 
> Here is a link to an article dated 1998 -
> https://svn.python.org/www/trunk/pydotorg/windows/OdbcHints.html
> 
> Among other interesting stuff, it states -
> 
> "Notice that result values are converted to Python objects. Dates in
> particular are returned as dbiDate objects. This can be a serious
> limitation, because dbiDate can not represent dates prior to the UNIX
> epoch (1 Jan 1970 00:00:00 GMT). If you try to retrieve earlier dates,
> you'll get garbage and may even provoke a crash."
> 
> I contacted Mark Hammond, author of the win32 extensions, to ask if
> there was a solution and particularly to suggest a modification to
> return a datetime.datetime object. This was his reply -
> 
> "I'd be happy with an option to use the datetime module - maybe it
> could even be on the cursor?  However, I wont have time to do this in
> the short term.
> You could consider using ADO via win32com too..."
> 
> It looks as if we will have to use ADO for now. There is an 'adodbapi'
> module available which is DB-API 2.0 compliant -
> adodbapi.sourceforge.net. I will give it a try.
> 
> Frank

Frank,

thanks for your effort. Looks indeed like it's not going to be solved in
the short term. I will give adodbapi a whirl then.

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


Re: IDLE - Customizing output format

2006-09-27 Thread Ilias Lazaridis
James Stroud wrote:
> Ilias Lazaridis wrote:
...
> Well, for example, the output (I'm indenting manually for visual clarity):
>
>   >>> print 'bob'
> : bob
>   >>> print [i for i in xrange(3)]
> : [0, 1, 2]
>
>
> Would create the following selection in "doctest" mode (again manually
> adding whitespace):
>
>   >>> print 'bob'
>   bob
>   >>> print [i for i in xrange(3)]
>   [0, 1, 2]

http://docs.python.org/lib/module-doctest.html

ok, I understand now.

then, for consistency reasons, the ":" could become ":::".

doctest would need to get a tiny addition to be able to 'see' those
":::".

> But, say for 'code copy' mode, this selection would be appended to the
> clipboard (again manually adding whitespace for clarity):
>
>   print 'bob'
>   print [i for i in xrange(3)]

I understand.

> This way you could either make doctest blocks or copy code drafted in
> the interactive interpreter. I often get carried away and write complete
> useful functions in the interpreter then have to do commands like the
> following in vim:
>
>   :.,+8s/^//
>
> to fix ">"s and ellipses, etc., in the copied function. Or if I want to
> tweak a function I'm writing in the interpreter, I painfully copy it one
> line at a time. This may or may not be the best way to use the
> interpreter (to draft actual code) but I find myself doing it all of the
> time.

I am wondering that this functionality (copy code) is not included
within IDLE.

It should be possible to add it quite simple.

.

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


Re: Computer Language Popularity Trend

2006-09-27 Thread cartercc
I, too, attempt to track the popularity of computer languages, but I
like to look at the job boards. My theory is that the number of
employers looking for particular skills indicates the relative
popularity of the language. This is a somewhat crude measure,
particularly with Microsoft technologies (VB, VB6, VB.NET, VS, etc). I
think it's much more reliable with open source languages, such as Java,
Perl, PHP, and so on.

'Popularity' is a slippery concept as well. C isn't real popular in
terms of jobs, but it is in terms of compensation. In system
administration (which I also follow), Windows has large numbers of
jobs, but a low level of compensation. OSes like AIX on the other hand
have lower numbers of available jobs, but those tend to be more highly
compensated. One could argue that compensation is a function of
popularity, with the more unpoular technologies having carrying a
bigger price to attract more people -- an example of supply and demand
-- but then one would have to argue that garbade collectors should be
more highly compensated that physicians.

You can also get a rough measure ot the popularity of web scripting
languages from an analysis of the URLs. The last time I did this was in
2003, and as I recall, these were the results:
PHP 30% and increasing
Perl 28% and falling
ASP 25% and falling fast
ColdFusion 6% and steady
Java and JSP 5% and increasing
others, Python, Ruby, ...

Again, this is a very rough measure. Java, for instance, is used by big
companies (like auto manufacturers, aerospace industries, defense
contractors, big retailers, etc.) One site/one vote isn't
representative necessarily, plus the bigger companies employ more
people than the smaller companies that tend to use FOSS.

Finally, in my area, we have a lot of banking and insurance jobs. These
companies internally are exclusively Microsoft shops. It's virtually
impossible to work there unless you know Visual Studio and SQL Server.
Misrosoft people tend not to prowl the newsgroups, and I would suspect
that any measurement based on numbers of newsgroup postings would be
skewed for this reason.

CC

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


Re: does anybody earn a living programming in python?

2006-09-27 Thread codefire

Mike C. Fletcher wrote:
> Job security and easy availability is not the be-all and end-all of
> happiness in life.  That said, if you know anyone who "just wants a
> job", please, push them at Java, someone has to spend the next 30
> years maintaining the Struts and J*EE sites people are putting
> together today in all those big institutions.
> 

Absolutely spot on Mike! :)

Tony

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


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread Antoon Pardon
On 2006-09-27, Peter Otten <[EMAIL PROTECTED]> wrote:
> Antoon Pardon wrote:
>
>> I had written my own module, which works similarly but
>> is somewhat extended. Here is an example of how it can
>> be used and how I would like to use it but get stuck.
>> 
>> from extreme import Top
> Top
>> Top
> Top + 1
>> Top
> Top - 30
>> Top
> Top > 1e99
>> True
> lst = range(10)
> lst[:Top]
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> TypeError: slice indices must be integers or None
>> 
>> So this is where I am stuck. I need this Top value in
>> a context where it can be used as a start or stop value
>> in a slice. My idea was that since a stop value greater
>> than the length of lst in this context would simply return
>> a copy of lst, using Top in such a way should behave so
>> too. However I don't see a way of doing that.
>> 
>> So can someone provide ideas to get this behaviour?
>
 import sys
 class Top(object):
> ... def __index__(self):
> ... return sys.maxint
> ...
 Top = Top()
 range(5)[:Top]
> [0, 1, 2, 3, 4]
>
> This can of course fail in many interesting ways...

To begin with this already fails:

>>> for i in xrange(Top):
...   print i
... 
Traceback (most recent call last):
  File "", line 1, in 
TypeError: an integer is required


What bothers me a bit about the rejection of PEP 326 is that one of the
reasons stated is:

  http://mail.python.org/pipermail/python-dev/2004-January/042306.html

  - it is easily implemented when you really need it

Well I thought it would simplify some things for me, so I tried an
implementation and then found that some of the things that I would
want to do with it wont work. So the "is easily implemented" bit
seems not to be correct.

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


baffling sql string

2006-09-27 Thread DarkBlue
Following is a code snippet from a pythoncard app
the problem is with the sql string called iq1
If either mysubject or mytalktext contains an 
apostrophe the update fails :
Example: mysubject="Let's Eat"  this fails
 mysubject="Lets Eat"   this works fine

What options do I have to avoid this issue but still
can use apostrophes in my input data ?

mysubject=self.components.TextField1.text  
mytalktext=self.components.TextArea1.text
mymsgno=self.myamsgno
iq1="update MSGTALK set msgdate='NOW',subject='%s',talktext='%s' where
msgno= %d " % (mysubject,mytalktext,mymsgno) 
try:
   self.cur.execute(iq1)
   con1.commit()
   self.components.TextArea2.appendText('Update ok\n')  
except:
   self.components.TextArea2.appendText('Problem during update command\n')  
  
   self.components.TextArea2.appendText(iq1)


(hope the intendation did not get too messed up )

Thanks 

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


Re: How to apply text changes to HTML, keeping it intact if inside "a" tags

2006-09-27 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hello,
> 
> I have HTML input to which I apply some changes.
> 
> Feature 1:
> ===
> I want to tranform all the text, but if the text is inside
> an "a href" tag, I want to leave the text as it is.
> 
> The HTML is not necessarily well-formed, so
> I would like to do that using BeautifulSoup (or
> maybe another tolerant parser).
> 



Use the BeautifulSoup + XSL. Writing your two features in xsl is close to a
no-brainer, and it is certainly the best tool for the job.

And there are a few implementations for python available.

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


Re: ruby %w equivalent

2006-09-27 Thread Antoine De Groote
Thorsten Kampe wrote:
> * Antoine De Groote (Tue, 26 Sep 2006 12:06:38 +0200)
>> Thorsten Kampe wrote:
>>> * John Machin (24 Sep 2006 15:32:20 -0700)
 Antoine De Groote wrote:
> is there a python equivalent for the ruby %w operator?
> %w{a b c} creates an array with strings "a", "b", and "c" in ruby...
>
 | >>> "a b c".split()
 | ['a', 'b', 'c']

 ... appears to match your single example.
>>> Something wrong with "list('abc')"? Or is it too simple?!
>>>
>>> Thorsten
>> As far as I can tell this works for single characters only. You're not 
>> able to split words, as in "one two three".split().
> 
> It does satisfy your example in your first posting nevertheless.
> 
> Thorsten

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


Re: IDLE - Customizing output format

2006-09-27 Thread Ilias Lazaridis
Gabriel Genellina wrote:
> At Tuesday 26/9/2006 15:29, Ilias Lazaridis wrote:
>
> > >  >>> def f(obj):
> > >   print '' + repr(obj)
> > >
> > >  >>> sys.displayhook = f
> >
> >I've placed this code within /Lib/sitecustomize.py, but have one
> >strange result:
...
> > >>> t.sayHello()
> >Hello world
> >   : None

> >1st: "Hello world" comes still on the beginning.
> >2nd: I got this "None"

import sys
def f(obj):
if obj:
print '::: ' + repr(obj)
sys.displayhook = f

> The replacement should be a bit more complicated, taking None into
> account - see the original PEP for details
> http://www.python.org/dev/peps/pep-0217/
> And notice that this replaces the output of *evaluated* expressions,
> not any print statement executed inside your code.

Any simple solution for this?

I've looked a little at the code, but get immediately demotivated
seeing 72 files within a flat directroy:

http://svn.python.org/view/python/trunk/Lib/idlelib/?rev=52013

.

--
http://lazaridis.com

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


Re: baffling sql string

2006-09-27 Thread Duncan Booth
DarkBlue <[EMAIL PROTECTED]> wrote:

> iq1="update MSGTALK set msgdate='NOW',subject='%s',talktext='%s' where
> msgno= %d " % (mysubject,mytalktext,mymsgno) 
> try:
>self.cur.execute(iq1)

Use parameterised queries and get rid of the quotes in the SQL:

iq1="update MSGTALK set msgdate='NOW',subject=%s,talktext=%s where
msgno= %d "
try:
   self.cur.execute(iq1, (mysubject,mytalktext,mymsgno))
...

depending on your actual database you might need to use something other 
than %s to specify the parameters. Check out 'paramstyle' for your database 
connection.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: does anybody earn a living programming in python?

2006-09-27 Thread GHUM
walterbyrd,

Answer: Yes. Definitely. And, to be correct, there are some who earn a
rather comfortable living programming in Python.

> If so, I doubt there are many.

depending on your definition of "many". if "many" is something around
"1% of population of earth", you are right.

If "many" is "more than 1000", than you are wrong.

I formyself earn the major part of my income doing Python - combined
with database knowledge, of course.


> I wonder why that is?
There seems to be a challenge to have more people programm Python: to
hire people with Python knowledge. Maybe the recruiters of Google can
enlighten you on the prospects of Python programmers on the market :)

Java is educated in a kind of vocational training in universities; but
at the moment only the elite gets in touch with Python.

Harald

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


Re: baffling sql string

2006-09-27 Thread skip

DarkBlue> Following is a code snippet from a pythoncard app
DarkBlue> the problem is with the sql string called iq1
DarkBlue> If either mysubject or mytalktext contains an 
DarkBlue> apostrophe the update fails :
DarkBlue> Example: mysubject="Let's Eat"  this fails
DarkBlue>  mysubject="Lets Eat"   this works fine

DarkBlue> What options do I have to avoid this issue but still can use
DarkBlue> apostrophes in my input data ?

You don't mention what database adapter you're communicating with, but they
all have argument quoting facilities.  You should be using them instead of
doing the string interpolation yourself.

For example, if I was using MySQL, my code might look something like this:

self.cur.execute("update MSGTALK"
 "  set msgdate='NOW', subject=%s, talktext=%s"
 "  where msgno=%s",
 (self.components.TextField1.text,
  self.components.TextArea1.text,
  self.myamsgno))

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


Re: baffling sql string

2006-09-27 Thread Paul Boddie
DarkBlue wrote:
>
> Example: mysubject="Let's Eat"  this fails
>  mysubject="Lets Eat"   this works fine
>
> What options do I have to avoid this issue but still
> can use apostrophes in my input data ?

Use proper "bind parameters" or "bind variables" when executing the
statement, rather than using string substitution/interpolation.

[...]

> iq1="update MSGTALK set msgdate='NOW',subject='%s',talktext='%s' where
> msgno= %d " % (mysubject,mytalktext,mymsgno)

This merely "edits" a statement, stuffing values directly into the
text. As you've noticed, merely substituting values for placeholders
isn't always going to work. Moreover, it's something that could cause
errors (in the nicest circumstances such as in a local application) or
security holes (in nasty circumstances such as in networked or Web
applications).

Instead try this:

iq1="update MSGTALK set msgdate='NOW',subject=%s,talktext=%s" \
  " where msgno=%d" # note that the parameters are not substituted here

Then execute the statement with the parameters as a separate argument:

self.cur.execute(iq1, [mysubject,mytalktext,mymsgno])

The database module will then ensure that the values you've supplied
really will get used properly when executing the statement, and things
like apostrophes won't cause any problems at all.

Paul

P.S. The above assumes that the "parameter style" of the database
module is "format", as found by looking at the paramstyle attribute of
the module (eg. MySQLdb.paramstyle). Other styles include "qmark" where
you use "?" instead of "%s" (or other format codes) to indicate where
your values will be used in a statement.

P.P.S. See also the DB-API 2.0 specification:
http://www.python.org/dev/peps/pep-0249/

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


Re: baffling sql string

2006-09-27 Thread John Machin
DarkBlue wrote:
> Following is a code snippet from a pythoncard app
> the problem is with the sql string called iq1
> If either mysubject or mytalktext contains an
> apostrophe the update fails :
> Example: mysubject="Let's Eat"  this fails
>  mysubject="Lets Eat"   this works fine
>
> What options do I have to avoid this issue but still
> can use apostrophes in my input data ?
>
> mysubject=self.components.TextField1.text
> mytalktext=self.components.TextArea1.text
> mymsgno=self.myamsgno
> iq1="update MSGTALK set msgdate='NOW',subject='%s',talktext='%s' where
> msgno= %d " % (mysubject,mytalktext,mymsgno)

Your SQL after the % formatting will read something like this:
update ... set ... subject='Let's Eat',talktext=
which is illegal SQL syntax -- if a string constant contains an
apostrophe, it must be doubled:
 ... subject='Let''s Eat', ...
which would require you to do data.replace("'", "''") on each text
column. In general, % formatting is *not* a good idea, for this reason
and also because it leaves you wide open to an SQL injection attack. It
is much better to use the placeholder system, and let the called
software worry about inserting apostrophes, converting date formats,
etc etc. So:

iq1="""\
update MSGTALK
set msgdate='NOW', subject=?, talktext=?
where msgno= ?
"""

self.cur.execute(iq1, (mysubject,mytalktext,mymsgno))

Your [unspecified] DBMS adaptor may use some other placeholdet than
"?"; this will be documented in its manual .

HTH,
John

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


Re: baffling sql string

2006-09-27 Thread DarkBlue
Duncan Booth wrote:
> ...
> 
> depending on your actual database you might need to use something other
> than %s to specify the parameters. Check out 'paramstyle' for your
> database connection.


Thank you all for prompt suggestions

I am using firebird 1.5.3 with kinterbasdb

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


Re: a different question: can you earn a living with *just* python?

2006-09-27 Thread Roy Smith
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> SQL I don't class as a programming language, but it's certainly worth
> learning for most modern programmers.

I suppose it's not a *programming* language in the sense that it's not  
Turning Complete, but it *is* a language, with a complex syntax.  But, more 
to the point, knowing SQL opens your eyes to a way to think about, 
organize, and manipulate data which is very different from conventional 
procedural languages.  That's the real value in learning it.

Oh, I left out regular expressions.  Again, not a programming language 
per-se, but a powerful and complex tool which manipulates data in a very 
different way from other things.  There are jobs for which good grasp of 
regexes will save you hundreds of lines of code.  It's not the right tool 
for every job, but it's a tool that anybody who calls themselves a 
professional programmer should have in their collection.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: identifying new not inherited methods

2006-09-27 Thread John Roth

[EMAIL PROTECTED] wrote:
> Hi,
>
> I am writing a library in which I need to find the names of methods
> which are implemented in a class, rather than inherited from another
> class. To explain more, and to find if there is another way of doing
> it, here is what I want to do: I am defining two classes, say A and B,
> as:
>
> class A(object):
> def list_cmds(self):
> 'implementation needed'
> ?
> def __init__(self):
> ... (rest of class)
>
> class B(A):
> def cmd1(self, args):
> pass
> def cmd2(self, args):
> pass
>
> I need an implementation of list_cmds in A above so that I can get a
> result:
>
> >>> b=B()
> >>> b.list_cmds()
> ['cmd1','cmd2']#order not important
>
> I will be happy if anybody can point to me any way of doing it, using
> class attributes, metaclasses or otherwise. What I don't want to do is
> modifying class B, which contains just the cmds, if possible.
>
> Many thanks in advance.
>
> k

When I want to do this, I scan the __dict__
attribute of the class. If all you care about is
instance methods (which is all I care about
at the moment), they're just ordinary functions.
Do an isinstance and you've got it.

If you want to dig deeper and look at class
methods, static methods, descriptors and
other stuff, it's a bit more complicated, but
not much.

John Roth
Python FIT

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


Re: a query on sorting

2006-09-27 Thread Paul McGuire

"Steve Holden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]


  >>> [x for x in enumerate(a)]
[(0, 9), (1, 4), (2, 3), (3, 5), (4, 2), (5, 6), (6, 7), (7, 1), (8, 2)]


Just curious, Steve, but why do this list comprehension when:

list(enumerate(a))

works just as well?

In the interests of beating a dead horse into the ground (metaphor-mixing?), 
I looked at using map to one-line the OP's request, and found an interesting 
inconsistency.

I tried using map(reversed, list(enumerate(a))), but got back a list of 
iterators.  To create the list of tuples, I have to call the tuple 
constructor on each one, as in:

map(tuple,map(reversed,list(enumerate(a

However, sorted returns a list, not a listsortediterator.  Why the 
difference in these two builtins?

I guess you can beat a dead horse into the ground, but you can't make him 
drink.

-- Paul


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


Re: does anybody earn a living programming in python?

2006-09-27 Thread Steven D'Aprano
On Tue, 26 Sep 2006 22:00:55 +1000, Anthony Baxter wrote:

> This seems to be a very, very silly original post. I know of plenty of
> people who make a living programming Python. It's been the vast
> majority of the programming (for money) I've done in the last ten
> years, and there's countless other people I know here in Melbourne in
> the same position.

Countless people? Are we talking aleph-zero people (countable infinity) or
one of the uncountable infinities?


-- 
Steven.

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


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread Paul McGuire
"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On 2006-09-27, Peter Otten <[EMAIL PROTECTED]> wrote:
>> Antoon Pardon wrote:
>>
>>> I had written my own module, which works similarly but
>>> is somewhat extended. Here is an example of how it can
>>> be used and how I would like to use it but get stuck.
>>>
>>> from extreme import Top
>> Top
>>> Top
>> Top + 1
>>> Top
>> Top - 30
>>> Top
>> Top > 1e99
>>> True
>> lst = range(10)
>> lst[:Top]
>>> Traceback (most recent call last):
>>>   File "", line 1, in ?
>>> TypeError: slice indices must be integers or None
>>>


What about this?

-- Paul


class TopClass(int):
def __add__(self,other):
return self
def __sub__(self,other):
return self
def __mul__(self,other):
return self
def __div__(self,other):
return self
def __iadd__(self,other):
return self
def __isub__(self,other):
return self
def __imul__(self,other):
return self
def __idiv__(self,other):
return self
def __str__(self):
return "Top"

import sys
Top = TopClass(sys.maxint)

print Top
print int(Top)
print int(Top-1e9)

a = range(10)
print a[:Top]
print a[Top:]
print a[3:Top]


Prints:
Top
2147483647
2147483647
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[]
[3, 4, 5, 6, 7, 8, 9] 


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


Re: does anybody earn a living programming in python?

2006-09-27 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> On Tue, 26 Sep 2006 22:00:55 +1000, Anthony Baxter wrote:
> 
> > This seems to be a very, very silly original post. I know of plenty of
> > people who make a living programming Python. It's been the vast
> > majority of the programming (for money) I've done in the last ten
> > years, and there's countless other people I know here in Melbourne in
> > the same position.
> 
> Countless people? Are we talking aleph-zero people (countable infinity) or
> one of the uncountable infinities?

Countless and uncountable are not the same thing.  The former simply means 
you haven't bothered to count them yet, which as a basis for number theory, 
sounds like it belongs in a Douglas Adams book.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterator question

2006-09-27 Thread [EMAIL PROTECTED]
Simple list comprehension?

>>> l = [1,2,3,4,5,6,7,8,9,0]
>>> [(x, x+1) for x in l if x%2 == 1]
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]

Danny

Neal Becker wrote:
> George Sakkis wrote:
>
> > [EMAIL PROTECTED] wrote:
> >
> >> def transform(seq, size):
> >> i = 0
> >> while i < len(seq):
> >> yield tuple(seq[i:i+size])
> >> i += size
> >
> > Or for arbitrary iterables, not just sequences:
> >
> > from itertools import islice
> > def transform(iterable, size):
> >  it = iter(iterable)
> >  while True:
> >  window = tuple(islice(it,size))
> >  if not window:
> > break
> >  yield window
> >
> > George
> > 
> 
> Thanks guys!
> 
> This one above is my personal favorite.

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


How to change menu text with Tkinter?

2006-09-27 Thread Phil Schmidt
I am making a little Tkinter GUI app that needs to be in several
languages (english, french, etc.), adjustable at runtime via a menu
pick to select the language. The only way I can see to change text in
the menus entries is to destroy them and recreate them usiing different
labels. This seems very clunky though, and there must be a better way.
Can anyone offer any pointers or a short example for how to do this?

Thanks,
Phil

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


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread Paul McGuire
"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On 2006-09-27, Peter Otten <[EMAIL PROTECTED]> wrote:
>> Antoon Pardon wrote:
>>
>>> I had written my own module, which works similarly but
>>> is somewhat extended. Here is an example of how it can
>>> be used and how I would like to use it but get stuck.
>>>
>>> from extreme import Top
>> Top
>>> Top
>> Top + 1
>>> Top
>> Top - 30
>>> Top
>> Top > 1e99
>>> True
>> lst = range(10)
>> lst[:Top]
>>> Traceback (most recent call last):
>>>   File "", line 1, in ?
>>> TypeError: slice indices must be integers or None
>>>

Here's a little more refined version of my previous post:

class StubbornInt(int):
def invariantOp(self,other):
return self
__add__ = invariantOp
__sub__ = invariantOp
__mul__ = invariantOp
__div__ = invariantOp
__iadd__ = invariantOp
__isub__ = invariantOp
__imul__ = invariantOp
__idiv__ = invariantOp
__radd__ = invariantOp
__rsub__ = invariantOp
__rmul__ = invariantOp
__rdiv__ = invariantOp
def __str__(self):
return self.name

import sys
Top = StubbornInt(sys.maxint)
Top.name = "Top"
Bottom = StubbornInt(-sys.maxint-1)
Bottom.name = "Bottom"

print Top
print int(Top)
print int(Top-1e9)
print Bottom
print Bottom+sys.maxint
print int(Bottom+sys.maxint)

a = range(10)
print a[:Top]
print a[Top:]
print a[3:Top]
print 3+Top
print Top+3
print 5+2/6*Top
print a[Bottom:3]

for i in xrange(Top):
print i
if i > 10: break


prints:

Top
2147483647
2147483647
Bottom
Bottom
-2147483648
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[]
[3, 4, 5, 6, 7, 8, 9]
Top
Top
Top
0
1
2
3
4
5
6
7
8
9
10
11
[0, 1, 2] 


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


Re: f2py on windows tutorials

2006-09-27 Thread Flavio
Ok,

I tried that and it seems we are making progress

so here is my command:

python setup.py build_ext --compiler=mingw32 --fcompiler=gnu

Now it is complaining about my pyf!!

error: unknown file type '.pyf'

here is my setup .py:

import setuptools, os
from numpy.distutils.core import setup, Extension

#Configuring Build
libs=[];libdirs=[];f2pyopts=[]
if os.name == 'nt':
f2pyopts.extend(["--compiler=mingw32","--fcompiler=gnu"])



flib = Extension(name='flib',
libraries=libs,
library_dirs=libdirs,
f2py_options=f2pyopts,

sources=['model-builder/Bayes/flib.f','model-builder/Bayes/flib.pyf',]
)
etc...
>
> More specifically:
>
>python setup.py build_ext --compiler=mingw --fcompiler=gnu
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>-- Umberto Eco

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


Re: iterator question

2006-09-27 Thread [EMAIL PROTECTED]
Er, whoops.  That would work if the last item in the list was 10 (and,
of course, this doesn't work for any arbitrary sequence).  Is there any
"look-ahead" function for list comprehensions?

Danny

[EMAIL PROTECTED] wrote:
> Simple list comprehension?
>
> >>> l = [1,2,3,4,5,6,7,8,9,0]
> >>> [(x, x+1) for x in l if x%2 == 1]
> [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
>
> Danny
>
> Neal Becker wrote:
> > George Sakkis wrote:
> >
> > > [EMAIL PROTECTED] wrote:
> > >
> > >> def transform(seq, size):
> > >> i = 0
> > >> while i < len(seq):
> > >> yield tuple(seq[i:i+size])
> > >> i += size
> > >
> > > Or for arbitrary iterables, not just sequences:
> > >
> > > from itertools import islice
> > > def transform(iterable, size):
> > >  it = iter(iterable)
> > >  while True:
> > >  window = tuple(islice(it,size))
> > >  if not window:
> > > break
> > >  yield window
> > >
> > > George
> > >
> > 
> > Thanks guys!
> > 
> > This one above is my personal favorite.

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


Re: How to change menu text with Tkinter?

2006-09-27 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Phil Schmidt
wrote:

> I am making a little Tkinter GUI app that needs to be in several
> languages (english, french, etc.), adjustable at runtime via a menu
> pick to select the language. The only way I can see to change text in
> the menus entries is to destroy them and recreate them usiing different
> labels. This seems very clunky though, and there must be a better way.
> Can anyone offer any pointers or a short example for how to do this?

Do you really need this at runtime or is it enough to store the language
in a config file and ask the user to restart the application?  Then using
the `gettext` module is a good way.  Maybe in combination with the
`locale` module so you can use the language of the operating system as
default if the user doesn't choose one explicitly.

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


Re: a different question: can you earn a living with *just* python?

2006-09-27 Thread John Salerno
[EMAIL PROTECTED] wrote:

> Yes, and making sure that the first several you learn are disparate in
> their common idioms and programming models is incredibly worthwile to
> your development as a programmer IMO.

You're right about that. While I'm definitely no expert in it, I did 
start learning C# last year (even before I started with Python), and 
though I never got too far with it, it was a great experience to learn a 
language like that, and then move on to something as different as 
Python. It really helped me to see how things are done differently given 
the type of language you are using.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.5 updates for syntax file

2006-09-27 Thread John Salerno
Fuzzyman wrote:

>> Who is using FAR and isn't happy ?
> 
> What is FAR ?

I'm glad I'm not the only one who doesn't know :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to change menu text with Tkinter?

2006-09-27 Thread Rob Wolfe

Phil Schmidt wrote:
> I am making a little Tkinter GUI app that needs to be in several
> languages (english, french, etc.), adjustable at runtime via a menu
> pick to select the language. The only way I can see to change text in
> the menus entries is to destroy them and recreate them usiing different
> labels. This seems very clunky though, and there must be a better way.
> Can anyone offer any pointers or a short example for how to do this?

Try this:

menu.entryconfig(index, label="new_name")

HTH,
Rob

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


Re: How to change menu text with Tkinter?

2006-09-27 Thread Eric Brunel
On Wed, 27 Sep 2006 15:29:32 +0200, Phil Schmidt  
<[EMAIL PROTECTED]> wrote:

> I am making a little Tkinter GUI app that needs to be in several
> languages (english, french, etc.), adjustable at runtime via a menu
> pick to select the language. The only way I can see to change text in
> the menus entries is to destroy them and recreate them usiing different
> labels. This seems very clunky though, and there must be a better way.
> Can anyone offer any pointers or a short example for how to do this?

Here is a way:

--
 from Tkinter import *

root = Tk()
mb = Menu(root)
root.configure(menu=mb)
fm = Menu(mb)
mb.add_cascade(label='File', menu=fm)

def chlg():
   mb.entryconfigure(1, label='Fichier')
   fm.entryconfigure(1, label='Changer de langue')
   fm.entryconfigure(2, label='Quitter')

fm.add_command(label='Change language', command=chlg)
fm.add_command(label='Quit', command=root.quit)

root.mainloop()
--

Note that the entry indices start at 1 because of the 'tearoff' entry that  
is always created in a menu. If you specify the option tearoff=0 when  
creating the menus, indices will start ot 0.

But Marc's answer still applies: it's a lot of work for something that  
will usually be configured once. So requiring to restart the tool when the  
UI language changes should be acceptable.

> Thanks,
> Phil

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread Sion Arrowsmith
Lawrence D'Oliveiro  <[EMAIL PROTECTED]> wrote:
>In message <[EMAIL PROTECTED]>, Antoon Pardon wrote:
>> I need this Top value in
>> a context where it can be used as a start or stop value
>> in a slice.
>But the only valid values allowed for indices are 0

>>> range(5)[:-1]
[0, 1, 2, 3]

>  up to the length of the
>array inclusive. Larger integers are not allowed, [ ... ]

>>> range(5)[:sys.maxint]
[0, 1, 2, 3, 4]

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for: else: - any practical uses for the else clause?

2006-09-27 Thread Ben Sizer
[EMAIL PROTECTED] wrote:
> metaperl> I'm wondering if anyone has ever found a practical use for the
> metaperl> else branch?
>
> Yeah, I use it from time to time:
>
> for foo in bar:
> if foo matches some condition:
> print "sail to tahiti!"
> break
> else:
> print "abandon ship!"

As a C++ programmer (which I'm sure undermines my argument before
you've even read it...), this feels 'backwards' to me. Although I am no
purist, the 'else' typically implies failure of a previous explicit
condition, yet in this case, it's executed by default, when the
previous clause was successfully executed. It would seem more natural
if the else clause was triggered by 'bar' being empty, or even if the
loop was explicitly broken out of, though I'm sure that would make the
construct much less useful.

-- 
Ben Sizer

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


Re: does anybody earn a living programming in python?

2006-09-27 Thread Steven D'Aprano
On Wed, 27 Sep 2006 09:17:28 -0400, Roy Smith wrote:

> In article 
> <[EMAIL PROTECTED]>,
>  Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> 
>> On Tue, 26 Sep 2006 22:00:55 +1000, Anthony Baxter wrote:
>> 
>> > This seems to be a very, very silly original post. I know of plenty of
>> > people who make a living programming Python. It's been the vast
>> > majority of the programming (for money) I've done in the last ten
>> > years, and there's countless other people I know here in Melbourne in
>> > the same position.
>> 
>> Countless people? Are we talking aleph-zero people (countable infinity) or
>> one of the uncountable infinities?
> 
> Countless and uncountable are not the same thing.  The former simply means 
> you haven't bothered to count them yet, which as a basis for number theory, 
> sounds like it belongs in a Douglas Adams book.

You're thinking of "uncounted", which means "not counted yet". The
dictionary definition of countless is "too many to count" (Pocket Oxford),
which I suppose could be 11 for some people if they didn't take their
shoes and socks off. Mathematically, any finite integer is able to be
counted, so "countless" is equivalent to "infinite in number".

Of course, I suppose it is conceivable that there isn't actually an
infinite number of Python programmers living in Melbourne, and Anthony was
exaggerating just a tad. Maybe it's not actually infinite, just very, very
large. Graham's Number perhaps?

http://en.wikipedia.org/wiki/Graham's_number



-- 
Steven.

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


Re: Top and Bottom Values [PEP: 326]

2006-09-27 Thread Antoon Pardon
On 2006-09-27, Paul McGuire <[EMAIL PROTECTED]> wrote:
> "Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> On 2006-09-27, Peter Otten <[EMAIL PROTECTED]> wrote:
>>> Antoon Pardon wrote:
>>>
 I had written my own module, which works similarly but
 is somewhat extended. Here is an example of how it can
 be used and how I would like to use it but get stuck.

 from extreme import Top
>>> Top
 Top
>>> Top + 1
 Top
>>> Top - 30
 Top
>>> Top > 1e99
 True
>>> lst = range(10)
>>> lst[:Top]
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: slice indices must be integers or None

>
> Here's a little more refined version of my previous post:
>
> class StubbornInt(int):
> def invariantOp(self,other):
> return self
> __add__ = invariantOp
> __sub__ = invariantOp
> __mul__ = invariantOp
> __div__ = invariantOp
> __iadd__ = invariantOp
> __isub__ = invariantOp
> __imul__ = invariantOp
> __idiv__ = invariantOp
> __radd__ = invariantOp
> __rsub__ = invariantOp
> __rmul__ = invariantOp
> __rdiv__ = invariantOp
> def __str__(self):
> return self.name
>
> import sys
> Top = StubbornInt(sys.maxint)
> Top.name = "Top"
> Bottom = StubbornInt(-sys.maxint-1)
> Bottom.name = "Bottom"

Well one problem I have with your solution is the following:

  >>> for x in xrange(sys.maxint - 2, Top):
  ...   print x
  ... 
  2147483645
  2147483646
  >>> 

The idea with a Top (and Bottom) variable is that you once and for
all have a value that is bigger (smaller) than any other value you are
going to use. AFAICS using a subclass of int will always
leave an opportunity open where an other value will be treated
as bigger (smaller), because functions like xrange will just
look at the int value of the object.

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


  1   2   3   >