Re: multiplication of lists of strings

2008-03-05 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(snip)
> 
> That reminds me:  Is there a generic 'relation' pattern/recipie, such
> as finding a computer that's "paired" with multiple users, each of who
> are "paired" with multiple computers, without maintaining dual-
> associativity?
> 
Yes : use a relational database.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Protocol for thread communication

2008-03-05 Thread bockman
On 5 Mar, 06:12, Michael Torrie <[EMAIL PROTECTED]> wrote:
> Does anyone have any recommended ideas/ways of implementing a proper
> control and status protocol for communicating with threads?  I have a
> program that spawns a few worker threads, and I'd like a good, clean way
> of communicating the status of these threads back to the main thread.
> Each thread (wrapped in a very simple class) has only a few states, and
> progress levels in those states.  And sometimes they can error out,
> although if the main thread knew about it, it could ask the thread to
> retry (start over).  How would any of you do this?  A callback method
> that the thread can call (synchronizing one-way variables isn't a
> problem)?  A queue?  How would the main thread check these things?
> Currently the main thread is polling some simple status variables.  This
> works, and polling will likely continue to be the simplest and easiest
> way, but simple status variables are very limited.  Are there any
> pythonic patterns people have developed for this.
>
> thanks.
>
> Michael

I've found that Queue.Queue objects are the easiest way to communicate
between threads in Python.
So, I'd suggets that you attach a Queue to each thread: the main
thread will use its queue to receive
the status messages from the other threads; the other threads will use
their queues to receive the retry command (or any other command that
may be needed) from the main thread.

Ciao
--
FB

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


draining pipes simultaneously

2008-03-05 Thread Dmitry Teslenko
Hello!
Here's my implementation of a function that executes some command and
drains stdout/stderr invoking other functions for every line of
command output:

def __execute2_drain_pipe(queue, pipe):
for line in pipe:
queue.put(line)
return

def execute2(command, out_filter = None, err_filter = None):
p = subprocess.Popen(command , shell=True, stdin = subprocess.PIPE, \
stdout = subprocess.PIPE, stderr = subprocess.PIPE, \
env = os.environ)

qo = Queue.Queue()
qe = Queue.Queue()

to = threading.Thread(target = __execute2_drain_pipe, \
args = (qo, p.stdout))
to.start()
time.sleep(0)
te = threading.Thread(target = __execute2_drain_pipe, \
args = (qe, p.stderr))
te.start()

while to.isAlive() or te.isAlive():
try:
line = qo.get()
if out_filter:
out_filter(line)
qo.task_done()
except Queue.Empty:
pass

try:
line = qe.get()
if err_filter:
err_filter(line)
qe.task_done()
except Queue.Empty:
pass

to.join()
te.join()
return p.wait()

Problem is my implementation is buggy and function hungs when there's
empty stdout/stderr. Can I have your feedback?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: draining pipes simultaneously

2008-03-05 Thread bockman
On 5 Mar, 10:33, "Dmitry Teslenko" <[EMAIL PROTECTED]> wrote:
> Hello!
> Here's my implementation of a function that executes some command and
> drains stdout/stderr invoking other functions for every line of
> command output:
>
> def __execute2_drain_pipe(queue, pipe):
>         for line in pipe:
>                 queue.put(line)
>         return
>
> def execute2(command, out_filter = None, err_filter = None):
>         p = subprocess.Popen(command , shell=True, stdin = subprocess.PIPE, \
>                 stdout = subprocess.PIPE, stderr = subprocess.PIPE, \
>                 env = os.environ)
>
>         qo = Queue.Queue()
>         qe = Queue.Queue()
>
>         to = threading.Thread(target = __execute2_drain_pipe, \
>                 args = (qo, p.stdout))
>         to.start()
>         time.sleep(0)
>         te = threading.Thread(target = __execute2_drain_pipe, \
>                 args = (qe, p.stderr))
>         te.start()
>
>         while to.isAlive() or te.isAlive():
>                 try:
>                         line = qo.get()
>                         if out_filter:
>                                 out_filter(line)
>                         qo.task_done()
>                 except Queue.Empty:
>                         pass
>
>                 try:
>                         line = qe.get()
>                         if err_filter:
>                                 err_filter(line)
>                         qe.task_done()
>                 except Queue.Empty:
>                         pass
>
>         to.join()
>         te.join()
>         return p.wait()
>
> Problem is my implementation is buggy and function hungs when there's
> empty stdout/stderr. Can I have your feedback?

The Queue.get method by default is blocking. The documentation is not
100% clear about that (maybe it should report
the full python definition of the function parameters, which makes
self-evident the default value) but if you do
help(Queue.Queue) in a python shell you will see it.

Hence, try using a timeout or a non-blocking get (but in case of a non
blocking get you should add a delay in the
loop, or you will poll the queues at naximum speed and maybe prevent
the other threads from accessing them).

Ciao
-
FB

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


Leopard and MySQL

2008-03-05 Thread arbo . newmedia
Hi,

can anyone help me with MySQL.
I've got Mac OSX Leopard and I'm trying to install MySQLdb for
Python.

I'm running build and it goes withous any errors and install.

But when I'm typing : import MySQLdb in IDLE I've got this:

Traceback (most recent call last):
  File "", line 1, in 
import MySQLdb
  File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line 19,
in 
  File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in

  File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in
__bootstrap__
ImportError: dlopen(/Users/lisek/.python-eggs/MySQL_python-1.2.2-py2.5-
macosx-10.3-fat.egg-tmp/_mysql.so, 2): Symbol not found:
_mysql_affected_rows
  Referenced from: /Users/lisek/.python-eggs/MySQL_python-1.2.2-py2.5-
macosx-10.3-fat.egg-tmp/_mysql.so
  Expected in: dynamic lookup

And I don't know what is wrong... ;/
-- 
http://mail.python.org/mailman/listinfo/python-list


Using re module better

2008-03-05 Thread Mike
I seem to fall into this trap (maybe my Perl background) where I want
to simultaneously test a regular expression and then extract its match
groups in the same action.  For instance:

if (match = re.search('(\w+)\s*(\w+)', foo)):
field1 = match.group(1)
field2 = match.group(2)
...

(compare to Perl:)

if($foo =~ /(\w+)\s*(\w+)/) {
$field1 = $1;
$field2 = $2;
...
}

Problem is, my python is invalid above.  What's the pythonic way to do
this?

Thanks in advance O Python Charmers

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


Re: draining pipes simultaneously

2008-03-05 Thread Dmitry Teslenko
On Wed, Mar 5, 2008 at 1:34 PM,  <[EMAIL PROTECTED]> wrote:
>  The Queue.get method by default is blocking. The documentation is not
>  100% clear about that (maybe it should report
>  the full python definition of the function parameters, which makes
>  self-evident the default value) but if you do
>  help(Queue.Queue) in a python shell you will see it.

>  Hence, try using a timeout or a non-blocking get (but in case of a non
>  blocking get you should add a delay in the
>  loop, or you will poll the queues at naximum speed and maybe prevent
>  the other threads from accessing them).

Thanks for advice! Finally I came up to following loop:

while to.isAlive() or te.isAlive():
try:
while True:
line = qo.get(False)
if out_filter:
out_filter(line)
except Queue.Empty:
pass

try:
while True:
line = qe.get(False)
if err_filter:
err_filter(line)
except Queue.Empty:
pass

Inserting delay in the beginning of the loop causes feeling of command
taking long to start and delay at the end of the loop may cause of
data loss when both thread became inactive during delay.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popening a process in a specific working directory

2008-03-05 Thread Sion Arrowsmith
Michael Torrie  <[EMAIL PROTECTED]> wrote:
>I'm currently using popen2.Popen4.  Is there a way to properly specify a
>particular working directory when launching a process in python?

Switch to using subprocess.Popen and specify the cwd argument.

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

Re: Using re module better

2008-03-05 Thread Tim Chase
> if (match = re.search('(\w+)\s*(\w+)', foo)):

Caveat #1:  use a raw string here
Caveat #2:  inline assignment is verboten

   match = re.search(r'(\w+)\s*(\w*+)', foo)
   if match:

> field1 = match.group(1)
> field2 = match.group(2)

This should then work more or less.  However, since you know 
there are two matches, you can just use

   field1, field2 = match.groups()


If the regexp is one you plan to reuse (or call in a loop), you 
can pre-compile it:

   r = re.compile(r'(\w+)\s*(\w*+)')
   for thing in bunch_of_things:
 m = r.search(thing)
 if m:
   field1, field2 = m.groups()
   do_something(field1, field2)

HTH,

-tkc



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


Re: Using re module better

2008-03-05 Thread Bruno Desthuilliers
Mike a écrit :
> I seem to fall into this trap (maybe my Perl background) where I want
> to simultaneously test a regular expression and then extract its match
> groups in the same action.
>  For instance:
> 
> if (match = re.search('(\w+)\s*(\w+)', foo)):
> field1 = match.group(1)
> field2 = match.group(2)
> ...
> 
> (compare to Perl:)
> 
> if($foo =~ /(\w+)\s*(\w+)/) {
> $field1 = $1;
> $field2 = $2;
> ...
> }
> 
> Problem is, my python is invalid above.  What's the pythonic way to do
> this?

In your above use case, the solution is obvious:

match = re.search('(\w+)\s*(\w+)', foo)
if match:
 field1 = match.group(1)
 field2 = match.group(2)


wrt/ assignement as an expression, this has been discussed about 2 days 
ago - look for a thread (badly) named "Is it possible to return a 
variable and use it...?"

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


Re: Altering imported modules

2008-03-05 Thread Bruno Desthuilliers
Tro a écrit :
> Hi, list.
> 
> I've got a simple asyncore-based server. However, I've modified the asyncore 
> module to allow me to watch functions as well as sockets. The modified 
> asyncore module is in a specific location in my project and is imported as 
> usual from my classes.
> 
> Now I'd like to use the tlslite library, which includes an asyncore mixin 
> class. However, tlslite imports "asyncore", which doesn't include my own 
> modifications.
> 
> I'd like to know if it's possible to make tlslite load *my* asyncore module 
> without changing any of the tlslite code.

Not sure this apply to your case (depends on how asyncore is implemented 
and the exact "modifications"), but monkeypatching is a possible solution.

http://en.wikipedia.org/wiki/Monkey_patch
http://wiki.zope.org/zope2/MonkeyPatch
http://mail.python.org/pipermail/python-dev/2008-January/076194.html


HTH

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


Re: draining pipes simultaneously

2008-03-05 Thread bockman

>
> Inserting delay in the beginning of the loop causes feeling of command
> taking long to start and delay at the end of the loop may cause of
> data loss when both thread became inactive during delay.

time.sleep() pauses ony the thread that executes it, not the
others. And queue objects can hold large amount of data (if you have
the RAM),
so unless your subprocess is outputting data very fast, you should not
have data loss.
Anyway, if it works for you ... :-)

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


Re: Leopard and MySQL

2008-03-05 Thread martin . laloux
There is a macpython list that you can consult at
http://www.nabble.com/Python---pythonmac-sig-f2970.html. When you
search for your problem
http://www.nabble.com/forum/Search.jtp?forum=2970&local=y&query=mysqldb

you have the solution
http://www.nickshanny.com/2007/10/os-x-105-python-and-mysqldb.html
-- 
http://mail.python.org/mailman/listinfo/python-list


documenting formal operational semantics of Python

2008-03-05 Thread gideon
Hi Everybody,

In the context of a master's thesis I'm currently looking into
Python's operational semantics. Even after extensive searching on the
web, I have not found any formal model of Python. Therefore I am
considering to write one myself. To make a more informed decision, I
would like to ask you:

What previous work has been done that I should be aware of? Currently
I have found exactly nothing on python itself. There is some
interesting work on other, related languages like Smalltalk.

Which version of Python is the most interesting? Python 3.0, although
it would be a moving target, seems promising. Because it will simplify
the language in some aspects by ditching backwards compatibility (e.g.
old style classes and coercion), the semantics will be more clean.

Of course I will get, answers to many questions I did not ask. In
fact, I would like you to vent your opinions on this matter.

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


Re: Leopard and MySQL

2008-03-05 Thread arbo . newmedia
On 5 Mar, 13:40, [EMAIL PROTECTED] wrote:
> There is a macpython list that you can consult 
> athttp://www.nabble.com/Python---pythonmac-sig-f2970.html. When you
> search for your 
> problemhttp://www.nabble.com/forum/Search.jtp?forum=2970&local=y&query=mysqldb
>
> you have the 
> solutionhttp://www.nickshanny.com/2007/10/os-x-105-python-and-mysqldb.html

Thanks a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python CGI & Webpage with an Image

2008-03-05 Thread rodmc
Hi,

I have a set of CGI scripts set up and in one page (which is stored in
an HTML file then printed via a python CGI) there is an image. However
the image never displays, can anyone recommend a way round this
problem?

Kind regards,

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


Better grammar.txt

2008-03-05 Thread MartinRinehart
I previously posted a link to an improved, HTML-based, hyperlinked
grammar.txt. Discard that one. This one is much better.

http://www.martinrinehart.com/articles/python-grammar.html

If you find it useful, thank Gabriel Genellina for encouraging me to
get it really right.

It includes three corrections to grammar.txt (imagnumber, xor_expr and
and_expr) that I've reported.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: draining pipes simultaneously

2008-03-05 Thread Dmitry Teslenko
On Wed, Mar 5, 2008 at 3:39 PM,  <[EMAIL PROTECTED]> wrote:
>  time.sleep() pauses ony the thread that executes it, not the
>  others. And queue objects can hold large amount of data (if you have
>  the RAM),
>  so unless your subprocess is outputting data very fast, you should not
>  have data loss.
>  Anyway, if it works for you ... :-)

After some testing I'll agree :) Without time.sleep() in main thread
python eats up all aviable processor time
-- 
http://mail.python.org/mailman/listinfo/python-list


Why """, not '''?

2008-03-05 Thread MartinRinehart
Why is """ the preferred delimiter for multi-line strings?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why """, not '''?

2008-03-05 Thread D'Arcy J.M. Cain
On Wed, 5 Mar 2008 06:56:24 -0800 (PST)
[EMAIL PROTECTED] wrote:
> Why is """ the preferred delimiter for multi-line strings?

Where did you see that?  The only place I saw it was the style guide
and it was only talking about docstrings.  Even there they used """ as
an example but the text talked about using triple quotes as opposed to
single quotes even when it is a single line docstring.  I don't think
that there is any preference for """ over ''' in general.  Pick one for
consistiency.

Note however that """ can't be confused with " followed by ' as in "'A'
is the first letter of the alphabet."

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why """, not '''?

2008-03-05 Thread George Sakkis
On Mar 5, 9:56 am, [EMAIL PROTECTED] wrote:
> Why is """ the preferred delimiter for multi-line strings?

Is it ? FWIW, I use single quotes whenever I can and double whenever I
have to (i.e. rarely).

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


Re: Protocol for thread communication

2008-03-05 Thread castironpi
On Mar 4, 11:12 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
> Does anyone have any recommended ideas/ways of implementing a proper
> control and status protocol for communicating with threads?  I have a
> program that spawns a few worker threads, and I'd like a good, clean way
> of communicating the status of these threads back to the main thread.
> Each thread (wrapped in a very simple class) has only a few states, and
> progress levels in those states.  And sometimes they can error out,
> although if the main thread knew about it, it could ask the thread to
> retry (start over).  How would any of you do this?  A callback method
> that the thread can call (synchronizing one-way variables isn't a
> problem)?  A queue?  How would the main thread check these things?
> Currently the main thread is polling some simple status variables.  This
> works, and polling will likely continue to be the simplest and easiest
> way, but simple status variables are very limited.  Are there any
> pythonic patterns people have developed for this.
>
> thanks.
>
> Michael

It depends on the messages.  In the general form, 'do X', there are a
lot of specifics relevant.

- Do X at time T

- for relative time T
- for absolute time T
- for conditional time T

While the wording is vague, it illustrates a contrast.

- Do X at time T

- relative T -- T is a time offset into the future
- absolute time T -- T is an absolute time, independent of the rest of
the program
- conditional time T -- under certain conditions, such as, right after
X' finishes, right before X' starts, if Y happens during X

In the big picture, the choice of X is irrelevant.  However, in a
particular PL, in a particular data, encapsulation, or abstraction
model, some combinations of ( T, X ) may be impossible, or even long-
winded, ugly, or wordy.

For the idealists, an pure imperative model may fit best, so let X =
'set a bit', and conflict never arises.  However such one restricts
the universal turing machine-- can only write one value, which may or
may not forbid solution of some problems.

But without loss of generality, for X in { set B, reset B }, you have
a conflict when for OPS= { (T1, X1), (T1, X2) }, X1= set B, and X2=
reset B.  Then there exists an ( X, T ) such that the semantics of the
program are undefined.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sympy: what's wrong with this picture?

2008-03-05 Thread Nanjundi
On Mar 4, 3:13 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Mar 4, 12:32 pm, Nanjundi <[EMAIL PROTECTED]> wrote:
>
>
> > Does seeding ( random.seed ) random with time fix this? It should.
>
> I suppose that depends on how long it takes factorint() to
> process a number. If the seed is reset before the next clock
> tick, you will get the same random numbers as the previous
> iteration.

Alright, then make it constant and don't worry about the clock tick.
>>> for i in xrange(10):
...   f1 = random.choice(f)
...   print f1,
...   f2 = random.choice(f)
...   print f2,
...   C = f1*f2
...   ff = None
...   ff = sympy.factorint(C)
...   print ff
...   random.seed(i)
...
5573 5171 [(5171, 1), (5573, 1)]
8537 7673 [(7673, 1), (8537, 1)]
2063 8573 [(2063, 1), (8573, 1)]
9551 9473 [(9473, 1), (9551, 1)]
2909 5659 [(2909, 1), (5659, 1)]
2897 1789 [(1789, 1), (2897, 1)]
6361 7541 [(6361, 1), (7541, 1)]
8017 8293 [(8017, 1), (8293, 1)]
3671 2207 [(2207, 1), (3671, 1)]
2803 9629 [(2803, 1), (9629, 1)]


> Frankly, I don't understand why factorint() reseeds at all.
Read the doc:
*The rho algorithm is a Monte Carlo method whose outcome can be
affected by changing the random seed value.  *

> Doesn't Random automatically initialize the seed?
> Doesn't constantly reseeding degrade the performance of the
> random number generator? With Robert Kern's patch, the reseeding
> is no longer a constant, fixing the immediate symptom.

Does it matter? The factorint reseeds using a constant seed (1234).

>
> But what if _I_ wanted to make a repeatable sequence for test
> purposes? Wouldn't factorint() destroy my attempt by reseeding
> on every call?

Repeatable sequence? save it and reuse!
Think about "What if"s doesn't get any work done.

-N

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


OT: Failed saving throw

2008-03-05 Thread Aahz
For anyone who hasn't heard, E. Gary Gygax died yesterday.  Some people
think we should build a tomb in his honor.  ;-)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Unit testing Web applications

2008-03-05 Thread Monica Leko
Hi!

Does Python has some testing frameworks for testing Web applications
(like Cactus and HttpUnit for Java), generating requests and checking
if the response is correct?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Failed saving throw

2008-03-05 Thread Dan Upton
On 5 Mar 2008 07:36:37 -0800, Aahz <[EMAIL PROTECTED]> wrote:
> For anyone who hasn't heard, E. Gary Gygax died yesterday.  Some people
>  think we should build a tomb in his honor.  ;-)

Yeah, I just saw a tribute on Order of the Stick:

http://www.giantitp.com/comics/oots0536.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python CGI & Webpage with an Image

2008-03-05 Thread Miki
Hello Rod,

> I have a set of CGI scripts set up and in one page (which is stored in
> an HTML file then printed via a python CGI) there is an image. However
> the image never displays, can anyone recommend a way round this
> problem?
We need more information, can you post a code snippet? error page? ...

My *guess* is that the web server don't know how to server the image
(wrong path configuration?)

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: Unit testing Web applications

2008-03-05 Thread Diez B. Roggisch
Monica Leko wrote:

> Hi!
> 
> Does Python has some testing frameworks for testing Web applications
> (like Cactus and HttpUnit for Java), generating requests and checking
> if the response is correct?

mechanize and webunit come to my mind.

Yet the most powerful will be selenium together with selenium-remote driven
via python. Don't forget to check out the brilliant selenium IDE.

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


ActiveX in Webpage?

2008-03-05 Thread Michael Wieher
Hello,

I'm trying to design a python-based web-app from scratch, based on a
standalone MFC application.
Obviously I'll be wrapping a lot of C++ functionality in custom extensions,
but is anyone aware of any documentation/techniques that could help me
"drop" an ActiveX control into a webpage, and just use it?
That, or, of course, a solid bit of writing detailing the idiosyncrasies of
MFC-wrapped Py-Extensions would be useful as well.

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

Re: Talking to a usb device (serial terminal)

2008-03-05 Thread blaine

> Because it is NOT 0x10007... It is OCTAL 010007 -- which just
> happens to map to hexadecimal 0x1007 
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/

oh wow - that makes a lot more sense. haha.

The processor we are going to use is ARM, yes, but our development at
this point (to keep it simple) is just on a simple linux laptop pc.

Thanks again for all the help :)
-- 
http://mail.python.org/mailman/listinfo/python-list


OT[1]: Re: SV: Polymorphism using constructors

2008-03-05 Thread Jeff Schwab
Dennis Lee Bieber wrote:
> On Tue, 4 Mar 2008 20:06:38 -0500, Tommy Grav <[EMAIL PROTECTED]> declaimed
> the following in comp.lang.python:
> 
>> SV = "Svar" is the Norwegian word for Reply.
>>
>   Ah, good... In my working life, "SV" => "Space Vehicle", often used
> to differentiate between the base satellite and "PL" Payload (the part
> that earns the money)

Which is which?  Aren't those both part of the space vehicle?  Btw, do 
you work for government or industry?  Do you enjoy  working with the 
space program?  I've heard only indirect reviews, and they've been mixed.

[1] "Av Emne," according to the free online translater.
http://www.tranexp.com:2000/Translate/result.shtml
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why """, not '''?

2008-03-05 Thread MartinRinehart


D'Arcy J.M. Cain wrote:
> Where did you see that?  The only place I saw it was the style guide
> and it was only talking about docstrings.

PEP 8 and 257, and you're right, they are both about docstrings.

Also, I'd never seen an example of the triple apostrophe form until I
dove
into the formal syntax specification.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better grammar.txt

2008-03-05 Thread MartinRinehart
[EMAIL PROTECTED] wrote:
> It includes three corrections to grammar.txt (imagnumber, xor_expr and
> and_expr) that I've reported.

Make that four corrections. Add augop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Short confusing example with unicode, print, and __str__

2008-03-05 Thread Gerard Brunick
I really don't understand the following behavior:

 >>> class C(object):
... def __init__(self, s): self.s = s
... def __str__(self): return self.s
...
 >>> cafe = unicode("Caf\xe9", "Latin-1")
 >>> c = C(cafe)
 >>> print "Print using c.s:", c.s
Print using c.s: Café
 >>> print "Print using just c:", c
Print using just c: Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
position 3: ordinal not in range(128)
 >>> str(c)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
position 3: ordinal not in range(128)

Why would "print c.s" work but the other two cases throw an exception?
Any help understanding this would be greatly appreciated.

Thanks in advance,
Gerard
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Short confusing example with unicode, print, and __str__

2008-03-05 Thread Gary Herron
Gerard Brunick wrote:
> I really don't understand the following behavior:
>
>  >>> class C(object):
> ... def __init__(self, s): self.s = s
> ... def __str__(self): return self.s
> ...
>  >>> cafe = unicode("Caf\xe9", "Latin-1")
>  >>> c = C(cafe)
>  >>> print "Print using c.s:", c.s
> Print using c.s: Café
>  >>> print "Print using just c:", c
> Print using just c: Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
> position 3: ordinal not in range(128)
>  >>> str(c)
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
> position 3: ordinal not in range(128)
>
> Why would "print c.s" work but the other two cases throw an exception?
> Any help understanding this would be greatly appreciated.
>
> Thanks in advance,
> Gerard
>   
It's the difference between how __str__ and __repr__  act on strings.

Here's s simpler example

 >>> d=unicode("Caf\xe9", "Latin-1")
 >>> repr(d)
"u'Caf\\xe9'"
 >>> str(d)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
position 3: ordinal not in range(128)

Gary Herron




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


What is a class?

2008-03-05 Thread castironpi
What is a class that is not a module?
-- 
http://mail.python.org/mailman/listinfo/python-list


Dual look-up on keys?

2008-03-05 Thread castironpi
I want to hash values to keys.  How do the alternatives compare?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using re module better

2008-03-05 Thread castironpi
On Mar 5, 6:12 am, Tim Chase <[EMAIL PROTECTED]> wrote:
> > if (match = re.search('(\w+)\s*(\w+)', foo)):
>
> Caveat #1:  use a raw string here
> Caveat #2:  inline assignment is verboten
>
>    match = re.search(r'(\w+)\s*(\w*+)', foo)
>    if match:
>
> >     field1 = match.group(1)
> >     field2 = match.group(2)
>
> This should then work more or less.  However, since you know
> there are two matches, you can just use
>
>    field1, field2 = match.groups()
>
> If the regexp is one you plan to reuse (or call in a loop), you
> can pre-compile it:
>
>    r = re.compile(r'(\w+)\s*(\w*+)')
>    for thing in bunch_of_things:
>      m = r.search(thing)
>      if m:
>        field1, field2 = m.groups()
>        do_something(field1, field2)
>
> HTH,
>
> -tkc

Opposed is to mimic MatchGroup that doesn't do anything, and returns
from a non-match call, field1, field2 = match.groups() or [ Dummy,
Dummy ], and similarly ...= [ None, None ].

On another note, why do people X, Y, and Z, including me, all hate to
write a= b(); if a: a.something()?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dual look-up on keys?

2008-03-05 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> I want to hash values to keys.  How do the alternatives compare?

http://catb.org/~esr/faqs/smart-questions.html
-- 
http://mail.python.org/mailman/listinfo/python-list


change user-agent

2008-03-05 Thread davidj411
I came across this post on the net and wanted to know what was meant
by down-level module.

So, how can we change the User-Agent? If we don't want to change the
headers using a lower-level module such as httplib, the solution is
quite easy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: documenting formal operational semantics of Python

2008-03-05 Thread davidj411
Python 3.0 might end up better, but converting all those scripts will
be a chore.
I'd be curious to know how that will be done.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why """, not '''?

2008-03-05 Thread Matthew Woodcraft
<[EMAIL PROTECTED]> wrote:
> Why is """ the preferred delimiter for multi-line strings?

One advantage is that a dumb syntax highlighter is more likely to cope
well if the content includes an apostrophe.

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


Re: What is a class?

2008-03-05 Thread Paul McGuire
On Mar 5, 12:50 pm, [EMAIL PROTECTED] wrote:
> What is a class that is not a module?

Please stop posting these one-liner beginner questions.  If you can
type it in one line, you can enter it on the Google.com or Ask.com
query page and get a wealth of *existing* information, from tutorials,
documentation, online presentations.  If you are able to phrase such a
question, you are capable of doing a little research and
experimentation on your own.

These posts translate to "I'm too lazy to use Google, or too cheap to
buy a Python book, or too lazy to read it, or too impatient to do my
own experimenting - much better to just post on c.l.py and have the
answer spoon-fed to me!"

I refuse to spoon feed you the answer to this question when plenty of
supporting material is already available.

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


Embedding vs Configuring Python build

2008-03-05 Thread [EMAIL PROTECTED]
I am using Python in an application that cannot depend on an existing
Python installation or require Python to
be installed. The application itself should not have an install
procedure, but rather should be runnable from any
location in the file system.

Ideally I would prefer not to embed at all, but would rather prefer to
configure. I found a couple of discussions on the
default sys.path in the archive and am currently reading through the
Py_GetPath. The path logic seems pretty specific to the platform,
whereas I would want it to be relative regardless of platform. I
figure that if I can just get to
my own site.py/sitecustomize.py then I'm in business.

This is what I wan't to achieve:

* The python executable location should be used to determine dynamic
libraries
* The python exe location should be used to determine standard library
scripts
* site.py should be executed rather than the shell if no parameters
are specified

Is it possible to change the build configuration of Python to support
this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: documenting formal operational semantics of Python

2008-03-05 Thread Paul Rubin
gideon <[EMAIL PROTECTED]> writes:
> In the context of a master's thesis I'm currently looking into
> Python's operational semantics. Even after extensive searching on the
> web, I have not found any formal model of Python. Therefore I am
> considering to write one myself. 

I doubt if anything serious has been done in that area, and I don't
think Python culture operates like that very much.  Python programming
tends to use informal processes with a lot of reliance on test-driven
development and unit tests, rather than formal specifications.  A lot
of the operational behavior that people rely on basically comes from
accidents of implementation, e.g. file descriptors being closed
automatically when the last reference goes away.  But of course that
should not be included in a formal semantics, yet that means the
semantics wouldn't describe actual production programs out there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a class?

2008-03-05 Thread castironpi
On Mar 5, 1:29 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Mar 5, 12:50 pm, [EMAIL PROTECTED] wrote:
>
> > What is a class that is not a module?
>
> Please stop posting these one-liner beginner questions.  If you can
> type it in one line, you can enter it on the Google.com or Ask.com
> query page and get a wealth of *existing* information, from tutorials,
> documentation, online presentations.  If you are able to phrase such a
> question, you are capable of doing a little research and
> experimentation on your own.
>
> These posts translate to "I'm too lazy to use Google, or too cheap to
> buy a Python book, or too lazy to read it, or too impatient to do my
> own experimenting - much better to just post on c.l.py and have the
> answer spoon-fed to me!"
>
> I refuse to spoon feed you the answer to this question when plenty of
> supporting material is already available.

In the future, shall I assume that other readers here have no ideas
(on this, read *ever*), that haven't already been published?  'Cause I
have.

For instance, in this example, I've tried a few approaches that didn't
turn out well.

Do you want a comparison of existing solutions?  Do you have a proof
that they exhaust the solution space?

I'm willing to address convention, in serial or parallel--- (change
subject to 'what goes on newsgroups'?), but it's not clear from fact
what assumption who has made.

Next time, why don't you say, "How much experience do you have?", or
"What level should I gear my answer toward?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dual look-up on keys?

2008-03-05 Thread castironpi
On Mar 5, 1:13 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
> > I want to hash values to keys.  How do the alternatives compare?
>
> http://catb.org/~esr/faqs/smart-questions.html

... without extending the whole way to a full relational database?
-- 
http://mail.python.org/mailman/listinfo/python-list


Def generating a function to be ran in another context

2008-03-05 Thread Marcelo de Moraes Serpa
I'd like a certain function to generate a method for another class and this
new method to be called in the context of the "new" class. Is it possible
with Python?

Thanks,

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

Bit twiddling floating point numbers

2008-03-05 Thread [EMAIL PROTECTED]
Hi All

Is there a simple way to twiddle the bits of a float? In particular, I
would like to round my float to the n most significant bits.

For example - 0.123 in binary is 0.00011
Rounding to 4 bits I get 0.0001.

I can pack and unpack a float into a long
e.g.
struct.unpack('I',struct.pack('f',0.123))[0]
but then I'm not sure how to work with the resulting long.

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


Re: documenting formal operational semantics of Python

2008-03-05 Thread Matthew Woodcraft
gideon  <[EMAIL PROTECTED]> wrote:
> In the context of a master's thesis I'm currently looking into
> Python's operational semantics. Even after extensive searching on the
> web, I have not found any formal model of Python. Therefore I am
> considering to write one myself. To make a more informed decision, I
> would like to ask you:

[...]

> Which version of Python is the most interesting? Python 3.0, although
> it would be a moving target, seems promising. Because it will simplify
> the language in some aspects by ditching backwards compatibility (e.g.
> old style classes and coercion), the semantics will be more clean.

Why not start with a common subset? Presumably the easiest thing will
be to start with a small core of the language and work up anyway. It
might turn out that all the interesting work has been done by the time
2.x/3.x makes any difference.

-M-

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


Re: sympy: what's wrong with this picture?

2008-03-05 Thread Mensanator
On Mar 5, 9:29 am, Nanjundi <[EMAIL PROTECTED]> wrote:
> On Mar 4, 3:13 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > On Mar 4, 12:32 pm, Nanjundi <[EMAIL PROTECTED]> wrote:
>
> > > Does seeding ( random.seed ) random with time fix this? It should.
>
> > I suppose that depends on how long it takes factorint() to
> > process a number. If the seed is reset before the next clock
> > tick, you will get the same random numbers as the previous
> > iteration.
>
> Alright, then make it constant and don't worry about the clock tick.

Reseeding with a constant always sets the sequence to the same
starting
point.

>>> for i in xrange(10):
>
> ...   f1 = random.choice(f)
> ...   print f1,
> ...   f2 = random.choice(f)
> ...   print f2,
> ...   C = f1*f2
> ...   ff = None
> ...   ff = sympy.factorint(C)
> ...   print ff
> ...   random.seed(i)
> ...
> 5573 5171 [(5171, 1), (5573, 1)]
> 8537 7673 [(7673, 1), (8537, 1)]
> 2063 8573 [(2063, 1), (8573, 1)]
> 9551 9473 [(9473, 1), (9551, 1)]
> 2909 5659 [(2909, 1), (5659, 1)]
> 2897 1789 [(1789, 1), (2897, 1)]
> 6361 7541 [(6361, 1), (7541, 1)]
> 8017 8293 [(8017, 1), (8293, 1)]
> 3671 2207 [(2207, 1), (3671, 1)]
> 2803 9629 [(2803, 1), (9629, 1)]
>
> > Frankly, I don't understand why factorint() reseeds at all.
>
> Read the doc:
> *    The rho algorithm is a Monte Carlo method whose outcome can be
> affected by changing the random seed value.  *

But that doesn't give it the right to mess with the state
of the random number generator _I'm_ using. Had I actually
known what was happening, I could have saved the state of
my random number generator s=random.getstate() and then restored
it after calling factorint(), random.setstate(s).

import sympy   # with RK's patch removed
import time
import random

f = [i for i in sympy.primerange(1000,1)]

for i in xrange(10):
  f1 = random.choice(f)
  print f1,
  f2 = random.choice(f)
  print f2,
  C = f1*f2
  ff = None
  rs = random.getstate()
  ff = sympy.factorint(C)
  random.setstate(rs)
  print ff

5669 3863 [(3863, 1), (5669, 1)]
1973 5431 [(1973, 1), (5431, 1)]
7577 6089 [(6089, 1), (7577, 1)]
8761 4957 [(4957, 1), (8761, 1)]
4153 2719 [(2719, 1), (4153, 1)]
4999 5669 [(4999, 1), (5669, 1)]
8863 5417 [(5417, 1), (8863, 1)]
7151 7951 [(7151, 1), (7951, 1)]
7867 9887 [(7867, 1), (9887, 1)]
9283 5227 [(5227, 1), (9283, 1)]

Of course, this is new as of Python 2.4, so if factorint()
tried to save & restore state, sympy wouldn't work on Python
2.3 or earlier.

If I'm reading RK's patch correctly, he doesn't reseed the
random number generator, he creates a new random object that
maintains it's own state that can be freely seeded to any
value without disturbing the state of my random number generator.

>
> > Doesn't Random automatically initialize the seed?
> > Doesn't constantly reseeding degrade the performance of the
> > random number generator? With Robert Kern's patch, the reseeding
> > is no longer a constant, fixing the immediate symptom.
>
> Does it matter?

I was wrong. It is a constant, just not 1234. If that's what
factorint() needs, fine. As long as it maintains a seperate state
than the one I'm using.

> The factorint reseeds using a constant seed (1234).

Not now it doesn't:

@@ -92,8 +92,8 @@ def pollard_pm1(n, B=10, seed=1234):

 """
 from math import log
-random.seed(seed + B)
-a = random.randint(2, n-1)
+prng = random.Random(seed + B)
+a = prng.randint(2, n-1)
 for p in sieve.primerange(2, B):
 e = int(log(B, p))
 a = pow(a, p**e, n)

>
> > But what if _I_ wanted to make a repeatable sequence for test
> > purposes? Wouldn't factorint() destroy my attempt by reseeding
> > on every call?
>
> Repeatable sequence? save it and reuse!

As part of my resolution to tone down my attitude,
I won't even reply to that.

> Think about "What if"s doesn't get any work done.

?

>
> -N

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


Re: Bit twiddling floating point numbers

2008-03-05 Thread Grant Edwards
On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Is there a simple way to twiddle the bits of a float? In particular, I
> would like to round my float to the n most significant bits.
>
> For example - 0.123 in binary is 0.00011
> Rounding to 4 bits I get 0.0001.
>
> I can pack and unpack a float into a long
> e.g.
> struct.unpack('I',struct.pack('f',0.123))[0]
> but then I'm not sure how to work with the resulting long.
>
> Any suggestions?

Just use the bitwise and/or/not operators: & | ~

-- 
Grant Edwards   grante Yow! Half a mind is a
  at   terrible thing to waste!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bit twiddling floating point numbers

2008-03-05 Thread Grant Edwards
On 2008-03-05, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

>> Any suggestions?
>
> Just use the bitwise and/or/not operators: & | ~

Oh, I forgot to mention the shift operators << and >>

-- 
Grant Edwards   grante Yow! All of life is a blur
  at   of Republicans and meat!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bit twiddling floating point numbers

2008-03-05 Thread [EMAIL PROTECTED]
On Mar 5, 10:48 pm, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-03-05, Grant Edwards <[EMAIL PROTECTED]> wrote:
>
> > On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> >> Any suggestions?
>
> > Just use the bitwise and/or/not operators: & | ~
>
> Oh, I forgot to mention the shift operators << and >>
>
> --
> Grant Edwards   grante Yow! All of life is a blur
>   at   of Republicans and meat!
>visi.com

thanks for the reply but I'm still unsure as to how to continue. Using
the bitwise operators will help me deal with integers but I really
want to work with floats. For instance - which bits do I twiddle to
round my float to the nearest number of bits?

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


Re: Bit twiddling floating point numbers

2008-03-05 Thread Grant Edwards
On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> thanks for the reply but I'm still unsure as to how to
> continue. Using the bitwise operators will help me deal with
> integers but I really want to work with floats.

In your original post, you said that you've got the values as
integers.

> For instance - which bits do I twiddle to round my float to
> the nearest number of bits?

The format of a float (actually Python uses doubles) depends on
your platform, but in all likelihood it's the IEEE-754 64-bit
format.

googling for "IEEE-754 format" finds some good references:

 http://en.wikipedia.org/wiki/IEEE_floating-point_standard
 http://steve.hollasch.net/cgindex/coding/ieeefloat.html
 http://www.psc.edu/general/software/packages/ieee/ieee.html

-- 
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: Bit twiddling floating point numbers

2008-03-05 Thread Mark Dickinson
On Mar 5, 3:25 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> I can pack and unpack a float into a long
> e.g.
> struct.unpack('I',struct.pack('f',0.123))[0]
> but then I'm not sure how to work with the resulting long.
>
> Any suggestions?

One alternative to using struct is to use math.ldexp and math.frexp:

>>> m, e = frexp(pi)
>>> m
0.78539816339744828
>>> e
2
>>> int(m*2**53)
7074237752028440L

Then you can do your bit twiddling on int(m*2**53), before using
ldexp to 'repack' the float.

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


Re: What is a class?

2008-03-05 Thread Paul McGuire
On Mar 5, 2:04 pm, [EMAIL PROTECTED] wrote:
> On Mar 5, 1:29 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
>
> > On Mar 5, 12:50 pm, [EMAIL PROTECTED] wrote:
>
> > > What is a class that is not a module?
>
> > Please stop posting these one-liner beginner questions.  If you can
> > type it in one line, you can enter it on the Google.com or Ask.com
> > query page and get a wealth of *existing* information, from tutorials,
> > documentation, online presentations.  If you are able to phrase such a
> > question, you are capable of doing a little research and
> > experimentation on your own.
>
> > These posts translate to "I'm too lazy to use Google, or too cheap to
> > buy a Python book, or too lazy to read it, or too impatient to do my
> > own experimenting - much better to just post on c.l.py and have the
> > answer spoon-fed to me!"
>
> > I refuse to spoon feed you the answer to this question when plenty of
> > supporting material is already available.
>
> In the future, shall I assume that other readers here have no ideas
> (on this, read *ever*), that haven't already been published?  'Cause I
> have.
>
> For instance, in this example, I've tried a few approaches that didn't
> turn out well.
>
Fair game.  Capture one of these classes (or better, distill it down
to a *small* example demonstrating the problem), tell us what you are
trying to achieve, post it, AND tell us what is "not turning out
well."  (Your previous posts have done a poor job in providing one or
more of these elements.)

> Do you want a comparison of existing solutions?  Do you have a proof
> that they exhaust the solution space?
>
*I* don't want *any* such thing, especially on the topics of "what is
a class?" and "how is a class different from a module?", nor do I need
proof that the basic background info on this topic covers the
mainstream applications of classes and modules.  These are basic OO
concepts in Python.  Try googling "python object-oriented".  And if
there were some esoteric aspect of "what is a class?" that you want to
pursue that might not be covered in the available material, I would
expect one to include that in the original post.

> I'm willing to address convention, in serial or parallel--- (change
> subject to 'what goes on newsgroups'?), but it's not clear from fact
> what assumption who has made.
>
Since you did not elaborate on what your efforts were and the extent
they were undesirable (certainly useful info from someone honestly
interested in a helpful answer), I assumed you had made none.

> Next time, why don't you say, "How much experience do you have?", or
> "What level should I gear my answer toward?"
>
I put the onus on the poster to realize that the question they are
asking is in fact a basic concept, *especially* when the subject of
the question is captured in a built-in method, type, class, or
keyword.  Surely you are aware that Python has been around for a
number of years, and that in all that time, it is entirely likely that
the topic of "what is a class?" has been covered, in any number of the
tutorials and docs so charitably written by many of the contributors
in this newsgroup.

Please stop asking those people to further expend their time repeating
this work just for your benefit.  It is like arriving late to a
meeting, and asking everyone to stop and bring you up to speed on what
you missed, in effect saying, "My time is more valuable than yours, I
can't be bothered to arrive on time, or do even the simplest research
for myself."

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


Re: Def generating a function to be ran in another context

2008-03-05 Thread Terry Reedy

"Marcelo de Moraes Serpa" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| I'd like a certain function to generate a method for another class and 
this
| new method to be called in the context of the "new" class. Is it possible
| with Python?

Yes.

(Assuming I understand your question correctly.)



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


Re: Bit twiddling floating point numbers

2008-03-05 Thread Mensanator
On Mar 5, 2:25 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi All
>
> Is there a simple way to twiddle the bits of a float? In particular, I
> would like to round my float to the n most significant bits.
>
> For example - 0.123 in binary is 0.00011
> Rounding to 4 bits I get 0.0001.
>
> I can pack and unpack a float into a long
> e.g.
> struct.unpack('I',struct.pack('f',0.123))[0]
> but then I'm not sure how to work with the resulting long.
>
> Any suggestions?

Here's one.

>>> import gmpy

# create a  base 10 float
>>> f = gmpy.mpf('123.456')
>>> f
mpf('1.23456e2')

# format in base 2, fixed point
>>> f2 = gmpy.fdigits(f,2,0,0,99)
>>> f2
'011.01110100100001101010011010011101101100100010111'

# seperate the characteristic from the mantissa
>>> fs = f2.split('.')

# re-assemble with the mantissa truncated to desired # of bits
>>> f3 = fs[0]+'.'+fs[1][:4]
>>> f3
'011.0111'

# convert the string back to a base 10 float
>>> f4 = gmpy.mpf(f3,0,2)
>>> print f4
123.4375

# check: print as base 2 and see how many digits are past radix point
>>> print gmpy.fdigits(f4,2,0,0,99)
011.0111

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


Re: Dual look-up on keys?

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote:

> On Mar 5, 1:13 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] schrieb:
>>
>> > I want to hash values to keys.  How do the alternatives compare?
>>
>> http://catb.org/~esr/faqs/smart-questions.html
> 
> ... without extending the whole way to a full relational database?



You didn't bother following the link and reading the advice, did you? If 
you did, you haven't done a good job of following that advice.



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

Re: What is a class?

2008-03-05 Thread Mike Driscoll
On Mar 5, 12:50 pm, [EMAIL PROTECTED] wrote:
> What is a class that is not a module?

Why is a raven like a writing desk?

As for Python class information, I would recommend reading the
following sites:

http://docs.python.org/tut/node11.html
http://www.diveintopython.org/object_oriented_framework/defining_classes.html

And for modules, check these out:

http://docs.python.org/tut/node8.html
http://www.penzilla.net/tutorials/python/modules/

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


Re: for-else

2008-03-05 Thread Troels Thomsen

>
> The primary use case is searching a container:
>
>   prep_tasks()
>   for item in container:
>   if predicate(item):
>   found_tasks()
>   break
>   else:
>   not_found_tasks()
>   follow_up_tasks
>

I've found myself mimicing this again and again in c, and was pleased to 
find it in python and use it regularely.
int i
for (i = 0 ; i < 10 ; ++i)
  blah
if i == 10
  not_found_tasks()

The discussion of words is silly. My surprise about "else following a for 
loop what the heck " lasted excactly as long as it takes to read 
this sentence.


tpt


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


Re: What is a class?

2008-03-05 Thread castironpi
> > > > What is a class that is not a module?
>
> > I'm willing to address convention, in serial or parallel--- (change
> > subject to 'what goes on newsgroups'?), but it's not clear from fact
> > what assumption who has made.
>
> Since you did not elaborate on what your efforts were and the extent
> they were undesirable (certainly useful info from someone honestly
> interested in a helpful answer), I assumed you had made none.

I agree.  To one of my friends, there's plenty of information in the
context that isn't a newsgroup.  So I'll state more about my
background.

Classes and modules are really similar.  In Python they're really
*really* similar.

Actually, at this point, that observation may have more of a
subjective component than I'm used to asserting.  I pause here for
corroboration and others' perspectives.  Aren't they?
-- 
http://mail.python.org/mailman/listinfo/python-list


Please keep the full address

2008-03-05 Thread D'Arcy J.M. Cain
On Wed, 5 Mar 2008 13:38:59 -0800 (PST)
Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Mar 5, 12:50 pm, [EMAIL PROTECTED] wrote:

I'm not sure why you change the address like this but could you please
include the full address.  Those of us who identify the time wasters
would also like to drop the responses to their posts and changing the
address makes this impossible.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dual look-up on keys?

2008-03-05 Thread castironpi
On Mar 5, 3:38 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote:
> > On Mar 5, 1:13 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] schrieb:
>
> >> > I want to hash values to keys.  How do the alternatives compare?
>
> >>http://catb.org/~esr/faqs/smart-questions.html
>
> > ... without extending the whole way to a full relational database?
>
> You didn't bother following the link and reading the advice, did you? If
> you did, you haven't done a good job of following that advice.

Well, obviously there's someone who's interested in computers and
programming that has a question.  Communication is not his forte, but
effort, willingness, devotion, and dedication are.  What should he do,
and what should the others, who are gifted speakers?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a class?

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 10:50:12 -0800, castironpi wrote:

> What is a class that is not a module?

Er, all of them?

I'm curious what classes you think are modules.


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


Re: Please keep the full address

2008-03-05 Thread Mike Driscoll
On Mar 5, 3:51 pm, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
> On Wed, 5 Mar 2008 13:38:59 -0800 (PST)
>
> Mike Driscoll <[EMAIL PROTECTED]> wrote:
> > On Mar 5, 12:50 pm, [EMAIL PROTECTED] wrote:
>
> I'm not sure why you change the address like this but could you please
> include the full address.  Those of us who identify the time wasters
> would also like to drop the responses to their posts and changing the
> address makes this impossible.
>
> --
> D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three


What are you talking about? I didn't change the address at all. I'm
not even sure what you mean. Are you talking about the post subject
line (which I have never touched in any post)? If you're talking about
the OP's email address, that's Google's fault for cropping them.

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


Re: Dual look-up on keys?

2008-03-05 Thread Grant Edwards
On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> I want to hash values to keys.  How do the alternatives compare?
>>
http://catb.org/~esr/faqs/smart-questions.html
>>
>>> ... without extending the whole way to a full relational database?
>>
>> You didn't bother following the link and reading the advice, did you? If
>> you did, you haven't done a good job of following that advice.
>
> Well, obviously there's someone who's interested in computers and
> programming that has a question.

It may be  obvious that he has a question.  It's not the least
bit obvious what that question is.

> Communication is not his forte, but effort, willingness,
> devotion, and dedication are.  What should he do, and what
> should the others, who are gifted speakers?

He should spend less time trying to generate "gifted speach"
and more time learning how to ask an understandable, meaningful
question.  The link which you ignored explains how to do that.

In your original post, it's not very clear what you mean by
"hash values to keys" means nor what alternatives you're asking
about. If you're trying to learn about hashing algorithms, then
google "hashing algorithms" and read the first half-dozen hits.

The first two are Wikipedia articles which are both quite good
and are almost certainly available in your native lanauge.

-- 
Grant Edwards   grante Yow! But they went to MARS
  at   around 1953!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using re module better

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 11:09:28 -0800, castironpi wrote:

> On another note, why do people X, Y, and Z, including me, all hate to
> write a= b(); if a: a.something()?


Is this a guessing game? You want us to guess why YOU hate to do 
something? Okay, I'm game for guessing games...

You were traumatized as a child by a newline byte, and now you try to 
write everything possible as a one-liner.

Am I close?

Speaking for myself, I *prefer* to separate the assignment from the 
comparison. I dislike greatly the syntax "if (a=b()): a.something()".


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


Re: sympy: what's wrong with this picture?

2008-03-05 Thread Nanjundi
On Mar 5, 3:34 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Mar 5, 9:29 am, Nanjundi <[EMAIL PROTECTED]> wrote:
>
> > On Mar 4, 3:13 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > > On Mar 4, 12:32 pm, Nanjundi <[EMAIL PROTECTED]> wrote:
>
> > > > Does seeding ( random.seed ) random with time fix this? It should.
>
> > > I suppose that depends on how long it takes factorint() to
> > > process a number. If the seed is reset before the next clock
> > > tick, you will get the same random numbers as the previous
> > > iteration.
>
> > Alright, then make it constant and don't worry about the clock tick.
>
> Reseeding with a constant always sets the sequence to the same
> starting
> point.
>

Right, not a good idea.

>
>
> >>> for i in xrange(10):
>
> > ...   f1 = random.choice(f)
> > ...   print f1,
> > ...   f2 = random.choice(f)
> > ...   print f2,
> > ...   C = f1*f2
> > ...   ff = None
> > ...   ff = sympy.factorint(C)
> > ...   print ff
> > ...   random.seed(i)
> > ...
> > 5573 5171 [(5171, 1), (5573, 1)]
> > 8537 7673 [(7673, 1), (8537, 1)]
> > 2063 8573 [(2063, 1), (8573, 1)]
> > 9551 9473 [(9473, 1), (9551, 1)]
> > 2909 5659 [(2909, 1), (5659, 1)]
> > 2897 1789 [(1789, 1), (2897, 1)]
> > 6361 7541 [(6361, 1), (7541, 1)]
> > 8017 8293 [(8017, 1), (8293, 1)]
> > 3671 2207 [(2207, 1), (3671, 1)]
> > 2803 9629 [(2803, 1), (9629, 1)]
>
> > > Frankly, I don't understand why factorint() reseeds at all.
>
> > Read the doc:
> > *The rho algorithm is a Monte Carlo method whose outcome can be
> > affected by changing the random seed value.  *
>
> But that doesn't give it the right to mess with the state
> of the random number generator _I'm_ using. Had I actually
> known what was happening, I could have saved the state of
> my random number generator s=random.getstate() and then restored
> it after calling factorint(), random.setstate(s).
>
> import sympy   # with RK's patch removed
> import time
> import random
>
> f = [i for i in sympy.primerange(1000,1)]
>
> for i in xrange(10):
>   f1 = random.choice(f)
>   print f1,
>   f2 = random.choice(f)
>   print f2,
>   C = f1*f2
>   ff = None
>   rs = random.getstate()
>   ff = sympy.factorint(C)
>   random.setstate(rs)
>   print ff
>
> 5669 3863 [(3863, 1), (5669, 1)]
> 1973 5431 [(1973, 1), (5431, 1)]
> 7577 6089 [(6089, 1), (7577, 1)]
> 8761 4957 [(4957, 1), (8761, 1)]
> 4153 2719 [(2719, 1), (4153, 1)]
> 4999 5669 [(4999, 1), (5669, 1)]
> 8863 5417 [(5417, 1), (8863, 1)]
> 7151 7951 [(7151, 1), (7951, 1)]
> 7867 9887 [(7867, 1), (9887, 1)]
> 9283 5227 [(5227, 1), (9283, 1)]
>
> Of course, this is new as of Python 2.4, so if factorint()
> tried to save & restore state, sympy wouldn't work on Python
> 2.3 or earlier.
>
> If I'm reading RK's patch correctly, he doesn't reseed the
> random number generator, he creates a new random object that
> maintains it's own state that can be freely seeded to any
> value without disturbing the state of my random number generator.
>
>
>
> > > Doesn't Random automatically initialize the seed?
> > > Doesn't constantly reseeding degrade the performance of the
> > > random number generator? With Robert Kern's patch, the reseeding
> > > is no longer a constant, fixing the immediate symptom.
>
> > Does it matter?
>
> I was wrong. It is a constant, just not 1234. If that's what
> factorint() needs, fine. As long as it maintains a seperate state
> than the one I'm using.
>
> > The factorint reseeds using a constant seed (1234).
>
> Not now it doesn't:

:)

>
> @@ -92,8 +92,8 @@ def pollard_pm1(n, B=10, seed=1234):
>
>  """
>  from math import log
> -random.seed(seed + B)
> -a = random.randint(2, n-1)
> +prng = random.Random(seed + B)
> +a = prng.randint(2, n-1)
>  for p in sieve.primerange(2, B):
>  e = int(log(B, p))
>  a = pow(a, p**e, n)
>
>
>
> > > But what if _I_ wanted to make a repeatable sequence for test
> > > purposes? Wouldn't factorint() destroy my attempt by reseeding
> > > on every call?
>
> > Repeatable sequence? save it and reuse!
>
> As part of my resolution to tone down my attitude,
> I won't even reply to that.
>
Thanks.

> > Think about "What if"s doesn't get any work done.
>
> ?
nevermind.

>
>
>
> > -N

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


Re: Dual look-up on keys?

2008-03-05 Thread castironpi
On Mar 5, 3:38 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote:
> > On Mar 5, 1:13 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] schrieb:
>
> >> > I want to hash values to keys.  How do the alternatives compare?
>
> >>http://catb.org/~esr/faqs/smart-questions.html
>
> > ... without extending the whole way to a full relational database?
>
> You didn't bother following the link and reading the advice, did you? If
> you did, you haven't done a good job of following that advice.

Well, obviously there's someone who's interested in computers and
programming that has a question.  Communication is not his forte, but
effort, willingness, devotion, and dedication are.  What should he do,
and what should the others, who are gifted speakers?
-- 
http://mail.python.org/mailman/listinfo/python-list


re: What is a class?

2008-03-05 Thread Michael Wieher
You import classes from modules.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Dual look-up on keys?

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 13:52:38 -0800, castironpi wrote:

> On Mar 5, 3:38 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote:
>> > On Mar 5, 1:13 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> >> [EMAIL PROTECTED] schrieb:
>>
>> >> > I want to hash values to keys.  How do the alternatives compare?
>>
>> >>http://catb.org/~esr/faqs/smart-questions.html
>>
>> > ... without extending the whole way to a full relational database?
>>
>> You didn't bother following the link and reading the advice, did you?
>> If you did, you haven't done a good job of following that advice.
> 
> Well, obviously there's someone who's interested in computers and
> programming that has a question.  Communication is not his forte, but
> effort, willingness, devotion, and dedication are.  What should he do,


Read the "Smart Questions" page and follow the advice in it.

Sheesh.



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

Re: What is a class?

2008-03-05 Thread Paul McGuire
On Mar 5, 3:49 pm, [EMAIL PROTECTED] wrote:
>
> Classes and modules are really similar.  In Python they're really
> *really* similar.
>
> Actually, at this point, that observation may have more of a
> subjective component than I'm used to asserting.  I pause here for
> corroboration and others' perspectives.  Aren't they?

If all you use classes for is for the purpose of a namespace, and all
of the methods in the class are just staticmethods, then you have used
a class to replicate a module, and they aren't just really, *really*
similar, they are the pretty much the same (at least BEHAVIORALLY
speaking).

But you can't do this:

import Zmodule
zobject = Zmodule()

If you are really using the OO model, and creating instances of
classes, then you *have* to use a class, a module wont cut it.  I'd
say, the less you use a class as an instance factory, the more similar
that class is to a module.

And you can't do this:

class Zclass:

import Zclass

If Zclass is not defined in your local script, you *have* to know what
module it is in, as in:

from zpackage.zmodule import Zclass

I have seen modules compared to classes that implement a Singleton
pattern.  In this case, a class is being used in an intentionally
degenerate way, such that it creates only one instance.  When doing
this in Python, one has the choice of replicating the standard pattern
with a class, or more simply, just using a module.  (Python's language/
object model also permits another option, usually referred to as the
Borg implementation, in which many Python names bind to many Python
instances, but all share the same underlying object state.  But this
is tangential to your question.)

In general I would say the similarity is a behavioral one, an artifact
of the language implementation.  Modules are for code packaging and
namespace definition, classes are for type definition and object
modeling.

For more discussions about how similar classes are to modules, you
might google for "Python singleton".

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


Re: What is a class?

2008-03-05 Thread castironpi
On Mar 5, 3:58 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Wed, 05 Mar 2008 10:50:12 -0800, castironpi wrote:
> > What is a class that is not a module?
>
> Er, all of them?
>
> I'm curious what classes you think are modules.
>
> --
> Steven

Thank you for your time in entertaining my questions so far.

Functions are first-class objects.
Modules are first-class objects.
Classes are first-class objects.

There's even a ModuleType in 'types'.

>>> set( dir(type('None',(),{})) )- set( dir( ModuleType ) )
{'__module__', '__weakref__'}

How superficial are the differences?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dual look-up on keys?

2008-03-05 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> On Mar 5, 3:38 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote:
>>> On Mar 5, 1:13 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
 [EMAIL PROTECTED] schrieb:
> I want to hash values to keys.  How do the alternatives compare?
 http://catb.org/~esr/faqs/smart-questions.html
>>> ... without extending the whole way to a full relational database?
>> You didn't bother following the link and reading the advice, did you? If
>> you did, you haven't done a good job of following that advice.
> 
> Well, obviously there's someone who's interested in computers and
> programming that has a question.  Communication is not his forte, but
> effort, willingness, devotion, and dedication are.  What should he do,

Effort, willingness & devotion? Certainly - but only to provoke, mislead 
and twaddle.

You have recieved more than enough earnest efforts to be helped, and yet 
proven again and again that you aren't worth these very efforts.

Luckily, this group is nice enough to not let your attitude poison it.

*plonk*

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


Re: What is a class?

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 13:49:20 -0800, castironpi wrote:

> Classes and modules are really similar.  In Python they're really
> *really* similar.

Yes they are.

Both are namespaces. The very last line of the Zen of Python says:

>>> import this
...
Namespaces are one honking great idea -- let's do more of those!


http://en.wikipedia.org/wiki/Namespace



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


Re: Why """, not '''?

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 19:19:08 +, Matthew Woodcraft wrote:

> <[EMAIL PROTECTED]> wrote:
>> Why is """ the preferred delimiter for multi-line strings?
> 
> One advantage is that a dumb syntax highlighter is more likely to cope
> well if the content includes an apostrophe.

But if the content contains double-quote marks, the "dumb syntax 
highligher" is more likely to cope well if you use '''. And, let's be 
realistic here, a "dumb syntax highlighter" is more likely to not cope 
well with triple-quote strings *at all*.

Python treats ' and " symmetrically. There is no difference between them, 
except that:

(1) to type " requires using the shift-key, typing ' does not (on English 
QWERTY keyboards at least);

(2) in some typefaces " (double-quote) may be confused with '' (two 
single-quotes); and

(3) they look different.

Pretty basic stuff really.


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


Identifying messages in a thread (was: Please keep the full address)

2008-03-05 Thread Ben Finney
"D'Arcy J.M. Cain" <[EMAIL PROTECTED]> writes:

> On Wed, 5 Mar 2008 13:38:59 -0800 (PST)
> Mike Driscoll <[EMAIL PROTECTED]> wrote:
> > On Mar 5, 12:50 pm, [EMAIL PROTECTED] wrote:
> 
> I'm not sure why you change the address like this but could you
> please include the full address.

It's a misfeature of Google's mail interface. The poster to whom
you're responding could choose a different mail interface, but you'll
have a difficult time convincing them of that.

> Those of us who identify the time wasters would also like to drop
> the responses to their posts and changing the address makes this
> impossible.

Not at all. AFAIK the messages from Google mail correctly include the
'In-Reply-To' field or the 'References' field in the message header.
So, you can know by those fields whether a message is part of a thread
you've previously identified.

-- 
 \ "I wish there was a knob on the TV to turn up the intelligence. |
  `\  There's a knob called 'brightness' but it doesn't work."  -- |
_o__)  Eugene P. Gallagher |
Ben Finney <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dual look-up on keys?

2008-03-05 Thread castironpi
On Mar 5, 4:00 pm, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > I want to hash values to keys.  How do the alternatives compare?
>
> http://catb.org/~esr/faqs/smart-questions.html
>
> >>> ... without extending the whole way to a full relational database?
>
> >> You didn't bother following the link and reading the advice, did you? If
> >> you did, you haven't done a good job of following that advice.
>
> > Well, obviously there's someone who's interested in computers and
> > programming that has a question.
>
> It may be  obvious that he has a question.  It's not the least
> bit obvious what that question is.
>
> > Communication is not his forte, but effort, willingness,
> > devotion, and dedication are.  What should he do, and what
> > should the others, who are gifted speakers?
>
> He should spend less time trying to generate "gifted speach"
> and more time learning how to ask an understandable, meaningful
> question.  The link which you ignored explains how to do that.
>
> In your original post, it's not very clear what you mean by
> "hash values to keys" means nor what alternatives you're asking
> about. If you're trying to learn about hashing algorithms, then
> google "hashing algorithms" and read the first half-dozen hits.
>
> The first two are Wikipedia articles which are both quite good
> and are almost certainly available in your native lanauge.
>
> --
> Grant Edwards                   grante             Yow! But they went to MARS
>                                   at               around 1953!!
>                                visi.com            

Are you vegetarian?  A little off topic.

Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a)
is also in it, and maps to the same object?
-- 
http://mail.python.org/mailman/listinfo/python-list


system32 directory

2008-03-05 Thread Robert Dailey
Hi,

Is there a way to get the System32 directory from windows through python?
For example, in C++ you do this by calling GetSystemDirectory(). Is there an
equivalent Python function for obtaining windows installation dependent
paths?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Dual look-up on keys?

2008-03-05 Thread Vlastimil Brom
2008/3/5, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
>
> ...
> Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a)
> is also in it, and maps to the same object?
> ...
>

Well, it's probably not the most effective way, but one can use something
like:

>>> d={frozenset(("a","b")):7}
>>> d[frozenset(("b","a"))]
7
>>> d[frozenset(("b","a"))]=94
>>> d[frozenset(("a","b"))]
94
>>>

HTH

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

Re: Dual look-up on keys?

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 14:51:04 -0800, castironpi wrote:

> Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a)
> is also in it, and maps to the same object?

It would take you approximately five seconds to answer that question for 
yourself.

>>> D = {(1,2): "x"}
>>> D[(2,1)]
Traceback (most recent call last):
  File "", line 1, in 
KeyError: (2, 1)


You've already been plonked by one long-time regular today. Are you 
aiming to get plonked by *everybody*?

http://en.wikipedia.org/wiki/Plonk



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


Re: Dual look-up on keys?

2008-03-05 Thread Grant Edwards
On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Are you vegetarian?

Some days.

> A little off topic.

Ya think?

> Anyway, if (a,b) is a key in dictionary d, can it guarantee
> that (b,a) is also in it, and maps to the same object?

Do you not know how to run the Python interpreter?

  >>> d = {(1,2): "onetwo"}
  >>> (1,2) in d
  True
  >>> (2,1) in d
  False

Tuples are ordered, so why would you expect that the tuple
(a,b) be considered equal to the tuple (b,a)?  There is, of
course, the degenerate case where a and b are the same so that
the tuple (a,b) does equal (b,a):

  >>> t = (1,2,3)
  >>> a = t 
  >>> b = t
  >>> d = {(a,b): "hi there"}
  >>> (b,a) in d
  True

An unoderded collection of objects in Python is called a set,
but sets are mutable so they're not hashable:

  >>> s1 = set((1,2))
  >>> s2 = set((2,1))
  >>> s1 == s2
  True
  >>> d = {s1: "hi there"}
  Traceback (most recent call last):
File "", line 1, in ?
  TypeError: set objects are unhashable
  
To solve that problem, Python provides the immutable
"frozenset" type:

  >>> s1 = frozenset((1,2))
  >>> s2 = frozenset((2,1))
  >>> s1 == s2
  True
  >>> d = {s1: "hi there"}
  >>> s1 in d
  True
  >>> s2 in d
  True


See how much better a result you get when you ask an
understandble, specific, concrete question?

-- 
Grant Edwards   grante Yow!  Do I hear th'
  at   SPINNING of various
   visi.comWHIRRING, ROUND, and WARM
   WHIRLOMATICS?!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why """, not '''?

2008-03-05 Thread Matthew Woodcraft
Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
>On Wed, 05 Mar 2008 19:19:08 +, Matthew Woodcraft wrote:
>> One advantage is that a dumb syntax highlighter is more likely to cope
>> well if the content includes an apostrophe.

> But if the content contains double-quote marks, the "dumb syntax 
> highligher" is more likely to cope well if you use '''.

That's right. But apostrophes are rather more common than quote marks
in English text.

> And, let's be realistic here, a "dumb syntax highlighter" is more
> likely to not cope well with triple-quote strings *at all*.

In practice they often do the right thing, what with three being an odd
number.

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


Re: Why """, not '''?

2008-03-05 Thread Steven D'Aprano
On Wed, 05 Mar 2008 23:27:21 +, Matthew Woodcraft wrote:

> Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
>>On Wed, 05 Mar 2008 19:19:08 +, Matthew Woodcraft wrote:
>>> One advantage is that a dumb syntax highlighter is more likely to cope
>>> well if the content includes an apostrophe.
> 
>> But if the content contains double-quote marks, the "dumb syntax
>> highligher" is more likely to cope well if you use '''.
> 
> That's right. But apostrophes are rather more common than quote marks in
> English text.

Surely it would depend on the type of text: pick up any random English 
novel containing dialogue, and you're likely to find a couple of dozen 
pairs of quotation marks per page, against a few apostrophes.



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


access to base class __init__

2008-03-05 Thread sambo q
I got myself in jam trying to be too fancy with  threading.Thread
Docs say / remind to call the base __init__
but I can't fighure out how.

---
def main()
.
ls.listen(5)
key = ' '
#while key != EXITCHARCTER:
while stop_serving == False:
cs, raddr = ls.accept()
print "Main_Thread: ",cs, raddr
nt = client_socket_handler( cs, raddr )
print threading.enumerate()
key = getkey()

#ls.close()
time.sleep(4)
print "Server Exiting."

class client_socket_handler(threading.Thread):
def __init__(self, cs, remote_address):
???
self.threading.Thread.__init__(self,self.socket_handler,None,None)
self.socket = cs
self.rhost_addr = remote_address
print "client_socket_handler.__init__(): ", self.socket, 
self.rhost_addr
#t1 = threading.Thread( None,self.socket_handler, None, (5,78) )
#t1.start()
self.start()
print "client_socket_handler.__init__(): ", self.socket, 
self.rhost_addr
print "client_socket_handler.__init__(): enumerate()", 
threading.enumerate()

def socket_handler( self, invar, indict ):
threadname = self.getName()
print "\"%s started\"" % threadname
print "client_socket_handler.socket_handler() invar: ", invar
instr = self.socket.recv( 500 )
#print instr
req_lines = string.split( instr, "\r" )
for line in req_lines:
line.strip( "\n")
print req_lines
print len( instr )

--

self.threading.Thread.__init__()
self.Thread.__init__()
??
-- 
http://mail.python.org/mailman/listinfo/python-list


2nd CFP: DATICS 2008 - Design, Analysis and Tools for Integrated Circuits and Systems

2008-03-05 Thread ss . dtvcs
Apologies for any multiple copies received. We would appreciate it if
you could distribute
the following call for papers to any relevant mailing lists you know
of.

   2nd CALL FOR PAPERS
===
Special session: Design, Analysis and Tools for Integrated Circuits
and Systems

  DATICS 2008

 July 22-24, 2008 (Crete Island, Greece)
 http://digilander.libero.it/systemcfl/datics
===

Aims and Scope
--
The main target of the Special Session: DATICS 2008 of the WSEAS CSCC
multi-conference
(http://www.wseas.org/conferences/2008/greece/icc/) is to bring
together software/hardware
engineering researchers, computer scientists, practitioners and people
from industry to
exchange theories, ideas, techniques and experiences related to all
areas of design, analysis and
tools for integrated circuits (e.g. digital, analog and mixed-signal
circuits) and
systems (e.g. real-time, hybrid and embedded systems).
The special session also focuses on the field of formal methods and
low power design methodologies for integrated circuits.

Topics
--
Topics of interest include, but are not limited to, the following:
* digital, analog, mixed-signal designs and test
* RF design and test
* design-for-testability and built-in self test methodologies
* reconfigurable system design
* high-level synthesis
* EDA tools for design, testing and verification
* low power design methodologies
* network and system on-a-chip
* application-specific SoCs
* specification languages: SystemC, SystemVerilog and UML
* all areas of modelling, simulation and verification
* formal methods and formalisms (e.g. process algebras, petri-nets,
automaton theory and BDDs)
* real-time, hybrid and embedded systems
* software engineering (including real-time Java, real-time UML and
performance metrics)

Industrial Collaborators

DATICS 2008 is partnered with:
* CEOL: Centre for Efficiency-Oriented Languages "Towards improved
software timing",
  University College Cork, Ireland ( http://www.ceol.ucc.ie)
* International Software and Productivity Engineering Institute, USA
(http://www.intspei.com )
* Intelligent Support Ltd., United Kingdom (http://www.isupport-
ltd.co.uk)
* Minteos, Italy (http://www.minteos.com)
* M.O.S.T., Italy (http://www.most.it)
* Electronic Center, Italy (http://www.el-center.com)

DATICS 2008 is sponsored by:
1. LS Industrial Systems, South Korea (http://eng.lsis.biz)
2. Solari, Hong Kong (http://www.solari-hk.com)



Technical Program Committee
---
* Prof. Vladimir Hahanov, Kharkov National University of Radio
Electronics, Ukraine
* Prof. Paolo Prinetto, Politecnico di Torino, Italy
* Prof. Alberto Macii, Politecnico di Torino, Italy
* Prof. Joongho Choi, University of Seoul, South Korea
* Prof. Wei Li, Fudan University, China
* Prof. Michel Schellekens, University College Cork, Ireland
* Prof. Franco Fummi, University of Verona, Italy
* Prof. Jun-Dong Cho, Sung Kyun Kwan University, South Korea
* Prof. AHM Zahirul Alam, International Islamic University Malaysia,
Malaysia
* Prof. Gregory Provan, University College Cork, Ireland
* Dr. Emanuel Popovici, University College Cork, Ireland
* Dr. Jong-Kug Seon, Telemetrics Lab., LG Industrial Systems Co. Ltd.,
South Korea
* Dr. Umberto Rossi, STMicroelectronics, Italy
* Dr. Graziano Pravadelli, University of Verona, Italy
* Dr. Vladimir Pavlov, International Software and Productivity
Engineering Institute, USA
* Dr. Jinfeng Huang, Philips & LiteOn Digital Solutions Netherlands,
Advanced Research Centre,
The Netherlands
* Dr. Thierry Vallee, Georgia Southern University, Statesboro,
Georgia, USA
* Dr. Menouer Boubekeur, University College Cork, Ireland
* Dr. Ana Sokolova, University of Salzburg, Austria
* Dr. Sergio Almerares, STMicroelectronics, Italy
* Ajay Patel (Director), Intelligent Support Ltd, United Kingdom
* Monica Donno (Director), Minteos, Italy
* Alessandro Carlo (Manager), Research and Development Centre of FIAT,
Italy
* Yui Fai Lam (Manager), Microsystems Packaging Institute, Hong Kong
University of
   Science and Technology, Hong Kong

Important Dates
---
March 31, 2008: Deadline for submission of completed papers
May 1, 2008: Notification of acceptance/rejection to authors

Please visit our web-site for further information on the hosting
conference of DATICS,
submission guidelines, proceedings and publications and international
technical reviewers.

Best regards,

General Chair of DATICS: Dr. K.L. Man (University College Cork,
Ireland)
and
Organising Committee Chair: Miss Maria O'Keeffe (University College
Cork, Ireland)

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


Re: for-else

2008-03-05 Thread bearophileHUGS
On Mar 5, 10:44 pm, "Troels Thomsen"  wrote:
> > The primary use case is searching a container:
>
> >   prep_tasks()
> >   for item in container:
> >   if predicate(item):
> >   found_tasks()
> >   break
> >   else:
> >   not_found_tasks()
> >   follow_up_tasks
>
> I've found myself mimicing this again and again in c, and was pleased to
> find it in python and use it regularely.
> int i
> for (i = 0 ; i < 10 ; ++i)
>   blah
> if i == 10
>   not_found_tasks()
>
> The discussion of words is silly. My surprise about "else following a for
> loop what the heck " lasted excactly as long as it takes to read
> this sentence.
>
> tpt

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


Re: ActiveX in Webpage?

2008-03-05 Thread Andrew Warkentin
Michael Wieher wrote:

> Hello,
>
> I'm trying to design a python-based web-app from scratch, based on a 
> standalone MFC application.
> Obviously I'll be wrapping a lot of C++ functionality in custom 
> extensions, but is anyone aware of any documentation/techniques that 
> could help me "drop" an ActiveX control into a webpage, and just use it?
> That, or, of course, a solid bit of writing detailing the 
> idiosyncrasies of MFC-wrapped Py-Extensions would be useful as well.
>
> -Mike

I would recommend against embedding ActiveX controls, especially if this 
web application is public (if it is internal, it's not as much of a 
problem, but you still might have problems later if you ever want to 
migrate off Windows). ActiveX controls are not only Windows-specific, 
but (mostly) IE-specific as well. Since you are developing it from 
scratch, I would say that you should do it right and use AJAX, or 
possibly Flash or Java applets, all of which are reasonably portable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-05 Thread bearophileHUGS
Troels Thomsen:
> The discussion of words is silly. My surprise about "else following a for
> loop what the heck " lasted excactly as long as it takes to read
> this sentence.

Maybe I don't follow what you are saying, but well chosen words are a
very important part of a well designed API. If you take a look at the
Python developers mailing list you may see that people discuss days,
weeks to find the best naming for things.

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


Returning a byte buffer from C extension

2008-03-05 Thread forwardshortleg
Hello,

I am new to Python programming. So, kindly excuse me if I don't use
correct terminology  here below.

I am trying to write an extension function that returns an array of
bytes as shown in the example below:


static PyObject* GetByteBuffer(PyObject* self, PyObject* args)
{
char byteBuffer[100];

// do something to fill byteBuffer with values.

   return Py_BuildValue("y", byteBuffer);
}


Is this valid? I get a run time error in Python 2.5 (actually 2.6) and
Python 3.0 returns null terminated byte string.
My byte buffer may contain one or more zeros and I want is the entire
buffer regardless of its contents. How do I do it?

Thanks,

Eknath

P.S: I know that 2.6 & 3.0 are not meant for a newcomers like me.
Unfortunately 2.5.2 and older for windows are built using MSCVC 6.0
and they pose problems building extensions.
-- 
http://mail.python.org/mailman/listinfo/python-list


http://httpd.apache.org/docs/2.2/mod/mod_dbd.html

2008-03-05 Thread gert
Would anybody explain to me what needs to be done to have a DB-API 2.0
layer for this ?
And how many lines of code we are talking ?

http://httpd.apache.org/docs/2.2/mod/mod_dbd.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please keep the full address

2008-03-05 Thread D'Arcy J.M. Cain
On Wed, 5 Mar 2008 14:00:17 -0800 (PST)
Mike Driscoll <[EMAIL PROTECTED]> wrote:
> What are you talking about? I didn't change the address at all. I'm
> not even sure what you mean. Are you talking about the post subject
> line (which I have never touched in any post)? If you're talking about
> the OP's email address, that's Google's fault for cropping them.

I'm talking about castironpi.  I find his posts a waste of my time so I
have them filtered out along with a few others and I also filter out
responses by searching for his address in the body so changing it
defeats that. However, if it is something that you have no control over
I apologize for the noise.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a byte buffer from C extension

2008-03-05 Thread forwardshortleg
I just realized that I could do this as follows:

static PyObject* GetByteBuffer(PyObject* self, PyObject* args)
{
char byteBuffer[100];

// do something to fill byteBuffer with values.

   return Py_BuildValue("s#", byteBuffer, numberOfBytesToReturn);

}

Sorry for the unnecessary distraction.

Eknath


On Mar 5, 4:42 pm, [EMAIL PROTECTED] wrote:
> Hello,
>
> I am new to Python programming. So, kindly excuse me if I don't use
> correct terminology  here below.
>
> I am trying to write an extension function that returns an array of
> bytes as shown in the example below:
>
> static PyObject* GetByteBuffer(PyObject* self, PyObject* args)
> {
> char byteBuffer[100];
>
> // do something to fill byteBuffer with values.
>
>return Py_BuildValue("y", byteBuffer);
>
> }
>
> Is this valid? I get a run time error in Python 2.5 (actually 2.6) and
> Python 3.0 returns null terminated byte string.
> My byte buffer may contain one or more zeros and I want is the entire
> buffer regardless of its contents. How do I do it?
>
> Thanks,
>
> Eknath
>
> P.S: I know that 2.6 & 3.0 are not meant for a newcomers like me.
> Unfortunately 2.5.2 and older for windows are built using MSCVC 6.0
> and they pose problems building extensions.

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


Re: Identifying messages in a thread (was: Please keep the full address)

2008-03-05 Thread D'Arcy J.M. Cain
On Thu, 06 Mar 2008 09:36:29 +1100
Ben Finney <[EMAIL PROTECTED]> wrote:
> > Those of us who identify the time wasters would also like to drop
> > the responses to their posts and changing the address makes this
> > impossible.
> 
> Not at all. AFAIK the messages from Google mail correctly include the
> 'In-Reply-To' field or the 'References' field in the message header.
> So, you can know by those fields whether a message is part of a thread
> you've previously identified.

I don't want to have to tag every thread.  I just want to *plonk*
certain posters.

Anyway, I'll live with Google's failings I guess.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] Re: Why """, not '''?

2008-03-05 Thread Matt Nordhoff
Steven D'Aprano wrote:
> Surely it would depend on the type of text: pick up any random English 
> novel containing dialogue, and you're likely to find a couple of dozen 
> pairs of quotation marks per page, against a few apostrophes.

That's an idea... Write a novel in Python docstrings.

Someone make me go to bed now.
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Classes and modules are singletons?

2008-03-05 Thread Steven D'Aprano
I recall that Python guarantees that module objects are singletons, and 
that this must hold for any implementation, not just CPython: you can 
only ever create one instance of a module via the import mechanism. But 
my google-foo is obviously weak today, I cannot find where the Python 
language reference guarantees that. Can somebody please point me at the 
link making that guarantee?

(Note: you can create multiple modules with the same name and state using 
new.module. I don't think that counts, although it may be a good way to 
win bar bets with your Python buddies.)


But what about classes? Are they singletons? Obviously classes aren't 
Singleton classes, that is, given an arbitrary class C you can create 
multiple instances of C. But what about class objects themselves? I've 
found a few odd references to "classes are singletons", but nothing in 
the language reference.

I've done some experimentation, e.g.:

>>> import module
>>> from module import Class
>>> module.Class is Class
True


but I'm not sure if that's (1) meaningful or (2) implementation-specific.


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


RE: Unit testing Web applications

2008-03-05 Thread Ryan Ginstrom
> On Behalf Of Monica Leko
> Does Python has some testing frameworks for testing Web 
> applications (like Cactus and HttpUnit for Java), generating 
> requests and checking if the response is correct?

I have got a lot of traction using mechanize [1] with nose [2]. Of course
that still leaves out testing JavaScript. For that, something like PAMIE [3]
is one way to go.

[1] http://wwwsearch.sourceforge.net/mechanize/
[2] http://somethingaboutorange.com/mrl/projects/nose/
[3] http://pamie.sourceforge.net/

Here's an example of how I use mechanize + nose:

# test_index.py
from mechanize import Browser

class TestPageLoads:

def setup(self):
self.mech = Browser()
self.mech.set_handle_robots(False) # use thought and
consideration...

def test_nonexistent(self):
try:
response =
self.mech.open("http://honyaku-archive.org/nonexistent/";)
assert False, "Should have thrown here"
except Exception, e:
assert "404" in str(e), e

def test_index(self):
response = self.mech.open("http://honyaku-archive.org/";)
assert response.code == 200, response.code

def test_index_title(self):
response = self.mech.open("http://honyaku-archive.org/";)
assert self.mech.title().strip() == "Honyaku Archive :: Home",
self.mech.title()

Regards,
Ryan Ginstrom

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


Re: Dual look-up on keys?

2008-03-05 Thread castironpi
On Mar 5, 5:31 pm, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-03-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > Anyway, if (a,b) is a key in dictionary d, can it guarantee
> > that (b,a) is also in it, and maps to the same object?

Er... -specialized- dictionary d.

> To solve that problem, Python provides the immutable
> "frozenset" type:
>
>   >>> s1 = frozenset((1,2))
>   >>> s2 = frozenset((2,1))
>   >>> s1 == s2
>   True
>   >>> d = {s1: "hi there"}
>   >>> s1 in d
>   True
>   >>> s2 in d
>   True

Ah.  Perfect.  With this, I can just call frozenset on keys in
__setitem__ and __getitem__... (though at that, it may be easier
verbatim*.)

*loosely introduced terminology, roughly equivalent to 'spell it out
by hand each time'**.
**__delitem__ too.

Only thing is, that's an extra check if 'key' is iterable.

(Yes.  I realize this is a little scattered... it's my belief it's
intelligible by party X... if not stop now speak up.)

Goal:
assert d[1,2] is d[2,1]
assert d[1] is d[1]
assert d[a] is d[a]
assert d[a,b] is d[b,a]

Only problem is, if a is iterable, then its contents get hashed.  I
don't see the general way around this.

a= SomeList( [ 1,2,3 ] )
b= SomeList( [ 1,2,3 ] )
assert a is not b
d[a]= True
assert b not in d
#there's the hangup

It is my loss that M. Roggisch plonks me-- I will be deprived of his
perspective and contributions.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >