Re: Python and CUDO

2007-09-07 Thread Paddy
On Sep 6, 10:12 pm, Robert Kern <[EMAIL PROTECTED]> wrote:
> Veronika Lindstrand Kant wrote:
> > Hi!
> > I just wonder if there are any plans for building any support using
> > NIVIDAS CUDO plattform into python?
>
> Not into Python itself, but we are working on interfacing with NVIDIA's CUDA,
> yes (presuming you actually meant "NVIDIA's CUDA" rather than "NIVIDAS CUDO").
>
> http://code.google.com/p/pystream/
>
> --
> 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

Maybe you and the CorePy guys at http://www.corepy.org/ could swap
notes and give us a similar way to work with these accellerators?

- Paddy.

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


How to convert None to null value

2007-09-07 Thread pradeep kumar
Hi ,

i am trying to insert records from one table to another table in postgres
sql using the the following code

posConn.query("insert into
usr(usr_id,usr_name,usr_passwd,grp_cde,usr_type,usr_chk_till_val, \

usr_active,usr_daily_auth,usr_lst_login,usr_lst_logout,usr_shift_id,usr_role_level)
values \
 ('%s','%s','%s',%s,%i,%d,'%s',%i,%i,%i,%i,%i)"
%(row[0],row[1],row[2],row[3],row[4],row[5], \
  row[7],row[8],row[10],row[11],row[12],row[14]) )

here row[4] column is having null value so python consides it as None but
will insert into the table it inserts as None not null value

please help how to convert None to null value
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Wildemar Wildenburger
gu wrote:
> hi to all!
> after two days debugging my code, i've come to the point that the 
> problem was caused by an unexpected behaviour of python. or by lack of 
> some information about the program, of course! i've stripped down the 
> code to reproduce the problem:
> 
> [snip FAQ]

Yes, basically you *created* a pointer. That's all that python has: 
pointers.

When saying
   >>> a = AnyOldObject()
   >>> b = a
then 'a' and 'b' are different /names/ for the /very same/ object (try 
"a is b", or "id(a)==id(b)").

This is really a FAQ (once a week or so?), but for the life of me I 
can't find the right words for a google query.
TO THE TROOP: What keywords would you attach to that question?

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


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Roel Schroeven
gu schreef:
> copyOfA = a
> 
> now, in the second "for" cycle and in functionA() i only 'touch' copyOfA 
> (altering it).

copyOfA isn't a copy of a; it's a different name bound to the same 
object as a. You can verify that: id(a) and id(copyOfA) will return the 
same value.

To make a copy of a (assuming a is a dict), you can do:

copyOfA = dict(a)

or

copyOfA = a.copy()

or more generally

import copy
copyOfA = copy.copy(a)


Cheers,
Roel

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 10:40:47 +, Steven D'Aprano wrote:

> Nor does it include "peek" and "poke" commands for reading and writing 
> into random memory locations.

I guess `ctypes` offers tools to write `peek()` and `poke()`.  :-)

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


Re: So what exactly is a complex number?

2007-09-07 Thread Bjoern Schliessmann
Grzegorz S?odkowicz wrote:
> Interesting. It appears that we are ran into a mathematical
> cultural difference. Were I come from vectors *are* defined as
> having four properties that I enumerated. After some research I
> found that English sources (Wikipedia) indeed give the definition
> you supplied. 

Indeed, interesting.

> However, given the following problem: (assuming 2-d Cartesian
> coordinate system and gravity acting 'downwards') "There are 3
> point masses: 2 kg at (0, 0), 1 kg at (5, 4) and 4 kg at (2, 2).
> The acting forces are given as vectors: [2, 2] [1, 1]. Find the
> trajectories of all point masses." how would you propose to solve
> it without knowing where the forces are applied?

I didn't say that you must not know the point of application, but I
said that it was not a property of the vector itself. It is true,
however, that in physical calculations you should not "mix" many
types of vectors (like force) that are, in the experiment, applied
to different points of application.

> Again, I think we were given different definitions. Mine states
> that direction is 'the line on which the vector lies', sense is
> the 'arrow' and magnitude is the 'length' (thus non-negative). The
> definition is separate from mathematical description (which can be
> '[1 1] applied at (0, 0)' or 'sqrt(2) at 45 deg applied at (0, 0)'
> or any other that is unambiguous).

Oh, I thought we were talking about quite mathematical vectors? In
physics, I learned that a vector is only what transforms like a
vector.

>> Represent the direction as one number? Only in a one-dimensional
>> space.
>   
> No. In one-dimensional 'space' direction is a ± quantity (a
> 'sense'). In 2-d it can be given as an angle.

Indeed, you're right. So, those vectors have different properties
depending on the used coordinate system? I myself prefer the
concise definition ...

Regards,


Björn

-- 
BOFH excuse #128:

Power Company having EMP problems with their reactor

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


Re: Any syntactic cleanup likely for Py3? And what about doc standards?

2007-09-07 Thread Paul Boddie
On 7 Sep, 06:19, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On Sep 6, 12:56 pm, Paul Boddie <[EMAIL PROTECTED]> wrote:
>
> > I think there's been a widespread "kitchen sink" mentality around the
> > Python language for some time, which is where the multimethods
> > proposal, amongst others, fits in here.
>
> Maybe that's one of two fixed points in the evolution of a programming
> language? The other one might be an almost non-designed and small
> language with a vast and flat library a la PHP and Zend. Apparently
> even Scheme moves into the kitchen sink today with the new R6RS
> specification.

My impression of PHP (before version 5), derived from anecdotes and
general criticism, is that both the language and the most promoted
libraries have accumulated features without much regard to how the end-
user experience works out. In contrast, it is said that Python has
been improved with more attention to the end-user experience (albeit
with limitations related to the main implementation and backwards
compatibility), with Python 3000 being the pinnacle of this user-
centric process. Regardless of whether Python 3000 really tidies up
the experience, it is notable that the promotional value of the
standard library has diminished, perhaps because the core developers
no longer feel that the language attracts embarrassing criticism which
is best answered by deflecting the critic to standard library
solutions.

> Python is going to be the-right-thing with abandoning the print
> statement or making lists a bit more monotyped with a type aware sort.
> The worse-is-better philosophy on the other hand is  indifferent
> towards stylistic consistency and equipped with less nominalistic
> pedantry ( "this is a list and therefore you only have to use it as a
> list and not as a multiset..." ).

I think you've swum into the philosophical "deep end" on this
point. ;-) But of the different articles on the PythonWarts page I
mentioned, Mertz's criticisms (which include notes on sorting
heterogeneous collections) are certainly worth reading, partly because
they do highlight awkward-to-address end-user expectations whilst
being fairly modern criticisms. That's not to say that I agree with
everything he writes, although I have some sympathy with his opinions
on iterators vs. sequences and the current level of convenience in
this area.

> This explains also the lack of interest into the std library which
> will be reduced to CPython services and basic datatypes. But there are
> also organizational issues and I don't even think that a lib that
> provides applications and domain specific services has to be
> necessarily maintained and approved by python-dev. I'd go even further
> and contend that's one of the issues where a rather large community
> such as Pythons could grow up and set code review standards ( and I
> mean *manual* code reviews of conscientous readers. I don't mean
> cheesecake or up(down)moddings in Web 2.0 style, implementing the
> "wisdom of the crowd" ). I can even live with Eggs and a not-so-common
> code base but not with low quality.

Once upon a time I wrote some thoughts down about marketing Python
where one considers a number of things as the "product" or "solution".
Certainly, in earlier times, adding stuff to the standard library was
a way of positioning Python as a solution to problems in particular
domains: if you needed to write a mail client, for example, Python
provided a working solution as standard that would potentially be
enough to persuade people to use Python for such a project. The belief
that modules should be included in the standard library is a
continuation of this "positioning" or advocacy-related sentiment, as
well as being an issue of convenience, of course.

As technical issues start to encourage other models for providing
solutions based on Python, one has to consider the social aspects of
such models. Where something in the standard library should have an
implicit stamp of approval, although opinions are divided on whether
some modules deserve their place, other models need to support notions
of approval, credibility, quality, and so on. And there we have
different approaches: repositories (optionally with rankings, noticing
that Ubuntu seems to be adding support for such things),
megaframeworks (where people effectively recommend a combination of
solutions), "heavy" distributions (with a selection of popular
packages in an enlarged standard library).

In my opinion, such wider work on promoting Python's usability is
possibly more beneficial to both potential and existing elements of
the community than merely polishing the language and hoping that
people are motivated to write great code because of the increased
elegance.

Paul

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


Best practice prompting for password

2007-09-07 Thread GiBo
Hi,

what's the best practice to securely prompt user for password on console
in Python? IIRC some programs like SSH do a lot to ensure that the input
comes from TTY and is not redirected from somewhere and several other
checks. In the case of OpenSSH even the password prompt is always
displayed regardless if the output is redirected to a file or not.

Any pointers to best practice or code snippet of python password prompt?

Thanks

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


Re: Class design (information hiding)

2007-09-07 Thread Alexander Eisenhuth
Bruno Desthuilliers schrieb:

> Nope. It's either 'interface' (no leading underscore),  'implementation' 
> (single leading underscore), 'implementation with some protection 
> against accidental overriding' (two leading underscores).

What do you mean with 'implementation'? What does it express?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Grant Edwards
On 2007-09-07, Peter Otten <[EMAIL PROTECTED]> wrote:
> Am Fri, 07 Sep 2007 10:40:47 + schrieb Steven D'Aprano:
>
>> Python doesn't have any pointers.
>
> Thinking of python variables or "names" as pointers should
> get you a long way when trying to understand python's behaviour.

But thinking of them as names bound to objects will get you
further (and get you there faster). ;)

> As long as you keep in mind that python doesn't have pointers
> to pointers, and no pointer arithmetic either...

-- 
Grant Edwards   grante Yow! Hello...  IRON
  at   CURTAIN?  Send over a
   visi.comSAUSAGE PIZZA!  World War
   III?  No thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython unexpected exit

2007-09-07 Thread kyosohma
On Sep 7, 3:10 am, Jimmy <[EMAIL PROTECTED]> wrote:
> Hi, wxPython is cool and easy to use, But I ran into a problem
> recently when I try to write a GUI.
> The thing is I want to periodically update the content of StatixText
> object, so after create them, I pack them into a list...the problem
> comes when I later try to extract them from the list! I don't know
> why?
> my code is as following:
>
> import wx, socket
> import thread
>
> class MyFrame(wx.Frame):
>
> firstrun = 0
> def __init__(self):
> wx.Frame.__init__(self, None, -1, 'Notifier')
> self.panel = wx.Panel(self, -1)
> self.length = 50
> self.scale = 0.6
> self.count = 5
> self.size = wx.Frame.GetSize(self)
> self.distance = self.size[1] / self.count
> self.labellist = []
> self.gaugelist = []
>
> def ParseAndDisplay(self, data):
> print "Successful access to main Frame class"
> print 'And receive data: ', data
> if MyFrame.firstrun == 0:
> print 'First time run'
> items = 3
> for i in range(items):
> 
> self.labellist.append(wx.StaticText(self.panel, -1, data+str(i),
> (150, 50+i*20), (300,30)))
> MyFrame.firstrun = 1
> else:
> self.labellist[0].SetLabel('AAA')//PROGRAM WILL ABORT 
> HERE!!!
> self.labellist[1].SetLabel("Guo")
> self.labellist[2].SetLabel("Qiang")
>
> class NetUdp:
>
> def __init__(self):
> self.port = 8081
> self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> self.s.bind(("", self.port))
> print "Listening on port", self.port
>
> def recvdata(self):
> data, addr = self.s.recvfrom(1024)
> return data
>
> def netThread():
> netudp = NetUdp()
> while True:
> data = netudp.recvdata()
> frame.ParseAndDisplay(data)
>
> if __name__ == '__main__':
> firstrun = 0
> app = wx.PySimpleApp()
> frame = MyFrame()
> frame.Show()
> # start network thread first
> id = thread.start_new_thread(netThread, ())
> # main wxpython loop begins
> app.MainLoop()
>
> I know the code is ugly, but can anyone really save me here!

If you use threads that update the GUI, you need to take a look at the
following wiki page:
http://wiki.wxpython.org/LongRunningTasks

I've used the techniques therein and they *just work*. I'm not sure if
you can set values on items in a list or not. I've tried that sort of
thing and sometimes it works and sometimes it doesn't.

The wxPython group is probably the best place to ask these questions
anyway: http://www.wxpython.org/maillist.php

Mike


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


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 06:57:35 -0700, cjt22 wrote:

> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> 
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> 
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.
> 
> Any help on how I can perform this whole operation would be much
> appreciated.

This should be enough::

  steps.sort(key=lambda s: s.startTime)

If you sort strings of the form 'hh:mm:ss' the represented times are
sorted chronological.  No need to convert them to a number first.

If the "natural" sort criterion for `Step` objects is the start time you
might override `__cmp__()` of `Step`\s instead::

def __cmp__(self, other):
return cmp(self.startTime, other.startTime)

Now you can just sort the list with ``steps.sort()``.

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


RE: application version checking against database

2007-09-07 Thread Hamilton, William
> From: imageguy
> 
> We are trying to implement a system that checks the version of the
> application against a version number stored in the database.  We don't
> want the app and the db don't become out of sync.
> 
> We have tried setting a __version__ variable in the top most module,
> however, it seems that this is not accessible for the modules that are
> subsequently imported.  There are a several locations in the app where
> we want to do the version check, but we would like to have one place
> to set the version number, namely the top level module.
> 
> We have thought of creating a Version class and passing it around, but
> aren't really keen on that idea.
> 
> Any suggestions/ideas would be helpful.
> 
> 
> NOTE: the app is developed in wxPython.
> 

You could add a Version module that contains the version number and any
functions related to the version checking, and import that into the
modules that do version checking.

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


Re: Class design (information hiding)

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 15:17:06 +0200, Alexander Eisenhuth wrote:

> Bruno Desthuilliers schrieb:
> 
>> Nope. It's either 'interface' (no leading underscore),  'implementation' 
>> (single leading underscore), 'implementation with some protection 
>> against accidental overriding' (two leading underscores).
> 
> What do you mean with 'implementation'? What does it express?

I guess he meant 'implementation detail', i.e. someone other then the
author of the class should not use until he really knows the
implementation and that this all might change without notice in the next
release.

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


Re: Checking if elements are empty

2007-09-07 Thread Wildemar Wildenburger
Steven D'Aprano wrote:
> On Fri, 07 Sep 2007 11:12:05 +0200, Wildemar Wildenburger wrote:
> 
>> Lawrence D'Oliveiro wrote:
>>> In message <[EMAIL PROTECTED]>, Chris
>>> Mellon wrote:
>>>
 On 9/5/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> Doran, Harold wrote:
>> Is there a way to check if the first element of y is null?
>>
> len(y[0]) == 0
>
 Better spelled as

 if y[0]:
>>> Not a good idea.
>> Why not?
> 
> 
> What happens if y is an empty list?
> 
> 
An exception pops up, of course ;).

It all depends on the (intended) semantics of the program; the original 
question sounds like that list is supposed to have at least one element 
at that point, so there is no problem. And if it's not then that has to 
be dealt with, but that is not the problem here.
So the usual way to check if the first element of a list y is True in a 
boolean context is indeed "if y[0]:" (or for False of course "if not 
y[0]:").

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


Re: exponential float formmating

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 06:08:19 -0700, zunbeltz wrote:

> For compatibility reasons with an old program I have to format string
> in exponential format with the following format
> 
> 0.xE-yy
> 
> This means that the number start always by 0 and after the exponent
> there should be alway the sing and 2 number for the exponent.
> 
> for example 13 shoud be 0.13000E+02
> I always get 1.3E001

I don't know if this is platform dependent but this works for me:

In [41]: '%e' % 1.3
Out[41]: '1.30e+00'

In [42]: ('%e' % 1.3).upper()
Out[42]: '1.30E+00'

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


Re: Finding specific date ranges

2007-09-07 Thread kyosohma
On Sep 7, 2:47 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> Zentrader wrote:
> > On Sep 6, 7:56 am, [EMAIL PROTECTED] wrote:
> >> December 31, 2006January 13, 2007 # doesn't earn
> >> January 14, 2007January 27, 2007 # does earn
> >> January 28, 2007February 10, 2007 # doesn't
> >> February 11, 2007   February 24, 2007 # does
>
> > Am I over simplifying if I say that since it appears to be a two week
> > pay period, the date has to be greater than the 11th unless the first,
> > or first and second, are on a weekend, in which case it would be > 12
> > or > 13?  Or a reasonable facsimile thereof, depending on whether or
> > not the two week period is Saturday through Friday.
>
> I think it's one of those things where the neatest answer
> could well depend on the sort of heuristic you mention. As
> a rule, when I come across this kind of requirement, I tend
> to put the most general solution in place, unless a *real*
> optimisation is clearly called for. In my experience, this
> makes it much easier for the next person who looks at the
> code, typically years later, even if that's me!
>
> (This is has just happened to me this week, having to review
> a date-related calculation to do the repost frequency of the
> adverts my company deals with. I wrote the original code five
> years ago, and commented it intelligently, but I *still* had
> to work through the code twice when we had a problem with a
> particular cycle!)
>
> TJG

I think it's foolish NOT to comment code unless it's very well self-
documented. Even then, a couple lines of comments can be helpful. I've
had to translate a bunch of Kixtart code into Python and none of it
was commented and it wasn't well formed code either.

And I've had the same thing happen with code that's only a year old.
I'll read it and then go "what the?!" It's just not possible to
remember every line of code you write. I wish it was.

Mike

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


Re: Class design (information hiding)

2007-09-07 Thread Daniel Larsson
On 9/7/07, Alexander Eisenhuth <[EMAIL PROTECTED]> wrote:
>
> Bruno Desthuilliers schrieb:
>
> > Nope. It's either 'interface' (no leading underscore),  'implementation'
> > (single leading underscore), 'implementation with some protection
> > against accidental overriding' (two leading underscores).
>
> What do you mean with 'implementation'? What does it express?


"Don't touch my _members, they're my private parts! If you do, face the
consequences!"

Again, this isn't enforced by the language (other than the slight name
mangling on __names), but a convention that python programmers should adhere
to.

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

Re: Finding specific date ranges

2007-09-07 Thread kyosohma
On Sep 6, 6:41 pm, Zentrader <[EMAIL PROTECTED]> wrote:
> On Sep 6, 7:56 am, [EMAIL PROTECTED] wrote:
>
> > December 31, 2006January 13, 2007 # doesn't earn
> > January 14, 2007January 27, 2007 # does earn
> > January 28, 2007February 10, 2007 # doesn't
> > February 11, 2007   February 24, 2007 # does
>
> Am I over simplifying if I say that since it appears to be a two week
> pay period, the date has to be greater than the 11th unless the first,
> or first and second, are on a weekend, in which case it would be > 12
> or > 13?  Or a reasonable facsimile thereof, depending on whether or
> not the two week period is Saturday through Friday.

Yeah it is a 2-week period, but the starting day can change depending
on whether or not you're salaried. I haven't even looked at how we
handle unions. Ugh. But yes, you are correct.

Mike

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


Re: py2exe - change name of exe created

2007-09-07 Thread Grant Edwards
On 2007-09-07, imageguy <[EMAIL PROTECTED]> wrote:

> Note that every thing works fine with this and creates an exe
> program called "myprogram.exe"
>
> I would like to setup program to create an output called;
> "MyBestProgram.exe"
>
> IS that at all possible ?

ADD this to the end of your script:

import os
os.rename('dist/myprogram.exe','dist/MyBestProgram.exe')

-- 
Grant Edwards   grante Yow! Zippy's brain cells
  at   are straining to bridge
   visi.comsynapses ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb: ValueError Something Stupid

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 05:52 -0700, mcl wrote:
> > ValueError: invalid literal for int(): 0-
> >   args = ('invalid literal for int(): 0-',)
> >
> > =
> > Thanks Richard
> 
> Sort of solved it.
> 
> On that particular table it did not like * for all fields.
> 
> Any reason why that would be the case ?

None that we can divine without more information. What's the schema for
the table in question, which column(s) are you excluding to make the
query work, and what kind of data is in the column(s) you're excluding?

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: How to convert None to null value

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 11:19 +0200, pradeep kumar wrote:
> Hi ,
> 
> i am trying to insert records from one table to another table in
> postgres sql using the the following code 
> 
> posConn.query("insert into
> usr(usr_id,usr_name,usr_passwd,grp_cde,usr_type,usr_chk_till_val, \ 
> 
> usr_active,usr_daily_auth,usr_lst_login,usr_lst_logout,usr_shift_id,usr_role_level)
>  values \
>  ('%s','%s','%s',%s,%i,%d,'%s',%i,%i,%i,%i,%i)"
> %(row[0],row[1],row[2],row[3],row[4],row[5], \ 
>   row[7],row[8],row[10],row[11],row[12],row[14]) )
> 
> here row[4] column is having null value so python consides it as None
> but will insert into the table it inserts as None not null value 
> 
> please help how to convert None to null value 

If you were using a DB-API compliant module, you should use parameter
binding instead of building query strings by hand:
http://informixdb.blogspot.com/2007/07/filling-in-blanks.html

However, nothing in DB-API has a .query method, so either you're using a
module that's not conforming to DB-API, or you're using some kind of
wrapper around a DB-API module. In any case, you should try to find out
how to do parameter binding with whatever it is you're using. If it
doesn't have a parameter binding mechanism, you should throw it away and
replace it with a DB-API complaint module.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: wxPython unexpected exit

2007-09-07 Thread Thin Myrna

"Jimmy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi, wxPython is cool and easy to use, But I ran into a problem
> recently when I try to write a GUI.
> The thing is I want to periodically update the content of StatixText
> object, so after create them, I pack them into a list...the problem
> comes when I later try to extract them from the list! I don't know
> why?
> my code is as following:
>
> import wx, socket
> import thread
>
> class MyFrame(wx.Frame):
>
> firstrun = 0
> def __init__(self):
> wx.Frame.__init__(self, None, -1, 'Notifier')
> self.panel = wx.Panel(self, -1)
> self.length = 50
> self.scale = 0.6
> self.count = 5
> self.size = wx.Frame.GetSize(self)
> self.distance = self.size[1] / self.count
> self.labellist = []
> self.gaugelist = []
>
> def ParseAndDisplay(self, data):
> print "Successful access to main Frame class"
> print 'And receive data: ', data
> if MyFrame.firstrun == 0:
> print 'First time run'
> items = 3
> for i in range(items):
> self.labellist.append(wx.StaticText(self.panel, -1, data+str(i),
> (150, 50+i*20), (300,30)))
> MyFrame.firstrun = 1
> else:
> self.labellist[0].SetLabel('AAA')//PROGRAM WILL ABORT HERE!!!
> self.labellist[1].SetLabel("Guo")
> self.labellist[2].SetLabel("Qiang")
>
>
> class NetUdp:
>
> def __init__(self):
> self.port = 8081
> self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> self.s.bind(("", self.port))
> print "Listening on port", self.port
>
> def recvdata(self):
> data, addr = self.s.recvfrom(1024)
> return data
>
>
> def netThread():
> netudp = NetUdp()
> while True:
> data = netudp.recvdata()
> frame.ParseAndDisplay(data)
>
> if __name__ == '__main__':
> firstrun = 0
> app = wx.PySimpleApp()
> frame = MyFrame()
> frame.Show()
> # start network thread first
> id = thread.start_new_thread(netThread, ())
> # main wxpython loop begins
> app.MainLoop()
>
> I know the code is ugly, but can anyone really save me here!
>

Communication OS thread -> wx has to be done in a certain way. You must not 
do this directly, i.e. you must not call wx code from w/i an OS thread. See 
the wxPython Demo for an example of what you want to do: Process and 
Events -> Threads.

Cheers
Thin


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


Re: Generating a unique identifier

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 12:03:23 +, Steven D'Aprano wrote:

> I have an application that will be producing many instances, using them 
> for a while, then tossing them away, and I want each one to have a unique 
> identifier that won't be re-used for the lifetime of the Python session.
> 
> I can't use the id() of the object, because that is only guaranteed to be 
> unique during the lifetime of the object.
> 
> For my application, it doesn't matter if the ids are predictable, so I 
> could do something as simple as this:
> 
> def unique_id():
> n = 1234567890
> while True:
> yield n
> n += 1
> 
> unique_id = unique_id()
> 
> while Application_Is_Running:
> make_an_object(id=unique_id())
> do_stuff_with_objects()
> delete_some_of_them()
> 
> which is easy enough, but I thought I'd check if there was an existing 
> solution in the standard library that I missed.

For that easy solution you can use `itertools.count()`.

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


application version checking against database

2007-09-07 Thread imageguy
We are trying to implement a system that checks the version of the
application against a version number stored in the database.  We don't
want the app and the db don't become out of sync.

