Re: Python HTML parser chokes on UTF-8 input

2008-10-10 Thread Marc 'BlackJack' Rintsch
On Fri, 10 Oct 2008 00:13:36 +0200, Johannes Bauer wrote:

> Terry Reedy schrieb:
>> I believe you are confusing unicode with unicode encoded into bytes
>> with the UTF-8 encoding.  Having a problem feeding a unicode string,
>> not 'UFT-8 code', which in Python can only mean a UTF-8 encoded byte
>> string.
> 
> I also believe I am. Could you please elaborate further?
> 
> Do I understand correctly when saying that type 'str' has no associated
> default encoding, but type 'unicode' does?

`str` doesn't know an encoding.  The content could be any byte data 
anyway.  And `unicode` doesn't know an encoding either, it is unicode 
characters.  How they are represented internally is not the business of 
the programmer.  If you want operate with unicode characters you have to 
decode a byte string (`str`) with the appropriate encoding.  If you want 
feed `unicode` to something that expects bytes and not unicode characters 
you have to encode again.

>>> This is incredibly ugly IMHO, as I would really like the parser to
>>> just accept UTF-8 input.

It accepts UTF-8 input but not `unicode` objects.

> However I am sure you will agree that explicit encoding conversions are
> cumbersome and error-prone.

But implicit conversions are impossible because the interpreter doesn't 
know which encoding to use and refuses to guess.  Implicit and guessed 
conversions are error prone too.

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


Re: Python 2.6, GUI not working on vista?

2008-10-10 Thread Michael Shih

no mind !
bad vista ...


--
From: ""Martin v. Löwis"" <[EMAIL PROTECTED]>
Sent: Friday, October 10, 2008 2:28 PM
To: 
Subject: Re: Python 2.6, GUI not working on vista?


I'm not a developer, just a lowly end user. I'm not in
a position to be able to fix anything. All I can do is
report it and if it's legitimate, then hopefully someone
who knows what he's doing will fix it.


Ok. It's then still unfortunate that nobody reported the
problem; your message to comp.lang.python was not "reported"
(through the usual bug report channels). Somebody might have
told you what those channels are; it's unfortunate that nobody
did.

Regards,
Martin




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


Re: FLexible formatted text involving nested lists?

2008-10-10 Thread davidsands
On Oct 10, 4:36 am, RossRGK <[EMAIL PROTECTED]> wrote:
> I'm having trouble getting my head around a solution for a situation
> where I need to flexibly format some text with a varying number of
> embedded fields.
>
> Here's a simplified description of my challenge...
>
> I have a list of lists called bigList:
>
> bigList = [ little, small, tiny]
>
> The sub-lists have varying sizes.  I won't know how many items they have
> but it will be between 0 and 3
>
> So perhaps little = [3, 2, 7]
> small = [6,4]
> tiny = [2]
>
> The values in those sub lists correspond to formatted print strings. The
> formatting strings will change over time and they are in a list called
> "fmts" where
>
> fmts = [fmtA, fmtB, fmtC]   where
>
> fmtA = 'oats %0d kilos over %0d days with %0d workers'
> fmtB = 'barley %0d lbs for %0d hours'
> fmtC = 'apples %0d baskets'
>
> If I knew how many fields were in each 'sub-list' in bigList ahead of
> time, and it never changed I could awkwardly do this:
>
> print fmtA %(little[0], little[1], little[2])
> print fmtB %(small[0], small[1])
> print fmtC %(tiny[0])
>
> or equivalently,
>
> print fmts[0] %(bigList[0][0], bigList[0][1], bigList[0][2])
> print fmts[1] %(bigList[1][0], bigList[1][1])
> print fmts[2] %(bigList[2][0])
>
> Both approaches would yield:
> oats 3 kilos over 2 days with 7 workers
> barley 6 lbs for 4 hours
> apples 2 baskets
>
> Now my challenge: since the number of fields is unknown at design time,
> my app needs to add be able to flexibly handle this.
>
> I though maybe I could use a loop that figures things out as it goes
> along. e.g...
>
> i=0
> for fmtString in fmts
>    numbOfFields = len(fmt[i])
>    print fmtString %(bigList[i][ need "for 0 to numbOffields" worth of
> indices!] )
>
> But I don't know how to have a number of items in the print expression
> that align to the numbOfFields value!?  Is there some other approach I
> can use?
>
> I thought perhaps it would accomodate extra elements in the %(...) part
> of the formatted print expression which would be ignored, but that
> doesn't work.
>
> Maybe I have to break my fmts up and do a field at a time?  Any thoughts
> are appreciated   :)
>
> -Ross.

The tuple() type-conversion function will do what you need:

   print fmts[0] % tuple(bigList[0])
   print fmts[1] % tuple(bigList[1])
   print fmts[2] % tuple(bigList[2])

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


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Hendrik van Rooyen

"Tino Wildenhain"  wrote:


> 
> byte1 byte2? this does not look very practical
> to me. In the simplest form of storing
> your values in a text string, you could just
> use ord() to get the byte value and
> operate on it with 1<<0 1<<1 1<<3 and so on.
> 
> If you want, put a module in which defines the
> constants
> 
> bit1=1<<0
> bit2=1<<1
> 
> and so on and use it via
> if byte & bit1: ...

This is what I meant by "jumping through hoops".

> 
> more efficiently for operations on really big
> bit strings is probably just using integers.

Sure, one could for instance make a list of eight-entry lists:

io = [[b0,b1,b2,b3,b4,b5,b6,b7],]

Then the hoop jumping goes in the opposite
direction - to get hold of an actual byte, you
have to rotate the bits into some byte one at a
time.
This approach has the advantage that you can
add a ninth "dirty" bit to indicate that the "byte" 
in question needs to be written out.

Is there not some OO way of hiding this
bit banging complexity?

Using getters and setters? - I tend to go "tilt" 
like a cheap slot machine when I read that stuff.

- Hendrik

--
Reality is the bane of the sane



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


Re: book recommendation for Python newbie?

2008-10-10 Thread Gabriel Rossetti

Joe Strout wrote:
I'm trying to (gently) convince my business partner that we should be 
adding Python to our core toolset.  He's never used it before, apart 
from poking around in the tutorial a bit at my urging.  But he's got a 
birthday coming up, and I'd like to get him a book that will help him 
make the transition more smoothly and enjoyably.


In case it matters: his background is mainly in databases (originally 
4D, more recently MySQL), and his current primary tools are REALbasic 
(which is a statically typed language with semantics similar to Java) 
and PHP.  He's primarily a Mac user, but occasionally has to dabble in 
Linux or Windows.  If we do make this change, he'll be using Python in 
a professional capacity to develop commercial apps.


There are a lot of Python books out there... which one would you 
recommend in this case?


Thanks,
- Joe

I Learned Python using "Core Python Programming" written by Wesley J. 
Chun, second edition, Prentice Hall, ISBN 0-13-226993-7


I found it to be really good, it starts by introducing the key concepts 
in the early chapters and then goes over each concept more in depth in 
the later chapters. The second part of the book has advances topics, 
like DB, network, RegEx, GUIs, etc. He'll need minimal OOP concepts 
though to grasp the OOP chapters though (classes, single/multiple 
inheritance, etc), but the book does not focus on OOP though. I use 
Python in a professional environment to develop a commercial app. I was 
very quickly able to program in Python with this book.


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


Re: Inefficient summing

2008-10-10 Thread Alexander Schmolck
beginner <[EMAIL PROTECTED]> writes:

> On Oct 9, 3:53 pm, Alexander Schmolck <[EMAIL PROTECTED]> wrote:
>> beginner <[EMAIL PROTECTED]> writes:
>> how about:
>>
>> ratio = (lambda c: c.real/c.imag)(sum(complex(r["F1"], r["F2"] for r in 
>> rec)))
>>
> Neat, but I will have a problem if I am dealing with three fields,
> right?

Sure but then how often do you want to take the ratio of 3 numbers? :) 

More seriously if you often find yourself doing similar operations and are
(legimately) worried about performance, numpy and pytables might be worth a
look. By "legitimately" I mean that I wouldn't be bothered by iterating twice
over rec; it doesn't affect the algorithmic complexity at all and I woudn't be
surprised if sum(imap(itemgetter("F1"),rec))/sum(imap(itemgetter("F2"),rec))
weren't faster than the explicit loop version for the cases you care about
(timeit will tell you). You're right that you loose some generality in not
being able to deal with arbitrary iterables in that case though.

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


Re: Accessing the message of Outlook inbox

2008-10-10 Thread venutaurus539
On Oct 9, 12:19 am, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Oct 8, 12:50 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > On Oct 8, 8:53 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
> > > On Oct 8, 9:24 am, [EMAIL PROTECTED] wrote:
>
> > > > Hi all,
> > > >         How can I access the body of a mail in Outlook Inbox? I tried
> > > > various options like message.Body or message.Mesg etc. but didn't
> > > > work. I could get the subject of the mail using message.Subject
> > > > though.
>
> > > > Any help is appreciated.
>
> > > > Thanks in advance,
> > > > Venu
>
> > > Can you connect via POP3? If so, the email module should be able to
> > > get it. Otherwise, you'll probably have to use the PyWin32 package's
> > > win32com module.
>
> > > Google is your friend. The following links should give you a general
> > > idea of how to access Outlook with Python:
>
> > >http://cephas.net/blog/2004/09/17/sending-your-outlook-calendar-using...
>
> > > Mike
>
> > Thanks Mike for your suggestion.. I am using PyWin32 package's Win32
> > module... I did go through those mails,, and am able to access the
> > Outlook inbox as they have mentioned.. but am not getting the exact
> > function with which I can refer the mails content ( Message of the
> > Body)... :-(
>
> > THank you,,
> > Venu.
>
> Our organization no longer uses Outlook, so I don't have a good way to
> test any more. I recommend re-posting to the pywin32 group 
> here:http://mail.python.org/mailman/listinfo/python-win32
>
> They'll be able to give you pointers and there's plenty of helpful
> people there.
>
> Mike

hmm. I tried posting it to the forum you have mentioned but still
in hunt of a solution.. :-|
--
http://mail.python.org/mailman/listinfo/python-list


a regular expression problem

2008-10-10 Thread lookon
I want to use django to dispatch url.
The url is like /test/Google/6,and my patten is r'^/test/(?P\b\W+
\b)/(?P\d+)$'.
It works when the string is English(like Google), but fails when the
string is in foreign language.

Can anyone tell me the righ regular expression?

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


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Hendrik van Rooyen
George Sakkis wrote:

>I don't know of a canonical way (bit hacking is not really common in
>Python) but pehaps BitPacket [1] comes close to what you're after.
>
>George
>
>[1] http://hacks-galore.org/aleix/BitPacket/

Thanks for the link - I will check it out

- Hendrik

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


Re: Debugging suggestions, efficiency - handling modules

2008-10-10 Thread Almar Klein
You might like IPython, it is an interactive python shell and you caneasily
run scripts from it. That way, the active session remains, as well
as all the imports.

Personally, I don't like the "from pylab import *", the python philosophy
says:
"Namespaces are one honking great idea -- let's do more of those!"
not "let's do less of those". In understand that by doing import * your
environment feels a bit more like Matlab, but I think the absense of
namespaces in Matlab is a weakness, not a strength.

I find that using "import pylab as pl" and then typing "pl." Gets me a list
of all
the nice pylab stuff, without polluting my global namespace...

Cheers,
  Almar

2008/10/10 Bruno Desthuilliers <[EMAIL PROTECTED]>

> John [H2O] a écrit :
>
>> Hello,
>>
>> I am writing some scripts that run a few calculations using scipy and plot
>> the results with matplotlib (i.e. pylab). What I have found, however, is
>> that the bulk of the time it takes to run the script is simply in loading
>> modules.
>>
>
> Is this loading time really that huge ???
>
>  Granted, I am currently using:
>> from pylab import *
>>
>> However, changing this to the specific classes/functions doesn't make a
>> significant difference in the execution time.
>>
>
> Indeed. the 'import' statement does two things : first load the module and
> cache it (so following imports of the same module will access the same
> module object), then populate the importing namespace. Obviously, the
> 'heavy' part is the first import of the module (which requires some IO and
> eventual compilation to .pyc).
>
>  Is there a way to have the modules stay loaded?
>>
>
> where ?
>
> But rerun the script?
>
> Each execution ('run') of a Python script - using the python
> /path/to/my/script syntax or it's point&click equivalent - starts a new
> Python interpreter process, which usually[1] terminates when the script ends
> (wether normally, or because of a sys.exit call or any other exception).
>
> [1] using the -i option keeps the interpreter up, switching to interactive
> mode, after execution.
>
>  One
>> solution I can think of is to set break points,
>>
>
> ???
>
>  and design my scripts more
>> as 'functions', then just run them from the command line.
>>
>
> You should indeed write as much as possible of your scripts logic as
> functions. Then you can use the " if __name__ == '__main__': " idiom as main
> entry point.
>
> Now if you're going to use the Python shell as, well, a shell, you may want
> to have a look at IPython, which is a much more featurefull:
>
> http://ipython.scipy.org/moin/Documentation
>
>
> HTH
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porn Addiction Solutions?

