Re: Finite State Machine GUI editor in python?

2007-12-16 Thread kib
Hendrik van Rooyen a écrit :
> I have spent some time googling and on wiki and came up with
> pyFSA in python. It may end up being useful, but it is not directly
> what I am looking for, as there is no GUI that I can see.
> 
> I know about SMC, but it is not Python, and I can't find the gui.
> 
> This looks good, but it seems to be in a Latin based language
> and I am linguistically challenged:
> 
> http://www.ucse.edu.ar/fma/sepa/edt.htm
> 
> I am looking for a similar front end, going from pretty pictures of 
> state diagrams to some sort of state machine descriptor language 
> or specification file, and I am not very fussy about the format of 
> the output at this stage.
> 
> Does anyone know of such an animal that is FOSS? - if written in 
> Python it will be a bonus!  
> 
> It will also help if its in a language I can understand.  : - (  
> 

Hi Hendrik,

I've bookmarked these ones :

http://www.univ-paris12.fr/lacl/pommereau/tlf/index.html [in French]
http://www.ncc.up.pt/~nam/ [look at the FAdo project]
http://www.cs.usfca.edu/~jbovet/vas.html [written in Java]

I hope it helps you,

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


Re: About Rational Number (PEP 239/PEP 240)

2007-12-16 Thread Lie
> Rationals are not that simple.

So do complex number, in fact most people are much more familiar with
rationals/fractions than with complex number. And notice that I don't
use the word simple, I use the word elementary. Elementary doesn't
always means simple (although it usually is), but rather it emphasizes
on it being essential and being a basic building block for other
things.

And if you think about it, floating numbers aren't that simple either.
It only seems simple because it's implemented natively in the
hardware, but I'm sure the engineers creating them have a heated
discussion when they first try to implement it. Remember the
discussion about Decimals? How many rounding methods are there?

> * Unless you are working under very controlled conditions, rationals
> very quickly grow enormous numerators and denominators, hence
> require arbitrary precision integers (which, I concede, are part of
> Python).

One part of the problem is solved (arbitrary length integers) another
problem is the growth of rationals. That could have easy workaround,
like a scientific calculator, by using a special operator to construct
a fractions, people would only _consciously_ use fractions, avoiding
unexpected return of fraction AND controlled environment for using
fraction. It's also possible to have lossy_simplify(n[, acc]) method
for calculations that need rationals but don't need such accuracy (in
that case, perhaps float could be a better substitute).

> * In order to have a canonical representation of integers, they need
> to be kept in normalised form.

There are methods to simplify fractions and there are addition,
subtraction, division, multiplication, etc can be made to
automatically returns the most simple form.
[btw, off topic, in music, isn't 1/4 and 2/8 different? I'm not very
keen of music though, so correct me if I'm wrong.]

> * Having yet another numerical type would make it difficult what
> type to expect from a calculation.
There is a simple rule of thumb:
If a (built-in) method receives floats returns floats, else returns
fractions << Please don't take me too literally here, apply some
compromises.
The rationale is simple: Float's can't be turned easily into fraction,
while the otherwise involves only a simple true division.

> Which only seems to me to prove that having integer division return
> a floating value is a mistake
Oh no, it's not a mistake. Only IEEE's floating point standard isn't
sufficient to cope with exact arithmetic. Another reason to use
fractions.

> So while rationals might be useful to have available for
> some things, you should have to explicitly ask for them.
> Returning rationals from '/' applied to integers would
> be a bad idea, for example.

> From my reading of the PEP, it doesn't suggest such automatic
> coercions (neither rejects them explicitly though). Given the huge
> discussions about integer vs true division, it would be very
> controversial to suggest implicit rational division.

Which I agree, implicit rational division would be evil. People should
explicitly use fractions, using a special division operators, just
like calculators (although mine seems to always use fractions 'behind-
the-scenes' whenever possible, but on presenting them to the user it
does the rule of thumbs I mentioned).

> Regardless, a builtin (or at least standard library) rational type
> would be nice to have. Of course folks that *really need* rationals
> are already using some 3rd party library, but for the rest of us it
> would be an improvement in several cases where currently floats are
> used, just like the motivation for Decimals. Only difference seems to
> be that there aren't so many or compelling use cases for rationals as
> for decimals (mainly money counting).

People have, for ages used floating numbers in calculation on
occasions where it shouldn't be used, and that's a really bad practice
and even prominent (paper) mathematician are accustomed to such
practice. Floating numbers involves rounding and continued use of them
would make the value wanders off far away.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inter-process communication, how?

2007-12-16 Thread ecir . hana
On Dec 16, 5:24 am, John Machin <[EMAIL PROTECTED]> wrote:
>
> Yes. Consider this: If you were to run your calculation script from
> the shell prompt [strongly recommended during testing], how would you
> tell it the name of the file? Now look at the docs again.
>

File arguments! Of course, totally forgot about them! Thanks a lot!

>
>
> > PS: both with mmpam and temp file you probably meant that I should
> > hard code some as-weirdest-filename-as-possible two both programs but
> > what if I run the computation several times?
>
> That's mmap, not mmpam. No, Dennis didn't mean that you should hard
> code a filename. Have a look at the tempfile module.

Now I recall I read I somewhere that network communication is so much
faster than disk access (especially on the same machine, as steve
howell suggested) so instead of file names I probably should find out
which port is open to use.

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


Re: Inter-process communication, how?

2007-12-16 Thread ecir . hana
On Dec 16, 6:38 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>
>
> Read the details for subprocess.Popen() again...
>
> """
> /args/ should be a string, or a sequence of program arguments. The
> program to execute is normally the first item in the args sequence or
> string, but can be explicitly set by using the executable argument.
> """
>
> IOWs, passing it what you would enter on a command line
>
> "subscript.py tempfilename"
> ["subscript.py", "tempfilename"]
>
> should be sufficient.
>

>
> There is a module that can generate temporary file names, though for
> this usage you could even do something to obtain the parent program
> process ID along with a timestamp and create a file name from all that.
> What are the odds that your "several times" would have the same clock
> time?
>

Quite small, I guess. However, perhaps I should better consider using
sockets.

Thanks!

ps: I really like how you format the paragraphs! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


How to generate pdf file from an html page??

2007-12-16 Thread abhishek
Hi everyone, I am trying to generate a PDF printable format file from
an html page. Is there a way to do this using   python. If yes then
which library and functions are required and if no then reasons why it
cant be done.

Thank you All
-- 
http://mail.python.org/mailman/listinfo/python-list


python-xlib question

2007-12-16 Thread giovanni . iovino
Hi,
sorry for my English.
I'm writing my first python script for Linux for a remote bluetooth
application.
I'm using python-xlib library to send keyboard and mouse events and at
the moment
I can send keyboard emulated input to the window where pointer is on,
i can also move the pointer over the
desktop.
I'm using python 2.5 on a Ubuntu 7.10 system with gnome and compiz
However the method fails when i try to emulate mouse clicks
Here follows  the code I'm using, if you change ButtonPress and
ButtonRelease with KeyPress and KeyRelease and change the detail of
ev_d it works

#!/usr/bin/env python

import Xlib.display
import Xlib.X
import Xlib.XK
import Xlib.error
import time

display = Xlib.display.Display()

screen = display.screen()
root = screen.root
pointer=root.query_pointer() #Get info like window where pointer is on
and pointer position
window=pointer.child

ev_d = dict(
time = 0, # Time of the event (useful for double-
clicks for mouse
events)
root = root,
window = pointer.child, #The window where is the
pointer
same_screen = 1,
child = Xlib.X.NONE,
root_x = pointer.root_x,
root_y = pointer.root_y,
event_x = pointer.win_x,
event_y = pointer.win_y,
state = Xlib.X.NONE,
detail =Xlib.X.Button1
)

ev2_dict = ev_d.copy()
ev2_dict['state'] = Xlib.X.Button1 << 8 # that is ButtonXMask
ev=Xlib.protocol.event.ButtonPress(**ev_d)
ev2=Xlib.protocol.event.ButtonRelease(**ev2_dict)

display.send_event(Xlib.X.PointerWindow,ev)

display.sync() # Send the inserted events
time.sleep(500/1000)
display.send_event(Xlib.X.PointerWindow,ev2)
display.sync()

#

Thanks to who wants help me
Bye,
Giovanni
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About Rational Number (PEP 239/PEP 240)

2007-12-16 Thread Steven D'Aprano
On Sat, 15 Dec 2007 22:20:22 -0800, Dennis Lee Bieber wrote:

> On Sun, 16 Dec 2007 06:09:06 -, Steven D'Aprano
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
>> Yes, but my point (badly put, I admit) was that people find fractions
>> far easier to work with than they find floating point numbers. And with
>> any rational data type worth the name, you simply should never get
>> anything as unintuitive as this:
>> 
>> >>> from __future__ import division
>> >>> 4/10 + 2/10 == 6/10
>> False
> 
> Which only seems to me to prove that having integer division return
> a floating value is a mistake  

What integer division? It's floating point division. The / operator 
creates floats. If I wanted integer division, I would have used //.


> My background with mostly ancient
> languages (FORTRAN) reads that and sees "0 + 0 == 0", 

With some floating point implementations, one can find values such that 
x == 0.0 and y == 0.0 but x + y != 0.0.

> and "4.0/10.0 + 2.0/10.0 == 6.0/10.0" automatically makes me leery...

*shrug*

That's the whole point. Floating point math is weird. Rationals are not. 
Using floats when you actually need rationals is dangerous.


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


Re: Inter-process communication, how?

2007-12-16 Thread ecir . hana
Just for the record:

http://www.amk.ca/python/howto/sockets/

"Of the various forms of IPC (Inter Process Communication), sockets
are by far the most popular. On any given platform, there are likely
to be other forms of IPC that are faster, but for cross-platform
communication, sockets are about the only game in town."
-- 
http://mail.python.org/mailman/listinfo/python-list


OpenOpt install

2007-12-16 Thread Neal Becker
What do I need to do?  I have numpy, scipy (Fedora F8)

 cd openopt/
[EMAIL PROTECTED] openopt]$ python setup.py build
running build
running config_cc
unifing config_cc, config, build_clib, build_ext, build commands --compiler 
options
running config_fc
unifing config_fc, config, build_clib, build_ext, build commands --fcompiler 
options
running build_py
creating build
creating build/lib
creating build/lib/scikits
copying scikits/__init__.py -> build/lib/scikits
creating build/lib/scikits/openopt
copying scikits/openopt/__init__.py -> build/lib/scikits/openopt
copying scikits/openopt/info.py -> build/lib/scikits/openopt
copying scikits/openopt/oo.py -> build/lib/scikits/openopt
Traceback (most recent call last):
  File "setup.py", line 101, in 