We have tried setting a __version__ variable in the top most module,
however, it seems that this is not accessible for the modules that are
subsequently imported.  There are a several locations in the app where
we want to do the version check, but we would like to have one place
to set the version number, namely the top level module.

We have thought of creating a Version class and passing it around, but
aren't really keen on that idea.

Any suggestions/ideas would be helpful.


NOTE: the app is developed in wxPython.

g.

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


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Peter Otten
Am Fri, 07 Sep 2007 10:40:47 + schrieb Steven D'Aprano:

> Python doesn't have any pointers.

Thinking of python variables or "names" as pointers should
get you a long way when trying to understand python's behaviour.

As long as you keep in mind that python doesn't have pointers to pointers,
and no pointer arithmetic either...

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


Re: Class design (information hiding)

2007-09-07 Thread Gregor Horvath
Alexander Eisenhuth schrieb:
> 
> I'm wodering how the information hiding in python is ment. As I 
> understand there  doesn't exist public / protected / private  mechanism, 
> but a '_' and '__' naming convention.
> 
> As I figured out there is only public and private possible as speakin in 
> "C++ manner". Are you all happy with it. What does "the zen of python" 
> say to that design? (protected is useless?)

My favourite thread to this FAQ:

http://groups.google.at/group/comp.lang.python/browse_thread/thread/2c85d6412d9e99a4/b977ed1312e10b21#b977ed1312e10b21

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


Re: py2exe - change name of exe created

2007-09-07 Thread imageguy
Sorry for the double post, sent it to quickly.

I have a setup script like this;

setup(windows = [{"script":"myprogram.py",
   "icon_resources":[(0,"nabbitt.ico")],
"other_resources": [(24,1,manifest)]}
],
name = "My Program ver 0.1",
data_files = [("",rootdata)],
zipfile = None,
options = {"py2exe": {
   "compressed" : 1,
   "dll_excludes":
["w9xpopen.exe"],
"bundle_files": 3
}
},
)


Note that every thing works fine with this and creates an exe program
called
"myprogram.exe"

I would like to setup program to create an output called;
"MyBestProgram.exe"

IS that at all possible ?

Geoff.

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


py2exe - change name of exe created

2007-09-07 Thread imageguy
I have a setup script like this;

setup(windows = [{"script":"myprogram.py",
   "icon_resources":[(0,"nabbitt.ico")],
"other_resources": [(24,1,manifest)]}
],
name = "Nabbitt ver 0.1",
data_files = [("",rootdata)],
zipfile = None,
options = {"py2exe": {
"compressed" : 1,
"dll_excludes": 
["w9xpopen.exe"],  #should also exclude
MSVCR71.dll
"bundle_files": 3 # 
1=Single .exe, 2=.exe with
pythonXX.dll
}
},
)

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


Re: interesting puzzle......try this you will be rewarded...

2007-09-07 Thread Basilisk96
On Sep 7, 5:08 am, "Andreas Tawn" <[EMAIL PROTECTED]> wrote:
>
> Maybe http://www.pythonchallenge.com/?

That's the one, thanks!
---

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


Re: Class design (information hiding)

2007-09-07 Thread Bruno Desthuilliers
Alexander Eisenhuth a écrit :
> Hi all,
> 
> I'm wodering how the information hiding in python is ment. 

Conventions...

> As I 
> understand there  doesn't exist public / protected / private  mechanism, 
> but a '_' and '__' naming convention.

Yes.

> As I figured out there is only public and private possible as speakin in 
> "C++ manner".

Nope. It's either 'interface' (no leading underscore),  'implementation' 
(single leading underscore), 'implementation with some protection 
against accidental overriding' (two leading underscores).

> Are you all happy with it.

Can't speak for others, but as far as I'm concerned, I'm perfectly happy 
with this.

> 
> class A:
> def __init__(self):
> self.__z = 1
> self._z = 2
> self.z = 3
> def _getX(self):
> return "X"
> def __getY(self):
> return "Y"
> def doAnything(self):
> print self.__getY()
> 
> 
> class B(A):
> def __init__(self):
> A.__init__(self)
> print dir (self)
>  >>> b = B()
> ['_A__getY', '_A__z', '__doc__', '__init__', '__module__', '_getX', 
> '_z', 'doAnything', 'z']
> 
> I was a bit surprised about '_A__getY' and '_A__z'.

It's documented.

(snip)

> What is the idea behind the _ and __ naming.

cf above.

You may also want to read this - while C++ is not Java either, some 
advises may still apply:
http://dirtsimple.org/2004/12/python-is-not-java.html

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


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 11:46:38 +0200, Wildemar Wildenburger wrote:

> gu wrote:
>> hi to all!
>> after two days debugging my code, i've come to the point that the
>> problem was caused by an unexpected behaviour of python. or by lack of
>> some information about the program, of course! i've stripped down the
>> code to reproduce the problem:
>> 
>> [snip FAQ]
> 
> Yes, basically you *created* a pointer. That's all that python has:
> pointers.

No, you are confusing the underlying C implementation with Python. Python 
doesn't have any pointers. CPython is implemented with pointers. PyPy, 
being written entirely in Python, is implemented with Python objects like 
lists and dicts. Jython, being implemented in Java, probably isn't 
implemented with pointers either -- although of course the underlying 
Java compiler might be. IronPython and Python for .Net, I have no idea 
how they work. Could be magic for all I know. (Probably necromancy.) 

Naturally, regardless of whether you are using CPython, IronPython, PyPy 
or some other variety of Python, the objects available to you include 
ints, floats, strings, lists, dicts, sets and classes... but not pointers.

Nor does it include "peek" and "poke" commands for reading and writing 
into random memory locations. Python is not C, and it is not Basic, nor 
is it Forth or Lisp or assembler, and you shouldn't hammer the round peg 
of Python objects into the square hole of C pointers.



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


Re: why should I learn python

2007-09-07 Thread Tim Williams
On 07/09/07, Tom Brown <[EMAIL PROTECTED]> wrote:
> On Thursday 06 September 2007 16:01, windandwaves wrote:
> > Hmmm, thank you all for your replies.  I will do some research on the
> > net (i did some already, but because I am really not much of a
> > programmer, it is often too detailed for me).  I have limited time,
> > but it does sound like something to learn, just for fun and for
> > practical use.  How would you use it in a web development
> > environment?  I mean, in real practical terms.  Could it assist with
> > php? Is it easy to write GUI programs in Python?
>
> Checkout http://www.djangoproject.com/ or http://turbogears.org/ for web
> development. Checkout http://www.riverbankcomputing.co.uk/pyqt/index.php for
> writing GUI programs. There are other options for GUI apps. That is the one I
> use all the time.

Also, check out Karrigell ( www.karrigell.com) .  It will show you
just how easy & fast Python can be for web development.  It has its
own web server, or it can sit behind Apache etc.

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


Re: Checking if elements are empty

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 11:12:05 +0200, Wildemar Wildenburger wrote:

> Lawrence D'Oliveiro wrote:
>> In message <[EMAIL PROTECTED]>, Chris
>> Mellon wrote:
>> 
>>> On 9/5/07, Steve Holden <[EMAIL PROTECTED]> wrote:
 Doran, Harold wrote:
> Is there a way to check if the first element of y is null?
>
 len(y[0]) == 0

>>> Better spelled as
>>>
>>> if y[0]:
>> 
>> Not a good idea.
> 
> Why not?


What happens if y is an empty list?


-- 
Steven.

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


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread Stefan Arentz
[EMAIL PROTECTED] writes:

> Hi there
> 
> I am fairly new to Python and have not really used regular expressions
> before (I think this might be needed for my query) and wondered if you
> could help
> 
> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> 
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> 
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.
> 
> Any help on how I can perform this whole operation would be much
> appreciated.

Code:

  class Step(object):
  def __init__(self, time):
  self.time = time
  def __repr__(self):
  return "" % self.time

  steps = [Step("03:23:23"), Step("12:59:12"), Step("02:32:17")]
  print steps

  steps.sort(key = lambda s: s.time)
  print steps

Output:

  [, , ]
  [, , ]

If the default sort order of a Step is always it's time then you can
also define a __cmp__ method like this:

  class Step(object):
 def __cmp__(self, other):
return cmp(self.time, other.time)

And simply do a steps.sort()

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


Re: py2exe - change name of exe created

2007-09-07 Thread Thomas Heller
imageguy schrieb:
> Sorry for the double post, sent it to quickly.
> 
> I have a setup script like this;
> 
> setup(windows = [{"script":"myprogram.py",
>"icon_resources":[(0,"nabbitt.ico")],
> "other_resources": [(24,1,manifest)]}
> ],
> name = "My Program ver 0.1",
> data_files = [("",rootdata)],
> zipfile = None,
> options = {"py2exe": {
>"compressed" : 1,
>"dll_excludes":
> ["w9xpopen.exe"],
> "bundle_files": 3
> }
> },
> )
> 
> 
> Note that every thing works fine with this and creates an exe program
> called
> "myprogram.exe"
> 
> I would like to setup program to create an output called;
> "MyBestProgram.exe"
> 
> IS that at all possible ?

Yes.  Use a 'dest_base' key in the dictionary, like so:

> setup(windows = [{"script":"myprogram.py",
>"icon_resources":[(0,"nabbitt.ico")],
 "dest_base": "MyBestProgram",
> "other_resources": [(24,1,manifest)]}
...

'dest_base' is the basename of the destination program that py2exe creates.

Thomas

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


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> Hi there
> 
> I am fairly new to Python and have not really used regular expressions
> before (I think this might be needed for my query) and wondered if you
> could help
> 
> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> 
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> 
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.

You're going to get a *lot* of answers on this one!

To start the ball rolling...


import random

class Step:

   def __init__ (self, name, startTime):
 self.name = name
 self.startTime = startTime

   def __cmp__ (self, other):
 return cmp (self.startTime, other.startTime)

   def __str__ (self):
 return str (self.startTime)
   __repr__ = __str__

steps = [Step (h, "%02d:00:00" % h) for h in range (10)]
random.shuffle (steps)
print "Shuffled:", steps

steps.sort ()
print "Sorted:", steps


In this case, I've given the class a ordering-semantic based
on its startTime attribute. Obviously, this only makes sense
if you *always* want your class to sort this way, rather than
in this one instance.

To do it on a per-sort basis, you *could* create simple per-sort
equivalent:



def compare_by_startTime (one, other):
   return cmp (one.startTime, other.startTime)

steps.sort (cmp=compare_by_startTime)



or, in the case you're asking about, you could use the
operator module's attrgetter function to do what you want:


import operator

steps.sort (key=operator.attrgetter ("startTime"))



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


Re: Generating a unique identifier

2007-09-07 Thread kyosohma
On Sep 7, 7:03 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> I have an application that will be producing many instances, using them
> for a while, then tossing them away, and I want each one to have a unique
> identifier that won't be re-used for the lifetime of the Python session.
>
> I can't use the id() of the object, because that is only guaranteed to be
> unique during the lifetime of the object.
>
> For my application, it doesn't matter if the ids are predictable, so I
> could do something as simple as this:
>
> def unique_id():
> n = 1234567890
> while True:
> yield n
> n += 1
>
> unique_id = unique_id()
>
> while Application_Is_Running:
> make_an_object(id=unique_id())
> do_stuff_with_objects()
> delete_some_of_them()
>
> which is easy enough, but I thought I'd check if there was an existing
> solution in the standard library that I missed. Also, for other
> applications, I might want them to be rather less predictable.
>
> --
> Steven.

You could always use the md5 module along with time.time() to generate
a unique id.

Mike

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


Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread André
In my application, I make use of the Borg idiom, invented by Alex
Martelli.

class Borg(object):
'''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273

Derive a class form this; all instances of that class will share
the
same state, provided that they don't override __new__; otherwise,
remember to use Borg.__new__ within the overriden class.
'''
_shared_state = {}
def __new__(cls, *a, **k):
obj = object.__new__(cls, *a, **k)
obj.__dict__ = cls._shared_state
return obj


This has worked very well so far, but is starting to impose some
unwanted constraints on my program design.

What I would like to do is, to put it figuratively, create a Borg
rebellion with various splinter groups.  In concrete Python terms, I
would like to have

class MyClass(Borg, ...):
   ...

seven_of_nine = MyClass(...)  # part of group "BORG"
two_of_nine = MyClass(...)

splinter1 = MyClass(..., group='splinter')
splinter2 = MyClass(..., group='splinter')

and have splinter 1 and splinter2 share the same state, but a
different state than the one shared by members of the BORG collective.

Any suggestions from the metaclass experts?

André

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


Re: Generating a unique identifier

2007-09-07 Thread Will Maier
On Fri, Sep 07, 2007 at 12:03:23PM -, Steven D'Aprano wrote:
[...]
> which is easy enough, but I thought I'd check if there was an existing 
> solution in the standard library that I missed. Also, for other 
> applications, I might want them to be rather less predictable.

2.5 includes the uuid module for RFC 4122 universally-unique IDs:

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

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Generating a unique identifier

2007-09-07 Thread Steven D'Aprano
I have an application that will be producing many instances, using them 
for a while, then tossing them away, and I want each one to have a unique 
identifier that won't be re-used for the lifetime of the Python session.

I can't use the id() of the object, because that is only guaranteed to be 
unique during the lifetime of the object.

For my application, it doesn't matter if the ids are predictable, so I 
could do something as simple as this:

def unique_id():
n = 1234567890
while True:
yield n
n += 1

unique_id = unique_id()

while Application_Is_Running:
make_an_object(id=unique_id())
do_stuff_with_objects()
delete_some_of_them()

which is easy enough, but I thought I'd check if there was an existing 
solution in the standard library that I missed. Also, for other 
applications, I might want them to be rather less predictable.



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


Re: Best practice prompting for password

2007-09-07 Thread Chris Mellon
On 9/7/07, GiBo <[EMAIL PROTECTED]> wrote:
> Hi,
>
> what's the best practice to securely prompt user for password on console
> in Python? IIRC some programs like SSH do a lot to ensure that the input
> comes from TTY and is not redirected from somewhere and several other
> checks. In the case of OpenSSH even the password prompt is always
> displayed regardless if the output is redirected to a file or not.
>
> Any pointers to best practice or code snippet of python password prompt?
>

The getpass module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb: ValueError Something Stupid

2007-09-07 Thread mcl
On 7 Sep, 14:11, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Fri, 2007-09-07 at 05:52 -0700, mcl wrote:
> > > ValueError: invalid literal for int(): 0-
> > >   args = ('invalid literal for int(): 0-',)
>
> > > =
> > > Thanks Richard
>
> > Sort of solved it.
>
> > On that particular table it did not like * for all fields.
>
> > Any reason why that would be the case ?
>
> None that we can divine without more information. What's the schema for
> the table in question, which column(s) are you excluding to make the
> query work, and what kind of data is in the column(s) you're excluding?
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

Thanks for replying.

I did not exclude any columns and the Schema is:

CREATE TABLE lstData (
  qlCat varchar(20) NOT NULL default '',
  qlTitle varchar(255) NOT NULL default '',
  qlSubTitle varchar(255) default NULL,
  qlDetails text,
  qlPic varchar(20) default NULL,
  qlPostCode varchar(16) default NULL,
  qlUpd timestamp NOT NULL default '-00-00 00:00:00' on update
CURRENT_TIMESTAMP,
  KEY `idx-qlCat` (qlCat)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Thanks again

Richard

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


Re: MySQLdb: ValueError Something Stupid

2007-09-07 Thread mcl
On 7 Sep, 12:08, mcl <[EMAIL PROTECTED]> wrote:
> I have just started with python and MySQL.
>
> I have a simple test for each of my tables.
>
> The first two work as expected, but the third 'qlooks', gives a
> ValueError.
>
> If I copy and paste the SQL in the traceback to phpMyAdmin, it works
> as expected.
>
> Can anyone give a clue as to what I am doing wrong
>
> Python 2.4
> MySQL  4.1.22-standard
>
> The tablename qlooks is LOWERCASE
>
> Code ===
> cursor = gv.conn.cursor()
> queries = ["%septi%"]
> fields = ("qlTitle", "qlSubTitle", "qlPostCode", "qlMap",
> "qlDetails")
> tblFields = "select * from qlooks "
> whereTests = 'Where qlTitle like "%septi%"'
> sql = tblFields + whereTests
> #cursor.execute(sql)
> cursor.execute('select * from PERMS')
> row = cursor.fetchone()
> print "Row=", row, gv.nl
> cursor.execute('select * from LISTS')
> row = cursor.fetchone()
> print "Row=", row, gv.nl
> cursor.execute('select * from qlooks')
> row = cursor.fetchone()
> print "Row=", row, gv.nl
>
> cursor.close()
>
> ERROR TRACEBACK 
>
>79 print "Row=", row, gv.nl
>80 cursor.execute('select * from qlooks')
>81 row = cursor.fetchone()
>82 print "Row=", row, gv.nl
> cursor = , cursor.execute =  method Cursor.execute of >
>  /usr/lib/python2.4/site-packages/MySQLdb/cursors.py in
> execute(self=, query='select * from
> qlooks', args=None)
>93 """
>94 del self.messages[:]
>95 return self._execute(query, args)
>96
>97 def _execute(self, query, args):
> self = , self._execute =  method Cursor._execute of >, query =
> 'select * from qlooks', args = None
>  /usr/lib/python2.4/site-packages/MySQLdb/cursors.py in
> _execute(self=, query='select * from
> qlooks', args=None)
>   112 exc, value, tb = exc_info()
>   113 del tb
>   114 self.errorhandler(self, exc, value)
>   115 self._executed = query
>   116 return r
> self = , self.errorhandler =  method Connection.defaulterrorhandler of ...l.connection open to
> 'db.sabren.com' at 936cac4>>, exc = ,
> value = 
>  /usr/lib/python2.4/site-packages/MySQLdb/connections.py in
> defaulterrorhandler(connection=<_mysql.connection open to
> 'db.sabren.com' at 936cac4>, cursor=,
> errorclass=,
> errorvalue=)
>31 else:
>32 connection.messages.append(error)
>33 raise errorclass, errorvalue
>34
>35
> errorclass = , errorvalue =
> 
>
> ValueError: invalid literal for int(): 0-
>   args = ('invalid literal for int(): 0-',)
>
> =
> Thanks Richard

Sort of solved it.

On that particular table it did not like * for all fields.

Any reason why that would be the case ?

Richard

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


Re: exponential float formmating

2007-09-07 Thread [EMAIL PROTECTED]
On Sep 7, 6:08 am, [EMAIL PROTECTED] wrote:
> Hi,
>
> For compatibility reasons with an old program I have to format string
> in exponential
> format with the following format
>
> 0.xE-yy
>
> This means that the number start always by 0 and after the exponent
> there should be alway the sing and 2 number for the exponent.
>
> for example 13 shoud be 0.13000E+02
> I always get 1.3E001
>


Perhaps it would then be worthwhile to subclass float?

import math
class ffloat(float):
"""Formatted float?"""
def __str__(self):
prefix = (self < 0) and '-' or ''
fabs = math.fabs(self)
exponent = math.floor(math.log10(fabs)) + 1
significand = fabs / math.pow(10, exponent)
width = exponent > 0 and 2 or 3
return '%s%fE%0*d' % (prefix,significand,width,exponent)


f = ffloat(13)
print f
f = ffloat(-12.23e-4)
print f


--
Hope this helps,
Steven

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


Re: interesting puzzle......try this you will be rewarded...

2007-09-07 Thread Andreas Tawn
>Basilisk96 wrote:
>> I remember seeing a more elaborate puzzle that involved coding,
>> cryptography knowledge, etc. to get through it. But what was the
link,
>> I forget now...
>
>There's this one http://www.inwardhellix.net/
>
>I haven't played it yet so I can't vouch for its quality.  (am playing 
>it now)

Maybe http://www.pythonchallenge.com/ ?

Cheers,

Drea

Andreas Tawn
Lead Technical Artist
Ubisoft Reflections
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: platform system may be Windows or Microsoft since Vista

2007-09-07 Thread p . lavarre
> > Log a bug @ bugs.python.org
>
> http://bugs.python.org/issue1082
> TITLE ... platform system may be Windows or Microsoft since Vista

Six days gone with no feedback. Something wrong with the input?

Maybe the blank Priority field?

I agree Severity Major.

I'm thinking no priority because there is no fixing this. We now
choose between two wrong ways to change the Python Msi installer of
Windows:

1. Hide that many people now and for months or years to come will
continue to need both halves of the (platform.system() in ('Windows',
'Microsoft') guard.

2. Leave unchanged to require many more people to need both halves in
future.

I find neither choice inspiring.

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


Re: exponential float formmating

2007-09-07 Thread zunbeltz
On 7 sep, 15:42, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Fri, 07 Sep 2007 06:08:19 -0700, zunbeltz wrote:
> > For compatibility reasons with an old program I have to format string
> > in exponential format with the following format
>
> > 0.xE-yy
>
> > This means that the number start always by 0 and after the exponent
> > there should be alway the sing and 2 number for the exponent.
>
> > for example 13 shoud be 0.13000E+02
> > I always get 1.3E001
>
> I don't know if this is platform dependent but this works for me:
>
> In [41]: '%e' % 1.3
> Out[41]: '1.30e+00'
>
> In [42]: ('%e' % 1.3).upper()
> Out[42]: '1.30E+00'
>
> Ciao,
> Marc 'BlackJack' Rintsch

I am working in windows I get
>>> '%e' % 13
'1.30e+001'

In all cases I need the number to start with 0
0.13000E+01

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


Re: Generating a unique identifier

2007-09-07 Thread Wildemar Wildenburger
Will Maier wrote:
> On Fri, Sep 07, 2007 at 12:03:23PM -, Steven D'Aprano wrote:
> [...]
>> which is easy enough, but I thought I'd check if there was an existing 
>> solution in the standard library that I missed. Also, for other 
>> applications, I might want them to be rather less predictable.
> 
> 2.5 includes the uuid module for RFC 4122 universally-unique IDs:
> 
> http://docs.python.org/lib/module-uuid.html
> 
Jesus Christ! What in all the world *doesn't* Python do already?!

Can't we now just write up a module for the standard lib that takes care 
of writing all the other code as well and just forget about getting our 
hands dirty with programming altogether?

/W
(just in case: ;)!)
-- 
http://mail.python.org/mailman/listinfo/python-list


re: getting the current function

2007-09-07 Thread Gary Robinson
> This all seems a bit too complicated. Are you sure you want to do
> this? Maybe you need to step back and rethink your problem.

In version 2.1 Python added the ability to add function attributes -- see 
http://www.python.org/dev/peps/pep-0232/ for the justifications. A counter 
probably isn't one of them, I just used that as a quick example of using 
thisfunc(). 

I've just never liked the fact that you have to name the function when 
accessing those attributes from within the function. And I thought there might 
be other uses for something like thisfunc().

-- 

Gary Robinson
CTO
Emergent Music, LLC
[EMAIL PROTECTED]
207-942-3463
Company: http://www.goombah.com
Blog:http://www.garyrobinson.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why should I learn python

2007-09-07 Thread JeffHua
 
In a message dated 2007-9-7 7:50:32, [EMAIL PROTECTED] writes:

Tom  Brown wrote:

> On Thursday 06 September 2007 15:44, Torsten Bronger  wrote:
>> Hallöchen!
>>
>> Tom Brown  writes:
>> > [...] Python has been by far the easiest to develop  in.  Some
>> > people might say it is not "real programming"  because it is so
>> > easy.
>>
>> I can't  believe this.  Have you really heard such a statement?
> 
>  Yes. I was told this by a C programmer. Something about doing it all
>  yourself and not using provided packages. I countered with something  about
> reinventing the wheel. :)

Point this so-called "C  Programmer" toward Henry Spencer's "Ten Commandments
of C  Programming".  Note in particular rule 7:

7. Thou shalt study thy libraries and strive not to reinvent  them
without cause, that thy code  may be short and readable and thy
days pleasant and productive.

You can find the whole list  here:

http://www.everything2.com/index.pl?node_id=783755

-- 
_http://mail.python.org/mailman/listinfo/python-list_ 
(http://mail.python.org/mailman/listinfo/python-list) 


 
 
 
[EMAIL PROTECTED] (mailto:[EMAIL PROTECTED]) ? This seems  like Bill 
Gates' email,does he also like Python? :-)



** Get a sneak peek of the all-new AOL at 
http://discover.aol.com/memed/aolcom30tour
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Bruno Desthuilliers
Jorgen Bodde a écrit :
> Hi All,
> 
> I have a dictionary with settings. The settinfgs can be strings, ints
> or bools. I would like to write this list dynamically to disk in a big
> for loop, unfortunately the bools need to be written as 0 or 1 to the
> config with WriteInt, the integers also with WriteInt and the strings
> with a simple Write.
> 
> The list is something like;
> 
> options[A] = True
> options[B] = 1
> options[C] = "Hello"
> 
> I wanted to use isinstance to determine if it is a bool or an int or a
> string. However I am confused trying it out in the interactive editor;
> 
 a = False
 if isinstance(a, bool):
> ...   print "OK"
> ...   
> OK
 if isinstance(a, int):
> ...   print "OK"
> ...   
> OK
> 
> I don't get it. is the bool derived from 'int' in some way?

Obviously : yes !-)

> What is
> the best way to check if the config I want to write is an int or a
> bool ?

 >>> isinstance(0, bool)
False
 >>> isinstance(1, bool)
False
 >>>

But anyway, I don't get the point, since "the bools need to be written 
as 0 or 1 to the config with WriteInt, the integers also with WriteInt". 
So you just don't care if it's a bool or not ? Or did I miss something ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Paul Rubin  writes:
> def unique_id():
>return os.urandom(10).encode('hex')

Sorry, make that 32 or 40 instead of 10, if the number of id's is large,
to make birthday collisions unlikely.

If you don't want the id's to be that large, you can implement a
Feistel cipher using md5 or sha as the round function pretty
straightforwardly, then just feed successive integers through it.
That also guarantees uniqueness, at least within one run of the
program.  I have some sample code around for that, let me know if you
need it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organizing Code - Packages

2007-09-07 Thread Bruno Desthuilliers
xkenneth a écrit :
> All,
> 
> I apologize if this is a commonly asked question, but I didn't
> find anything that answered my question while searching.
> 
> So what I have right now is a few packages that contain some commonly
> used functions and another package that contains all of my custom
> error classes. I want these error classes available to me in all of
> the other packages in my library. Currently to achieve this at the top
> of every module file I have the line "from My.Library.Errors import
> *", my problem with this is that it manages to import the Errors into
> every scope that they are used. 

Ain't that what you want ??? Having "these error classes available to me 
in all of the other packages in my library" ?

If you're worried about perfs or whatever, don't worry, a module is only 
imported once - next imports will only bind the names in the importing 
namespace.

> I'm still pretty new to Python, and my
> approachs are probably very rooted in C/C++ (I've had the hardest time
> getting over not being able to overload functions), but am I doing
> this correctly?

Yes, that's the right thing to do.

>Also, are there any good tutorials/examples out there of how to
> organize your python code into packges?

Most of the Python-specific aspects should be covered by the tutorial 
(the one in the doc). Else, it's as usual, trying to have high cohesion 
and low coupling.

Ah, yes, a couple of things:
- avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens 
of classes in a same module
- plain functions are ok too - no need to stick everything in classes.

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


Organizing Code - Packages

2007-09-07 Thread xkenneth
All,

I apologize if this is a commonly asked question, but I didn't
find anything that answered my question while searching.

So what I have right now is a few packages that contain some commonly
used functions and another package that contains all of my custom
error classes. I want these error classes available to me in all of
the other packages in my library. Currently to achieve this at the top
of every module file I have the line "from My.Library.Errors import
*", my problem with this is that it manages to import the Errors into
every scope that they are used. I'm still pretty new to Python, and my
approachs are probably very rooted in C/C++ (I've had the hardest time
getting over not being able to overload functions), but am I doing
this correctly?

   Also, are there any good tutorials/examples out there of how to
organize your python code into packges?

Thanks for all the help!

Regards,
Ken

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


How to determine the bool between the strings and ints?

2007-09-07 Thread Jorgen Bodde
Hi All,

I have a dictionary with settings. The settinfgs can be strings, ints
or bools. I would like to write this list dynamically to disk in a big
for loop, unfortunately the bools need to be written as 0 or 1 to the
config with WriteInt, the integers also with WriteInt and the strings
with a simple Write.

The list is something like;

options[A] = True
options[B] = 1
options[C] = "Hello"

I wanted to use isinstance to determine if it is a bool or an int or a
string. However I am confused trying it out in the interactive editor;

>>> a = False
>>> if isinstance(a, bool):
... print "OK"
... 
OK
>>> if isinstance(a, int):
... print "OK"
... 
OK
>>>

I don't get it. is the bool derived from 'int' in some way? What is
the best way to check if the config I want to write is an int or a
bool ?

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


Re: Class design (information hiding)

2007-09-07 Thread Bruno Desthuilliers
Alexander Eisenhuth a écrit :
> Bruno Desthuilliers schrieb:
> 
>> Nope. It's either 'interface' (no leading underscore),  
>> 'implementation' (single leading underscore), 'implementation with 
>> some protection against accidental overriding' (two leading underscores).
> 
> What do you mean with 'implementation'? What does it express?

The fact that a given attribute (or method - which are just callable 
attributes FWIW) is an implementation detail, and not a part of the 
class interface.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Jorgen Bodde
Awesome! Thanks you!

As for why caring if they are bools or not, I write True and False to
the properties, the internal mechanism works like this so I need to
make that distinction.

Thanks again guys,
- Jorgen

ps. Sorry TheFlyingDutch for mailing you personally, I keep forgetting
this mailinglist does not default back to the user list when replying
;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: concise code (beginner)

2007-09-07 Thread Rhamphoryncus
On Sep 6, 1:56 pm, Karthik Gurusamy <[EMAIL PROTECTED]> wrote:
> That said, it may be a good future language enhancement to define a
> reasonable consistent behavior for an iterator over a changing
> collection. This occurs quite common when we walk a collection and
> usually delete the current item.
>
> For a sequence, what the expected behavior is quite obvious (just
> remove this element and go over to the next). For other collections
> like dictionary/set, again if the operation is delete, the expected
> behavior is obvious. If we are doing insertion, for sequence a well-
> defined behavior can be formulated (based on insert before or after
> current position -- if after we will see it in the walk, if before we
> won't see it) . For dict/set I see this isn't simple (as based on hash
> key we may insert ahead or later of the current 'cursor'/position.

Removing from a list while you iterate will had quadratic performance
though.  O(n) to find the element you wish to remove and move over
everything after it, multiplied by your original O(n) of iterating,
gives O(n**2).  That, combined with the fact that adding enough
accounting to invalidate or update your iterator would be a cost on
all the correct users too, is why it's not done.

The best approach in almost all cases in python is to create a new
container as you iterate over the old one.  After you finish, you
replace the old one with the new one.  This lets you keep an overall
O(n) performance, as well as avoiding the tricky semantics.

--
Adam Olsen, aka Rhamphoryncus

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


Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread cjt22
Hi there

I am fairly new to Python and have not really used regular expressions
before (I think this might be needed for my query) and wondered if you
could help

I have a step class and store in a list step instances
A step instance contains variables: name, startTime etc and startTime
is stored as a string %H:%M:%S

What I would like to do is to be able to sort this list of objects
based on the startTime object so that the first item in the list is
the object with the earliest Start time and last item is the object
with the last Start time.

I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
But don't know how to create the comparison funciton.

Any help on how I can perform this whole operation would be much
appreciated.

Thanks
Chris

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


Re: why should I learn python

2007-09-07 Thread vanrpeterson
Why use Python?
1)Easy to read, debug and think.
2)Same language for batch scripting, server programming and dynamic
web page creation.
3)Libraries like wxPython for desktop and Cherrypy for web
development.
4)Pythonic JavaScript Library Mochikit.
5)Engineered for reality, not corporate proprietary control
(Microsoft).
6)Less code than Java the Huge.
7)Friendly with C for optimization, if necessary.
8)Works well with SQL, especially PostgreSQL.
9)Everybody is using it, even Microsoft with IronPython.
10)One of the dominant languages driving robotics.
11)Works nicely with UNICODE.
12)Liberal license.
13)And lastly, if you hate programming as I do, you will love Python.
Belief is when someone else does the thinking.  ~ Buckminster Fuller


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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 12:31 +, André wrote:
> In my application, I make use of the Borg idiom, invented by Alex
> Martelli.
> 
> class Borg(object):
> '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273
> 
> Derive a class form this; all instances of that class will share
> the
> same state, provided that they don't override __new__; otherwise,
> remember to use Borg.__new__ within the overriden class.
> '''
> _shared_state = {}
> def __new__(cls, *a, **k):
> obj = object.__new__(cls, *a, **k)
> obj.__dict__ = cls._shared_state
> return obj
> 
> 
> This has worked very well so far, but is starting to impose some
> unwanted constraints on my program design.
> 
> What I would like to do is, to put it figuratively, create a Borg
> rebellion with various splinter groups.  In concrete Python terms, I
> would like to have
> 
> class MyClass(Borg, ...):
>...
> 
> seven_of_nine = MyClass(...)  # part of group "BORG"
> two_of_nine = MyClass(...)
> 
> splinter1 = MyClass(..., group='splinter')
> splinter2 = MyClass(..., group='splinter')
> 
> and have splinter 1 and splinter2 share the same state, but a
> different state than the one shared by members of the BORG collective.
> 
> Any suggestions from the metaclass experts?

You don't need a metaclass. Just turn _shared_state into a dictionary of
shared states, keyed by the group name:

class SplinterBorg(object):
_shared_states = {}
def __new__(cls, *a, **k):
group = k.pop("group","BORG")
obj = object.__new__(cls, *a, **k)
obj.__dict__ = cls._shared_states.setdefault(group,{})
return obj

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


exponential float formmating

2007-09-07 Thread zunbeltz
Hi,

For compatibility reasons with an old program I have to format string
in exponential
format with the following format

0.xE-yy

This means that the number start always by 0 and after the exponent
there should be alway the sing and 2 number for the exponent.

for example 13 shoud be 0.13000E+02
I always get 1.3E001

Thanks,

Zunbeltz

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


Re: py2exe - change name of exe created

2007-09-07 Thread imageguy
On Sep 7, 11:22 am, Thomas Heller <[EMAIL PROTECTED]> wrote:
> imageguy schrieb:
>
>
>
>
>
> > Sorry for the double post, sent it to quickly.
>
> > I have a setup script like this;
>
> > setup(windows = [{"script":"myprogram.py",
> >"icon_resources":[(0,"nabbitt.ico")],
> > "other_resources": [(24,1,manifest)]}
> > ],
> > name = "My Program ver 0.1",
> > data_files = [("",rootdata)],
> > zipfile = None,
> > options = {"py2exe": {
> >"compressed" : 1,
> >"dll_excludes":
> > ["w9xpopen.exe"],
> > "bundle_files": 3
> > }
> > },
> > )
>
> > Note that every thing works fine with this and creates an exe program
> > called
> > "myprogram.exe"
>
> > I would like to setup program to create an output called;
> > "MyBestProgram.exe"
>
> > IS that at all possible ?
>
> Yes.  Use a 'dest_base' key in the dictionary, like so:
>
> > setup(windows = [{"script":"myprogram.py",
> >"icon_resources":[(0,"nabbitt.ico")],
>
>  "dest_base": "MyBestProgram",> 
> "other_resources": [(24,1,manifest)]}
>
> ...
>
> 'dest_base' is the basename of the destination program that py2exe creates.
>
> Thomas- Hide quoted text -
>
> - Show quoted text -

Thanks.
I really appreciate the response.
Where would I find that in the docs ?  Thought I had searched
everywhere.

G.

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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread André
On Sep 7, 10:27 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Fri, 2007-09-07 at 12:31 +, André wrote:
> > In my application, I make use of the Borg idiom, invented by Alex
> > Martelli.
>
> > class Borg(object):
> > '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273
>
> > Derive a class form this; all instances of that class will share
> > the
> > same state, provided that they don't override __new__; otherwise,
> > remember to use Borg.__new__ within the overriden class.
> > '''
> > _shared_state = {}
> > def __new__(cls, *a, **k):
> > obj = object.__new__(cls, *a, **k)
> > obj.__dict__ = cls._shared_state
> > return obj
>
> > 
> > This has worked very well so far, but is starting to impose some
> > unwanted constraints on my program design.
>
> > What I would like to do is, to put it figuratively, create a Borg
> > rebellion with various splinter groups.  In concrete Python terms, I
> > would like to have
>
> > class MyClass(Borg, ...):
> >...
>
> > seven_of_nine = MyClass(...)  # part of group "BORG"
> > two_of_nine = MyClass(...)
>
> > splinter1 = MyClass(..., group='splinter')
> > splinter2 = MyClass(..., group='splinter')
>
> > and have splinter 1 and splinter2 share the same state, but a
> > different state than the one shared by members of the BORG collective.
>
> > Any suggestions from the metaclass experts?
>
> You don't need a metaclass. Just turn _shared_state into a dictionary of
> shared states, keyed by the group name:
>
> class SplinterBorg(object):
> _shared_states = {}
> def __new__(cls, *a, **k):
> group = k.pop("group","BORG")
> obj = object.__new__(cls, *a, **k)
> obj.__dict__ = cls._shared_states.setdefault(group,{})
> return obj
>
> HTH,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

Unfortunately, it fails.  Here's what I tried, followed by the
traceback
class SplinterBorg(object):
_shared_states = {}
def __new__(cls, *a, **k):
group = k.pop("group","BORG")
obj = object.__new__(cls, *a, **k)
obj.__dict__ = cls._shared_states.setdefault(group,{})
return obj

class MyClass(SplinterBorg):
   def __init__(self, name):
   self.name = name

a1 = MyClass('a')
a2 = MyClass('aa')
b1 = MyClass('b', group="B")


Traceback (most recent call last):
  File "test.py", line 15, in 
b1 = MyClass('b', group="B")
TypeError: __init__() got an unexpected keyword argument 'group'


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


Re: interesting puzzle......try this you will be rewarded...

2007-09-07 Thread Evil Bert
Andreas Tawn wrote:
> Maybe http://www.pythonchallenge.com/ ?

Fun!  Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Dustan
On Sep 7, 3:07 am, gu <[EMAIL PROTECTED]> wrote:
> hi to all!

Hi!

> after two days debugging my code, i've come to the point that the
> problem was caused by an unexpected behaviour of python. or by lack of
> some information about the program, of course! i've stripped down the
> code to reproduce the problem:
>
> 
> a = {}
>
> for x in range(10):
>  for y in range(10):
>  a[x,y] = "0"
>
> copyOfA = a
>
> def functionA(x,y):
>  print a[x,y],
>  copyOfA[x,y] = "*"
>  print a[x,y],copyOfA[x,y]
>
> for x in range(10):
>  for y in range(10):
>  functionA(x,y)
>
> 
>
> now, in the second "for" cycle and in functionA() i only 'touch' copyOfA
> (altering it). as i don't touch the variable "a", i expect it not to be
> affected by any change, but copyOfA acts like a pointer to a and
> altering copyOfA's values result in altering the values of "a", so the
> result that i expect is:
> 0 0 *
> 0 0 *
> 0 0 *
> 0 0 *
> [..]
>
> but i get:
> 0 * *
> 0 * *
> 0 * *
> 0 * *
> [..]
>
> what's going on?
> thanks in advance.

Welcome to Python! You might want to look at the documentation:
http://docs.python.org/

And the tutorials:
http://docs.python.org/tut/tut.html

Leaping into python from another language without looking at the above
documentation is not wise, since python has both a very different
structure and a somewhat different philosophy from other languages.

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


debugging program that uses ctypes

2007-09-07 Thread marco_347
hi all, I have a python program that calls a dll through ctypes
(py2.5). In some (reproducible)
conditions the program crashes with an error in ctypes module.
How can I trace down the problem? I have created a debug build of
python but I also use pyodbc
and dateutil libraries in my program and I don't know how to make them
visible to python_d.exe
Am I using the right approach?

thanks in advance for hints,
Marco

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


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> def unique_id():
> n = 1234567890
> while True:
> yield n
> n += 1

unique_id = itertools.count(1234567890)

> which is easy enough, but I thought I'd check if there was an existing 
> solution in the standard library that I missed. Also, for other 
> applications, I might want them to be rather less predictable.

def unique_id():
   return os.urandom(10).encode('hex')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of Python

2007-09-07 Thread S bastien Boisg rault

On Sep 7, 6:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:

Matlab (aka MATrix LABoratory) has been designed with numeric
computations in mind (every object being natively a n-dim
array). If you wish to develop that kind of applications in
Python, consider using the numerical array structure provided
by Numpy. Numpy being mostly written in C, that should speed
up your application ... In this context, additional 3rd party
libs such as Scipy, Matplotlib, PIL, etc. will also be useful.

Cheers,

SB

> Hi,
>
> While comparing the speed of octave and matlab, I decided to do a similar
> test for python and matlab. The result shows that python is slower than
> matlab by a factor of 5. It is not bad since octave is about 30 time slower
> than matlab.
>
> Here is the result in matlab:
> Elapsed time is 0.015389 seconds.
>
> and in Python:>>> t=timeit.Timer("bench1.bench1(10)","import bench1")
> >>> t.repeat(1,1)
>
> [0.071012377266015392]
>
> Here is the bench1.py:
> import math
> def bench1(n):
> for i in range(n):
> for j in range(1000):
> m=j+1
> z=math.log(m)
> z1=math.log(m+1)
> z2=math.log(m+2)
> z3=math.log(m+3)
> z4=math.log(m+4)
> z5=math.log(m+5)
> z6=math.log(m+6)
> z7=math.log(m+7)
> z8=math.log(m+8)
> z9=math.log(m+9)
> return z9
>
> Is my conclusion correct that Python is slower than matlab? Are there any
> way to speed it up? It seems Python automatically created bench1.pyc. Does
> Python automatically execute the bench1.pyc to speed it up?
>
> Thanks
>
> Frank
>
> _
> 「地図マガ」特集 残暑を吹きとばせ!ご当地アイスクリームマップが登場http://chizumaga.jp/


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

passing command line arguments

2007-09-07 Thread Brian McCann
 
Hi,
 
when I run the script show_args2.py

# ./show_args2.py 1 2 3

I get the following error

Traceback (most recent call last):
  File "./show_args2.py", line 4, in ?
print 'The arguments of %s are "%s"' %s \
NameError: name 's' is not defined


#
 
this is the script
 #!/usr/bin/python
import sys, string
print 'The arguments of %s are "%s"' %s \
(sys.argv[0], string.join(sys.argv[1:]))

 

any help would be greatly appreciated

-Brian


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

Re: Organizing Code - Packages

2007-09-07 Thread Paul Rudin
xkenneth <[EMAIL PROTECTED]> writes:

>> Ah, yes, a couple of things:
>> - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens
>
> Yes but i find it hard to edit classes easily when I have more than
> one class per file.

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


Re: debugging program that uses ctypes

2007-09-07 Thread Thomas Heller
[EMAIL PROTECTED] schrieb:
> hi all, I have a python program that calls a dll through ctypes
> (py2.5). In some (reproducible)
> conditions the program crashes with an error in ctypes module.

You mean a segfault?

> How can I trace down the problem? I have created a debug build of
> python but I also use pyodbc
> and dateutil libraries in my program and I don't know how to make them
> visible to python_d.exe
> Am I using the right approach?

I would say yes.  It seems you are using windows - running debug builds of
python on windows start a dialog box that allows to attach the MSVC debugger
to the running program. Usually this allows to locate the error fairly quickly.

As you have discovered, the problem is that you need to build all the extensions
that you use in debug mode otherwise you cannot use them.

If you cannot rebuild the extensions you have to reproduce the crash in
a script that doesn't use these extensions.

Thomas

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


Re: Organizing Code - Packages

2007-09-07 Thread xkenneth

> Ah, yes, a couple of things:
> - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens

Yes but i find it hard to edit classes easily when I have more than
one class per file.

Regards,
Ken

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


Re: How to convert None to null value

2007-09-07 Thread Gabriel Genellina
En Fri, 07 Sep 2007 06:19:25 -0300, pradeep kumar <[EMAIL PROTECTED]>  
escribi�:

> i am trying to insert records from one table to another table in postgres
> sql using the the following code
>
> posConn.query("insert into
> usr(usr_id,usr_name,usr_passwd,grp_cde,usr_type,usr_chk_till_val, \
>
> usr_active,usr_daily_auth,usr_lst_login,usr_lst_logout,usr_shift_id,usr_role_level)
> values \
>  ('%s','%s','%s',%s,%i,%d,'%s',%i,%i,%i,%i,%i)"
> %(row[0],row[1],row[2],row[3],row[4],row[5], \
>   row[7],row[8],row[10],row[11],row[12],row[14]) )
>
> here row[4] column is having null value so python consides it as None but
> will insert into the table it inserts as None not null value

- You are building the sql statement "by hand": don't do that. The query  
method receives two arguments: an sql template with placeholders, and a  
tuple of arguments. This way, None objects are correctly translated into  
NULL values, embedded quotes are correctly handled, etc. An important  
point is security - building the sql statement by hand may open the door  
to sql injection attacks.
See  for details.

- You don't need those \ for line continuation: any expression containing  
an open ( [ { automatically continues on the following lines until all ) ]  
} are closed.

- Python automatically joins contiguous strings.

Combining all the above:

posConn.query("insert into usr "
"(usr_id,usr_name,usr_passwd,grp_cde,usr_type,"
"usr_chk_till_val,usr_active,usr_daily_auth,"
"usr_lst_login,usr_lst_logout,usr_shift_id,"
"usr_role_level) values "
"(%s,%s,%s,%s,%i,%d,%s,%i,%i,%i,%i,%i)" ,
(row[0],row[1],row[2],row[3],row[4],row[5],
 row[7],row[8],row[10],row[11],row[12],row[14]))

Note the TWO arguments to the query method: all those string fragments are  
joined into a single string, followed by a comma, and a tuple containing 6  
parameters.

Parameter markers may be %s,%s,%s... as above, or :1,:2,:3... or ?,?,?...
The exact syntax depends on your specific database adapter - you'll have  
to read its documentation.

-- 
Gabriel Genellina

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

Re: why should I learn python

2007-09-07 Thread [EMAIL PROTECTED]
On Sep 6, 10:32 pm, windandwaves <[EMAIL PROTECTED]> wrote:
> Can someone tell me why I should learn python?  I am a webdeveloper,
> but I often see Python mentioned and I am curious to find out what I
> am missing out on.
>
> Thank you
>
> Nicolaas

 - You never really have to reinvent the wheel, and many python
modules are included by default. This means that you can accomplish
what you wanted to do much faster. Thus You can write a lot less code
to get to what you want to do. If a module does not exist yet, you can
create it!
 - It is kinda close to pseudo code, so you can 'think' much easier in
python.
 - It can be used for many many tasks, and you can adapt your
application as need be.
 - It is still quite fast and lightweight!
 - The community in general is quite helpful
 - It is quite fun to use
 - If it's good enough for nasa.. :-P

In regards to people claiming it is not 'real', that is a load of poo!
Ignore thy c elitists. Eric Raymond wrote a nice 'Why Python?'
article. http://www.linuxjournal.com/article/3882

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


Re: Class design (information hiding)

2007-09-07 Thread Daniel Larsson
On 9/7/07, Alexander Eisenhuth <[EMAIL PROTECTED]> wrote:
>
> Hi all,
>
> I'm wodering how the information hiding in python is ment. As I understand
> there
>   doesn't exist public / protected / private  mechanism, but a '_' and
> '__'
> naming convention.
>
> As I figured out there is only public and private possible as speakin in
> "C++
> manner". Are you all happy with it. What does "the zen of python" say to
> that
> design? (protected is useless?)


Strictly speaking, everything is public in python. Members prefixed with
"__" just get name mangled. But conceptually, yes, there is only public and
private members. Information hiding is based on convention, otherwise it
would be hard to write debuggers in python, which by definition wants to
break the information hiding principle. If you're not writing a debugger,
doc generator, or other type of meta level program, follow the conventions
of not peeking under the hood.

class A:
> def __init__(self):
> self.__z = 1
> self._z = 2
> self.z = 3
> def _getX(self):
> return "X"
> def __getY(self):
> return "Y"
> def doAnything(self):
> print self.__getY()
>
>
> class B(A):
> def __init__(self):
> A.__init__(self)
> print dir (self)
> >>> b = B()
> ['_A__getY', '_A__z', '__doc__', '__init__', '__module__', '_getX', '_z',
> 'doAnything', 'z']
>
> I was a bit surprised about '_A__getY' and '_A__z'.


This is so that in class B, you can also have members called __getY and __z,
and they won't interfere with class A (they'll be called _B__getY and _B__z
respectively ).

What would you say to a C++ Programmer about class interfaces in big Python
> systems? What is the idea behind the _ and __ naming.


As a rough analogy:

__name -> private
_name -> protected

Use or don't use '_'
> methods ? (As Designer of the software, as Programmer of the software)


I don't know if you're making a distinction here between "designer" and
"programmer". Are you meaning "implementer of library" and "user of
library"? As a user of a library, never ever explicitly call members
starting with an underscore.

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

Re: Speed of Python

2007-09-07 Thread Roberto Bonvallet
On Sep 7, 12:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:
> Here is the bench1.py:
> import math
> def bench1(n):
> for i in range(n):
> for j in range(1000):
> m=j+1
> z=math.log(m)
> z1=math.log(m+1)
> z2=math.log(m+2)
> z3=math.log(m+3)
> z4=math.log(m+4)
> z5=math.log(m+5)
> z6=math.log(m+6)
> z7=math.log(m+7)
> z8=math.log(m+8)
> z9=math.log(m+9)
> return z9
>
> Is my conclusion correct that Python is slower than matlab?

Show us your Matlab code in order to see if both are equivalent.
Your Python code creates n lists of 1000 elements, so you're not
actually
measuring only the numeric computations.

Cheers,
--
Roberto Bonvallet

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

Re: Changing data in an QAbstractListModel

2007-09-07 Thread exhuma.twn
On Sep 7, 12:42 am, Jonathan Gardner
<[EMAIL PROTECTED]> wrote:
> On Sep 6, 9:12 am, "exhuma.twn" <[EMAIL PROTECTED]> wrote:
>
> > I defined a simple "update" method in the model which I call on
> > certain events to fetch the new data in the DB. I tried to "emit" the
> > "dataChanged()" signal of the Model without success. I don't know
> > where I should get the two required "index" parameters from.
>
> > Any hints?
>
> Shouldn't the index method give you the indexes you need?

Right... The update method now looks like this:

   def update(self):
  c = db_con.cursor()
  # SELECT only the most recent entry for each company
  c.execute("SELECT DISTINCT ON (unit_id) nom FROM unit ORDER BY
unit_id, year DESC")
  for unit in c.fetchall():
 self.__units.append( unit[0] )
  c.close()

  si = self.index(0)
  se = self.index(len(self.__units)-1)

  self.emit(Signal("dataChanged()"), si, se)


Still, nothing is happening when I call this method. Do I still need
to handle the "dataChanged" signal somehow? Or does the ListView take
care of this?

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


MySQL: Global Connection

2007-09-07 Thread mcl
It is tough when the grey matter is getting past it.

I am starting to use MySQL and I would like to make my connection to
my database a variable in my Global Variable Class, but I just can not
see how to do it.

Class GlobalVars :

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


Re: Why 'class spam(object)' instead of class spam(Object)' ?

2007-09-07 Thread Carl Banks
On Fri, 07 Sep 2007 01:30:00 -0500, Sergio Correia wrote:
> Hi, I'm kinda new to Python (that means, I'm a total noob here), but
> have one doubt which is more about consistency that anything else.
> 
> Why if PEP 8 says that "Almost without exception, class names use the
> CapWords convention", does the most basic class, object, is lowercase?

It said "almost".  :)


> I found a thread about this:
> http://mail.python.org/pipermail/python-list/2007-April/437365.html
> where its stated that -object- is actually a type, not a class; but the
> idea still doesn't convince me.

There's a false dichotomy there: it's not an either-or situation.  Almost 
everyone would agree that new-style classes, defined by the Python class 
statement, are both classes and types.  Some might squabble over whether 
object is class, but it has nothing to do with why object is spelled in 
lower-case.

The reason why "object" is lower case is because built-in types are 
spelled in lower-case.  Why are built-in types lower case?  Because many 
built-in types were originially functions.  For example, "int" and "str" 
were once functions.  When these symbols became the names of their 
respective types, they kept the lower-case spelling, and it became 
convention for built-in types to be spelled lower-case.


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


wxPython unexpected exit

2007-09-07 Thread Jimmy
Hi, wxPython is cool and easy to use, But I ran into a problem
recently when I try to write a GUI.
The thing is I want to periodically update the content of StatixText
object, so after create them, I pack them into a list...the problem
comes when I later try to extract them from the list! I don't know
why?
my code is as following:

import wx, socket
import thread

class MyFrame(wx.Frame):

firstrun = 0
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Notifier')
self.panel = wx.Panel(self, -1)
self.length = 50
self.scale = 0.6
self.count = 5
self.size = wx.Frame.GetSize(self)
self.distance = self.size[1] / self.count
self.labellist = []
self.gaugelist = []

def ParseAndDisplay(self, data):
print "Successful access to main Frame class"
print 'And receive data: ', data
if MyFrame.firstrun == 0:
print 'First time run'
items = 3
for i in range(items):
self.labellist.append(wx.StaticText(self.panel, 
-1, data+str(i),
(150, 50+i*20), (300,30)))
MyFrame.firstrun = 1
else:
self.labellist[0].SetLabel('AAA')//PROGRAM WILL ABORT 
HERE!!!
self.labellist[1].SetLabel("Guo")
self.labellist[2].SetLabel("Qiang")


class NetUdp:

def __init__(self):
self.port = 8081
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.s.bind(("", self.port))
print "Listening on port", self.port

def recvdata(self):
data, addr = self.s.recvfrom(1024)
return data


def netThread():
netudp = NetUdp()
while True:
data = netudp.recvdata()
frame.ParseAndDisplay(data)

if __name__ == '__main__':
firstrun = 0
app = wx.PySimpleApp()
frame = MyFrame()
frame.Show()
# start network thread first
id = thread.start_new_thread(netThread, ())
# main wxpython loop begins
app.MainLoop()

I know the code is ugly, but can anyone really save me here!

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


unexpected behavior: did i create a pointer?

2007-09-07 Thread gu
hi to all!
after two days debugging my code, i've come to the point that the 
problem was caused by an unexpected behaviour of python. or by lack of 
some information about the program, of course! i've stripped down the 
code to reproduce the problem:


a = {}

for x in range(10):
 for y in range(10):
 a[x,y] = "0"

copyOfA = a

def functionA(x,y):
 print a[x,y],
 copyOfA[x,y] = "*"
 print a[x,y],copyOfA[x,y]


for x in range(10):
 for y in range(10):
 functionA(x,y)




now, in the second "for" cycle and in functionA() i only 'touch' copyOfA 
(altering it). as i don't touch the variable "a", i expect it not to be 
affected by any change, but copyOfA acts like a pointer to a and 
altering copyOfA's values result in altering the values of "a", so the 
result that i expect is:
0 0 *
0 0 *
0 0 *
0 0 *
[..]

but i get:
0 * *
0 * *
0 * *
0 * *
[..]

what's going on?
thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and Cron

2007-09-07 Thread Greg Lindstrom
This may be more of a Linux question, but I'm hoping some of you may be able
to help me.

I have a python (2.4) routine running on Gentoo Linux.  It creates a file
and, after the file is complete, renames the file using the os.rename()
command.  When I run the file from the command line everything works great,
but when I schedule the job to run from the crontab file, the original file
is created and populated, but the rename fails.  I am using full paths for
both the original and destination file, and run the command line version
after I 'su' to the production account (named 'edith').  I am told by my
sysadmin that the cron jobs run as edith as well, so he does not think it is
a permission issue (he points out the original file is being created and
populated as expected...the rename fails)

Have any of you dealt with anything like this?  It really has me scratching
my head.

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

Re: Why 'class spam(object)' instead of class spam(Object)' ?

2007-09-07 Thread Bruno Desthuilliers
Sergio Correia a écrit :
> Hi, I'm kinda new to Python (that means, I'm a total noob here), but
> have one doubt which is more about consistency that anything else.
> 
> Why if PEP 8 says that "Almost without exception, class names use the
> CapWords convention", does the most basic class, object, is lowercase?

Because it is an exception ?-)

Notice that all builtin types (list, dict, set, str, unicode, int, long, 
float, tuple, file, object, type, function, classmethod, staticmethod, 
property etc) are lower-case.

(snip interrogations about "object"'s type)

 class Eggs(object):
>   def __init__(self):
>   self.x = 1
 type(Eggs)
> 
> 
> Type 'type'? What is that supposed to mean?

type(Eggs) is roughly equivalent to Eggs.__class__, ie it returns the 
class of the Eggs class object, IOW the metaclass. In Python, classes 
are objects, so they are themselves instances of a class - by default, 
for new-style classes, instances of the class 'type'. In case you 
wonder, class 'type' is an instance of itself.


> Hope this makes any sense ;),

Idem !-)

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


Re: interesting puzzle......try this you will be rewarded...

2007-09-07 Thread Neil Cerutti
On 2007-09-07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Thu, 06 Sep 2007 22:57:21 -0300, Basilisk96 <[EMAIL PROTECTED]>  
> escribi?:
>
>> I got to 14 :)
>>
>> It's rather silly.
>>
>> I remember seeing a more elaborate puzzle that involved coding,
>> cryptography knowledge, etc. to get through it. But what was the link,
>> I forget now...
>
> Me too, and I can't find that link either. #15 is a bit
> difficult for people outside US, and spelling on #21 is
> questionable, but I liked this woody thing :)

Y'all may be thinking of The Euler Project, which provides math
puzzles for programmers.

http://projecteuler.net/

-- 
Neil Cerutti
I pulled away from the side of the road, glanced at my mother-in-law and
headed over the embankment. --Insurance Claim Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Wildemar Wildenburger
Steven D'Aprano wrote:
> On Fri, 07 Sep 2007 11:46:38 +0200, Wildemar Wildenburger wrote:
> 
>> gu wrote:
>>> hi to all!
>>> after two days debugging my code, i've come to the point that the
>>> problem was caused by an unexpected behaviour of python. or by lack of
>>> some information about the program, of course! i've stripped down the
>>> code to reproduce the problem:
>>>
>>> [snip FAQ]
>> Yes, basically you *created* a pointer. That's all that python has:
>> pointers.
> 
> No, you are confusing the underlying C implementation with Python.
I do not, as I have no clue of the C implementation :).
I just thought I'd go along with the analogy the OP created as that was 
his mindset and it would make things easier to follow if I didn't try to 
forcibly change that.
Please note that I had intended for the word 'created' to be in quotes 
rather than asterisks. I bit myself after I read my mistake online but 
then thought "Who cares?". I should have, maybe :).
And yes, I will admit that going along with that analogy isn't the best 
way to explain it. Grant Edwards in reply to Peter Otten makes it much 
clearer, I guess.

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


Re: library to launch program in linux

2007-09-07 Thread Neil Cerutti
On 2007-09-07, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> In message <[EMAIL PROTECTED]>, Laszlo Nagy
> wrote:
>
>> Grant Edwards wrote:
>>
>>> On 2007-09-06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>>>   
 I'm a new user. What library should I use so that I can launch
 program in linux using python?
 
>>>
>>> subprocess
>>>   
>> Hmm, there are some others...
>
> subprocess subsumes them all.

And someday soon, subprocess will RULE THE WORLD! BWA-HAHAHAHAH!

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


py2exe - change name of exe created

2007-09-07 Thread imageguy
I have a setup script like this;

setup(windows = [{"script":"myprogram.py",
   "icon_resources":[(0,"nabbitt.ico")],
"other_resources": [(24,1,manifest)]}
],
name = "Nabbitt ver 0.1",
data_files = [("",rootdata)],
zipfile = None,
options = {"py2exe": {
"compressed" : 1,
"dll_excludes": 
["w9xpopen.exe"],  #should also exclude
MSVCR71.dll
"bundle_files": 3 # 
1=Single .exe, 2=.exe with
pythonXX.dll
}
},
)

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


Re: Text processing and file creation

2007-09-07 Thread Paddy
On Sep 7, 3:50 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Sep 5, 5:17 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
> wrote:
> If this was a code golf challenge,

I'd choose the Unix split solution and be both maintainable as well as
concise :-)

- Paddy.

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


Python wrapper, problem with subprocess read/write

2007-09-07 Thread NeoGregorian
Hello, I am writing a wrapper to a basic Input/Output programs (where
you type a one line command at a time and then get 0 or more lines of
output before you can input the next command).

I'm sorry if this problem description is a bit long, but I wanted to
make the problem clear.

Example run of the original program:
C:\home\>start
Starting up program
   [Welcome to program v.X.Y.Z]
blahblahblah
and some more lines
>input command
program response...
more program response...
etc.
>another command
...

This is what the wrapper is expected to do...

1: Start up the program.
2: Forward the startup printouts by the program until the line where
it first asks for a command.
3: When waiting for input, input a command from a sequential list of
strings (or other source of strings).
4: Forward the programs printouts until all lines are read and the
program prompts for new command.
5: Repeat 3-4 until list is depleted or program is terminated and then
close the program.


Now, to the problem:
In step 2/4, how to read all lines except the one which is unfinished
(in the example, the lines beginning with >) and waiting for input?

My attempts use something like this:

proc = Popen(['programname'], stdout = PIPE, stdin = PIPE )
for string_element in string_source :
proc.stdin.write(string_element)
lines = proc.stdout.readlines()
method_that_processes_output(lines)

The problem with this is that stdout.readlines() doesn't return since
it reads until EOF...
I tried instead to use:

lines = []
line = proc.stdout.readline()
while line :
lines.append(line)
line = proc.stdout.readline()

This prints out everything except the ">" line, which is good. But
then freezes while waiting for input, which is bad.

Any suggestions on how to solve this in a good way?

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


Speed of Python

2007-09-07 Thread wang frank
Hi, 

While comparing the speed of octave and matlab, I decided to do a similar 
test for python and matlab. The result shows that python is slower than 
matlab by a factor of 5. It is not bad since octave is about 30 time slower 
than matlab.


Here is the result in matlab:
Elapsed time is 0.015389 seconds.

and in Python:

t=timeit.Timer("bench1.bench1(10)","import bench1")
t.repeat(1,1)

[0.071012377266015392]

Here is the bench1.py:
import math
def bench1(n):
for i in range(n):
for j in range(1000):
m=j+1
z=math.log(m)
z1=math.log(m+1)
z2=math.log(m+2)
z3=math.log(m+3)
z4=math.log(m+4)
z5=math.log(m+5)
z6=math.log(m+6)
z7=math.log(m+7)
z8=math.log(m+8)
z9=math.log(m+9)
return z9   

Is my conclusion correct that Python is slower than matlab? Are there any 
way to speed it up? It seems Python automatically created bench1.pyc. Does 
Python automatically execute the bench1.pyc to speed it up?



Thanks

Frank

_
「地図マガ」特集 残暑を吹きとばせ!ご当地アイスクリームマップが登場 
http://chizumaga.jp/ 

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

Re: Why 'class spam(object)' instead of class spam(Object)' ?

2007-09-07 Thread Steve Holden
Carl Banks wrote:
> On Fri, 07 Sep 2007 01:30:00 -0500, Sergio Correia wrote:
>> Hi, I'm kinda new to Python (that means, I'm a total noob here), but
>> have one doubt which is more about consistency that anything else.
>>
>> Why if PEP 8 says that "Almost without exception, class names use the
>> CapWords convention", does the most basic class, object, is lowercase?
> 
> It said "almost".  :)
> 
Indeed it did, and never forget that most of PEP 8 was derived from an 
essay by Guido whose original title was "A Foolish Consistency is the 
Hobgoblin of Little Minds" ...
> 
>> I found a thread about this:
>> http://mail.python.org/pipermail/python-list/2007-April/437365.html
>> where its stated that -object- is actually a type, not a class; but the
>> idea still doesn't convince me.
> 
You don't have to be convinced. You just have to do what the PEP says 
yourself and ignore the people who *haven't* done what it says 
(particularly if they are core Python developers).

> There's a false dichotomy there: it's not an either-or situation.  Almost 
> everyone would agree that new-style classes, defined by the Python class 
> statement, are both classes and types.  Some might squabble over whether 
> object is class, but it has nothing to do with why object is spelled in 
> lower-case.
> 
> The reason why "object" is lower case is because built-in types are 
> spelled in lower-case.  Why are built-in types lower case?  Because many 
> built-in types were originially functions.  For example, "int" and "str" 
> were once functions.  When these symbols became the names of their 
> respective types, they kept the lower-case spelling, and it became 
> convention for built-in types to be spelled lower-case.
> 
In other words: "Get over it" ;-)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: startswith( prefix[, start[, end]]) Query

2007-09-07 Thread Steve Holden
Bruno Desthuilliers wrote:
> Steve Holden a écrit :
[...]
>>
>> Probably not really necessary, though, and they do say that premature 
>> optimization is the root of all evil ...
> 
> I wouldn't call this one "premature" optimization, since it doesn't 
> change the algorithm, doesn't introduce (much) complication, and is 
> proven to really save on lookup time.
> 
> Now I do agree that unless you have quite a lot of prefixes to test, it 
> might not be that necessary in this particular case...

The defense rests.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Class design (information hiding)

2007-09-07 Thread Alexander Eisenhuth
Hi all,

I'm wodering how the information hiding in python is ment. As I understand 
there 
  doesn't exist public / protected / private  mechanism, but a '_' and '__' 
naming convention.

As I figured out there is only public and private possible as speakin in "C++ 
manner". Are you all happy with it. What does "the zen of python" say to that 
design? (protected is useless?)


class A:
def __init__(self):
self.__z = 1
self._z = 2
self.z = 3
def _getX(self):
return "X"
def __getY(self):
return "Y"
def doAnything(self):
print self.__getY()


class B(A):
def __init__(self):
A.__init__(self)
print dir (self)
 >>> b = B()
['_A__getY', '_A__z', '__doc__', '__init__', '__module__', '_getX', '_z', 
'doAnything', 'z']

I was a bit surprised about '_A__getY' and '_A__z'.

What would you say to a C++ Programmer about class interfaces in big Python 
systems? What is the idea behind the _ and __ naming. Use or don't use '_' 
methods ? (As Designer of the software, as Programmer of the software)

Regards Alexander




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


Re: library to launch program in linux

2007-09-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Laszlo Nagy
wrote:

> Grant Edwards wrote:
>
>> On 2007-09-06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>>   
>>> I'm a new user. What library should I use so that I can launch
>>> program in linux using python?
>>> 
>>
>> subprocess
>>   
> Hmm, there are some others...

subprocess subsumes them all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: startswith( prefix[, start[, end]]) Query

2007-09-07 Thread Duncan Booth
"Tim Williams" <[EMAIL PROTECTED]> wrote:

> Isn't slicing still faster than startswith?As you mention timeit,
> then you should probably add slicing to the pot too :)
> 

Possibly, but there are so many other factors that affect the timing 
that writing it clearly should be your first choice.

Some timings:

@echo off
setlocal
cd \python25\lib
echo "startswith"
..\python timeit.py -s "s='abracadabra1'*1000;t='abracadabra2'" s.startswith(t)
..\python timeit.py -s "s='abracadabra1'*1000;t='abracadabra1'" s.startswith(t)
echo "prebound startswith"
..\python timeit.py -s 
"s='abracadabra1'*1000;t='abracadabra2';startswith=s.startswith" startswith(t)
..\python timeit.py -s 
"s='abracadabra1'*1000;t='abracadabra1';startswith=s.startswith" startswith(t)
echo "slice with len"
..\python timeit.py -s "s='abracadabra1'*1000;t='abracadabra2'" s[:len(t)]==t
..\python timeit.py -s "s='abracadabra1'*1000;t='abracadabra1'" s[:len(t)]==t
echo "slice with magic number"
..\python timeit.py -s "s='abracadabra1'*1000;t='abracadabra2'" s[:12]==t
..\python timeit.py -s "s='abracadabra1'*1000;t='abracadabra1'" s[:12]==t

and typical output from this is:

"startswith"
100 loops, best of 3: 0.542 usec per loop
100 loops, best of 3: 0.514 usec per loop
"prebound startswith"
100 loops, best of 3: 0.472 usec per loop
100 loops, best of 3: 0.474 usec per loop
"slice with len"
100 loops, best of 3: 0.501 usec per loop
100 loops, best of 3: 0.456 usec per loop
"slice with magic number"
100 loops, best of 3: 0.34 usec per loop
100 loops, best of 3: 0.315 usec per loop

So for these particular strings, the naive slice wins if the comparison is 
true, but loses to the pre-bound method if the comparison fails. The slice is 
taking a hit from calling len every time, so pre-calculating the length
(which should be possible in the same situations as pre-binding startswith)
might be worthwhile, but I would still favour using startswith unless I knew
the code was time critical.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: startswith( prefix[, start[, end]]) Query

2007-09-07 Thread Bruno Desthuilliers
Steve Holden a écrit :
> TheFlyingDutchman wrote:
>>> Else, you could as well write your own testing function:
>>>
>>> def str_starts_with(astring, *prefixes):
>>>startswith = astring.startswith
>>>for prefix in prefixes:
>>>  if startswith(prefix):
>>>return true
>>>return false
>>>
>>
>> What is the reason for
>>   startswith = astring.startswith
>>   startswith(prefix)
>>
>> instead of
>>   astring.startswith(prefix)
>>
> It's an optimization: the assigment creates a "bound method" (i.e. a 
> method associated with a specific string instance) and avoids having to 
> look up the startswith method of astring for each iteration of the inner 
> loop.
> 
> Probably not really necessary, though, and they do say that premature 
> optimization is the root of all evil ...

I wouldn't call this one "premature" optimization, since it doesn't 
change the algorithm, doesn't introduce (much) complication, and is 
proven to really save on lookup time.

Now I do agree that unless you have quite a lot of prefixes to test, it 
might not be that necessary in this particular case...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe - change name of exe created

2007-09-07 Thread Thomas Heller
imageguy schrieb:
[...]
>> > Note that every thing works fine with this and creates an exe program
>> > called
>> > "myprogram.exe"
>>
>> > I would like to setup program to create an output called;
>> > "MyBestProgram.exe"
>>
>> > IS that at all possible ?
>>
>> Yes.  Use a 'dest_base' key in the dictionary, like so:
>>
>> > setup(windows = [{"script":"myprogram.py",
>> >"icon_resources":[(0,"nabbitt.ico")],
>>
>>  "dest_base": "MyBestProgram",> 
>> "other_resources": [(24,1,manifest)]}
>>
>> ...
>>
>> 'dest_base' is the basename of the destination program that py2exe creates.
>>
>> Thomas- Hide quoted text -
>>
>> - Show quoted text -
> 
> Thanks.
> I really appreciate the response.
> Where would I find that in the docs ?  Thought I had searched
> everywhere.


If you have searched everywhere then it isn't in the docs.  You can probably
learn a lot about py2exe when you try out and study the supplied samples; they
are in the Lib\site-packages\py2exe\samples subdirectories.

The next step would be to consult the source code ;-)

The current maintainer of pyexe, Jimmy Retzlaff, seems to have disappeared
from the net as it seems; I hope he is well.  So, the current state of py2exe
itself and the documentation is not so good; OTOH there is a wiki on
www.py2exe.org where anyone can contribute tips tricks and docs.

Thomas

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


MySQLdb: ValueError Something Stupid

2007-09-07 Thread mcl
I have just started with python and MySQL.

I have a simple test for each of my tables.

The first two work as expected, but the third 'qlooks', gives a
ValueError.

If I copy and paste the SQL in the traceback to phpMyAdmin, it works
as expected.

Can anyone give a clue as to what I am doing wrong

Python 2.4
MySQL  4.1.22-standard

The tablename qlooks is LOWERCASE

Code ===
cursor = gv.conn.cursor()
queries = ["%septi%"]
fields = ("qlTitle", "qlSubTitle", "qlPostCode", "qlMap",
"qlDetails")
tblFields = "select * from qlooks "
whereTests = 'Where qlTitle like "%septi%"'
sql = tblFields + whereTests
#cursor.execute(sql)
cursor.execute('select * from PERMS')
row = cursor.fetchone()
print "Row=", row, gv.nl
cursor.execute('select * from LISTS')
row = cursor.fetchone()
print "Row=", row, gv.nl
cursor.execute('select * from qlooks')
row = cursor.fetchone()
print "Row=", row, gv.nl

cursor.close()

ERROR TRACEBACK 

   79 print "Row=", row, gv.nl
   80 cursor.execute('select * from qlooks')
   81 row = cursor.fetchone()
   82 print "Row=", row, gv.nl
cursor = , cursor.execute = >
 /usr/lib/python2.4/site-packages/MySQLdb/cursors.py in
execute(self=, query='select * from
qlooks', args=None)
   93 """
   94 del self.messages[:]
   95 return self._execute(query, args)
   96
   97 def _execute(self, query, args):
self = , self._execute = >, query =
'select * from qlooks', args = None
 /usr/lib/python2.4/site-packages/MySQLdb/cursors.py in
_execute(self=, query='select * from
qlooks', args=None)
  112 exc, value, tb = exc_info()
  113 del tb
  114 self.errorhandler(self, exc, value)
  115 self._executed = query
  116 return r
self = , self.errorhandler = >, exc = ,
value = 
 /usr/lib/python2.4/site-packages/MySQLdb/connections.py in
defaulterrorhandler(connection=<_mysql.connection open to
'db.sabren.com' at 936cac4>, cursor=,
errorclass=,
errorvalue=)
   31 else:
   32 connection.messages.append(error)
   33 raise errorclass, errorvalue
   34
   35
errorclass = , errorvalue =


ValueError: invalid literal for int(): 0-
  args = ('invalid literal for int(): 0-',)


=
Thanks Richard

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


  1   2   >