2008-10-10 Thread Dotan Cohen
2008/10/10  <[EMAIL PROTECTED]>:
> I have to compliment you guys with your suggestions and support.  Most
> other groups would have a field day and not be helpful.
> Compassion is rarely present on usenet.

Actually, I suspect that the OP was trolling. But in any case it is a
problem that is pretty widespread.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: component / event based web framework for python?

2008-10-10 Thread lkcl
On Sep 15, 4:53 pm, Jaime Barciela <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> I've been surveying the field ofpythonweb frameworks for a while but
> there are just too many so I ask mighty Usenet.
>
> Is there a component / event based web framework forpython? Something
> that can abstract you from the request/response mechanism and ideally
> from html and javascript altogether?

 yep.  Pyjamas.  http://pyjs.org

 in fact, it's _so_ abstracted from html and javascript that i ported
pyjamas to the desktop, using python bindings to glib bindings to
webkit - see http://webkit.org or better:

   http://pyjd.org


> As examples -- in other languages -- of what I have in mind:
> - in java: wingS,GWT, echo (2,3), karora, thinwire, itmill,

  Pyjamas is a port of GWT to python.

> I would like to be able to write code equivalent to this C# example:
>
> 
> namespace WebApplication1
> {
> public partial class _Default : System.Web.UI.Page
> {
> protected void Page_Load(object sender, EventArgs e)
> {
> Button b = new Button();
> b.Text = "say hello";
> b.Click += Button1_Click;
> Panel1.Controls.Add(b);
> }
>
> protected void Button1_Click(object sender, EventArgs e)
> {
> Label1.Text = "Hello dynamically created on the fly
> UI !!!";
> }
> }}

how about this:

   from pyjamas import Window
   from pyjamas.ui import Button, RootPanel

   def greet(sender):
   Window.alert("Hello, AJAX!")

   class Hello:
   def onModuleLoad(self):
   b = Button("Click me", greet)
   RootPanel().add(b)

is that close enough? :)  does it look _remotely_ like javascript,
html, or even like it's web programming?  doesn't it remind you of
pygtk2 rather a lot? :)

more working examples at http://pyjs.org/examples/

l.

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


Re: python 3: sorting with a comparison function

2008-10-10 Thread Kay Schluehr
On 9 Okt., 22:36, [EMAIL PROTECTED] wrote:

> Yes, that's a wonderful thing, because from the code I see around
> 99.9% of people see the cmp and just use it, totally ignoring the
> presence of the 'key' argument, that allows better and shorter
> solutions of the sorting problem.

Me too because I don't get this:

"key specifies a function of one argument that is used to extract a
comparison key from each list element: key=str.lower. The default
value is None."

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


Home Shop 18 - Zenith Desktop Model No: G31645

2008-10-10 Thread Ayushi Mehra
Home Shop 18 - Zenith Desktop Model No: G31645
Features:

Processor:
* Pentium Core2Duo - E4600
* 2.4GHz
* 2MB Cache
* 800 MHz FSB
RAM:
* 512MB DDR2-667 SDRAM
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the thighest bit position in big integers?

2008-10-10 Thread mmgarvey
On Oct 8, 10:56 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:
>> I think that (0).numbits()==-1 is the natural solution.
>
> Can you clarify this?  Why is -1 the natural solution? I
> can see a case for 0, for -infinity (whatever that means),
> or for raising an exception, but I can't see why -1 would
> be at all useful or natural.

You are right. I misunderstood the definition of nbits(). I initially
had asked for a function get_highest_bin_num(), which is always one
off
nbits() as it seems. I correct my sentence to

  The choice get_highest_bin_num(0) == -1 is the natural one (in
  concerns of cryptography). This property is needed for the
  algorithms I listed above.

If get_highest_bit_num(n) == nbits(n) - 1 holds for all n >= 0 then
we
both agree.

I cite from MRAB's post:
> int.numbits should return the position of the highest set bit (>=0)
> or -1 if none found.
It seems that MRAB had the same misunderstanding.

Perhaps one should implement both: numbits() and get_highest_bit_num()
where
numbits(0) = 0 and get_highest_bit_num(0) raises an exception?
--
http://mail.python.org/mailman/listinfo/python-list


Re: a regular expression problem

2008-10-10 Thread Bruno Desthuilliers

lookon a écrit :

I want to use django to dispatch url.
The url is like /test/Google/6,and my patten is r'^/test/(?P\b\W+
\b)/(?P\d+)$'.
It works when the string is English(like Google), but fails when the
string is in foreign language.


Care to give an exemple of url that fails ?

Anyway, if you want to match just *anything* in that path segment, you 
can try:


r'^/test/(?P.+?)/(?P\d+)$'.



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


Re: default value in __init__

2008-10-10 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> Bruno Desthuilliers:
>> You mean : "to people that don't bother reading the FineManual *nor*
>> searching the newsgroup / ML archives ?"
> 
> Are there ways to change how Python3 manages arguments and functions,
> to remove this antifeature of Python, avoiding this common mistake
> done by every newbie?
> I don't care if it reduces the performance of Python a little.
> 
You can't just copy the default values on every call: you would still get 
people confused by the semantics whether you did a shallow or deep copy or 
as now no copy. I don't think simply re-executing the default argument 
expression on each call works either: that would confuse at least as many 
people as the current system.

It would be possible, but extremely annoying to limit default arguments to 
being literal constants, or slightly less drastically limit them to being 
of types known to be immutable. Of course that blocks you from using any 
user defined types unless you invent some kind of scheme for declaring that 
a type is safe to use as a default argument.

Another option might just be to generate a warning the first time a program 
uses a not obviously immutable default.

I think in this situation the best solution is to expect people to learn to 
use the language, and accept that those people who don't RTFM will keep on 
asking here. Even if you could change the behaviour of default arguments we 
would still get equivalent regular questions from the people who initialise 
class attributes with lists or dictionaries.

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: book recommendation for Python newbie?

2008-10-10 Thread Abah Joseph
Core Python Programming" written by Wesley J. Chun, second edition, Prentice
Hall, ISBN 0-13-226993-7, go for it. I`m only a PHP programmer and this book
have helped me a lot from basic to advance level. though i`m still
reading...



On 10/10/08, slais-www <[EMAIL PROTECTED]> wrote:
>
> Mike Driscoll wrote:
>
>> A lot of people recommend Lutz's "Learning Python". While I haven't
>> read it, I have read his follow-up "Programming Python" and it was
>>
>
> I found Learning Python good for learning, and a useful reference
> sometimes, but it can seem very slow paced if you already know some other
> language. Another problem is that the author seems unable to drop any
> material that is out of date; the pace is slowed by explanations of what you
> might need to do if using a very old version. The third edition is even
> worse is that respect. Also, being based of the author's training
> experience, is not always a good thing. I prefer a book to sitting in a
> class because I don't want to fall asleep whilst the instructor repeats an
> explanation yet again for the benefit of those at the back, nor wait while
> clever-clogs at the front asks an arcane question of no general interest.
> Learning Python is too much like sitting in a classroom for me.
>
> If you already know some programming Python in a Nutshell is very useful.
>
>
> good. You might also look at Hetland's "Beginning Python" or even the
>> "Python for Dummies" book.
>>
>> Mike
>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
I develop dynamic website with PHP & MySql, Let me know about your site
--
http://mail.python.org/mailman/listinfo/python-list


Re: Debugging suggestions, efficiency - handling modules

2008-10-10 Thread Bruno Desthuilliers

John [H2O] a écrit :

Hello,

I am writing some scripts that run a few calculations using scipy and plot
the results with matplotlib (i.e. pylab). What I have found, however, is
that the bulk of the time it takes to run the script is simply in loading
modules. 


Is this loading time really that huge ???


Granted, I am currently using:
from pylab import *

However, changing this to the specific classes/functions doesn't make a
significant difference in the execution time.


Indeed. the 'import' statement does two things : first load the module 
and cache it (so following imports of the same module will access the 
same module object), then populate the importing namespace. Obviously, 
the 'heavy' part is the first import of the module (which requires some 
IO and eventual compilation to .pyc).



Is there a way to have the modules stay loaded?


where ?

But rerun the script?

Each execution ('run') of a Python script - using the python 
/path/to/my/script syntax or it's point&click equivalent - starts a new 
Python interpreter process, which usually[1] terminates when the script 
ends (wether normally, or because of a sys.exit call or any other 
exception).


[1] using the -i option keeps the interpreter up, switching to 
interactive mode, after execution.



One
solution I can think of is to set break points,


???


and design my scripts more
as 'functions', then just run them from the command line.


You should indeed write as much as possible of your scripts logic as 
functions. Then you can use the " if __name__ == '__main__': " idiom as 
main entry point.


Now if you're going to use the Python shell as, well, a shell, you may 
want to have a look at IPython, which is a much more featurefull:


http://ipython.scipy.org/moin/Documentation


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


Enormous amount webcams womans showing groupsex. Free

2008-10-10 Thread fernandena
Enormous amount webcams womans showing groupsex. 
http://sexystory.psend.com/groupsex.htm
--
http://mail.python.org/mailman/listinfo/python-list


indexing arrays

2008-10-10 Thread John [H2O]

I'm having trouble slicing arrays:

I thought I could do the following:
>>> i = array(range(140,149))
>>> j = array(range(5,20))
>>> a = acc[i,j]
Traceback (most recent call last):
  File "", line 1, in 
ValueError: shape mismatch: objects cannot be broadcast to a single shape

It's strange, because I can do this:

>>> a = acc[140:148,5:19]
>>> 


Anyone know what I am doing wrong?

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

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


Re: python 3: sorting with a comparison function

2008-10-10 Thread Thomas Heller
> Thomas Heller wrote:
>> Does Python 3 have no way anymore to sort with a comparison function?
>> 
>> Both [].sort() and sorted() seem to accept only 'key' and 'reverse' 
>> arguments,
>> the 'cmp' argument seems to be gone.  Can that be?

Terry Reedy schrieb:

> Yes.  When this was discussed, no one could come up with an actual use 
> case in which the compare function was not based on a key function. 
> Calling the key function n times has to be faster than calling a compare 
> function n to O(nlogn) times with 2 keys computed for each call.  The 
> main counter argument would be if there is no room in memory for the 
> shadow array of key,index pairs.  And that can be at least sometimes 
> handled by putting the original on disk and sorting an overt key,index 
> array.  Or by using a database.
> 

[EMAIL PROTECTED] schrieb:

> Yes, that's a wonderful thing, because from the code I see around
> 99.9% of people see the cmp and just use it, totally ignoring the
> presence of the 'key' argument, that allows better and shorter
> solutions of the sorting problem. So removing the cmp is the only way
> to rub the nose of programmers on the right solution, and it goes well
> with the Python "There should be one-- and preferably only one --
> obvious way to do it.".


Thanks, I got it now.

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


Re: FLexible formatted text involving nested lists?

2008-10-10 Thread RossRGK

Kerri Reno wrote:

Ross,

I'm no expert in python, so excuse me if this is inane.

What I would do is have fmts be a dictionary where
fmts = { 3 = 'oats %0d kilos over %0d days with %0d workers',
 2 = 'barley %0d lbs for %0d hours',
 1 = 'apples %0d baskets'}

then something like
  for x in bigList:
 print fmts[len(x)] % x

I didn't test this, but in theory it should work.

Hope this helps,
Kerri



Thx for the suggestion - i think that would match the number of fields 
to the number of parameters in the specific example but not the general 
case.  ie fmts[3] could have 3fields this time, but might be 2 another 
time or something else.


Plus I don't think print will accept a list 'x' in the %x part of it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: FLexible formatted text involving nested lists?

2008-10-10 Thread RossRGK

davidsands wrote:



The tuple() type-conversion function will do what you need:

   print fmts[0] % tuple(bigList[0])
   print fmts[1] % tuple(bigList[1])
   print fmts[2] % tuple(bigList[2])



I never thought of the tuple type conversion - that looks promising. 
Thanks for that!


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


Re: indexing arrays

2008-10-10 Thread Emily Rodgers

"John [H2O]" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> I'm having trouble slicing arrays:
>
> I thought I could do the following:
 i = array(range(140,149))
 j = array(range(5,20))
 a = acc[i,j]
> Traceback (most recent call last):
>  File "", line 1, in 
> ValueError: shape mismatch: objects cannot be broadcast to a single shape
>
> It's strange, because I can do this:
>
 a = acc[140:148,5:19]

>
>
> Anyone know what I am doing wrong?

What data structure is acc, and what are you trying to do? 


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