import scikits
ImportError: No module named scikits

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


python docs in contrib?

2007-12-16 Thread Tshepang Lekhonkhobe
Hi,
I was surprised to find python2.{4,5}-doc in contrib and wondered why?

-- 
my place on the web:
floss-and-misc.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python really a scripting language?

2007-12-16 Thread MonkeeSage
On Dec 14, 3:15 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Dec 14, 2:48 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 14, 2007 2:09 PM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > > On Dec 11, 10:34 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> > > > "Ron Provost" <[EMAIL PROTECTED]> wrote in message
>
> > > >news:[EMAIL PROTECTED]
> > > > But here's my problem, most of my coworkers, when they see my apps and
> > > > learn that they are written in Python ask questions like, "Why would you
> > > > write that in a scripting language?"  Whenever I hear a comment like 
> > > > that I
> > > > can feel myself boiling inside.
> > > > ===
>
> > > > I don't blame you.  Python is an full-fledged algorithm/programming
> > > > language that was designed to *also* be used a scripting language.
>
> > > When you buy a new car, which is more important, the styling
> > > or what's under the hood?
>
> > 
>
> > > That's for the whole sequence, not a single term!
>
> > > 25.67 MINUTES compared to 17.65 HOURS!
>
> > > So, sure, some languages compile to .exe programs.
>
> > > In the trade, we call that "polishing a turd".
>
> > While I agree with the sentiment, surely this can't be a good example
> > of F#s general performance?
>
> Of course. They example was deliberately chosen to make
> F#'s BigInt library look as bad as possible.
>
> > I would expect .NET code to smoke stock
> > (non-Psycoed) Python in this benchmark.
>
> Probably. It just so happens that the example chosen
> is typical of _my_ number theory research and I was
> toying with the idea of converting my Collatz Conjecture
> function library to F#.
>
> And that would take a lot of work since F# doesn't have
> anywhere near the functionality of gmpy. There isn't
> even a BigInt.mod function for cryin' out loud, let alone
> stuff like GCD or modular inverse, critical to my research.
>
> Sure, I could write my own Extended Euclidean Algorithm,
> but now that I now that F# is just a Volkswagen with a
> fiberglass shell that looks like a Ferrari, there isn't
> much point, eh?
>
> And don't even get me started about the stupid stuff,
> like having TWO different type of Big Rationals. One's
> more efficient than the other, they say. So why two?
> The less efficient one has functions not implemented
> in the other. And F# is strongly typed, so you can't
> use BigRational methods with BigNum types. And they
> have all sorts of conversion methods for to/from ints,
> strings, bigints, etc. Guess which conversions they
> don't have? BigRational <-> BigNum, of course.
>
> MAybe I'll check it out again in the future after it
> has gone through several revisions.

Since F# is a caml derivative, you may want to look at OCaml. Though,
I've never used OCaml for any kind of heavy number-crunching, so maybe
it has even worse library support; can't say. Ps. The two types are
probably for boxed and unboxed versions, q.v. this article, about half-
way down: http://msdn.microsoft.com/msdnmag/issues/1200/dotnet/

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


Re: python docs in contrib?

2007-12-16 Thread Jorge Godoy
Tshepang Lekhonkhobe wrote:

> Hi,
> I was surprised to find python2.{4,5}-doc in contrib and wondered why?

What contrib? 

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


Re: python docs in contrib?

2007-12-16 Thread Tshepang Lekhonkhobe
On Dec 16, 2007 4:33 PM, Jorge Godoy <[EMAIL PROTECTED]> wrote:
> Tshepang Lekhonkhobe wrote:
>
> > Hi,
> > I was surprised to find python2.{4,5}-doc in contrib and wondered why?
>
> What contrib?

contrib section of the archive, as opposed to main


-- 
my place on the web:
floss-and-misc.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python docs in contrib?

2007-12-16 Thread Arnaud Delobelle
On Dec 16, 2:43 pm, "Tshepang Lekhonkhobe" <[EMAIL PROTECTED]> wrote:
> On Dec 16, 2007 4:33 PM, Jorge Godoy <[EMAIL PROTECTED]> wrote:
>
> > Tshepang Lekhonkhobe wrote:
>
> > > Hi,
> > > I was surprised to find python2.{4,5}-doc in contrib and wondered why?
>
> > What contrib?
>
> contrib section of the archive, as opposed to main

Are you refering to debian packages for python?  In this case
you may be better off posting on one of the debian mailing lists.

--
Arnaud

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


Re: python docs in contrib?

2007-12-16 Thread Jorge Godoy
Tshepang Lekhonkhobe wrote:

> On Dec 16, 2007 4:33 PM, Jorge Godoy <[EMAIL PROTECTED]> wrote:
>> Tshepang Lekhonkhobe wrote:
>>
>> > Hi,
>> > I was surprised to find python2.{4,5}-doc in contrib and wondered why?
>>
>> What contrib?
> 
> contrib section of the archive, as opposed to main

doc is right on the root of the tarball for Python 2.5.1.  

Are you sure you are not talking about any distribution package or something
like that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python docs in contrib?

2007-12-16 Thread Tshepang Lekhonkhobe
On Dec 16, 2007 4:49 PM, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> On Dec 16, 2:43 pm, "Tshepang Lekhonkhobe" <[EMAIL PROTECTED]> wrote:
> > On Dec 16, 2007 4:33 PM, Jorge Godoy <[EMAIL PROTECTED]> wrote:
> >
> > > Tshepang Lekhonkhobe wrote:
> >
> > > > Hi,
> > > > I was surprised to find python2.{4,5}-doc in contrib and wondered why?
> >
> > > What contrib?
> >
> > contrib section of the archive, as opposed to main
>
> Are you refering to debian packages for python?  In this case
> you may be better off posting on one of the debian mailing lists.

Second time I made the mistake of posting to python-list instead of
debian-python. Forgive me.

-- 
my place on the web:
floss-and-misc.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


why this error?

2007-12-16 Thread python.jiang
hello friends, the question had show bellow, any friend can tell me why. thanks.
 
list:
def test():
  exec "import sys"
  a=range(15)
  b=[13,3]
  c=filter(lambda x: x not in b,a)
  return c
print test()
 
run result:
  File "a.py", line 2
exec "import sys"
SyntaxError: unqualified exec is not allowed in function 'test' it contains a 
nested function with free variables
 
and must be change to bellow, then OK:
b=None
def testFilter(x):
  global b
  return x not in b
def test():
  exec "import sys"
  global b
  a=range(15)
  b=[13,3]
  c=filter(testFilter,a)
  return c
print test()
last run result is:
[0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14]
 
any friend can tell me why?
thanks alot very much!!-- 
http://mail.python.org/mailman/listinfo/python-list

IDLE question

2007-12-16 Thread rocco . rossi
I'm using IDLE for my  Python programming. I can't seem to solve one
issue though. Whenever I try to indent a region of code, I simply
select it and hit the tab key, as I usually do in most editors, like
GEdit or Geany on Linux, for instance, and it works fine. But, if I
try to unindent a region of code, which i would do by pressing Shift-
Tab in other editors, it just won't work, and I can't find any
combination that will.

Anybody know if this operation is possible at all with IDLE, and if it
is, what's the combination of keys?

Thanx.

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


Re: How to generate pdf file from an html page??

2007-12-16 Thread Zentrader
I'm sure it can be done but there is no reason to reinvent the wheel
unless it's for a programming exercise.  You can use pdftohtml and run
it from a Python program if you want.
http://pdftohtml.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate pdf file from an html page??

2007-12-16 Thread Zentrader
Sorry, I read that backwards.  I do it the opposite of you.  Anyway a
google for "html to pdf python" turns up a lot of hits.  Again, no
reason to reinvent the wheel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About Rational Number (PEP 239/PEP 240)

2007-12-16 Thread Aahz
In article <[EMAIL PROTECTED]>,
George Sakkis  <[EMAIL PROTECTED]> wrote:
>
>Regardless, a builtin (or at least standard library) rational type
>would be nice to have. Of course folks that *really need* rationals
>are already using some 3rd party library, but for the rest of us it
>would be an improvement in several cases where currently floats are
>used, just like the motivation for Decimals. Only difference seems to
>be that there aren't so many or compelling use cases for rationals as
>for decimals (mainly money counting).

You've precisely hit on the problem: previous discussion about rationals
has bogged down because proponents insisted on making it a built-in type
rather than a library.  If a PEP were submitted with code for a library,
there would be little trouble getting it accepted -- just like Decimal.

Even now, after a couple of releases with Decimal in the library, there
remains much opposition to a Decimal built-in, not even talking about
Decimal literals.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Typing is cheap.  Thinking is expensive."  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About Rational Number (PEP 239/PEP 240)

2007-12-16 Thread Mel
Steven D'Aprano wrote:

> Yes, but my point (badly put, I admit) was that people find fractions far 
> easier to work with than they find floating point numbers. 

I'm not so sure.  I got caught by the comic XKCD's 
infinite-resistor-grid thing, and simplified it to a ladder network -- 
call it L -- made up of 2 1-ohm resistors in series with a 1-ohm 
resistor paralleled by L.  Simulating this -- assuming an arbitrary 
endpoint with resistance 3 -- well, it takes a little thought to 
decide that 11/15 < 3/4, and a lot more to decide the same thing for 
153/209 and thus decide whether the series is coming or going.

Then when you work out the right answer from

L = 2 + (L / (L+1))

that answer depends on sqrt(12), which Rationals handle just as badly 
as floats, and at far greater expense.

I wrote a Rational class back when I was learning to do these things 
in Python, and it was actually pretty easy: a dash of GCD, a pinch of 
partial fractions, and a lot of following the Python Reference Manual. 
It eventually worked as advertised, but I haven't used it since. 
It could stand to be updated to use the __new__ method and produce 
genuinely immutable instances, if I could find the source.

Mel.
And with any
> rational data type worth the name, you simply should never get anything 
> as unintuitive as this:
> 
 from __future__ import division
 4/10 + 2/10 == 6/10
> False
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate pdf file from an html page??

2007-12-16 Thread Ramsey Nasser
On Dec 16, 2007 7:26 PM, Zentrader <[EMAIL PROTECTED]> wrote:
> Sorry, I read that backwards.  I do it the opposite of you.  Anyway a
> google for "html to pdf python" turns up a lot of hits.  Again, no
> reason to reinvent the wheel.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Like Zentrader said, theres no reason to reinvent the wheel. An HTML
to PDF converter is no trivial task. You would essentially have to
implement an HTML layout engine that outputs PDF files. Not only does
that mean you would have to programatically produce a PDF file, but it
means you would have to parse and correctly render HTML and CSS
according to accepted web standards, the W3C's specifications. This
has proved difficult to do and get right in practice, as is evident
from the browser compatibility issues that continue to plague the web.

Theres a package called Prince that's supposed to do an excellent job.
Check it out:

http://www.princexml.com/

Its layout engine surpasses some browsers in terms of compatibility
with web standards. I don't think its free for commercial use, though,
so this might depend on what exactly you're trying to do.

An alternative idea it to wait for Firefox 3 to come out. If I'm not
mistaken, it will feature a new version of the Gecko layout engine
which will use Cairo for all its rendering. Coincidently, Cairo can be
made to output PDF files. So, you may be able to hack something
together.

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


Re: IDLE question

2007-12-16 Thread bizcomputing
On Dec 16, 11:47 am, [EMAIL PROTECTED] wrote:
> I'm using IDLE for my  Python programming. I can't seem to solve one
> issue though. Whenever I try to indent a region of code, I simply
> select it and hit the tab key, as I usually do in most editors, like
> GEdit or Geany on Linux, for instance, and it works fine. But, if I
> try to unindent a region of code, which i would do by pressing Shift-
> Tab in other editors, it just won't work, and I can't find any
> combination that will.
>
> Anybody know if this operation is possible at all with IDLE, and if it
> is, what's the combination of keys?
>
> Thanx.
>
> Rock
Dealt just recently myself with this issue.  You don't say which
platform, and honestly I've not been doing Python long enough to know
what diffs may be in IDLE between platforms.  I'm running on XP.  In
the IDLE shell, I chose Options/Configure IDLE.  This brings up the
configure dialog.  Choose the Keys tab. Scroll the Action - Key(s)
list until you find dedent-region.  I'm not sure what the default
keystroke is, seem to recall something like CTRL-6 but I could be
totally wrong with that.  Anyhow, when you find that entry, you can
see what keystroke is currently assigned to that function.  You can
also Use the "Get New Keys for Selection" button to change the key
sequence.  I successfully changed it to shift tab.  When you make the
change, it will require that you name your new custom key set.  Don't
remember the whole process, but hopefully this is enough to get you
the functionality you want under the familure key sequence.

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


Re: How to generate pdf file from an html page??

2007-12-16 Thread Shane Geiger
Just some thoughts to get you started:

You may not get any responses because you weren't specific enough about
what you want to do.  Since you are asking about doing this via Python,
it seems you want to automate something which can be done from a menu
option in various Web browsers (use the print feature and print to
PDF).  You could, of course, download the files (as with the
command-line Web client, wget) and then convert html to PDF using
various tools.  Of course, this gives you a different result--of
course--because you would be using a different HTML rendering engine. 
So you have to ask yourself:  Is your goal to have a page that looks
exactly like it looks in Firefox? or in IE? or Safari?  Or are you only
concerned that you have the words of the document?


> Hi everyone, I am trying to generate a PDF printable format file from
> an html page. Is there a way to do this using   python. If yes then
> which library and functions are required and if no then reasons why it
> cant be done.
>
> Thank you All
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

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


Re: Python implementation of "include"

2007-12-16 Thread Luke
Gabriel Genellina wrote:

> En Thu, 13 Dec 2007 19:53:49 -0300, <[EMAIL PROTECTED]> escribió:
> 
>> As I understand it, import myFile and include "myFile.py" are not quite
>> the same.
>>
>> --
>> for import to work myFile.py must be in the same directory as the code
>> that calls it accessible through PYTHONPATH, whereas include
>> "../somedirectory/myFile.py" works in Karrigell, even though it is not
>> accessible through PYTHONPATH.
>>
>> -- if imported, the print
>> statement myFile.py would only run the first time through unless
>> reload(myFile) is executed in the proper place.
> 
> execfile("../somedirectory/myFile.py") does not have those problems.
> 


place your code within the module into a function, then in the calling file
just include the module using "include myFile", to get at the code you want
to use, simply call the function as "myFile.myFunction()". (obviously, drop
the quotes and use the names you made for the module and function...)
-- 
http://mail.python.org/mailman/listinfo/python-list

MySQLdb syntax issues - HELP

2007-12-16 Thread Luke
Im very new to SQL in general, let alone coding it into python. I can
interact with a MySQL database just fine for the most part, but im running
into some problems here... This is the function in my script that keeps
raising errors:

-

def NewChar():
""" NewChar() -
Call this function to begin new character generation. 

At this time it is the only function you need to call from the
NewCharacter module.

It takes no arguments.

"""
CharAccount = NewAccount()
CharName = raw_input("Enter New Characters Name: \n")
CharGender = NewGender()
CharJob = NewJob()
CharLevel = "1"
Attributes = GetAtt() ###--- imports the attributes to be added to
character info
Strength = Attributes[0]
Dexterity = Attributes[1]
Inteligence = Attributes[2]
Charm = Attributes[3]
Luck = Attributes[4]

###--- This will print the results to a script that will be used to
store 
###--- and retrieve character data for use in the game. It will
eventually
###--- be phased out by a database or encrypted file and calling scripts
so
###--- it wont be accessable by the user.
#AppendChar = '\n["' + CharName + '", "' + CharGender + '", "' + CharJob
+ '", ' + CharLevel + ', ' + Strength + ', ' + Dexterity + ', ' +
Inteligence + ', ' + Charm + ', ' + Luck + ']'

#CharSheet = "Character.hro"
#CharOutput = open(CharSheet, 'a', 5000)
#CharOutput.writelines(AppendChar)
#CharOutput.close()


###--- MySQL implementation of the new character save.
conn = MySQLdb.connect(host = 'localhost', user = 'hero', passwd
= 'password', db = 'hero')
cursor = conn.cursor()

cursor.execute("""
CREATE TABLE %s
( 
 name CHAR(40),
 gender   CHAR(40),
 job  CHAR(40),
 levelTEXT,
 str  TEXT,
 dex  TEXT,
 intelTEXT,
 cha  TEXT,
 luc  TEXT
) 
""" % CharAccount)

CharInfo = (CharAccount, CharName, CharGender, CharJob, CharLevel,
Strength, Dexterity, Inteligence, Charm, Luck)

cursor.execute("""
   INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
   VALUES
(%s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
Dexterity, Inteligence, Charm, Luck))

cursor.execute("SELECT name, job FROM %s" % CharAccount)
while (1):
row = cursor.fetchone()
if row == None:
break
print "\n \n \n You just created: %s \n Job class is: %s" % (row[0],
row[1])

cursor.close()
conn.commit()
conn.close()

print "\n \n \n Your character is made!"

MakeAgain = raw_input("\n \n \n Would you like to make another character
while we are at it? (y, n): \n")
MakeAgain = MakeAgain.lower()
MakeAgain = MakeAgain[0]
if MakeAgain == "y":
NewChar()
else:
return

---

The part that keeps getting me errors is:

---

cursor.execute("""
   INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
   VALUES
(%s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
Dexterity, Inteligence, Charm, Luck))

---

i have tried various ways to do this string insertion, and i keep getting
errors. it seems that MySQLdb doesnt like me assigning a string to the
table name if im going to assign more to values... I have reworked the last
line so many times its pathetic and have seen about 3 or 4 different
errors, but they are almost all being raised by the same functions within
the MySQLdb code. All variables i am attempting to assign are in string
form and have worked in a test script i made that does everything the same
except substituting the strings within my query. Ive been stuck on this all
week and have read numerous tutorials, the DB-API specification sheet, the
MySQL manual, the MySQLdb documentation, and a few books... none of which
seem to adress my problem since they are all only assigning variables to
the table name OR the values of the query, not both. Please help me figure
this out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb syntax issues - HELP

2007-12-16 Thread Bruno Desthuilliers
Luke a écrit :
> Im very new to SQL in general, let alone coding it into python. I can
> interact with a MySQL database just fine for the most part, but im running
> into some problems here... 
(snip)
> 
> -
> 
> def NewChar():
> """ NewChar() -
> Call this function to begin new character generation. 
> 
> At this time it is the only function you need to call from the
> NewCharacter module.
> 
> It takes no arguments.
> 
> """
> CharAccount = NewAccount()
(snip)

> 
> cursor.execute("""
> CREATE TABLE %s
> ( 
>  name CHAR(40),
>  gender   CHAR(40),
>  job  CHAR(40),
>  levelTEXT,
>  str  TEXT,
>  dex  TEXT,
>  intelTEXT,
>  cha  TEXT,
>  luc  TEXT
> ) 
> """ % CharAccount)

Err... Are you sure you want a new table here ?

> CharInfo = (CharAccount, CharName, CharGender, CharJob, CharLevel,
> Strength, Dexterity, Inteligence, Charm, Luck)
> 
> cursor.execute("""
>INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
>VALUES
> (%s, %s, %s, %s, %s, %s, %s, %s, %s)
> """, (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
> Dexterity, Inteligence, Charm, Luck))
> 
(snip)
> The part that keeps getting me errors is:
> 
> ---
> 
> cursor.execute("""
>INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
>VALUES
> (%s, %s, %s, %s, %s, %s, %s, %s, %s)
> """, (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
> Dexterity, Inteligence, Charm, Luck))
> 
> ---
> 
> i have tried various ways to do this string insertion, and i keep getting
> errors. it seems that MySQLdb doesnt like me assigning a string to the
> table name if im going to assign more to values... 

Your problem comes from confusion between Python's string formating 
system and db-api query arguments system - which sometimes (as here) use 
the same placeholder mark.

What you want here is:

sql = """
INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s)
""" % CharAccount

cursor.execute(sql,  (CharName, CharGender, CharJob, CharLevel, 
Strength, Dexterity, Inteligence, Charm, Luck))

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


Re: MySQLdb syntax issues - HELP

2007-12-16 Thread wes
Luke wrote:
> Im very new to SQL in general, let alone coding it into python. I can
> interact with a MySQL database just fine for the most part, but im running
> into some problems here... This is the function in my script that keeps
> raising errors:
> 
> -
> 
> def NewChar():
> """ NewChar() -
> Call this function to begin new character generation. 
> 
> At this time it is the only function you need to call from the
> NewCharacter module.
> 
> It takes no arguments.
> 
> """
> CharAccount = NewAccount()
> CharName = raw_input("Enter New Characters Name: \n")
> CharGender = NewGender()
> CharJob = NewJob()
> CharLevel = "1"
> Attributes = GetAtt() ###--- imports the attributes to be added to
> character info
> Strength = Attributes[0]
> Dexterity = Attributes[1]
> Inteligence = Attributes[2]
> Charm = Attributes[3]
> Luck = Attributes[4]
> 
> ###--- This will print the results to a script that will be used to
> store 
> ###--- and retrieve character data for use in the game. It will
> eventually
> ###--- be phased out by a database or encrypted file and calling scripts
> so
> ###--- it wont be accessable by the user.
> #AppendChar = '\n["' + CharName + '", "' + CharGender + '", "' + CharJob
> + '", ' + CharLevel + ', ' + Strength + ', ' + Dexterity + ', ' +
> Inteligence + ', ' + Charm + ', ' + Luck + ']'
> 
> #CharSheet = "Character.hro"
> #CharOutput = open(CharSheet, 'a', 5000)
> #CharOutput.writelines(AppendChar)
> #CharOutput.close()
> 
> 
> ###--- MySQL implementation of the new character save.
> conn = MySQLdb.connect(host = 'localhost', user = 'hero', passwd
> = 'password', db = 'hero')
> cursor = conn.cursor()
> 
> cursor.execute("""
> CREATE TABLE %s
> ( 
>  name CHAR(40),
>  gender   CHAR(40),
>  job  CHAR(40),
>  levelTEXT,
>  str  TEXT,
>  dex  TEXT,
>  intelTEXT,
>  cha  TEXT,
>  luc  TEXT
> ) 
> """ % CharAccount)
> 
> CharInfo = (CharAccount, CharName, CharGender, CharJob, CharLevel,
> Strength, Dexterity, Inteligence, Charm, Luck)
> 
> cursor.execute("""
>INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
>VALUES
> (%s, %s, %s, %s, %s, %s, %s, %s, %s)
> """, (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
> Dexterity, Inteligence, Charm, Luck))
> 
> cursor.execute("SELECT name, job FROM %s" % CharAccount)
> while (1):
> row = cursor.fetchone()
> if row == None:
> break
> print "\n \n \n You just created: %s \n Job class is: %s" % (row[0],
> row[1])
> 
> cursor.close()
> conn.commit()
> conn.close()
> 
> print "\n \n \n Your character is made!"
> 
> MakeAgain = raw_input("\n \n \n Would you like to make another character
> while we are at it? (y, n): \n")
> MakeAgain = MakeAgain.lower()
> MakeAgain = MakeAgain[0]
> if MakeAgain == "y":
> NewChar()
> else:
> return
> 
> ---
> 
> The part that keeps getting me errors is:
> 
> ---
> 
> cursor.execute("""
>INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
>VALUES
> (%s, %s, %s, %s, %s, %s, %s, %s, %s)
> """, (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
> Dexterity, Inteligence, Charm, Luck))
> 
> ---
> 
> i have tried various ways to do this string insertion, and i keep getting
> errors. it seems that MySQLdb doesnt like me assigning a string to the
> table name if im going to assign more to values... I have reworked the last
> line so many times its pathetic and have seen about 3 or 4 different
> errors, but they are almost all being raised by the same functions within
> the MySQLdb code. All variables i am attempting to assign are in string
> form and have worked in a test script i made that does everything the same
> except substituting the strings within my query. Ive been stuck on this all
> week and have read numerous tutorials, the DB-API specification sheet, the
> MySQL manual, the MySQLdb documentation, and a few books... none of which
> seem to adress my problem since they are all only assigning variables to
> the table name OR the values of the query, not both. Please help me figure
> this out.

Luke,
It would be most helpful if you assigned the sql to
a string, printed the string, executed the string, and
posted the error message.

sql = "INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc) 
VALUES \
  (%s, %s, %s, %s, %s, %s, %s, %s, %s) \
  " % (CharAccount, C

Terminate capability ....

2007-12-16 Thread temp2
Hello,

I'm new to Python. I have a small task to do. I need to be able to
find a running app (preferrably by name) and kill it. This is for the
XP environment. What is best way to do this?
Thanks,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Terminate capability ....

2007-12-16 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Hello,
> 
> I'm new to Python. I have a small task to do. I need to be able to
> find a running app (preferrably by name) and kill it. This is for the
> XP environment. What is best way to do this?

1/ search the Windows XP APIs for such a task
2/ found out how you can call these APIs from Python

> Thanks,

You're welcome.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb syntax issues - HELP

2007-12-16 Thread Luke
Bruno Desthuilliers wrote:

> Luke a écrit :
 (snip)   
>> cursor.execute("""
>> CREATE TABLE %s
>> (
>>  name CHAR(40),
>>  gender   CHAR(40),
>>  job  CHAR(40),
>>  levelTEXT,
>>  str  TEXT,
>>  dex  TEXT,
>>  intelTEXT,
>>  cha  TEXT,
>>  luc  TEXT
>> )
>> """ % CharAccount)
> 
> Err... Are you sure you want a new table here ?
 (snip)

yes, thats the easier way i can think of for now since i am so new to SQL,
eventually im sure i will put all the characters into one larger table
though... but for now i just dont feal like figuring out how to scan the
table for the records i need based on name of character... ill save that
for later. (unless there is a very easy way to do it that doesnt require
re)

 (snip)
>> The part that keeps getting me errors is:
>> 
>> ---
>> 
>> cursor.execute("""
>>INSERT INTO %s (name, gender, job, level, str, dex, intel, cha,
>>luc) VALUES
>> (%s, %s, %s, %s, %s, %s, %s, %s, %s)
>> """, (CharAccount, CharName, CharGender, CharJob, CharLevel,
>> Strength,
>> Dexterity, Inteligence, Charm, Luck))
>> 
>> ---
>> 
>> i have tried various ways to do this string insertion, and i keep getting
>> errors. it seems that MySQLdb doesnt like me assigning a string to the
>> table name if im going to assign more to values...
> 
> Your problem comes from confusion between Python's string formating
> system and db-api query arguments system - which sometimes (as here) use
> the same placeholder mark.
> 
> What you want here is:
> 
> sql = """
> INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
> VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s)
> """ % CharAccount
> 
> cursor.execute(sql,  (CharName, CharGender, CharJob, CharLevel,
> Strength, Dexterity, Inteligence, Charm, Luck))

wow, i was so focused on learning the MySQLdb module i have been overlooking
simply escaping my % signs the whole time... nice catch, thanks alot. it
works like a charm now.


PROBLEM SOLVED, BUT IF YOU WANT TO ADD ANYTHING, FEEL FREE...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Terminate capability ....

2007-12-16 Thread paul
[EMAIL PROTECTED] schrieb:
> Hello,
> 
> I'm new to Python. I have a small task to do. I need to be able to
> find a running app (preferrably by name) and kill it. This is for the
> XP environment. What is best way to do this?
> Thanks,
import os

os.system('taskkill /IM explorer.exe')

cheers
  Paul

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


Re: IDLE question

2007-12-16 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> I'm using IDLE for my  Python programming. I can't seem to solve one
> issue though. Whenever I try to indent a region of code, I simply
> select it and hit the tab key, as I usually do in most editors, like
> GEdit or Geany on Linux, for instance, and it works fine. But, if I
> try to unindent a region of code, which i would do by pressing Shift-
> Tab in other editors, it just won't work, and I can't find any
> combination that will.
> 
> Anybody know if this operation is possible at all with IDLE, and if it
> is, what's the combination of keys?

On my copy of idle the 'format' menu lists indent region, dedent region and 
a bunch of similar commands along with their accelerators.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why this error?

2007-12-16 Thread Joshua Kugler
python.jiang wrote:

> hello friends, the question had show bellow, any friend can tell me why.
> thanks.
>  
> list:
> def test():
>   exec "import sys"
>   a=range(15)
>   b=[13,3]
>   c=filter(lambda x: x not in b,a)
>   return c
> print test()
>  
> run result:
>   File "a.py", line 2
> exec "import sys"
> SyntaxError: unqualified exec is not allowed in function 'test' it
> contains a nested function with free variables

I have no reason why you're getting the error, but there is no reason to try
to exec an import.  Just use

import sys

Hope that helps.

j

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


Re: MySQLdb syntax issues - HELP

2007-12-16 Thread John Machin
On Dec 17, 7:48 am, Luke <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers wrote:
> > Luke a écrit :
>  (snip)
> >> cursor.execute("""
> >> CREATE TABLE %s
> >> (
> >>  name CHAR(40),
[snip]
> >>  luc  TEXT
> >> )
> >> """ % CharAccount)
>
> > Err... Are you sure you want a new table here ?
>
>  (snip)
>
> yes, thats the easier way i can think of for now since i am so new to SQL,
> eventually im sure i will put all the characters into one larger table
> though... but for now i just dont feal like figuring out how to scan the
> table for the records i need based on name of character...

Have you figured out how to scan a list of table names for the records
you need? Where will you keep that list -- in another table? in a
file? hard-coded in your scripts?

> ill save that
> for later. (unless there is a very easy way to do it that doesnt require
> re)
>

If you have one table (as you should) called (say) "character", with
the primary key column called (say) "characcount", you can find one
exact match like this:
   SELECT * FROM character WHERE characcount = 'Ronin88'
or do a wild-card search like this:
   SELECT * FROM character WHERE characcount LIKE 'Ron%'
[I'm presuming that's what you mean by your reference to 're']

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


Re: state machine and a global variable

2007-12-16 Thread Michael Sparks
[EMAIL PROTECTED] wrote:

> Basically, I agree that often the local state is much more useful. It
> just seems to me that for some application it's an overkill. Like say,
> for Turtle [1] (no jokes, please :) or PostScript [2].

Sounds also a bit similar to what happens under the hood in Open GL and some
other systems which revolve around display lists. The approach generally
taken there is to recognise that you often have a "current" context which
is being operated on.

A basic version of this might look like this:

file: statemachine_user.py

#!/usr/bin/python

from statemachine import *

context = statemachine()
context2 = statemachine()

set_context(context)
set_state(3)
print get_state()

set_context(context2)
set_state(1)
print get_state()

set_context(context)
print get_state()


file: statemachine.py

#!/usr/bin/python

class statemachine(object):
def __init__(self):
self.state = None
def set_state(self, value):
self.state = value
def get_state(self):
return self.state

context = statemachine()

def set_context(somecontext):
global context
context = somecontext

def set_state(value):
context.set_state(value)

def get_state():
return context.get_state()

A more interesting example which probably relates closer to your example,
and also can be quite useful for interpretting little languages is where
the "states" that get stored are matrices representing transforms and are
used to put objects into a 3D space. 

You might in that circumstance want to use your a statemachine more like
this: (this code is untested)

class statemachine(object):
default = None
def __init__(self, **argd):
self.__dict__.update(**argd)
self.state = self.default
def set_state(self, value):
self.state = value
def get_state(self):
return self.state

context = [ statemachine() ] # default context

def push_context(somecontext):
global context
context.append( somecontext )

def pop_context(somecontext):
global context
return context.pop( -1 )

def set_state(value): context[-1].set_state(value)

def get_state(): return context[-1].get_state()

def get_allstates(): return [ x.get_state() for x in context ]

This isn't really quite what the do, but gives a different possible
perspective.


Michael.
--
http://yeoldeclue.com/blog
http://kamaelia.sourceforge.net/Developers/

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


Re: MySQLdb syntax issues - HELP

2007-12-16 Thread Gabriel Genellina
On 16 dic, 17:48, Luke <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers wrote:

>> Err... Are you sure you want a new table here ?
>
> yes, thats the easier way i can think of for now since i am so new to SQL,
> eventually im sure i will put all the characters into one larger table
> though... but for now i just dont feal like figuring out how to scan the
> table for the records i need based on name of character... ill save that
> for later. (unless there is a very easy way to do it that doesnt require
> re)

re No. Just plain SQL, see below. As you wouldn't -in general-
define a new class for each character, the same happens for the
tables: you wouldn't create a new table for each character, as they
all share the same set of attributes; just insert a new *row* of data
into the table. BTW, it's similar to what you appear to be doing
previously: appending a new row to Character.hro file, conceptually
it's the same thing.
Table names and column names are usually known when you define the
application and remain fixed. And they can't be provided as parameters
in the execute method: that's why Bruno split it in two steps,
building a sql statement first (with the table name in it) and then
executing it with the remaining parameters.
So, I would create the table ONCE, with name Character, and a new
column Account.

To insert a new character:
sql = """
INSERT INTO Character (account, name, gender, job, level, str, dex,
intel, cha, luc)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cursor.execute(sql, (CharAccount, CharName, CharGender, CharJob,
CharLevel,
Strength, Dexterity, Inteligence, Charm, Luck))

Retrieving a certain character is not harder:
sql = """
SELECT name, gender, job, level, str, dex, intel, cha, luc
FROM Character
WHERE account = %s"""
cursor.execute(sql, (CharAccount,))
CharName, CharGender, CharJob, CharLevel, Strength, Dexterity,
Inteligence, Charm, Luck = cursor.fetchone()

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


Re: why this error?

2007-12-16 Thread John Machin
On Dec 17, 8:18 am, Joshua Kugler <[EMAIL PROTECTED]> wrote:
> python.jiang wrote:
> > hello friends, the question had show bellow, any friend can tell me why.
> > thanks.
>
> > list:
> > def test():
> >   exec "import sys"
> >   a=range(15)
> >   b=[13,3]
> >   c=filter(lambda x: x not in b,a)
> >   return c
> > print test()
>
> > run result:
> >   File "a.py", line 2
> > exec "import sys"
> > SyntaxError: unqualified exec is not allowed in function 'test' it
> > contains a nested function with free variables
>
> I have no reason why you're getting the error, but there is no reason to try
> to exec an import.  Just use
>
> import sys
>

or, given that you [Jiang the OP] are not using the sys module, omit
the whole statement!

The 'unqualified' exec means you have not specified a context by using
the 'in' keyword; as the manual says "the code is executed in the
current scope".

The 'nested function' is the lambda.

The 'free variable' is b ... if you do
c = filter(lambda x: x not in [13, 3], a)
it "works".

The short story is that Python is not so wildly dynamic that you can
mix all of the above.

Is there something practical that you are trying to achieve that we
could help you with?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested Reading

2007-12-16 Thread scripteaze
On Dec 16, 1:47 am, Thin Myrna <[EMAIL PROTECTED]> wrote:
> Benoit wrote:
> > I got myself into programming late in the summer and have dabbled in
> > python for the most part in that time, recently beginning work on a
> > music player.  In January, I start my minor in Information
> > Technology.  I'd like to get ahead a bit, however, and over the break
> > would like to do some reading. I seek your recommendations in the
> > field of database design basics and network programming, with a bias
> > towards texts which specifically address Python.  By network
> > programming, I mean fundamental understanding of sockets, TCP/UDP,
> > right up to HTTP serving, etc.  Thanks ahead of time.
>
> Steve Holden's Python Web Programming might be what you are looking for.
> It covers all the topics needed to deal with sockets, databases, up to
> building complete web apps. One of my books I'd never give away.
>
> HTH
> Thin

urls
http://docs.python.org/lib/module-socket.html
http://www.amk.ca/python/howto/sockets/
http://www.devshed.com/c/a/Python/Sockets-in-Python/

books
http://www.amazon.com/Foundations-Python-Network-Programming/dp/1590593715

you might also want to read up on twisted, (just for the heck of it)
http://twistedmatrix.com/trac/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allingn controls wxPython

2007-12-16 Thread kyosohma
On Dec 15, 2:14 pm, SMALLp <[EMAIL PROTECTED]> wrote:
> Hy. I need help. I'm using BoxSizer and i put TextCtrl and StaticText
> next to each other and they gor alligned by top of TextCtrl and it looks
> terrible. How can i make thm to be alligned by center of each controll.
>
> Thnaks!

A shortcut flag is to just use wx.CENTER. You might find this wiki
entry useful:

http://wiki.wxpython.org/UsingSizers

This article may be fruitful as well:

http://www.devshed.com/c/a/Python/A-Close-Look-at-wxPython-Controls/

I personally use the wxPython in Action book by Dunn quite a bit. It's
got lots of information, although it's not well organized.

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


Re: MySQLdb syntax issues - HELP

2007-12-16 Thread John Nagle
Bruno Desthuilliers wrote:
> Luke a écrit :
>> Im very new to SQL in general, let alone coding it into python. I can
>> interact with a MySQL database just fine for the most part, but im 
>> running
>> into some problems here... 
> (snip)

 OK.  Bruno has pointed out why you're having trouble with
the syntax, but that's not the real problem.  You probably
don't want a separate MySQL database for each account,
which is what you're doing.   You only need one database
for multiple accounts.  The account name can be a field.
You can look up things by any field, which is the whole
point of having a database.

 (The database looks up much faster if you specify that
some fields are INDEX fields.  But that can come later.)

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


RE:Windows XP unicode and escape sequences

2007-12-16 Thread jyoung79
Thank you John and Tim.

With your help I found that the XP console code page is set up for 'cp437' and 
with a little bit of browsing I found that 869 is the code page for Modern 
Greek.  After changing it to 869 that did the trick!  Thanks very much for this 
advice.

This brings up another question.  If I run some Python code that starts off 
with 'os.system('cp869')' so it will change to the correct code page, then when 
it starts printing the Greek characters it breaks.  But run the same Python 
code again and it works fine.  Is there another way to do this so I can change 
over to the 869 code page and continue on with the Greek letters printing 
correctly?

Thanks Tim for the info about the CONFIG.NT file as well as the curses-like 
info.  I'll continue to research these.

Thanks again!

Jay

> CONFIG.NT only affects 16-bit programs running in the NTVDM (the Virtual
> DOS Machine).

> 32-bit console apps (which Python is) simply cannot use ANSI escape
> sequences.  You have to use the Win32 APIs to do color.  There are
> curses-like libraries available for Python.  Or:

> http://www.effbot.org/zone/console-handbook.htm
> -- 
> Tim Roberts, timr at probo.com
> Providenza & Boekelheide, Inc.

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


int vs long

2007-12-16 Thread Troels Thomsen

The readFile function from the win32 package aparently really expect an 
integer :

def inWaiting(self):
"""Returns the number of bytes waiting to be read"""
flags, comstat = ClearCommError(self.__handle)
return comstat.cbInQue

ReadFile(h, s.inWaiting())

My code crashes because inWaiting returns a long, not an int

Why is that different on my machine and my collegues ? Have I or he 
installed a wrong version of a package?
CPython 2.5.

Was not expecting int<->long type problems in excactly python language.
Is that because we are navigating so close to the win32 api that the types 
are more strictly enforced ?

Thx in advance
Troels




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


Re: Clearing a DOS terminal in a script

2007-12-16 Thread Larry Bates
Stephen_B wrote:
> On Dec 13, 11:21 am, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
>> It opens "clear" with it's own virtual terminal and clears that
>> instead.
> 
> Even when I launch the script from a cmd shell with "python
> myscript.py"?
> 
>> There's an ANSI control code you can use to reset the screen, try printing 
>> that.
> 
> I googled "[2J" as an ascii sequence that it is supposed to clear
> the screen. How do I send that?
> 
> Stephen
Normally you would do:

import sys
sys.stdout.write(chr(27)+'[2J')
sys.stdout.flush()

Unfortunately that doesn't clear the screen because the ANSI module isn't 
loaded 
by default.  Use os.system('cls') as mentioned instead.

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


Re: looking for gui for python code

2007-12-16 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> hi
> i have written some python scripts which take command line arguments
> and do some job. i would like to make it into a .exe using py2exe and
> distribute it with innosetup.. befor that i would like to add some GUI
> support..i mean select some values using a folder explorer etc..which
> would be a good gui builder for this? i have heard about  guibuilder
> from http://spectcl.sourceforge.net/  or is it better to use tkinter
> (i have little experience with gui designing)
> 
> can someone  give a suggestion?
> TIA
> dn

I think wxWindows works extremely well but the learning curve is quite steep. 
The upside is that it is cross-platform and there is virtually nothing you 
can't 
write using wxPython/Windows.  BTW-They hae an excellent newsgroup at:

gmane.comp.python.wxpython

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


List problem

2007-12-16 Thread Alan Bromborsky
I wish to create a list of empty lists and then put something in one of 
the empty lists.  Below is what I tried, but instead of appending 1 to 
a[2] it was appended to all the sub-lists in a.  What am I doing wrong?

 a = 6*[[]]
 >>> a
[[], [], [], [], [], []]
 >>> a[2].append(1)
 >>> a
[[1], [1], [1], [1], [1], [1]]
 >>>  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows XP unicode and escape sequences

2007-12-16 Thread MonkeeSage
On Dec 16, 5:28 pm, <[EMAIL PROTECTED]> wrote:
> Thank you John and Tim.
>
> With your help I found that the XP console code page is set up for 'cp437' 
> and with a little bit of browsing I found that 869 is the code page for 
> Modern Greek.  After changing it to 869 that did the trick!  Thanks very much 
> for this advice.
>
> This brings up another question.  If I run some Python code that starts off 
> with 'os.system('cp869')' so it will change to the correct code page, then 
> when it starts printing the Greek characters it breaks.  But run the same 
> Python code again and it works fine.  Is there another way to do this so I 
> can change over to the 869 code page and continue on with the Greek letters 
> printing correctly?
>
> Thanks Tim for the info about the CONFIG.NT file as well as the curses-like 
> info.  I'll continue to research these.
>
> Thanks again!
>
> Jay
>
> > CONFIG.NT only affects 16-bit programs running in the NTVDM (the Virtual
> > DOS Machine).
> > 32-bit console apps (which Python is) simply cannot use ANSI escape
> > sequences.  You have to use the Win32 APIs to do color.  There are
> > curses-like libraries available for Python.  Or:
> >http://www.effbot.org/zone/console-handbook.htm
> > --
> > Tim Roberts, timr at probo.com
> > Providenza & Boekelheide, Inc.

Try using the unicode switch ( cmd.exe /u ), rather than trying to set
the codepage. See here:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true

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


Re: List problem

2007-12-16 Thread Mel
Alan Bromborsky wrote:
> I wish to create a list of empty lists and then put something in one of 
> the empty lists.  Below is what I tried, but instead of appending 1 to 
> a[2] it was appended to all the sub-lists in a.  What am I doing wrong?
> 
> a = 6*[[]]
>  >>> a
> [[], [], [], [], [], []]
>  >>> a[2].append(1)
>  >>> a
> [[1], [1], [1], [1], [1], [1]]
>  >>> 

What you've done is equivalent to

x = []
a = [x, x, x, x, x, x]
del x

An idiom for what you want is

a = [[] for y in xrange (6)]

which will populate a with 6 distinct empty lists.

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


Re: in-client web server

2007-12-16 Thread Larry Bates
David Montgomery wrote:
> Hi,
> 
> I am working on a thick-client application that serves
> a lot of content as locally generated and modified
> web pages.
> 
> I'm beginning to look at serving (and updating, via AJAX)
> these pages from a web server running within the client
> (mostly to provide a more natural and powerful way of
> interacting with the browser control).
> 
> For a first cut I imagine just starting a web server within
> the client and serving the pages from localhost:.
> 
> I have a couple questions for anyone with experience with
> this sort of architecture:
> 
>  * First, are there any existing open source libraries that
>exemplify this approach?  I have a vague recollection that
>TurboGears started out based on a project with this kind
>of architecture, but I haven't been able to find anything
>so far.
> 
>  * Second, are there any gotchas you would point out?  In
>particular I'm wondering if even this localhost connection
>will be a problem with many users' firewalls.
> 
> In case it matters, the application is being developed in python
> 2.5.x with wxPython 2.8.x, aimed first at a Windows platform,
> but intended to be portable to Linux and Mac ASAP.
> 
> Thanks for any pointers,
> David

If I understand you correctly, I did something like this recently.  I wanted to 
monitor a long running process via web browser.  I used twisted to create 
simplehttpserver and ran the long running process in another process. 
Periodically I would update information in a python dictionary that was visible 
to the httpserver to generate a proper HTML page by merging a template and the 
progress data upon a request from web browser.  Does this sound at all like 
what 
you are looking for?  No firewall issues and I even tunneled ports securely 
over 
ssh and it worked flawlessly.

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


Re: IDLE question

2007-12-16 Thread MRAB
On Dec 16, 4:47 pm, [EMAIL PROTECTED] wrote:
> I'm using IDLE for my  Python programming. I can't seem to solve one
> issue though. Whenever I try to indent a region of code, I simply
> select it and hit the tab key, as I usually do in most editors, like
> GEdit or Geany on Linux, for instance, and it works fine. But, if I
> try to unindent a region of code, which i would do by pressing Shift-
> Tab in other editors, it just won't work, and I can't find any
> combination that will.
>
> Anybody know if this operation is possible at all with IDLE, and if it
> is, what's the combination of keys?
>
In IDLE 1.2.1 (Windows) the keys are ctrl-] or tab for indent and ctrl-
[ for dedent. You can change them in Options->Configure IDLE...->Keys.
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] Fractions on musical notation

2007-12-16 Thread Gabriel Genellina
On 16 dic, 06:40, Lie <[EMAIL PROTECTED]> wrote:

> [btw, off topic, in music, isn't 1/4 and 2/8 different? I'm not very
> keen of music though, so correct me if I'm wrong.]

As a time signature 1/4 has no sense, but 3/4 and 6/8 are different
things. In the standard musical notation both numbers are written one
above the other, and no "division" line is used. Note that they just
*look* like a fraction when written in text form, like here, because
it's not easy to write one above the other.
3/4 is read as "three by four", not "three quarters" -at least in my
country- so there is even less confussion.

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


Re: why this error?

2007-12-16 Thread Larry Bates
Joshua Kugler wrote:
> python.jiang wrote:
> 
>> hello friends, the question had show bellow, any friend can tell me why.
>> thanks.
>>  
>> list:
>> def test():
>>   exec "import sys"
>>   a=range(15)
>>   b=[13,3]
>>   c=filter(lambda x: x not in b,a)
>>   return c
>> print test()
>>  
>> run result:
>>   File "a.py", line 2
>> exec "import sys"
>> SyntaxError: unqualified exec is not allowed in function 'test' it
>> contains a nested function with free variables
> 
> I have no reason why you're getting the error, but there is no reason to try
> to exec an import.  Just use
> 
> import sys
> 
> Hope that helps.
> 
> j
> 

Don't exec "import sys" just do import sys.

Also.

a=range(15)
b=[13,3]
c=filter(lambda x: x not in b,a)

is just:

c=[x for x in xrange(15) if x not in [13,3]]

IMHO this is much easier to read.

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


Donate to the Python Software Foundation!

2007-12-16 Thread Stephan Deibel (PSF)
Hi,

Please consider donating to the Python Software Foundation (PSF)
this year in your year-end charitable giving.

The PSF is the non-profit that holds and protects the intellectual
property rights behind Python, keeping it free and open for all
to use.

We also provide the financial backing that makes PyCon possible,
donate to other Python conferences around the world, and fund
grants and special projects in the Python community.

For general information about the PSF, please see our pages on
the Python website:  http://www.python.org/psf/

Donations from individuals are tax deductible in the US and may
be tax deductible in other countries, or as a business expense.

We take credit cards, checks, wire transfers, and PayPal:

   http://www.python.org/psf/donations/

Businesses invested in Python can also consider becoming a
sponsor member of the PSF:

   http://www.python.org/psf/sponsorship/

Or become a sponsor of PyCon 2008, a great way to gain exposure
for your business or find talented Python programmers to hire:

   http://us.pycon.org/2008/sponsors/

If you have any questions, please email me directly.

Thanks, and Happy Holidays!

-- 

Stephan Deibel
Chairman of the Board
Python Software Foundation

http://python.org/psf

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


Re: [OT] Fractions on musical notation

2007-12-16 Thread Brian Victor
Gabriel Genellina wrote:
> On 16 dic, 06:40, Lie <[EMAIL PROTECTED]> wrote:
>
>> [btw, off topic, in music, isn't 1/4 and 2/8 different? I'm not very
>> keen of music though, so correct me if I'm wrong.]
> As a time signature 1/4 has no sense

Actually, I'm playing a show right now that has a one beat vamp.  It's a
single repeated measure in 1/4 time.

To addres the real point, though, I don't think of a time signature as a
rational number, although it correctly reflects what portion of a whole
note can be found within a measure.  I consider it to have two separate
pieces of information: the length of the beat and the number of those
beats per bar.  When I've written code to represent music I have used
rationals to represent when something occurs, but a different structure
to represent time signatures.

-- 
Brian

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


Immutable Geometry Types

2007-12-16 Thread [EMAIL PROTECTED]
Hi,

I am learning python, having learnt most of my object orientation with
java, and decided to port some of my geometry classes over. I haven't
used immutability in python before, so thought this would be an
interesting chance to learn.

I am looking for feedback on any ways in which I might have left
variables unprotected, and ways in which I am not being pythonic.

Cheers!


#!/usr/bin/env python
#
#   geometry.py
#
#   Peter Braden 
#
#   Released under the GPLv2 (http://www.gnu.org/licenses/
gpl-2.0.txt).
#
#   Disclaimer:
#
#  All following code is provided "as is". Peter Braden hereby
disclaims
#  solely to the extent permitted by law all express, implied and
statutory
#  warranties, conditions and terms including, without limitation,
those
#  regarding the security, reliability, timeliness, and performance of
the code.
#
#

import math

class Angle (object):
"""
The Angle class represents angles; the inclination to each other,
in a plane,
of two lines which meet each other, and do not lie straight with
respect to
each other.

* By default angles are measured in radians.

* Angles are immutable
   """



def __init__(self, val, type = 'rad'):
"""
Create a new angle.

* To specify type of value use either type = "deg" or type
="rad"
* default is radians
"""
if type == 'rad':
super(Angle, self).__setattr__('_value', val)
else:
super(Angle, self).__setattr__('_value',
math.radians(val))


def __eq__(self, other):
"""
Test equality
"""
if isinstance(other, Angle):
return self._value == other._value
return NotImplemented

def __ne__(self, other):
"""
Test Inequality
"""
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result

def __str__(self):
"""
Create Readable String
"""
return "%s (%s degrees)" % (str(self._value),
str(self.degrees))

def __repr__(self):
"""
Serialise data
"""
return "Angle(%s)" % self._value

def __setattr__(self, name, value):
"""
Suppress setting of data - Angle is immutable
"""
self._immutableError()

def __delattr__(self, name):
"""
Suppress deleting of data - Angle is immutable
"""
self._immutableError()

def __add__(self, other):
"""
return self + other
"""
if isinstance(other, Angle):
return Angle(self._value + other._value)
return NotImplemented

def __sub__(self, other):
"""
return self - other
"""
if isinstance(other, Angle):
return Angle(self._value - other._value)
return NotImplemented

def __mul__(self, other):
"""
return self * other
"""
if isinstance(other, Angle):
return Angle(self._value * other._value)
return NotImplemented

def __div__(self, other):
"""
return self / other
"""
if isinstance(other, Angle):
return Angle(self._value / other._value)
return NotImplemented

def __lt__(self, other):
"""
return self < other
"""
if isinstance(other, Angle):
return self._value < other._value
return NotImplemented

def __gt__(self, other):
"""
return self > other
"""
if isinstance(other, Angle):
return self._value > other._value
return NotImplemented

def __le__(self, other):
"""
return self >= other
"""
if isinstance(other, Angle):
return self._value <= other._value
return NotImplemented

def __ge__(self, other):
"""
return self <= other
"""
if isinstance(other, Angle):
return self._value >= other._value
return NotImplemented


def fromCos(self, c):
"""
return angle with specified cos
"""
return Angle(math.acos(c))

fromCos = classmethod(fromCos)

def fromSin(self, s):
"""
return angle with specified sin
"""
return Angle(math.asin(c))

fromSin = classmethod(fromSin)

def fromTan(self, t):
"""
return angle with specified tan
"""
return Angle(math.atan(c))

fromTan = classmethod(fromTan)


def _immutableError(self):
"""
Throw error about angles immutability
"""
raise TypeError("Angle is immutable - cannot alter variables")

radians = property(lambda self: self._value, lambda x:
self._immutableError())
degrees = property(lambda self: math.degrees(self._value), lambda
x: self._immutableError())
cos = property(lambda self: math.cos(self._value), lamb

Re: [OT] Fractions on musical notation

2007-12-16 Thread Dan Upton
> Since the US, at least, uses whole/half/quarter/eighth/sixteenth...
> notes, three-quarter and six-eight time falls out...

I don't think this is technically true, but I've never been able to
tell the difference.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows XP unicode and escape sequences

2007-12-16 Thread Ross Ridge
<[EMAIL PROTECTED]> wrote:
>This brings up another question.  If I run some Python code that starts
>off with 'os.system('cp869')' so it will change to the correct code page,
>then when it starts printing the Greek characters it breaks.  But run
>the same Python code again and it works fine.

That's probably because the encoding of stdin, stdout, and stderr is set
according to the code page of the console they're connected to (if any)
when Python starts.

>Is there another way to do this so I can change over to the 869 code
>page and continue on with the Greek letters printing correctly?

Unfortunately, you can't easily change the encoding of file object after
it's been created.  It's probably simpler convert Unicode strings to cp869
before printing them instead of having Python do it automatically for you.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Python dummy interpreter

2007-12-16 Thread [EMAIL PROTECTED]
Hi all,

I remember a tool which (basically) creates a directory somewhere in
the user's home directory and puts a copy (or perhaps link to) the
python interpreter, adding that directory to the search path. In this
way, it is possible for a user without root permissions to install
additional packages using easy_install (i.e. python setup.py install).

I can't find it now that I go looking again. Can anyone give me a
pointer on this?

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


Re: Python dummy interpreter

2007-12-16 Thread [EMAIL PROTECTED]
On Dec 17, 2:25 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
Never mind, I found it. Virtualpython, docs available under easy
install.

-T

> Hi all,
>
> I remember a tool which (basically) creates a directory somewhere in
> the user's home directory and puts a copy (or perhaps link to) the
> python interpreter, adding that directory to the search path. In this
> way, it is possible for a user without root permissions to install
> additional packages using easy_install (i.e. python setup.py install).
>
> I can't find it now that I go looking again. Can anyone give me a
> pointer on this?
>
> Thanks,
> -Tennessee

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


Re: Immutable Geometry Types

2007-12-16 Thread Gabriel Genellina
En Sun, 16 Dec 2007 23:13:47 -0300, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribi�:

> Hi,
>
> I am learning python, having learnt most of my object orientation with
> java, and decided to port some of my geometry classes over. I haven't
> used immutability in python before, so thought this would be an
> interesting chance to learn.
>
> I am looking for feedback on any ways in which I might have left
> variables unprotected, and ways in which I am not being pythonic.

Immutable classes usually implement __new__ and leave __init__  
unimplemented:

 def __new__(cls, val, measure='rad'):
 # using 'type' as a name shadows the builtin type
 instance = super(Angle, self).__new__()
 if measure == 'rad': pass
 elif measure == 'deg': value = math.radians(value)
 else: raise ValueError, "unknown Angle measure: %r" % measure
 instance._value = value
 return instance

For the various comparison operators, since this class "plays well" with  
ordering, it's easier to implement __cmp__ and make all operators refer to  
it:

 def __cmp__(self, other):
if isinstance(other, Angle):
   return cmp(self._value, other._value)
raise NotImplementedError

 __eq__ = lambda self,other: self.__cmp__(other)==0
 __ne__ = lambda self,other: self.__cmp__(other)!=0
 __lt__ = lambda self,other: self.__cmp__(other)<0
 __ge__ = lambda self,other: self.__cmp__(other)>=0
 __gt__ = lambda self,other: self.__cmp__(other)>0
 __le__ = lambda self,other: self.__cmp__(other)<=0

> def __setattr__(self, name, value):
> """
> Suppress setting of data - Angle is immutable
> """
> self._immutableError()

Why? This class contains a single attribute, value, and we could make it  
immutable. But why restrict the possibility to add *other* attributes?
(There is __slots__ too, but I would not recommend it at this stage)

> def __delattr__(self, name):

Same as above.

> def __mul__(self, other):
> def __div__(self, other):

(I've never seen those operations on angles)

> def fromCos(self, c):
> """
> return angle with specified cos
> """
> return Angle(math.acos(c))
>
> fromCos = classmethod(fromCos)

I prefer to write

 @classmethod
 def fromCos(self, c):

> radians = property(lambda self: self._value, lambda x:
> self._immutableError())
> degrees = property(lambda self: math.degrees(self._value), lambda
> x: self._immutableError())
> cos = property(lambda self: math.cos(self._value), lambda x:
> self._immutableError())
> sin = property(lambda self: math.sin(self._value), lambda x:
> self._immutableError())
> tan = property(lambda self: math.tan(self._value), lambda x:
> self._immutableError())

You don't have to write them that way. Just omit the property setter, and  
it will be read-only.

 tan = property(lambda self: math.tan(self._value))

Or:

 @property
 def tan(self):
 return math.tan(self.value)

> def withinRange(self, angle, range):
> """
> angle is within range of self
> """
> return (self._value < angle._value + range) and (self._value >
> angle._value - range)

I think this is more readable:

return angle.value-range < self.value < angle.value+range

> class Point2D (object):

Same as above, replace __init__ by __new__. You may inherit from tuple  
instead, and get some basic methods already implemented.

> length = property(lambda self: return math.sqrt(self.x*self.x +
> self.y*self.y), lambda x: self._immutableError())

Using math.hypot is safer in some circunstances.

> def normalise(self):
> return Point2D(self.x/self.length, self.y/self.length);
> def translate(self, other) {
> return self + other
> }

I'd use "normalised", "translated", etc. because they return a *new*  
object, instead of modifying self.
(You forgot to remove some braces, I presume...)

-- 
Gabriel Genellina

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

strptime() in _strptime.py vs lib-dynload/time.so

2007-12-16 Thread igor . tatarinov
It looks like there are two implementation of strptime() (why?) and
the one that's used by default is the Python version in _strptime.py

Unfortunately, it's pretty slow and takes up a big chunk of my code's
execution time. Is there a way to use the C version instead (is there
a C version in time.so?)

 6199597 function calls (6199433 primitive calls) in 45.820
CPU seconds

   Ordered by: internal time
   List reduced from 183 to 10 due to restriction <10>
   ncalls  tottime  percall  cumtime  percall
filename:lineno(function)
577656.0200.000   12.9700.000 /usr/lib64/python2.4/
_strptime.py:273(strptime)
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime() in _strptime.py vs lib-dynload/time.so

2007-12-16 Thread igor . tatarinov
On Dec 16, 8:47 pm, [EMAIL PROTECTED] wrote:
>ncalls  tottime  percall  cumtime  percall filename:lineno(function)
> 577656.0200.000   12.9700.000 
> /usr/lib64/python2.4/_strptime.py:273(strptime)
> ...

actually, the C-version of strptime() is also getting called:
577650.9600.000   13.9400.000 :0(strptime)

that's pretty confusing. Does the Python version call the C-version
(or the other way around)?

Thanks,
igor

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


Re: int vs long

2007-12-16 Thread Gabriel Genellina
En Sun, 16 Dec 2007 20:28:02 -0300, Troels Thomsen <"nej  
tak..."@bag.python.org> escribi�:

>
> The readFile function from the win32 package aparently really expect an
> integer :
>
> def inWaiting(self):
> """Returns the number of bytes waiting to be read"""
> flags, comstat = ClearCommError(self.__handle)
> return comstat.cbInQue
>
> ReadFile(h, s.inWaiting())
>
> My code crashes because inWaiting returns a long, not an int

That's very strange. The cbInQue field is a DWORD in C, seen as an int in  
Python. How do you know it returns a long?

> Why is that different on my machine and my collegues ? Have I or he
> installed a wrong version of a package?
> CPython 2.5.

And pywin32 build 210, I presume.

> Was not expecting int<->long type problems in excactly python language.
> Is that because we are navigating so close to the win32 api that the  
> types
> are more strictly enforced ?

Somewhat. At the API level, function arguments have to be converted to  
native C types, like ReadFile expecting a DWORD. Any number greater than  
2**32 won't fit, but I can't think how such thing could happen looking at  
those few posted code lines.

-- 
Gabriel Genellina

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

Re: Immutable Geometry Types

2007-12-16 Thread I V
On Sun, 16 Dec 2007 18:13:47 -0800, [EMAIL PROTECTED] wrote:
> I am learning python, having learnt most of my object orientation with
> java, and decided to port some of my geometry classes over. I haven't
> used immutability in python before, so thought this would be an
> interesting chance to learn.
>
> I am looking for feedback on any ways in which I might have left
> variables unprotected, and ways in which I am not being pythonic.

I'm not sure it's pythonic to worry too much about enforcing the 
immutability; and disabling setattr makes the internal attribute setting 
a pain in the arse, for little real gain.

> class Angle (object):

I'm not sure about this, but you might want to make Angle a subclass of 
float ; it would save you re-implementing the comparison operators 
(although you'ld still have to re-implement the arithmetic operators to 
get them to return an Angle instance rather than a float).

> def __init__(self, val, type = 'rad'):
> if type == 'rad':
> super(Angle, self).__setattr__('_value', val)
> else:
> super(Angle, self).__setattr__('_value',
> math.radians(val))

You might want to normalize the angle to between 0 and 2*pi here (though 
you might not, depending on exactly what you want to represent).

Assuming that the user meant degrees in the else branch strikes me as a 
mistake; what if they mis-typed "rad" as "rsd" or something? Better to 
explicitly check, and raise an exception if the value isn't one of 'rad' 
or 'deg'. Another thing you might want to consider is using keyword 
arguments, rather than a string. Like:

def __init__(self, radians=None, degrees=None):
if radians is not None:
self._value = radians
elif degrees is not None:
self._value = math.radians(degrees)
else:
raise TypeError("Angle creation must specify \
keyword argument 'radians' or 'degrees')

Used like:
a = Angle(math.pi) # Uses radians by default
a = Angle(radians=2*math.pi) # Or you can specify it explicitly
a = Angle(degrees=180) # Or specify degrees

> def __setattr__(self, name, value):
> """
> Suppress setting of data - Angle is immutable """
> self._immutableError()
> 
> def __delattr__(self, name):
> """
> Suppress deleting of data - Angle is immutable """
> self._immutableError()

As I say, I wouldn't bother with these, as they make the implementation 
more annoying to no real gain.

> def __add__(self, other):
> if isinstance(other, Angle):
> return Angle(self._value + other._value)
> return NotImplemented

Using 'isinstance' is usually a mistake - rather than checking for type, 
you should just use an object as if it were the correct type and, if 
necessary, deal with the resulting exceptions. This means you can use 
objects of a different type, as long as they have the right interface. 
Here, I'd do:

def __add__(self, other):
return Angle(self.radians + other.radians)

and likewise for __sub__.
 
> def __mul__(self, other):
> """
> return self * other
> """
> if isinstance(other, Angle):
> return Angle(self._value * other._value)
> return NotImplemented

Leaving aside my earlier point about not checking for types, does it even 
make sense to multiply an angle by another angle? I would have thought 
you multiplied angles by numbers. So just do:

def __mul__(self, other):
return Angle(self._value * other)

And the same for __div__
 

> def fromCos(self, c):
> """
> return angle with specified cos
> """
> return Angle(math.acos(c))
> 
> fromCos = classmethod(fromCos)

You could use decorators here; and the preferred python style for method 
names is all lower case, separated by underscores:

@classmethod
def from_cos(self, c):
return Angle(math.acos(c))

> radians = property(lambda self: self._value, lambda x:
> self._immutableError())

You don't need to explicitly raise an exception in the setter; just don't 
specify a setter function, and attempting to set the property will raise 
an AttributeError.

> DEG_30 = Angle(math.radians(30))

Given that you've gone to the trouble of creating a constructor that will 
take values as degrees, why not use it here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate pdf file from an html page??

2007-12-16 Thread Waldemar Osuch
On Dec 16, 3:51 am, abhishek <[EMAIL PROTECTED]> wrote:
> Hi everyone, I am trying to generate a PDF printable format file from
> an html page. Is there a way to do this using   python. If yes then
> which library and functions are required and if no then reasons why it
> cant be done.
>
> Thank you All

You may want to investigate.
http://pisa.spirito.de/
It worked for me in some simple conversions
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why this error?

2007-12-16 Thread python.jiang
thanks all first. but i had one class bellow to get object info what user had 
inputed when run application. because the problem that i had showed yestoday, i 
must write the code so hard to understand.
can any friend tell me one way to solve this problem?
thanks!!
 
list:

import inspect
 
vtStd,vtIron=range(2)
versionType=vtStd

moduleName=None
objectName=None
 
def _functionFilter(name):  #because the problem, i must write this function
 exec "import %s"%(moduleName,)
 a=getattr(eval(objectName),name)
 return callable(a)
 
def _classFilter(name):  #because the problem, i must write this function
 exec "import %s"%(moduleName,)
 a=getattr(eval(objectName),name)
 return inspect.isclass(a)
 
def _varFilter(name):  #because the problem, i must write this function
 exec "import %s"%(moduleName,)
 a=getattr(eval(objectName),name)
 return not(callable(a) or inspect.isclass(a))
 
class moduleInfo(object):
 def __init__(self):
  self.dirs=None
  self.moduleName=None
  self.objectName=None
  self.classes=None
  self.functions=None
  self.variants=None
  self.objectType=None
 
 def readContent(self,mname,name):
  global moduleName,objectName
  exec "import %s"%(mname)  #because this line, can't write code like "listA 
not in listB"
  self.dirs=dir(eval(name))
  self.objectType=type(eval(name))
  self.dirs.sort()
  self.dirs=tuple(self.dirs)
  self.moduleName=moduleName=mname
  self.objectName=objectName=name

  self.classes=filter(_classFilter,self.dirs)
  self.functions=filter(_functionFilter,self.dirs)
  self.variants=filter(_varFilter,self.dirs)
#because the problem, i can't write code like bellow:
#  self.variants=filter(lambda a: (a not in self.classes) and (a not in 
self.functions),self.dirs)

  return self.dirs
 
 def readHelp(self,mname,objName,memName):
  global moduleName,objectName
  exec "import %s"%(mname)
  s="%s.%s"%(objName,memName)
  shelp=str(eval("type(%s)\n"%(s,)))
  shelp+=str(eval("\n%s.__doc__"%(s,)))
  return shelp
 
if __name__=="__main__":
 mi=moduleInfo()
 a=mi.readContent("sys","sys")
 print "dir:",a
 print "class:",mi.classes
 print "fun:",mi.functions
 print "var:",mi.variants
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: assemble a webpage!

2007-12-16 Thread Gabriel Genellina
En Thu, 13 Dec 2007 19:18:48 -0300, yi zhang <[EMAIL PROTECTED]>  
escribi�:

> Now I am able to use urlretrieve to download the text part of a webpage  
> and wget to get the embedded image. Thanks for the tips!
> but how can I assemble them together so the image can be displayed in  
> the webpage automatically once I click on the .html file.
> Right now I only saw the text part of the webpage when I click on it,  
> even I put the .html file and image file in the same directory.
> Any script can do this job?

You have to replace all references to external images in the HTML source,  
with local ones. That is, replace http://aaa.bbb.com/ddd/images/circle.jpg";> to   
and place circle.jpg in the same directory as the html. The same for  
background images, css, etc.

wget can also do that for you, so why insist on using Python?

-- 
Gabriel Genellina

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

[no subject]

2007-12-16 Thread gregory . miller

I will be out of the office starting  12/17/2007 and will not return until
12/19/2007.
-- 
http://mail.python.org/mailman/listinfo/python-list

Detecting memory leaks on apache, mod_python

2007-12-16 Thread Ilias Lazaridis
How to detect memory leaks of python programms, which run in an
environment like this:

 * Suse Linux 9.3
 * Apache
 * mod_python

The problem occoured after some updates on the infrastructure. It's
most possibly caused by trac and it's dependencies, but several
components of the OS where updated, too.

Any nice tools which play with the above constellation?

Thank's for any hints!

context:

http://dev.lazaridis.com/base/ticket/148
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DB Query Parse Hangup

2007-12-16 Thread Gabriel Genellina
En Fri, 14 Dec 2007 13:17:32 -0300, Merrigan <[EMAIL PROTECTED]>  
escribi�:

> I have been working on this script, and the part that this issue that
> I have occurs in is when iterating through some results from the db,
> asking the admin input to delete the entry or not - everything works
> fine up until the last entry, then it bombs out. I know why - but I am
> not quite sure how to fix it:

You could get some help if you explain what you mean by "it bombs out"  
(the program stops with an exception? post the full traceback), and since  
you know "why", telling it would be a good thing too.

-- 
Gabriel Genellina

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

Re: Finite State Machine GUI editor in python?

2007-12-16 Thread Hendrik van Rooyen
"kib" <[EMAIL PROTECTED]> wrote:

>Hi Hendrik,
>
>I've bookmarked these ones :
>
>http://www.univ-paris12.fr/lacl/pommereau/tlf/index.html [in French]
>http://www.ncc.up.pt/~nam/ [look at the FAdo project]
>http://www.cs.usfca.edu/~jbovet/vas.html [written in Java]
>

Thanks I will check them out - at least the non French ones.
My French is constrained to making the noises for "yes" and 
"no", without being able to spell them...

-  Hendrik


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


programming container object

2007-12-16 Thread bambam
I wish to create a generic container object, devlist, such that

devlist.method(arguments)

runs as

for each dev in devlist.pool:
dev.method(arguments)

and
s = devlist.method(arguments)

runs as

for each dev in devlist.pool:
s.append(dev.method(arguments))

...but it is outside my ability to do so.

Can anyone provide an example of how to do that?

Thanks,
Steve 


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


MySQL_python install failed on Ubuntu 7.1

2007-12-16 Thread Bruza
I installed MySQL 5.0.45 on Ubuntu 7.1 and download MySQL_python from
Sourceforge (http://sourceforge.net/project/showfiles.php?
group_id=22307). Then I untar the package and executed "python
setup.py install". But I got compilation errors (see part of the
failed messages below).

Looks like the installation tried to compile the _mysql extension and
failed. Anybody knows a solution to this problem?

Thanks,

Bruza
==
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info/PKG-INFO
writing top-level names to MySQL_python.egg-info/top_level.txt
writing dependency_links to MySQL_python.egg-info/dependency_links.txt
reading manifest file 'MySQL_python.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'MySQL_python.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-i686/egg
running install_lib
running build_py
copying MySQLdb/release.py -> build/lib.linux-i686-2.5/MySQLdb
running build_ext
building '_mysql' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-
prototypes -fPIC -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -
I/usr/include/mysql -I/usr/include/python2.5 -c _mysql.c -o build/
temp.linux-i686-2.5/_mysql.o -DBIG_JOINS=1
In file included from _mysql.c:29:
pymemcompat.h:10:20: error: Python.h: No such file or directory
_mysql.c:30:26: error: structmember.h: No such file or directory
In file included from /usr/include/mysql/mysql.h:43,
 from _mysql.c:40:
/usr/include/sys/types.h:153: error: duplicate 'unsigned'
/usr/include/sys/types.h:153: error: two or more data types in
declaration specifiers
_mysql.c:64: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:65: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:66: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:67: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:68: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:69: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:70: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:71: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:72: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:73: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:74: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
_mysql.c:77: error: expected specifier-qualifier-list before
'PyObject_HEAD'
_mysql.c:87: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '_mysql_ConnectionObject_Type'
_mysql.c:90: error: expected specifier-qualifier-list before
'PyObject_HEAD'
_mysql.c:98: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '_mysql_ResultObject_Type'
_mysql.c:107: error: expected '=', ',', ';', 'asm' or '__attribute__'
before '*' token
  :
  :
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help: Trouble with imp.load_module

2007-12-16 Thread Gabriel Genellina
En Tue, 11 Dec 2007 16:09:22 -0300, David Hirschfield <[EMAIL PROTECTED]>  
escribi�:

> So this must have something to do with the "." in the name of module
> "test.B.py" but what is the problem, exactly? And how do I solve it? I
> will sometimes need to run load_module on filenames which happen to have
> "." in the name somewhere other than the ".py" extension. Is the
> find_module somehow thinking this is a package?

Module names must be identifiers (see section 6.12 in the Python Reference  
Manual) so test.B *cannot* be a module name. Just avoid such names as  
module names; if you know where the file is located, call load_module  
directly with an already open file and a fake module name.

-- 
Gabriel Genellina

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