Re: Porn Addiction Solutions?

2008-10-10 Thread pheeh . zero
On Oct 10, 7:03 am, Um Jammer NATTY <[EMAIL PROTECTED]> wrote:
> On Oct 10, 5:37 am, [EMAIL PROTECTED] wrote:
>
> > It's very simple. You need to know the world is much more than the
> > imaginery life you are looking. Spend some time in the feet of the
> > Lord Jesus who would help you to come out of this trouble.
>
> Does anyone else find it amusing that this poster assumes 'imaginary'
> and the Lord Jesus are polar opposites???

I'm guessing...only you!
--
http://mail.python.org/mailman/listinfo/python-list


Re: FLexible formatted text involving nested lists?

2008-10-10 Thread Tino Wildenhain

Hi,

RossRGK wrote:

Kerri Reno wrote:

Ross,

I'm no expert in python, so excuse me if this is inane.

What I would do is have fmts be a dictionary where
fmts = { 3 = 'oats %0d kilos over %0d days with %0d workers',
 2 = 'barley %0d lbs for %0d hours',
 1 = 'apples %0d baskets'}

then something like
  for x in bigList:
 print fmts[len(x)] % x

I didn't test this, but in theory it should work.

Hope this helps,
Kerri



Thx for the suggestion - i think that would match the number of fields 
to the number of parameters in the specific example but not the general 
case.  ie fmts[3] could have 3fields this time, but might be 2 another 
time or something else.


Maybe you want to reconsider your approach and instead of use "lists"
just a dict or class with the correct naming?

If you use a class you could also attach all the meta information
for formatting.

Dicts are easily aliased to your formats using named arguments:

'oats %(weight)0d kilos over %(days)0d days with %(workers)0d workers' % 
dict(weight=5,days=3,workers=10)


which would make more sense when you read it and/or edit the sentence
sometime later. You could also consider extending the attributes
to have the unit (e.g. kg, pound, days, ...) attached to it
and decide to add a clever get() method to your container class
(which replaces the list) and use it like this:

'oats %(weight.kg)s ...' % yourinstance ...

where instance.get() would be called with 'weight.kg',
splits on the . for the attribute: weight,

calls self.weight.format(unit='kg')

to retrieve "5 kilos" or something :-)

Just some random thoughts.

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Hendrik van Rooyen

Mensanator wrote:

>I use the gmpy module for all my bit related work and
>have been very satisfied with the results.

8<--- gmpy function list ---

Thanks. All of this looks good. Will check out
gmpy too.

- Hendrik







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


Re: default value in __init__

2008-10-10 Thread Bruno Desthuilliers

David C. Ullrich a écrit :
In article 
<[EMAIL PROTECTED]>,

 kenneth <[EMAIL PROTECTED]> wrote:


On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:

kenneth wrote:

the 'd' variable already contains the 'self.d' value of the first
instance and not the default argument {}.
Am I doing some stupid error, or this is a problem ?

No, it always contains the default argument because default values are
created just ONE 
TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects..

.


Wow, it's a very "dangerous" behavior ...

Just to know, is this written somewhere in the python documentation or
one has to discover it when his programs fails to work ;-) ?


At least once a week someone discovers this "problem", makes a
post about it here, and then someone points to the spot in the
documentation where it's explained.

Seems to me that people often site the "important warning" in
the tutorial. Of course there's no reason anyone would bother
going through the tutorial


Indeed. No reason at all.


- just for fun I looked in the
official Python Reference Manual to see whether they're explicit
about this or require the reader to figure it out from something
else they say.

There's a section titled "7.6 Function definitions". About halfway
through that section there's a _bold face_ statement 
"Default parameter values are evaluated when the function definition is 
executed.", followed by an explanation of how that can lead to

the sort of problem above.


But there's no reason to read the reference manual neither.


So I guess it _is_ awfully dangerous. They should really explain
this aspect of the language's behavior to people who don't read
the formal definition and also don't work through the tutorial.


You mean : "to people that don't bother reading the FineManual *nor* 
searching the newsgroup / ML archives ?"


Well... How to say.. Is there any chance these people will read anything 
*at all* ?

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


Re: default value in __init__

2008-10-10 Thread bearophileHUGS
Bruno Desthuilliers:
> You mean : "to people that don't bother reading the FineManual *nor*
> searching the newsgroup / ML archives ?"

Are there ways to change how Python3 manages arguments and functions,
to remove this antifeature of Python, avoiding this common mistake
done by every newbie?
I don't care if it reduces the performance of Python a little.

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


Re: default value in __init__

2008-10-10 Thread bearophileHUGS
Duncan Booth:
> You can't just copy the default values on every call: you would still get
> people confused by the semantics whether you did a shallow or deep copy or
> as now no copy.

I think I agree.


> I don't think simply re-executing the default argument
> expression on each call works either: that would confuse at least as many
> people as the current system.

May I ask you why? I think I don't agree, but I am not sure.


> It would be possible, but extremely annoying to limit default arguments to
> being literal constants,

This is a possible solution, beside re-executing the default argument
expression on each call.


> unless you invent some kind of scheme for declaring that
> a type is safe to use as a default argument.

Well, it seems functional-style programming may become more common in
the future, and seeing languages like Scala, etc, maybe it can be
useful to add to Python some way to define immutable classes (in an
explicit way). Maybe subclasses of Immutable?


> Another option might just be to generate a warning the first time a program
> uses a not obviously immutable default.

I don't like this solution much.


> Even if you could change the behaviour of default arguments we
> would still get equivalent regular questions from the people who initialise
> class attributes with lists or dictionaries.

I have seen professional programmers too use class attributes instead
of instance ones...

Well, you can't create a fool-proof language that is useful too, but
in a language that is designed for new programmers too, like Python,
and that doesn't put the running speed as its most important feature,
then I think patching the most known and common pitfalls/traps is
useful, even if you can't patch them all (without turning the language
into something useless).

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


Wanted: something more Pythonic than _winreg.

2008-10-10 Thread Jonathan Fine

Hello

I'm using the _winreg module to change Windows registry settings, but 
its rather low level, and I'd prefer to be working with something more 
Pythonic.


Does anyone have any recommendations?


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


Re: book recommendation for Python newbie?

2008-10-10 Thread slais-www

Mike Driscoll wrote:

A lot of people recommend Lutz's "Learning Python". While I haven't
read it, I have read his follow-up "Programming Python" and it was


I found Learning Python good for learning, and a useful reference 
sometimes, but it can seem very slow paced if you already know some 
other language. Another problem is that the author seems unable to drop 
any material that is out of date; the pace is slowed by explanations of 
what you might need to do if using a very old version. The third edition 
is even worse is that respect. Also, being based of the author's 
training experience, is not always a good thing. I prefer a book to 
sitting in a class because I don't want to fall asleep whilst the 
instructor repeats an explanation yet again for the benefit of those at 
the back, nor wait while clever-clogs at the front asks an arcane 
question of no general interest. Learning Python is too much like 
sitting in a classroom for me.


If you already know some programming Python in a Nutshell is very useful.



good. You might also look at Hetland's "Beginning Python" or even the
"Python for Dummies" book.

Mike

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


Get "code object" of class

2008-10-10 Thread Okko Willeboordse
To get the "code object" c of my_class I can do;

c = compile(inspect.getsource(my_class), "

Re: Efficient Bit addressing in Python.

2008-10-10 Thread Ross Ridge
Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
>Is there a canonical way to address the bits in a structure
>like an array or string or struct?
>
>Or alternatively, is there a good way to combine eight
>ints that represent bits into one of the bytes in some
>array or string or whatever?

This is the code I use to convert large bit arrays to byte strings and
back:

import string
import binascii
import array

_tr_16 = string.maketrans("0123456789abcdef",
  "\x00\x01\x02\x03"
  "\x10\x11\x12\x13"
  "\x20\x21\x22\x23"
  "\x30\x31\x32\x33")
_tr_4 = string.maketrans("0123",
 "\x00\x01"
 "\x10\x11")
_tr_2 = string.maketrans("01", "\x00\x01")

def string_to_bit_array(s):
"""Convert a string to an array containing a sequence of bits."""
s = binascii.hexlify(s).translate(_tr_16)
s = binascii.hexlify(s).translate(_tr_4)
s = binascii.hexlify(s).translate(_tr_2)
a = array.array('B', s)
return a

_tr_rev_2 = string.maketrans("\x00\x01", "01")
_tr_rev_4 = string.maketrans("\x00\x01"
 "\x10\x11",
 "0123")
_tr_rev_16 = string.maketrans("\x00\x01\x02\x03"
  "\x10\x11\x12\x13"
  "\x20\x21\x22\x23"
  "\x30\x31\x32\x33",
  "0123456789abcdef")
def bit_array_to_string(a):
"""Convert an array containing a sequence of bits to a string."""
remainder = len(a) % 8
if remainder != 0:
a.fromlist([0] * (8 - remainder))
s = a.tostring()
s = binascii.unhexlify(s.translate(_tr_rev_2))
s = binascii.unhexlify(s.translate(_tr_rev_4))  
return binascii.unhexlify(s.translate(_tr_rev_16))

I don't think you can do anything faster with standard modules, although
it might not be effecient if you're only working with a single byte.

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


extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Gordon Allott
Hello :)

The result of various incompatibilities has left me needing to somehow
extract the address that a null pointer is pointing to with the null
pointer being exposed to python via PyCObject_FromVoidPtr

the code that creates the PyCObject is as follows:
tmp = PyCObject_FromVoidPtr (info.info.x11.display, NULL);
PyDict_SetItemString (dict, "display", tmp);
Py_DECREF (tmp);

which is exposed to python via a dictionary (the 'display' key). python
identifies that its a PyCObject but doesn't give any way to expose the
functionality. Essentially I am after the address that the void pointer
'info.info.x11.display' points to (as a long type)

As far as I can tell ctypes will only expose the pyObject type to me and
not actually let me deal with the data I am after, but being rather new
to ctypes I'm not sure weather this is correct.

-- 
Gord Allott ([EMAIL PROTECTED])



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


List Order of Initialization

2008-10-10 Thread SamFeltus
When a list initializes, will it always evaluate in order starting at
element 0 and finishing with the last element?

def f1(x):
return x + 2

def f2(x):
return x * 2

def f3(x):
return x * 3

the_list = [f1(7), f2(8), f3(4)]
--
http://mail.python.org/mailman/listinfo/python-list


Re: List Order of Initialization

2008-10-10 Thread Diez B. Roggisch

SamFeltus schrieb:

When a list initializes, will it always evaluate in order starting at
element 0 and finishing with the last element?

def f1(x):
return x + 2

def f2(x):
return x * 2

def f3(x):
return x * 3

the_list = [f1(7), f2(8), f3(4)]


Yes.

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


Re: a regular expression problem

2008-10-10 Thread Leefurong
> > I want to use django to dispatch url.
> > The url is like /test/Google/6,and my patten is r'^/test/(?P\b\W+
\W should be \w, a typo? :)
> > \b)/(?P\d+)$'.
> > It works when the string is English(like Google), but fails when the
> > string is in foreign language.
Try this:
r'(?u)^/test/(?P\b\w+\b)/(?P\d+)$'
if ?u doesn't work, try ?L.
I'm not sure which encoding a url uses.(locale or unicode? I guess
unicode)
>
> Care to give an exemple of url that fails ?
>
> Anyway, if you want to match just *anything* in that path segment, you
> can try:
>
> r'^/test/(?P.+?)/(?P\d+)$'.
I don't think he wants to match anything :)

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


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Tino Wildenhain

Hendrik van Rooyen wrote:

"Tino Wildenhain"  wrote:



byte1 byte2? this does not look very practical
to me. In the simplest form of storing
your values in a text string, you could just
use ord() to get the byte value and
operate on it with 1<<0 1<<1 1<<3 and so on.

If you want, put a module in which defines the
constants

bit1=1<<0
bit2=1<<1

and so on and use it via
if byte & bit1: ...


This is what I meant by "jumping through hoops".


more efficiently for operations on really big
bit strings is probably just using integers.


Sure, one could for instance make a list of eight-entry lists:

io = [[b0,b1,b2,b3,b4,b5,b6,b7],]


what should that represent? Which byte order
do you have in mind etc?


Then the hoop jumping goes in the opposite
direction - to get hold of an actual byte, you
have to rotate the bits into some byte one at a
time.


Well, thats one would expect by your proposed interface.

Can you perhaps outline what kind of application
you have in mind and which operations look meaningfull
to that?

I'm familar with embedded hardware where you would have
a couple of registers where you usually only have
the distinction between 8-bit or 16 bit flag registers
where it makes sense to individually influence bits.
Personally I can't follow you on the path to have
arbitrary lengthy bitfields - even nore to
have artifically attributes (like bit5) on them.

Just using a big integer to represent your bitfield
and using binary operators on it does not sound
so wrong to me in this case.

Of course one could create a type which derives
from sequence types and implement something
like

bitfieldinstance[bitindex] (where 0 is LSB)

would you like fries... err slices with that?

e.g.

>>> bf=BitField(10)
>>> int(bf[1:])
5

?




This approach has the advantage that you can
add a ninth "dirty" bit to indicate that the "byte" 
in question needs to be written out.


What do you mean by "written out" to where?


Is there not some OO way of hiding this
bit banging complexity?


foo & bar is complex? So you want to replace foo + bar
as well with something? ;)

Using getters and setters? - I tend to go "tilt" 
like a cheap slot machine when I read that stuff.


Getters setters? Where would that improve the situation
beside having to write lots of unneccessary code?

Regards
Tino




smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


a regular expression problem

2008-10-10 Thread gita ziabari
>
>
>
>
> -- Forwarded message --
> From: lookon <[EMAIL PROTECTED]>
> To: python-list@python.org
> Date: Fri, 10 Oct 2008 03:58:08 -0700 (PDT)
> Subject: a regular expression problem
> I want to use django to dispatch url.
> The url is like /test/Google/6,and my patten is r'^/test/(?P\b\W+
> \b)/(?P\d+)$'.
> It works when the string is English(like Google), but fails when the
> string is in foreign language.
>
> Can anyone tell me the righ regular expression?
>
> Thank you!
>
>
>
> Add:  # -*- coding: utf-8 -*- at the beginning of your script and try
again. This is for handling non-ascii characters.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Hendrik van Rooyen
Lie Ryan wrote:


>You'll find that in most cases, using integer or Boolean is enough. There
>are some edge cases, which requires bit addressing for speed or memory
>optimizations, in python, the usual response to that kind of optimization
>requirement is to move that part of the code to C.
>
>If, for the more usual case, you require the bit addressing because the
>data structure is more convenient to work with that way, you could use a
>class that implements the __getitem__, __setitem__, and a "join" method.

I had a vague feeling that this was the way to go,(see
my reply to Tino) but I have been resisting, kicking
and screaming, to get deeply involved in OO - Using
Tkinter is enough OO for my microprocessor biased
taste.

>anyway, if you used str, it isn't hard to have both behavior (easy
>indexing and easy joining) the bits:
>
 a =3D '01101010'
 a[0], a[1]
>('0', '1')
 a
>'01101010'
 int(a, 2)
>106
 chr(int(a, 2))
>'j'
 def bin2int(b): return int(a, 2)
...
 def bin2chr(b): return chr(int(a, 2))

Thanks. This is the best I have seen up to now.

I was stuck because I was insisting on
storing real bits in real strings, eight
bits per byte, instead of storing ascii bits
and remembering about int(x,2).

In fact I keep forgetting about the
second argument of int...

I could go with a list like this:

inputs = [['10001000',''],['',''],['01010101','']]

Where the second entry in the list is a "changed" bit.

Outputs are a bit more of a hassle - strings are immutable,
so I can't  write:

input[1][0][3]='1'

but that is easily fixed by using array.array.

Thanks for the response

- Hendrik



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


Debugging suggestions, efficiency - handling modules

2008-10-10 Thread John [H2O]

Hello,

I am writing some scripts that run a few calculations using scipy and plot
the results with matplotlib (i.e. pylab). What I have found, however, is
that the bulk of the time it takes to run the script is simply in loading
modules. Granted, I am currently using:
from pylab import *

However, changing this to the specific classes/functions doesn't make a
significant difference in the execution time.

Is there a way to have the modules stay loaded? But rerun the script? One
solution I can think of is to set break points, and design my scripts more
as 'functions', then just run them from the command line.

Any advice is appreciated!
-john
-- 
View this message in context: 
http://www.nabble.com/Debugging-suggestions%2C-efficiency---handling-modules-tp19915639p19915639.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: inspect feature

2008-10-10 Thread Bruno Desthuilliers

Aaron "Castironpi" Brady a écrit :

On Oct 9, 3:48 am, Bruno Desthuilliers  wrote:

Aaron "Castironpi" Brady a écrit :




Hello,
The 'inspect' module has this method:
inspect.getargvalues(frame)
It takes a frame and returns the parameters used to call it, including
the locals as defined in the frame, as shown.

def f( a, b, d= None, *c, **e ):

... import inspect
... return inspect.getargvalues( inspect.currentframe() )
...

f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' )

(['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1,
'e': {'h': 'g
hi'}, 'd': 'abc', 'inspect': })
However, if you wanted a decorator that examines the parameters to a
function, you're out of luck.  By the time you have a frame, you're
already in the function.

Hem...

def decorator(func):
 def _decorator(*args, *kw):
 print "func args are ", *args, **kw
 return func(*args, **kw)
 return _decorator


It is less of a problem without tuple unpacking, but you still have
code like:

if len( args )>= 2:
   b= args[ 1 ]
else:
   try:
  b= (somehow check b's default val.)
   except NoDefaultVal:
  raise ArgumentError

Worse yet, you have it for each parameter.  Unless I missed something,
this is the only way to mimic/recreate the signature of the decoratee.


I don't get what you're after ??? The decorator has full access to both 
the actual params *and* the function's signature (via 
inspect.getargspec). So your initial question "if you wanted a decorator 
that examines the parameters to a function" seems fully answered. You 
will indeed have to write a couple lines of code if you want the same 
formating as the one you'd get with inspect.currentframe(), but what ?


FWIW, Michele Simionato's decorator module has some trick to allow for 
signature-preserving decorators, so you may want to have a look - but 
I'm not sure if this would solve your problem - at least in a sane way.

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


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Hendrik van Rooyen
 "Tino Wildenhain"  wrote:

> Hendrik van Rooyen wrote:
> > "Tino Wildenhain"  wrote:

8<
> > Sure, one could for instance make a list of eight-entry lists:
> > 
> > io = [[b0,b1,b2,b3,b4,b5,b6,b7],]
> 
> what should that represent? Which byte order
> do you have in mind etc?

Each list of bits in the io list would represent bits from least to most
significant, and would have to be collected into one byte before
being output to the hardware in the case of outputs, and would
have their source in one of the bytes read from the hardware, being
scattered from the input byte to the individual bits

8<--
> 
> Can you perhaps outline what kind of application
> you have in mind and which operations look meaningfull
> to that?

I am working on a controller for a small machine - I am using
the GPIO port on an eBox to form a slow bus that addresses
latches and buffers on external boards via a ribbon cable.
The idea is that the ebox and the io boards would clip on a 
DIN rail and form a PAC (Programmable Automation Controller)

Each external board has either 8 inputs, or 8 outputs, and the 
addressing scheme allows eight such pairs of boards, so that the 
complete io structure could be represented in 16 bytes - eight
for the inputs, and eight for the outputs, giving 2 arrays of 64 bits,
if I use a real bit to represent the state of the voltage on the wire.

> 
> I'm familar with embedded hardware where you would have
> a couple of registers where you usually only have
> the distinction between 8-bit or 16 bit flag registers
> where it makes sense to individually influence bits.
> Personally I can't follow you on the path to have
> arbitrary lengthy bitfields - even nore to
> have artifically attributes (like bit5) on them.
> 

something like bit5 represents a name for the input or
output in question - in practice, it would have a name
like "e_stop" for an emergency stop input, or "push"
for an actuator that pushes something.

> Just using a big integer to represent your bitfield
> and using binary operators on it does not sound
> so wrong to me in this case.
> 
> Of course one could create a type which derives
> from sequence types and implement something
> like
> 
> bitfieldinstance[bitindex] (where 0 is LSB)
> 
> would you like fries... err slices with that?
> 
> e.g.
> 
>  >>> bf=BitField(10)
>  >>> int(bf[1:])
> 5

If I can just address the thing by name I would be happy:

if e_stop:
   put_everything_off ()

and a simple sequence:

push = 1  # actuates the pneumatic pusher

while not push_forward:   # waits for it to arrive
 time.sleep(0.001)

push = 0 # reverses the motion again.

This of course means that there has to be another
thread active to actually do the i/o on a periodic basis,
gathering the outputs and writing them out, and reading
the inputs and scattering them to the various named input
bits

I would even not mind if I have to write:

if e_stop():
put_everything_off()

or:

set(push,1)

> 
> > This approach has the advantage that you can
> > add a ninth "dirty" bit to indicate that the "byte" 
> > in question needs to be written out.
> 
> What do you mean by "written out" to where?
> 

See above explanation - see also a recent thread here
about "Python string immutability broken" where I posted the
prototype ctypes code, if you are really interested...

> > Is there not some OO way of hiding this
> > bit banging complexity?
> 
> foo & bar is complex? So you want to replace foo + bar
> as well with something? ;)
> 
> > Using getters and setters? - I tend to go "tilt" 
> > like a cheap slot machine when I read that stuff.
> 
> Getters setters? Where would that improve the situation
> beside having to write lots of unneccessary code?
> 

Not necessarily unnecessary - the getters and setters could be
used to actually do the i/o to the relevant card when anything 
makes an access to one of the bits on the memory representation
of that card - that would obviate the necessity for a second thread...

- Hendrik


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


Re: Porn Addiction Solutions?

2008-10-10 Thread Um Jammer NATTY
On Oct 10, 5:37 am, [EMAIL PROTECTED] wrote:

> It's very simple. You need to know the world is much more than the
> imaginery life you are looking. Spend some time in the feet of the
> Lord Jesus who would help you to come out of this trouble.

Does anyone else find it amusing that this poster assumes 'imaginary'
and the Lord Jesus are polar opposites???


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


Re: Wanted: something more Pythonic than _winreg.

2008-10-10 Thread Christian Heimes

Jonathan Fine wrote:

Hello

I'm using the _winreg module to change Windows registry settings, but 
its rather low level, and I'd prefer to be working with something more 
Pythonic.


Does anyone have any recommendations?


Yeah, please implement a nice wrapper and submit a patch to 
bugs.python.org. We are looking for a decent wrapper for the windows 
registry for some time.


Thanks :)

Christian

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


Re: Wanted: something more Pythonic than _winreg.

2008-10-10 Thread Mike Driscoll
On Oct 10, 9:44 am, Jonathan Fine <[EMAIL PROTECTED]> wrote:
> Hello
>
> I'm using the _winreg module to change Windows registry settings, but
> its rather low level, and I'd prefer to be working with something more
> Pythonic.
>
> Does anyone have any recommendations?
>
> Jonathan

I've used YARW before for nested deletion. It's a little nicer:

http://code.activestate.com/recipes/476229/

There's also this recipe: http://code.activestate.com/recipes/174627/

Other than those, I'm not really aware of much.

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


Re: How to do regular BASH work in Python?

2008-10-10 Thread Michael Torrie
Frantisek Malina wrote:
> What is the best way to do the regular bash commands in native python?
> 
> - create directory
> - create file
> - make a symlink
> - copy a file to another directory
> - move a file
> - set permissions
> 
> I need to write a program that creates real application/FTP accounts
> and make regular backups to external disk and I think its best to do
> it all consistently with my application in Python.
> This way I can easily link it to the customer database and front-end
> web application. I'd want to avoid BASH/SHELL if that's possible.

As others have said, the os and shutils modules should fulfill most of
your needs.

But unfortunately Python is definitely not a shell-scripting language
and some things that are easy in bash are really, really hard in python,
such as interacting with and stringing together processes, redirecting
outputs, etc.  Whereas in bash it's easy to create pipes between
processes and redirect inputs with '|', '>', '2>', etc, in Python you'd
have to use the subprocess module to spawn a real shell to do much of
that.

In many circumstances, though, the purpose of the piping and redirection
in Bash is to do text processing, which is very easy to do with python
and generators.  See http://www.dabeaz.com/generators/ for the real
power that python can bear on the problems traditionally solved with
bash.  I find that in most cases in python, a simple wrapper around
subprocess to run a command and get its stdout, stderr and return error
code works pretty well.

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


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Aaron "Castironpi" Brady
On Oct 10, 5:24 am, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Hello :)
>
> The result of various incompatibilities has left me needing to somehow
> extract the address that a null pointer is pointing to with the null
> pointer being exposed to python via PyCObject_FromVoidPtr
>
> the code that creates the PyCObject is as follows:
>     tmp = PyCObject_FromVoidPtr (info.info.x11.display, NULL);
>     PyDict_SetItemString (dict, "display", tmp);
>     Py_DECREF (tmp);
>

Did you try:

tmp= PyLong_FromLong( ( long ) info.info.x11.display );
PyDict_SetItemString (dict, "display", tmp);
Py_DECREF (tmp);

Or also try:

PyCObject_AsVoidPtr( tmp );
--
http://mail.python.org/mailman/listinfo/python-list


unified_diff

2008-10-10 Thread [EMAIL PROTECTED]
I can create a unified diff as follows:

udiff = difflib.unified_diff(text1, text2)

Is there an available function somewhere to apply udiff to text1 and
construct text2, like this?

text2 = some_func(text1, udiff)

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


Python Boot Camp 11/10-11/14

2008-10-10 Thread Kerri Reno
Anyone thinking about attending the Python Boot Camp at Big Nerd
Ranch?  This is the time.  If they don't get one more person they will
cancel the session.  So if you're on the fence, take one for the
Gipper, and sign up for the November session.

http://www.bignerdranch.com/classes/python.shtml

Kerri

-- 
Yuma Educational Computer Consortium
Compass Development Team
Kerri Reno
[EMAIL PROTECTED]  (928) 502-4240
.·:*¨¨*:·.   .·:*¨¨*:·.   .·:*¨¨*:·.
--
http://mail.python.org/mailman/listinfo/python-list


GzipFile(fileobj=sys.stdin) Why not?

2008-10-10 Thread Brian Cole
Appears like a patch was submitted to allow GzipFile to work from
pipes long ago. But there's no comment on why this was never accepted.
Is there a good reason?

http://mail.python.org/pipermail/patches/2006-June/020064.html

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


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Gordon Allott
Aaron "Castironpi" Brady wrote:
> Did you try:
> 
> tmp= PyLong_FromLong( ( long ) info.info.x11.display );
> PyDict_SetItemString (dict, "display", tmp);
> Py_DECREF (tmp);
> 
> Or also try:
> 
> PyCObject_AsVoidPtr( tmp );
> --
> http://mail.python.org/mailman/listinfo/python-list

the problem is that I can't edit the C code - well I can and might
submit a patch to the project but I also need a solution that works from
the python side of things.


-- 
Gord Allott ([EMAIL PROTECTED])



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


Re: inspect feature

2008-10-10 Thread Aaron "Castironpi" Brady
On Oct 10, 3:36 am, Bruno Desthuilliers  wrote:
> Aaron "Castironpi" Brady a écrit :
>
>
>
> > On Oct 9, 3:48 am, Bruno Desthuilliers  > [EMAIL PROTECTED]> wrote:
> >> Aaron "Castironpi" Brady a écrit :
>
> >>> Hello,
> >>> The 'inspect' module has this method:
> >>> inspect.getargvalues(frame)
> >>> It takes a frame and returns the parameters used to call it, including
> >>> the locals as defined in the frame, as shown.
> >> def f( a, b, d= None, *c, **e ):
> >>> ...     import inspect
> >>> ...     return inspect.getargvalues( inspect.currentframe() )
> >>> ...
> >> f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' )
> >>> (['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1,
> >>> 'e': {'h': 'g
> >>> hi'}, 'd': 'abc', 'inspect':  >>> \Python26\lib\in
> >>> spect.pyc'>})
> >>> However, if you wanted a decorator that examines the parameters to a
> >>> function, you're out of luck.  By the time you have a frame, you're
> >>> already in the function.
> >> Hem...
>
> >> def decorator(func):
> >>      def _decorator(*args, *kw):
> >>          print "func args are ", *args, **kw
> >>          return func(*args, **kw)
> >>      return _decorator
>
> > It is less of a problem without tuple unpacking, but you still have
> > code like:
>
> > if len( args )>= 2:
> >    b= args[ 1 ]
> > else:
> >    try:
> >       b= (somehow check b's default val.)
> >    except NoDefaultVal:
> >       raise ArgumentError
>
> > Worse yet, you have it for each parameter.  Unless I missed something,
> > this is the only way to mimic/recreate the signature of the decoratee.
>
> I don't get what you're after ??? The decorator has full access to both
> the actual params *and* the function's signature (via
> inspect.getargspec). So your initial question "if you wanted a decorator
> that examines the parameters to a function" seems fully answered. You
> will indeed have to write a couple lines of code if you want the same
> formating as the one you'd get with inspect.currentframe(), but what ?
>
> FWIW, Michele Simionato's decorator module has some trick to allow for
> signature-preserving decorators, so you may want to have a look - but
> I'm not sure if this would solve your problem - at least in a sane way.

It's not exactly the next Millennium problem, but there are some
substantial checks you have to do on a per-parameter basis to see the
same thing that a function sees, when all you have is *args, **kwargs.

You are wrapping a function with this signature:

def f( a, b, c= None, *d, **e ):

You want to find out the values of 'a', 'b', and 'c' in a decorator.
You have these calls:

f( 0, 1, 'abc', 'def', h= 'ghi' )
f( 0, 1 )
f( 0, 1, h= 'abc' )
f( 0, 1, 'abc', c= 'def' ) #raise TypeError: multiple values

How do you determine 'a', 'b', and 'c'?
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-10 Thread Chris Rebert
On Fri, Oct 10, 2008 at 4:36 AM,  <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers:
>> You mean : "to people that don't bother reading the FineManual *nor*
>> searching the newsgroup / ML archives ?"
>
> Are there ways to change how Python3 manages arguments and functions,
> to remove this antifeature of Python, avoiding this common mistake
> done by every newbie?
> I don't care if it reduces the performance of Python a little.

The general idea been discussed ad-nauseum on the list several times
before, including just 2 months ago. See e.g.:

[Python-3000] default argument surprises
http://mail.python.org/pipermail/python-3000/2008-August/014658.html

[Python-ideas] proto-PEP: Fixing Non-constant Default Arguments
http://mail.python.org/pipermail/python-ideas/2007-January/000121.html

[Python-3000] pre-PEP: Default Argument Expressions
http://mail.python.org/pipermail/python-3000/2007-February/005704.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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


Re: python 3: sorting with a comparison function

2008-10-10 Thread pruebauno
On Oct 10, 8:35 am, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On 9 Okt., 22:36, [EMAIL PROTECTED] wrote:
>
> > Yes, that's a wonderful thing, because from the code I see around
> > 99.9% of people see the cmp and just use it, totally ignoring the
> > presence of the 'key' argument, that allows better and shorter
> > solutions of the sorting problem.
>
> Me too because I don't get this:
>
> "key specifies a function of one argument that is used to extract a
> comparison key from each list element: key=str.lower. The default
> value is None."
>
> Kay

Don't know if further explanation is needed, but here is the deal:

cmp is a function that receives two values and you return -1, 0 or 1
depending if the first is smaller, equal or bigger. 99% of the time
you will do some operation on the values that come in and then do a if
statement with ">" or "<" and return -1,0,1.

key is a function that receives one value and you return the value
that you would normally compare against.

Let me show an example:

>>> data=[(4,'v'),(2,'x'),(1,'a')]
>>> sorted(data)
[(1, 'a'), (2, 'x'), (4, 'v')]

OK, we sorted the data, but What if we want to sort by the letter
instead of the number? Let's use cmp:

>>> def comp(x, y):
  key_of_x=x[1]
  key_of_y=y[1]
  if key_of_x < key_of_y:
return -1
  elif key_of_x > key_of_y:
return 1
  else:
return 0 #key_of_x == key_of_y

>>> sorted(data,cmp=comp)
[(1, 'a'), (4, 'v'), (2, 'x')]

Very well, so how do we do this using key?

>>> def keyfunc(x):
  key_of_x=x[1]
  return key_of_x

>>> sorted(data,key=keyfunc)
[(1, 'a'), (4, 'v'), (2, 'x')]


Same output. Very good.

(Of course a smart python developer would use the operator module so
he doesn't even have to write keyfunc but this was just an example)

In summary to transform most cmp functions to a key function you just
take the code that calculates the first value to be compared and leave
out the rest of the logic.

Hope that was helpful.
--
http://mail.python.org/mailman/listinfo/python-list


Subprocess problem on multiple OS's

2008-10-10 Thread Amanda Jamin
Subprocess issues with platform independence

Postby ajamin on Wed Oct 08, 2008 10:46 am
I am writing a python script that will act as a wrapper for another
program. The python script will provide the inputs for this program
and will verify that the output is correct. The application runs on
multiple OS's including windows and *nix.

This is the code:

Code: Select all

Help with Code Tags
python Syntax (Toggle Plain Text)

   1.
  import os, sys, string, time, subprocess
   2.
  command = "OK\r\n"
   3.
  p = subprocess.Popen( ("C:\setup-winnt.exe", "-console"),
   4.
  stdin = subprocess.PIPE,
   5.
  stdout = subprocess.PIPE,
   6.
  stderr = subprocess.PIPE)
   7.
  stdout_text, stderr_text = p.communicate(command)
   8.
  sys.stdout.writelines(stdout_text.rstrip())

import os, sys, string, time, subprocess command = "OK\r\n" p =
subprocess.Popen( ("C:\setup-winnt.exe", "-console"), stdin =
subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout_text, stderr_text = p.communicate(command)
sys.stdout.writelines(stdout_text.rstrip())


On the *nix version, the application to open ("C:\setup-winnt.exe")
and the command ("OK\r\n") are different. The plan is to refactor this
as the code develops.

The above code works fine on *nix. On these OS's the application
launches in the same console that the command is issued from. On
windows the behavior is different. When the command is executed an
initialization window opens. When this window closes, a command window
is opened. It is this command window that I wish to send commands to.
I believe this command window may be started as a child process of the
application. However it is opened, it does not accept input from the
stdin of the process.

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


Re: default value in __init__

2008-10-10 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

>> I don't think simply re-executing the default argument
>> expression on each call works either: that would confuse at least as
>> many people as the current system.
> 
> May I ask you why? I think I don't agree, but I am not sure.
> 
My thought (which may well be wrong) is that people would still expect the 
default argument expression to use the values of variables at the time when 
the function is defined, not the values at the point of calling it.

e.g. in this hypothetical universe:

>>> y = 0
>>> def f(x=y): return x*x

>>> y = 1
>>> f()
1

would certainly be suprising to anyone used to the current behaviour and I 
think would also suprise anyone who hadn't read the manual in sufficient 
details.

We already get people asking why code like this doesn't return 3:

>>> fns = [ lambda: x for x in range(10) ]
>>> fns[3]()
9

i.e. they expect the variable lookup to be done at function definition time 
rather than function call time. This implies to me that some people are 
going to get confused whichever way round these things happen although 
perhaps it is the behaviour of default arguments that makes them expect 
this.

As an aside, making this change to default arguments would mean the 
solution usually proposed to the function scoping question above would no 
longer work:

>>> fns = [ lambda y=x: y for x in range(10) ]
>>> fns[3]()
3

I wonder whether it is the way the default argument expressions are 
embedded inside the function that causes the confusion? If for example 
default arguments were defined like this:

class C:
  @default(d={})
  def __init__(self, i=10, d):
self.d = d
self.i = i

would moving the expression before the 'def' make people less inclined to 
be suprised that the object is shared?
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Aaron "Castironpi" Brady
On Oct 10, 12:04 pm, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> > Did you try:
>
> > tmp= PyLong_FromLong( ( long ) info.info.x11.display );
> > PyDict_SetItemString (dict, "display", tmp);
> > Py_DECREF (tmp);
>
> > Or also try:
>
> > PyCObject_AsVoidPtr( tmp );
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> the problem is that I can't edit the C code - well I can and might
> submit a patch to the project but I also need a solution that works from
> the python side of things.
>

I see.  If I understand, you have a PyCObject in a dictionary.

Look at the 'ctypes' module and try calling PyCObject_AsVoidPtr.  Its
return type should be 'c_void_p', and you can use 'result.value' to
get the original pointer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-10 Thread bearophileHUGS
Chris Rebert:
> The general idea been discussed ad-nauseum on the list several times
> before, including just 2 months ago. See e.g.:

Okay, it can't be fixed then.

Bye and thank you,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porn Addiction Solutions?

2008-10-10 Thread John Ladasky
On Oct 8, 12:30 pm, [EMAIL PROTECTED] wrote:
> On Oct 8, 3:07 pm, [EMAIL PROTECTED] wrote:
> > Any suggestions?

Sure -- my suggestion is to post in relevant newsgroups!

Rec.music.hip-hop, comp.lang.python, comp.lang.ruby, and
alt.comp.freeware are not appropriate places for your inquiries.
Alt.support.divorce?  That group is possibly relevant, I'm not sure.

A quick look through the newsgroup hierarchy brings up
alt.recovery.addiction.sexual.

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


Re: urlparse import Faillure

2008-10-10 Thread Wojtek Walczak
On Thu, 9 Oct 2008 22:47:58 -0700 (PDT), Robert Hancock wrote:

 import CGIHTTPServer
...
> ImportError: cannot import name urlparse

...
> It points to the third line of the comment.  Any ideas on how to
> proceed with the debugging?

Have you tried getting rid of this comment? I doubt that
the comment is a reason of this error, but it seems that
it shadows the real problem. Moreover, try to import urlparse
itself and check if you got the pyc file for urlparse.py
in your */lib/python2.5/ directory.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Lie
On Oct 11, 5:27 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> This of course means that there has to be another
> thread active to actually do the i/o on a periodic basis,
> gathering the outputs and writing them out, and reading
> the inputs and scattering them to the various named input
> bits

Not necessarily. You've mentioned two ways.

> I would even not mind if I have to write:
>
> if e_stop():
>     put_everything_off()
>
> or:
>
> set(push,1)
>

PS: Umm, a little bit off note: set is a built-in name, I'm a little
confused whether you meant on creating a "set" or setting the push bit
to 1, if the latter case it might be better to use set and clear
instead of passing a second parameter (and also to choose another
name).

Alternatively, there is one more way:
if bb.e_stop:
bb.e_stop = 0
where bb is some kind of "property bag" and .e_stop is a "property"
instead of an "instance member".

> > > This approach has the advantage that you can
> > > add a ninth "dirty" bit to indicate that the "byte"
> > > in question needs to be written out.
>
> > What do you mean by "written out" to where?
>
> See above explanation - see also a recent thread here
> about "Python string immutability broken" where I posted the
> prototype ctypes code, if you are really interested...
>
> > > Is there not some OO way of hiding this
> > > bit banging complexity?
>
> > foo & bar is complex? So you want to replace foo + bar
> > as well with something? ;)
>
> > > Using getters and setters? - I tend to go "tilt"
> > > like a cheap slot machine when I read that stuff.
>
> > Getters setters? Where would that improve the situation
> > beside having to write lots of unneccessary code?
>
> Not necessarily unnecessary - the getters and setters could be
> used to actually do the i/o to the relevant card when anything
> makes an access to one of the bits on the memory representation
> of that card - that would obviate the necessity for a second thread...

Rather than directly using getters and setters, I'd go with property.
It (usually) makes a cleaner external interface of the class. And for
the mess of having to write lots of boilerplate codes, you _could_
dynamically generate the boilerplate code from a dictionary (of name
to bit position) and currying (or something to that effect).
Alternatively, you could also do some magic with getattr and setattr.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python 3: sorting with a comparison function

2008-10-10 Thread Kay Schluehr
On 10 Okt., 19:22, [EMAIL PROTECTED] wrote:
> On Oct 10, 8:35 am, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
> > On 9 Okt., 22:36, [EMAIL PROTECTED] wrote:
>
> > > Yes, that's a wonderful thing, because from the code I see around
> > > 99.9% of people see the cmp and just use it, totally ignoring the
> > > presence of the 'key' argument, that allows better and shorter
> > > solutions of the sorting problem.
>
> > Me too because I don't get this:
>
> > "key specifies a function of one argument that is used to extract a
> > comparison key from each list element: key=str.lower. The default
> > value is None."
>
> > Kay
>
> Don't know if further explanation is needed, but here is the deal:
>
> cmp is a function that receives two values and you return -1, 0 or 1
> depending if the first is smaller, equal or bigger. 99% of the time
> you will do some operation on the values that come in and then do a if
> statement with ">" or "<" and return -1,0,1.
>
> key is a function that receives one value and you return the value
> that you would normally compare against.
>
> Let me show an example:
>
> >>> data=[(4,'v'),(2,'x'),(1,'a')]
> >>> sorted(data)
>
> [(1, 'a'), (2, 'x'), (4, 'v')]
>
> OK, we sorted the data, but What if we want to sort by the letter
> instead of the number? Let's use cmp:
>
> >>> def comp(x, y):
>
>       key_of_x=x[1]
>       key_of_y=y[1]
>       if key_of_x < key_of_y:
>         return -1
>       elif key_of_x > key_of_y:
>         return 1
>       else:
>         return 0 #key_of_x == key_of_y
>
> >>> sorted(data,cmp=comp)
>
> [(1, 'a'), (4, 'v'), (2, 'x')]
>
> Very well, so how do we do this using key?
>
> >>> def keyfunc(x):
>
>       key_of_x=x[1]
>       return key_of_x
>
> >>> sorted(data,key=keyfunc)
>
> [(1, 'a'), (4, 'v'), (2, 'x')]
>
> Same output. Very good.
>
> (Of course a smart python developer would use the operator module so
> he doesn't even have to write keyfunc but this was just an example)
>
> In summary to transform most cmp functions to a key function you just
> take the code that calculates the first value to be compared and leave
> out the rest of the logic.
>
> Hope that was helpful.

Yes, thanks a lot. In essence the "key" is a function that maps each
list element onto a value of a type for which a known order is defined
e.g. an integer. Applying sorted() sorts the list elements according
to the list of those values.

Sometimes it helps when people just make clear how they use technical
terms instead of invoking vague associations.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get "code object" of class

2008-10-10 Thread Matimus
On Oct 10, 5:50 am, Okko Willeboordse <[EMAIL PROTECTED]>
wrote:
> To get the "code object" c of my_class I can do;
>
> c = compile(inspect.getsource(my_class), "

Re: Efficient Bit addressing in Python.

2008-10-10 Thread Lie
On Oct 11, 5:27 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> This of course means that there has to be another
> thread active to actually do the i/o on a periodic basis,
> gathering the outputs and writing them out, and reading
> the inputs and scattering them to the various named input
> bits

Not necessarily. You've mentioned two ways.

> I would even not mind if I have to write:
>
> if e_stop():
>     put_everything_off()
>
> or:
>
> set(push,1)
>

PS: Umm, a little bit off note: set is a built-in name, I'm a little
confused whether you meant on creating a "set" or setting the push bit
to 1, if the latter case it might be better to use set and clear
instead of passing a second parameter (and also to choose another
name).

Alternatively, there is one more way:
if bb.e_stop:
bb.e_stop = 0
where bb is some kind of "property bag" and .e_stop is a "property"
instead of an "instance member".

> > > This approach has the advantage that you can
> > > add a ninth "dirty" bit to indicate that the "byte"
> > > in question needs to be written out.
>
> > What do you mean by "written out" to where?
>
> See above explanation - see also a recent thread here
> about "Python string immutability broken" where I posted the
> prototype ctypes code, if you are really interested...
>
> > > Is there not some OO way of hiding this
> > > bit banging complexity?
>
> > foo & bar is complex? So you want to replace foo + bar
> > as well with something? ;)
>
> > > Using getters and setters? - I tend to go "tilt"
> > > like a cheap slot machine when I read that stuff.
>
> > Getters setters? Where would that improve the situation
> > beside having to write lots of unneccessary code?
>
> Not necessarily unnecessary - the getters and setters could be
> used to actually do the i/o to the relevant card when anything
> makes an access to one of the bits on the memory representation
> of that card - that would obviate the necessity for a second thread...

Rather than directly using getters and setters, I'd go with property.
It (usually) makes a cleaner external interface of the class. And for
the mess of having to write lots of boilerplate codes, you _could_
dynamically generate the boilerplate code from a dictionary (of name
to bit position) and currying (or something to that effect).
Alternatively, you could also do some magic with getattr and setattr.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5.3: call for patches

2008-10-10 Thread troelswh
On Oct 7, 9:27 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> In principle, the release will include all changes that are already on
> the release25-maint branch in subversion [1]. If you think that specific
> changes should be considered, please create an issue in the bug tracker
> [2], and label it with the 2.5.3 version. Backports of changes that
> are already released in Python 2.6 but may apply to 2.5 are of
> particular interest.

There is a number of Python 2.5.2 security vulnerabilities registered
with CVE. It would be great if the 2.5.3 release included fixes for
all of these!

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3144
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3142
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2316
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2315
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1887
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1721
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1679

For some reason none of these have made it into Python security
advisories (http://www.python.org/news/security/), but many vendors
who ship Python have released patched versions already.

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


Modification of a urllib2 object ?

2008-10-10 Thread vincehofmeister
I have several ways to the following problem.

This is what I have:

...
import ClientForm
import BeautifulSoup from BeautifulSoup


request = urllib2.Request('http://form.com/)

self.first_object = urllib2.open(request)

soup = BeautifulSoup(self.first_object)

forms = ClienForm.ParseResponse(self.first_object)


Now, when I do this, forms returns an index errror because no forms
are returned, but the BeautifulSoup registers fine.

Now, when I switch the order to this:


import ClientForm
import BeautifulSoup from BeautifulSoup


request = urllib2.Request('http://form.com/)

self.first_object = urllib2.open(request)

forms = ClienForm.ParseResponse(self.first_object)

soup = BeautifulSoup(self.first_object)

Now, the form is returned correctly, but the BeautifulSoup objects
returns empty.

So what I can draw from this is both methods erase the properties of
the object, so i tried importing the copy module and uses
copy.deepcopy(self.first_object)...

this didn't work either.

Does anyone have any idea on this or what I should do so the object
does not get erased.

Thanks in advance for any advice in advance.



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


Re: python 3: sorting with a comparison function

2008-10-10 Thread bearophileHUGS
Kay Schluehr:
> Sometimes it helps when people just make clear how they use technical
> terms instead of invoking vague associations.

And generally Python docs can enjoy growing few thousands examples...

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


Re: python 3: sorting with a comparison function

2008-10-10 Thread Paul McGuire
On Oct 10, 12:22 pm, [EMAIL PROTECTED] wrote:
> On Oct 10, 8:35 am, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
> > On 9 Okt., 22:36, [EMAIL PROTECTED] wrote:
>
> > > Yes, that's a wonderful thing, because from the code I see around
> > > 99.9% of people see the cmp and just use it, totally ignoring the
> > > presence of the 'key' argument, that allows better and shorter
> > > solutions of the sorting problem.
>
> > Me too because I don't get this:
>
> > "key specifies a function of one argument that is used to extract a
> > comparison key from each list element: key=str.lower. The default
> > value is None."
>
> > Kay
>
> Don't know if further explanation is needed, but here is the deal:
>
> cmp is a function that receives two values and you return -1, 0 or 1
> depending if the first is smaller, equal or bigger. 99% of the time
> you will do some operation on the values that come in and then do a if
> statement with ">" or "<" and return -1,0,1.
>
> key is a function that receives one value and you return the value
> that you would normally compare against.
>
> Let me show an example:
>
> >>> data=[(4,'v'),(2,'x'),(1,'a')]
> >>> sorted(data)
>
> [(1, 'a'), (2, 'x'), (4, 'v')]
>
> OK, we sorted the data, but What if we want to sort by the letter
> instead of the number? Let's use cmp:
>
> >>> def comp(x, y):
>
>       key_of_x=x[1]
>       key_of_y=y[1]
>       if key_of_x < key_of_y:
>         return -1
>       elif key_of_x > key_of_y:
>         return 1
>       else:
>         return 0 #key_of_x == key_of_y
>
> >>> sorted(data,cmp=comp)
>
> [(1, 'a'), (4, 'v'), (2, 'x')]
>
> Very well, so how do we do this using key?
>
> >>> def keyfunc(x):
>
>       key_of_x=x[1]
>       return key_of_x
>
> >>> sorted(data,key=keyfunc)
>
> [(1, 'a'), (4, 'v'), (2, 'x')]
>
> Same output. Very good.
>
> (Of course a smart python developer would use the operator module so
> he doesn't even have to write keyfunc but this was just an example)
>
IIRC, the return values are not limited to -1, 0, and 1, but are more
like "any value less than 0", 0, and "any value greater than 0".  This
allows you to implement numeric cmp routines as:

def cmp(x,y):
  return x-y

or just:

cmp = lambda x,y: x-y

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


Where/how to propose an addition to a standard module?

2008-10-10 Thread Joe Strout
I would like to propose a new method for the string.Template class.   
What's the proper procedure for doing this?  I've joined the python- 
ideas list, but that seems to be only for proposed language changes,  
and my idea doesn't require any change to the language at all.


From , it sounds like the  
PEP process is appropriate here, though other PEPs (like  make it sound as though these are meant for proposals for "Python  
3000", which is not necessarily my intent.


Here's a brief sketch of my proposal, in case it helps:

Add a "match" function to string.Template, which takes a text string  
as a parameter.  If this text string can be matched to the template,  
by substituting some portion of the given string for each field of the  
template, then .match returns a dictionary, where each key is a field  
name and the value is the corresponding text from the input.  If the  
text string cannot be matched to the template, then .match returns None.


I understand that if I'm to write a PEP, I'll need to flesh this out  
considerably as per PEP 0001.  But that document also suggests first  
discussing it here.  I'm still a newbie (or actually, oldbie-turned- 
nonbie-turned-newbie-again), so I could use some advice.  What's the  
next step in advocating for this idea?


Thanks,
- Joe



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


Re: How to create a tuple quickly with list comprehension?

2008-10-10 Thread Hatem Nassrat
on Wed Jun 13 10:17:24 CEST 2007, Diez B. Roggisch deets at nospam.web.de wrote:
>markacy wrote:
>
>> On 13 Cze, 09:45, "fdu.xia... at gmail.com" > gmail.com> wrote:
>>> Hi all,
>>>
>>> I can use list comprehension to create list quickly. So I
>>> expected that I
>>> can created tuple quickly with the same syntax. But I
>>> found that the
>>> same syntax will get a generator, not a tuple. Here is my
>>> example:
>>>
>>> In [147]: a = (i for i in range(10))
>>>
>>> In [148]: b = [i for i in range(10)]
>>>
>>> In [149]: type(a)
>>> Out[149]: 
>>>
>>> In [150]: type(b)
>>> Out[150]: 
[...]
 
>> You should do it like this:
>> 
> a = tuple([i for i in range(10)])
> type(a)
>> 
[...]

>No need to create the intermediate list, a generator
>expression works just
>fine:
>
>a = tuple(i for i in range(10))


Well I have looked into this and it seems that using the list
comprehension is faster, which is reasonable since generators require
iteration and stop iteration and what not.

# If you really really want a tuple, use [24] style
# if you need a generator use [27] style (without the tuple keyword
# off course)

In [24]: %timeit tuple([x for x in range(1000)])
1 loops, best of 3: 185 ??s per loop

In [25]: %timeit tuple([x for x in range(1000)])
1000 loops, best of 3: 195 ??s per loop

In [26]: %timeit tuple([x for x in range(1000)])
1 loops, best of 3: 194 ??s per loop

#

In [27]: %timeit tuple((x for x in range(1000)))
1000 loops, best of 3: 271 ??s per loop

In [28]: %timeit tuple((x for x in range(1000)))
1000 loops, best of 3: 253 ??s per loop

In [29]: %timeit tuple((x for x in range(1000)))
1000 loops, best of 3: 276 ??s per loop

Thanks

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


Re: Python 2.5.3: call for patches

2008-10-10 Thread Michael Ströder
[EMAIL PROTECTED] wrote:
> On Oct 7, 9:27 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
>> In principle, the release will include all changes that are already on
>> the release25-maint branch in subversion [1]. If you think that specific
>> changes should be considered, please create an issue in the bug tracker
>> [2], and label it with the 2.5.3 version. Backports of changes that
>> are already released in Python 2.6 but may apply to 2.5 are of
>> particular interest.
> 
> There is a number of Python 2.5.2 security vulnerabilities registered
> with CVE. It would be great if the 2.5.3 release included fixes for
> all of these!
> 
> http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3144
> http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3142
> http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2316
> http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2315
> http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1887
> http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1721
> http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1679

Yes!

> For some reason none of these have made it into Python security
> advisories (http://www.python.org/news/security/), but many vendors
> who ship Python have released patched versions already.

Yes, this is strange. I asked for this a couple of weeks ago. That the
upstream release is behind the packages shipped by vendors regarding
security patches is pretty poor.

Ciao, Michael.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where/how to propose an addition to a standard module?

2008-10-10 Thread Skip Montanaro
> I would like to propose a new method for the string.Template class.  What's
> the proper procedure for doing this?

There is a python-ideas mailing list.  I think that's probably the
right place to start.
If it gets a generally favorable response there, adding a feature
request with an
implementation to the bug tracker (http://bugs.python.org/) would be the next
step.

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


Set Your EMAIL CLIENT dates correctly.

2008-10-10 Thread Hatem Nassrat
I am sure this has been ranted about. People who have their dates in
their client set to 2020 should be banned from using the internet,
unless they have a legitimate reason like doing y3k testing on the
Python Mailing list.

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


Re: Porn Addiction Solutions?

2008-10-10 Thread Aspersieman

On Fri, 10 Oct 2008 16:11:07 +0200, <[EMAIL PROTECTED]> wrote:


On Oct 10, 7:03 am, Um Jammer NATTY <[EMAIL PROTECTED]> wrote:

On Oct 10, 5:37 am, [EMAIL PROTECTED] wrote:

> It's very simple. You need to know the world is much more than the
> imaginery life you are looking. Spend some time in the feet of the
> Lord Jesus who would help you to come out of this trouble.

Does anyone else find it amusing that this poster assumes 'imaginary'
and the Lord Jesus are polar opposites???


I'm guessing...only you!
--
http://mail.python.org/mailman/listinfo/python-list


Nope, not only him.

On another note, why is this a discussion on c.l.p? Shouldn't we
discourage these kinds of posts?

Nicol

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


Re: Porn Addiction Solutions?

2008-10-10 Thread Reacher
On Oct 8, 2:07 pm, [EMAIL PROTECTED] wrote:
> Help, I'm addicted to porn. I've been spending a lot of time
> downloading hardcore porn and masturbating to it. It's ruining my
> life. I just found out that one of these sites somehow hacked my card
> and rang up $5K in charges which they won't even refund me. Even with
> that I haven't stopped my habit and it's only getting worse. How can I
> end this addiction?
>
> Any suggestions?

Try calling the base class constructor:
[code]
class Foo < Bar
  def initialize
super
  end
end
[/code]
oh wait ... nevermind
--
http://mail.python.org/mailman/listinfo/python-list


Re: python 3: sorting with a comparison function

2008-10-10 Thread Kay Schluehr
On 10 Okt., 20:38, [EMAIL PROTECTED] wrote:
> Kay Schluehr:
>
> > Sometimes it helps when people just make clear how they use technical
> > terms instead of invoking vague associations.
>
> And generally Python docs can enjoy growing few thousands examples...

Cleaning up and extending documentation is a large community effort
that requires an informational PEP for guidelines and management
support by the python-dev leads. The official documentation is ad hoc
and just about better than nothing. A Python documentation guideline
might also have positive impact on 3rd party package authors like us.

Generally Python has become a very well managed project. I hope the
docs as well as the stdlib will become the major concerns of Python
3.1.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modification of a urllib2 object ?

2008-10-10 Thread George Sakkis
On Oct 10, 2:32 pm, [EMAIL PROTECTED] wrote:
> I have several ways to the following problem.
>
> This is what I have:
>
> ...
> import ClientForm
> import BeautifulSoup from BeautifulSoup
>
> request = urllib2.Request('http://form.com/)
>
> self.first_object = urllib2.open(request)
>
> soup = BeautifulSoup(self.first_object)
>
> forms = ClienForm.ParseResponse(self.first_object)
>
> Now, when I do this, forms returns an index errror because no forms
> are returned, but the BeautifulSoup registers fine.

First off, please copy and paste working code; the above has several
syntax errors, so it can't raise IndexError (or anything else for that
matter).

> Now, when I switch the order to this:
>
> import ClientForm
> import BeautifulSoup from BeautifulSoup
>
> request = urllib2.Request('http://form.com/)
>
> self.first_object = urllib2.open(request)
>
> forms = ClienForm.ParseResponse(self.first_object)
>
> soup = BeautifulSoup(self.first_object)
>
> Now, the form is returned correctly, but the BeautifulSoup objects
> returns empty.
>
> So what I can draw from this is both methods erase the properties of
> the object,

No, that's not the case. What happens is that the http response object
returned by urllib2.open() is read by the ClienForm.ParseResponse or
BeautifulSoup - whatever happens first - and the second call has
nothing to read.

The easiest solution is to save the request object and call
urllib2.open twice. Alternatively check if ClientForm has a parse
method that accepts strings instead of urllib2 requests and then read
and save the html text explicitly:

>>> text = urllib2.open(request).read()
>>> soup = BeautifulSoup(text)
>>> forms = ClientForm.ParseString(text)

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


Re: python 3: sorting with a comparison function

2008-10-10 Thread Thomas Heller
[EMAIL PROTECTED] schrieb:
> Kay Schluehr:
>> Sometimes it helps when people just make clear how they use technical
>> terms instead of invoking vague associations.
> 
> And generally Python docs can enjoy growing few thousands examples...

Well, that may not be necessary.  But I think that a clear example how to use
the 'key=' parameter in the sort() and sorted() method/function is badly needed.

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


Using multiprocessing

2008-10-10 Thread nhwarriors
I am attempting to use the (new in 2.6) multiprocessing package to
process 2 items in a large queue of items simultaneously. I'd like to
be able to print to the screen the results of each item before
starting the next one. I'm having trouble with this so far.

Here is some (useless) example code that shows how far I've gotten by
reading the documentation:

from multiprocessing import Process, Queue, current_process

def main():
facs = []
for i in range(5,50005):
facs.append(i)

tasks = [(fac, (i,)) for i in facs]
task_queue = Queue()
done_queue = Queue()

for task in tasks:
task_queue.put(task)

for i in range(2):
Process(target = worker, args = (task_queue, 
done_queue)).start()

for i in range(len(tasks)):
print done_queue.get()

for i in range(2):
task_queue.put('STOP')

def worker(input, output):
for func, args in iter(input.get, 'STOP'):
result = func(*args)
output.put(result)

def fac(n):
f = n
for i in range(n-1,1,-1):
f *= i
return 'fac('+str(n)+') done on '+current_process().name

if __name__ == '__main__':
main()

This works great, except that nothing can be output until everything
in the queue is finished. I'd like to write out the result of fac(n)
for each item in the queue as it happens.

I'm probably approaching the problem all wrong - can anyone set me on
the right track?
--
http://mail.python.org/mailman/listinfo/python-list


Re: python 3: sorting with a comparison function

2008-10-10 Thread Terry Reedy

Kay Schluehr wrote:


Me too because I don't get this:

"key specifies a function of one argument that is used to extract a
comparison key from each list element: key=str.lower. The default
value is None."


I am not sure what you do not get, but it should say 'for example, 
key=str.lower."  None is the default value of key.


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


Read data from Serial Command

2008-10-10 Thread brianrpsgt1
I am new to scripting.  I am trying to read the settings from a serial
device using Python.  I have been able to successfully connect to the
device and change baud rate settings, ect... with PySerial.  I am
trying to send a command to the serial device and capture the returned
info, however, it is not working.  Code is below:

import serial
import time

s = serial.Serial(port=1, timeout=None, baudrate=9600)
print s
time.sleep(5)
print "Enter CFG"
s.write('CFG')
print "Change baud"
s.baudrate=115200
print s
time.sleep(5)
print "New line"
s.write('\n')


time.sleep(2)
print "Show Encryption Setting"
nw = s.write('sh nw enc')

time.sleep(1)

print nw
s.close()

Thanks

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


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Gordon Allott
Aaron "Castironpi" Brady wrote:
> I see.  If I understand, you have a PyCObject in a dictionary.
> 
> Look at the 'ctypes' module and try calling PyCObject_AsVoidPtr.  Its
> return type should be 'c_void_p', and you can use 'result.value' to
> get the original pointer.
> --
> http://mail.python.org/mailman/listinfo/python-list

I have a hard time following that, if using ctypes you used PyDLL to
call PyCObject_AsVoidPtr on the PyCObject I already have surely it would
 give me back a pointer (void for sake of simplicity) but it would be a
pointer to a new PyCObject and thus calling result.value on it would
only return the memory address of the new PyCObject?
-- 
Gord Allott ([EMAIL PROTECTED])



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


Re: indexing arrays

2008-10-10 Thread Terry Reedy

John [H2O] wrote:

I'm having trouble slicing arrays:


If these are numpy arrays, as appears, rather that array module arrays, 
then the numpy list might be a better place.  In any case, using 'numpy' 
would have gotten the attention of someone scanning for posts about numpy.




I thought I could do the following:

i = array(range(140,149))
j = array(range(5,20))
a = acc[i,j]

Traceback (most recent call last):
  File "", line 1, in 
ValueError: shape mismatch: objects cannot be broadcast to a single shape

It's strange, because I can do this:


a = acc[140:148,5:19]


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


Re: Read data from Serial Command

2008-10-10 Thread Grant Edwards
On 2008-10-10, brianrpsgt1 <[EMAIL PROTECTED]> wrote:
> I am new to scripting.  I am trying to read the settings from a serial
> device using Python.  I have been able to successfully connect to the
> device and change baud rate settings, ect... with PySerial.  I am
> trying to send a command to the serial device and capture the returned
> info, however, it is not working.

It works fine for me.

I'm afraid you're going to have to be a bit more detailed than
"it is not working".  Are we supposed to guess what it's doing
and how that differs from what you want it to do?

Do you have the serial cable plugged in?

Is the device to which you're talking powered on?

> Code is below:
>
> import serial
> import time
>
> s = serial.Serial(port=1, timeout=None, baudrate=9600)
> print s
> time.sleep(5)
> print "Enter CFG"
> s.write('CFG')
> print "Change baud"
> s.baudrate=115200
> print s
> time.sleep(5)
> print "New line"
> s.write('\n')
>
>
> time.sleep(2)
> print "Show Encryption Setting"
> nw = s.write('sh nw enc')
>
> time.sleep(1)
>
> print nw
> s.close()

-- 
Grant Edwards   grante Yow! Well, I'm INVISIBLE
  at   AGAIN ... I might as well
   visi.compay a visit to the LADIES
   ROOM ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Read data from Serial Command

2008-10-10 Thread brianrpsgt1
Thanks for the message

What exactly is happening is that the return is "None" for the command
that I am sending.  If I connect through Hyperterminal and execute the
'sh nw enc' command, it returns 'WEP'

I have confirmed that the serial port is correct and open with the
s.isOpen() function.  Also able to successfully connect in
Hypterterminal with the same configuration settings.




Grant Edwards wrote:
> On 2008-10-10, brianrpsgt1 <[EMAIL PROTECTED]> wrote:
> > I am new to scripting.  I am trying to read the settings from a serial
> > device using Python.  I have been able to successfully connect to the
> > device and change baud rate settings, ect... with PySerial.  I am
> > trying to send a command to the serial device and capture the returned
> > info, however, it is not working.
>
> It works fine for me.
>
> I'm afraid you're going to have to be a bit more detailed than
> "it is not working".  Are we supposed to guess what it's doing
> and how that differs from what you want it to do?
>
> Do you have the serial cable plugged in?
>
> Is the device to which you're talking powered on?
>
> > Code is below:
> >
> > import serial
> > import time
> >
> > s = serial.Serial(port=1, timeout=None, baudrate=9600)
> > print s
> > time.sleep(5)
> > print "Enter CFG"
> > s.write('CFG')
> > print "Change baud"
> > s.baudrate=115200
> > print s
> > time.sleep(5)
> > print "New line"
> > s.write('\n')
> >
> >
> > time.sleep(2)
> > print "Show Encryption Setting"
> > nw = s.write('sh nw enc')
> >
> > time.sleep(1)
> >
> > print nw
> > s.close()
>
> --
> Grant Edwards   grante Yow! Well, I'm INVISIBLE
>   at   AGAIN ... I might as well
>visi.compay a visit to the LADIES
>ROOM ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: List Order of Initialization

2008-10-10 Thread Terry Reedy

Diez B. Roggisch wrote:

SamFeltus schrieb:

When a list initializes, will it always evaluate in order starting at
element 0 and finishing with the last element?

def f1(x):
return x + 2

def f2(x):
return x * 2

def f3(x):
return x * 3

the_list = [f1(7), f2(8), f3(4)]


Yes.


From the fine manual:

Python evaluates expressions from left to right. Notice that while 
evaluating an assignment, the right-hand side is evaluated before the 
left-hand side.


In the following lines, expressions will be evaluated in the arithmetic 
order of their suffixes:


expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2

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


Re: Python 2.5.3: call for patches

2008-10-10 Thread Terry Reedy

[EMAIL PROTECTED] wrote:

On Oct 7, 9:27 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:

In principle, the release will include all changes that are already on
the release25-maint branch in subversion [1]. If you think that specific
changes should be considered, please create an issue in the bug tracker
[2], and label it with the 2.5.3 version. Backports of changes that
are already released in Python 2.6 but may apply to 2.5 are of
particular interest.


There is a number of Python 2.5.2 security vulnerabilities registered
with CVE. It would be great if the 2.5.3 release included fixes for
all of these!

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3144


This references
http://bugs.python.org/issue2588
http://bugs.python.org/issue2589
both of which report fixes backported to 2.5.3
I will let you investigate whether the name is true of the rest, or 
whether someone should be nudged to either report or submit a patch

or help review a patch.


http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3142
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2316
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2315
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1887
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1721
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1679

For some reason none of these have made it into Python security
advisories (http://www.python.org/news/security/), but many vendors
who ship Python have released patched versions already.


Presumably, none were considered really critical, or the volunteer core 
developers were busy doing something else.  Also, release schedules differ.


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


python debugger tips?

2008-10-10 Thread just . another . random . user
Hi All,

I'm switching to python from perl, and like the language a ton, but I
find pdb and pydb to be vastly inferior debuggers to the perl version.

In particular, I've grown very used to stepping into arbitrary
functions interactively.  For instance, in perl you can do this:

casqa1:~> perl -de 42

Loading DB routines from perl5db.pl version 1.28
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1):   42
  DB<1> sub foo {return 42}



  DB<2> s foo()
main::((eval 7)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3:  foo();


  DB<<3>> s
main::foo((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:2):
2:  sub foo {return 42};
  DB<<3>>



Which is quite awesome; I don't have to restart the program if I want
to step through a given function call with a different set of values.

Does anyone have advice on any macros or something that i could use to
do this?

Additionally, what do people recommend as good "advanced" python
debugger guides?  Explaining breakpoints and all is useful, but I
really want to know how to make sophisticated macros and interact with
the debugger from the interactive prompt.

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


Re: List Order of Initialization

2008-10-10 Thread Ben Finney
SamFeltus <[EMAIL PROTECTED]> writes:

> When a list initializes, will it always evaluate in order starting at
> element 0 and finishing with the last element?
> 
> def f1(x):
> return x + 2
> 
> def f2(x):
> return x * 2
> 
> def f3(x):
> return x * 3
> 
> the_list = [f1(7), f2(8), f3(4)]

The new list won't even *exist* until all the arguments to the
constructor are evaluated; its initialiser will receive values, not
expressions. So, you're not asking about the behaviour of a list
initialising; you're asking about the order of evaluating an
expression.

In the above expression, yes, the several items in the literal list
expression will be evaluated left to right.

-- 
 \  “Two rules to success in life: 1. Don't tell people everything |
  `\you know.” —Sassan Tat |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: python debugger tips?

2008-10-10 Thread Stef Mientki

take a look at winpdb (which has no relation with Windows-OS !!

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


How to uninstall/update modules

2008-10-10 Thread pjacobi . de
Dear All,


It seems I don't understand how Python packages are handled. Here's my
specific problem

* I'm on Win32
* I've installed Enthought Python 2.5 because it got all the numerical
stuff included
* Later I tried to install Twisted 8.1

Twisted ended up in
C:\Python\Lib\site-packages\twisted

But there's an older Twisted included in the Enthought distribution.
It is at
C:\Python\Lib\site-packages\Twisted-2.5.0.0002-py2.5-win32.egg

Now, the strange thing (for the uninitiated, like me) is:

When doing a "import twisted" I get to older version in directory
Twisted-2.5.0.0002-py2.5-win32.egg, not the newer version in directory
twisted.

(A) What magic is going on in redirecting the import?
(B) How can I switch to use the newer version?


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


Re: Read data from Serial Command

2008-10-10 Thread Grant Edwards
On 2008-10-10, brianrpsgt1 <[EMAIL PROTECTED]> wrote:
> Thanks for the message
>
> What exactly is happening is that the return is "None" for the command
> that I am sending.  If I connect through Hyperterminal and execute the
> 'sh nw enc' command, it returns 'WEP'

It looks to me like you're never reading from the serial port.
All you're calling is write().

Also, are you sure that the device doesn't expect commands to
be termined by carriage returns?

>> > import serial
>> > import time
>> >
>> > s = serial.Serial(port=1, timeout=None, baudrate=9600)
>> > print s
>> > time.sleep(5)
>> > print "Enter CFG"
>> > s.write('CFG')
>> > print "Change baud"
>> > s.baudrate=115200
>> > print s
>> > time.sleep(5)
>> > print "New line"
>> > s.write('\n')
>> >
>> >
>> > time.sleep(2)
>> > print "Show Encryption Setting"
>> > nw = s.write('sh nw enc')
>> > time.sleep(1)

Try changing that to

 s.write('sh nw enc')
 time.sleep(1) 
 nw = s.read(1024)

>> > print nw
>> > s.close()

There are plenty of example programs at:

http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/

-- 
Grant Edwards   grante Yow!
  at   
BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


PIL on windows XP x64 (64-bit)?

2008-10-10 Thread Berco Beute
Has anybody here got PIL (the Image lib) working on Windows XP x64 (64-
bit)? There is no version available for that platform from
pythonware.com.

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


Re: Modification of a urllib2 object ?

2008-10-10 Thread vincehofmeister
On Oct 10, 1:02 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 10, 2:32 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > I have several ways to the following problem.
>
> > This is what I have:
>
> > ...
> > import ClientForm
> > import BeautifulSoup from BeautifulSoup
>
> > request = urllib2.Request('http://form.com/)
>
> > self.first_object = urllib2.open(request)
>
> > soup = BeautifulSoup(self.first_object)
>
> > forms = ClienForm.ParseResponse(self.first_object)
>
> > Now, when I do this, forms returns an index errror because no forms
> > are returned, but the BeautifulSoup registers fine.
>
> First off, please copy and paste working code; the above has several
> syntax errors, so it can't raise IndexError (or anything else for that
> matter).
>
>
>
> > Now, when I switch the order to this:
>
> > import ClientForm
> > import BeautifulSoup from BeautifulSoup
>
> > request = urllib2.Request('http://form.com/)
>
> > self.first_object = urllib2.open(request)
>
> > forms = ClienForm.ParseResponse(self.first_object)
>
> > soup = BeautifulSoup(self.first_object)
>
> > Now, the form is returned correctly, but the BeautifulSoup objects
> > returns empty.
>
> > So what I can draw from this is both methods erase the properties of
> > the object,
>
> No, that's not the case. What happens is that the http response object
> returned by urllib2.open() is read by the ClienForm.ParseResponse or
> BeautifulSoup - whatever happens first - and the second call has
> nothing to read.
>
> The easiest solution is to save the request object and call
> urllib2.open twice. Alternatively check if ClientForm has a parse
> method that accepts strings instead of urllib2 requests and then read
> and save the html text explicitly:
>
> >>> text = urllib2.open(request).read()
> >>> soup = BeautifulSoup(text)
> >>> forms = ClientForm.ParseString(text)
>
> HTH,
> George

request = urllib2.Request(settings.register_page)

self.url_obj = urllib2.urlopen(request).read()

soup = BeautifulSoup(self.url_obj);

forms = ClientForm.ParseResponse(self.url_obj,
backwards_compat=False)

print forms

images =  HtmlHelper.getCaptchaImages(soup)

self.webView.setHtml(str(soup))

#here we generate the popup dialog
Dialog = QtGui.QDialog()
ui = captcha_popup.Ui_Dialog()
ui.setupUi(Dialog, self)
ui.webView.setHtml(str(images[0]));
ui.webView_2.setHtml(str(images[1]));
Dialog.raise_()
Dialog.activateWindow()
Dialog.exec_()
Dialog.show()


Now I am getting this error:

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\PyQt4\POS Pounder\Oct7\oct.py",
line 1251, in createAccounts
forms = ClientForm.ParseResponse(self.url_obj,
backwards_compat=False)
  File "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg
\ClientForm.py", line 1054, in ParseResponse
AttributeError: 'str' object has no attribute 'geturl'
--
http://mail.python.org/mailman/listinfo/python-list


DNS Zonefile editor

2008-10-10 Thread preacher37
  I am looking for a web based zone file editor written in python to
be used to allow customers to modify their DNS records in a bind style
DNS system. Any info regarding existing projects is appreciated.
  Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Read data from Serial Command

2008-10-10 Thread brianrpsgt1
Gave that a shot  what is happening is that the script is
hanging.  Does that mean that the write function is not making it
through, thus there is nothing to return?



Grant Edwards wrote:
> On 2008-10-10, brianrpsgt1 <[EMAIL PROTECTED]> wrote:
> > Thanks for the message
> >
> > What exactly is happening is that the return is "None" for the command
> > that I am sending.  If I connect through Hyperterminal and execute the
> > 'sh nw enc' command, it returns 'WEP'
>
> It looks to me like you're never reading from the serial port.
> All you're calling is write().
>
> Also, are you sure that the device doesn't expect commands to
> be termined by carriage returns?
>
> >> > import serial
> >> > import time
> >> >
> >> > s = serial.Serial(port=1, timeout=None, baudrate=9600)
> >> > print s
> >> > time.sleep(5)
> >> > print "Enter CFG"
> >> > s.write('CFG')
> >> > print "Change baud"
> >> > s.baudrate=115200
> >> > print s
> >> > time.sleep(5)
> >> > print "New line"
> >> > s.write('\n')
> >> >
> >> >
> >> > time.sleep(2)
> >> > print "Show Encryption Setting"
> >> > nw = s.write('sh nw enc')
> >> > time.sleep(1)
>
> Try changing that to
>
>  s.write('sh nw enc')
>  time.sleep(1)
>  nw = s.read(1024)
>
> >> > print nw
> >> > s.close()
>
> There are plenty of example programs at:
>
> http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/
>
> --
> Grant Edwards   grante Yow!
>   at   
> BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-
>visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: python 3: sorting with a comparison function

2008-10-10 Thread Kay Schluehr
On 10 Okt., 23:04, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Kay Schluehr wrote:
> > Me too because I don't get this:
>
> > "key specifies a function of one argument that is used to extract a
> > comparison key from each list element: key=str.lower. The default
> > value is None."
>
> I am not sure what you do not get, but it should say 'for example,
> key=str.lower."  None is the default value of key.

See the discussion above.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >