Implementing an 8 bit fixed point register

2008-07-01 Thread nickooooola
Hello to all
I'm about to write a simulator for a microcontroller in python
(why python? because I love it!!!)

but I have a problem.

The registry of this processor are all 8 bit long (and 10 bit for some
other strange register)
and I need to simulate the fixed point behaviour of the register,
and to access the single bit.

f.x. (this is a pseudo python session, only for understanding)

>>> reg1 = fixed_int(8)
>>> reg2 = fixed_int(10)
>>> reg1[0].set()
or
>>> reg1[0] = 1 # or True? how to rapresent a binary bit
>>> reg1[0]
1
>>> reg1[1]
0
>>> reg1[9]

>>> reg2 = 0x7FE   # in binary  110 , or 11 bit long
>>> reg2
0x7FE
#or 10, the memorization truncate the upper bits ( or perhaps
generate an exception?)
>>> reg2 += 0x02 #the result is 100, again not contained in 10 bit
>>> reg2
0x00
# truncated again
>>> myprocessor.flags['z']
1
# or True? Z flag indicated an overflow in arithmetic operations

Is possibile to do so in python?

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


Re: Are the following supported in scipy.sparse

2008-07-01 Thread Matt Nordhoff
dingo_1980 wrote:
> I wanted to know if scipy.sparse support or will support the following
> functions which are available in scipy.linalg or scipy or numpy:
> 
> Inverse
> Cholesky
> SVD
> multiply
> power
> append
> eig
> concatenate
> 
> Thanks...

You should probably ask on a SciPy mailing list.


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


how to judge urllib.Request is finished?

2008-07-01 Thread oyster
currently I am using
[code]
req=urllib2.Request(url)
data=''
if '' not in data:
fd=urllib2.urlopen(req)
data=fd.read()
time.sleep(10)
time.sleep(10)
blahblah
[/code]

Is there any other ready-to-use function? And what if the internet
connection is chocked so that the html page can not be loaded
entirely?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How make regex that means "contains regex#1 but NOT regex#2" ??

2008-07-01 Thread A.T.Hofkamp
On 2008-07-01, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I'm looking over the docs for the re module and can't find how to
> "NOT" an entire regex.

(?! R)

> How make regex that means "contains regex#1 but NOT regex#2" ?

(\1|(?!\2))

should do what you want.

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


Re: How make regex that means "contains regex#1 but NOT regex#2" ??

2008-07-01 Thread Paul McGuire
On Jul 1, 2:34 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> On 2008-07-01, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > I'm looking over the docs for the re module and can't find how to
> > "NOT" an entire regex.
>
> (?! R)
>
> > How make regex that means "contains regex#1 but NOT regex#2" ?
>
> (\1|(?!\2))
>
> should do what you want.
>
> Albert

I think the OP wants both A AND not B, not A OR not B.  If the OP want
to do re.match(A and not B), then I think this can be done as ((?!
\2)\1), but if he really wants CONTAINS A and not B, then I think this
requires 2 calls to re.search.  See test code below:

import re

def test(restr,instr):
print "%s match %s? %s" %
(restr,instr,bool(re.match(restr,instr)))

a = "AAA"
b = "BBB"

aAndNotB = "(%s|(?!%s))" % (a,b)

test(aAndNotB,"AAA")
test(aAndNotB,"BBB")
test(aAndNotB,"AAABBB")
test(aAndNotB,"zAAA")
test(aAndNotB,"CCC")

aAndNotB = "((?!%s)%s)" % (b,a)

test(aAndNotB,"AAA")
test(aAndNotB,"BBB")
test(aAndNotB,"AAABBB")
test(aAndNotB,"zAAA")
test(aAndNotB,"CCC")

def test2(arestr,brestr,instr):
print "%s contains %s but NOT %s? %s" % \
(instr,arestr,brestr,
 bool(re.search(arestr,instr) and
  not re.search(brestr,instr)))

test2(a,b,"AAA")
test2(a,b,"BBB")
test2(a,b,"AAABBB")
test2(a,b,"zAAA")
test2(a,b,"CCC")

Prints:

(AAA|(?!BBB)) match AAA? True
(AAA|(?!BBB)) match BBB? False
(AAA|(?!BBB)) match AAABBB? True
(AAA|(?!BBB)) match zAAA? True
(AAA|(?!BBB)) match CCC? True
((?!BBB)AAA) match AAA? True
((?!BBB)AAA) match BBB? False
((?!BBB)AAA) match AAABBB? True
((?!BBB)AAA) match zAAA? False
((?!BBB)AAA) match CCC? False
AAA contains AAA but NOT BBB? True
BBB contains AAA but NOT BBB? False
AAABBB contains AAA but NOT BBB? False
zAAA contains AAA but NOT BBB? True
CCC contains AAA but NOT BBB? False


As we've all seen before, posters are not always the most precise when
describing whether they want match vs. search.  Given that the OP used
the word "contains", I read that to mean "search".  I'm not an RE pro
by any means, but I think the behavior that the OP wants is given in
the last 4 tests, and I don't know how to do that in a single RE.

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


Re: how to judge urllib.Request is finished?

2008-07-01 Thread Marc 'BlackJack' Rintsch
On Tue, 01 Jul 2008 15:16:03 +0800, oyster wrote:

> currently I am using
> [code]
> req=urllib2.Request(url)
> data=''
> if '' not in data:
> fd=urllib2.urlopen(req)
> data=fd.read()
> time.sleep(10)
> time.sleep(10)
> blahblah
> [/code]

That looks very strange.  Why the ``if`` and the `sleep()`\s?  The ``if``
condition is always true, so it's completely unnecessary.  The `read()`
call is blocking, that means it returns iff the complete data is read.  So
there's no need to wait or to check if all is read.  If there's a problem
with the connection an exception should be raised by `urllib2`.

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


Re: Freeze problem with Regular Expression

2008-07-01 Thread Kirk
On Mon, 30 Jun 2008 13:43:22 -0700, John Machin wrote:

>> I reply here to all of you about such point: that's not important,
>> although I appreciate very much your suggestions! My point was
>> 'something that works in Perl, has problems in Python'.
> 
> It *is* important; our point was 'you didn't define "works", and it was

ok...

> near-impossible (without transcribing your regex into verbose mode) to
> guess at what you suppose it might do sometimes'.

fine: it's supposed to terminate! :-)

Do you think that hanging is an *admissible* behavior? Couldn't we learn 
something from Perl implementation?

This is my point.

Bye

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


Embedding Python

2008-07-01 Thread Marcin Krol

Hello everyone,

I'm trying to embed Python interpreter in C code, but in a specific way:
loading compiled bytecode into a memory location and executing it (don't
ask why, complicated reasons).

PyImport_ExecCodeModule seems like obvious candidate, docs say:

"Given a module name (possibly of the form package.module) and a code
object read from a Python bytecode file or obtained from the built-in
function compile(), load the module."

Code:

---cut---
#include 
#include 
#include 
#include 
#include 


int load_file(char *fname, unsigned char** result)
{
 int size = 0;
 FILE *f = fopen(fname, "rb");
 if (f == NULL)
 {
  *result = NULL;
 return -1;
 }
 fseek(f, 0, SEEK_END);
 size = ftell(f);
 *result = (unsigned char *) malloc(size+1);
 fseek(f, 0, SEEK_SET);
 size = fread(*result, sizeof(unsigned char), size, f);
 return size;
}

int main(int argc, char **argv)
{
int size;
unsigned char *python_code;
PyObject *mainobj;
size = load_file("multiply.pyc", &python_code);

Py_Initialize();
mainobj = PyImport_ExecCodeModule("multiply", (PyObject *)
python_code);
Py_Finalize();

}
---cut---

Compiling it following way works fine:

${CC} testit.c -g -o testit -I/usr/include/python2.4 -lpython2.4 -lm
-lutil -lpthread -ldl  -L/usr/lib/python2.4/config


However, the damn thing crashes on this call:

33  mainobj = PyImport_ExecCodeModule("multiply", (PyObject
*) python_code);
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x0804e7f6 in PyImport_ExecCodeModuleEx ()

The .pyc file woks just fine in Python interpreter:


import multiply
multiply.multiply()

The result of 12345 x 6789 : 83810205
83810205





What I am doing wrong? Please help.




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


Re: Functions associated with a class.

2008-07-01 Thread Bruno Desthuilliers

Kurda Yon a écrit :

Hi,

I start to learn the object oriented programing in Python. As far as I
understood, every class has a set of corresponding methods and
variables.


Every object has a set of attributes. Some of these attributes are 
methods (which are thmeselves objects too), some are not. Some are in 
fact attributes of the class of the object accessed thru the instance 
(mostly, the methods), some are instance-specific (mostly, non-methods).



For me it is easy to understand a method as a one-argument


Why "one-argument" ? A method can take as amny arguments as necessary.


function associated with a class.


s/class/object/. While methods are usually attributes of the class 
(accessed thru an instance), nothing prevents you from adding methods on 
a per-instance basis. This set aside, truth is that methods are just 
thin wrapper objects around a function, an instance and/or a class. The 
responsability of the method object is to delegate call to it's function 
object, inserting the instance (or the class in the case of a 
classmethod) as the first argument.




For example, if I call "x.calc" and
"y.calc" and if "x" and "y" belongs to different classes I, actually,
call to different function (the first one is associated with the first
class and the second one with the second class).


Here again, it's a bit more complex. But this is a correct enough 
description of the most common case.



If "x" and "y"
belongs to the same class, the "x.calc" and "y.calc" refer to the same
function


Usually, yes, but not necessarily:

def yadda(obj):
   print "yadda(%s)" % obj

class Bar(object):
   def foo(self):
   print "foo(%s)" % self

b1 = Bar()
b1.foo()

b2 = Bar()
b2.foo()

b2.foo = yadda.__get__(b2, type(b2))
b2.foo()



(but called with different arguments ("x" and "y",
respectively)).

In the above described case we have one-argument function. But what
should we do if we one two have a two-argument function.


class Baaz(object):
def gluuk(self, other):
print "gluuk(%s, %s)" % (self, other)


For example,
we want to have a method "calc" which take two objects and returns one
value. How do we call this method? Like "x&y.calc"?


class X(object):
   def calc(self, other):
   # this is silly since we don't use neither
   # self nor other, but you get the idea
   return "one value"

Nope.


Or just calc(x,y)?


That's one of the possibilities, but it's not a method anymore, just a 
plain function. The others solutions are either "x.calc(y)" or 
"y.calc(x)". Now which one is the right one depends on what calc do and 
how it relates to the respective classes of x and y. If the operation is 
really a responsability of one of the classes, then it should be a 
method of this class. Else it's probably better to stick to a plain 
function.



In the case of the one-argument functions Pythons automatically decide
which function to call


Actually, x.calc() is (usually) a shortcut for type(x).calc(x), so you 
could say that in fact *you* make the decision of which function will be 
called !-)



(associated with the first class or with the
second class). Will it be the same in the case of the two-argument
function.


It can't. OO polymorphic dispatch is (more or less by nature) a single 
dispatch mechanism. If you want a multiple dispatch (ie: dispatch on an 
arbitrary number of arguments) system, there are a couple packages 
providing this kind of features, but nothing builtin. Also, for a double 
dispatch mechanism, you can have a look at the Visitor design pattern.


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


Having problems using Tkinter

2008-07-01 Thread viv1tyagi
Hi everyone ! ! !

I'm just a month old in the world of Python and trying to develop an
application using Tkinter in which a new window pops out on a
particular button press.The code for this new window is in
"AddKlas.py" file.
The  problem is  all the content of the new window is overwritten on
the previous window.
Below is the code of the two files

PLEASE help me out ! ! ! !

#1st file
#Klass.py
from Tkinter import *
import AddKlass
class Klass(Frame):
def __init__(self):
self.labels()
self.buttons()
self.menubuttons()
self.scrollandcanvas()


def labels(self):
label1=Label(relief='groove',text=" Class
Id",width=20,anchor=W)
label1.grid(row=0,column=0)
label2=Label(relief='groove',text=" Class
Name",width=20,anchor=W)
label2.grid(row=0,column=1)
label3=Label(relief='groove',text=" Class Room
No.",width=20,anchor=W)
label3.grid(row=0,column=2)
label4=Label(relief='groove',text=" Category
Id",width=80,anchor=W)
label4.grid(row=0,column=3)

def buttons(self):
button1=Button(text="Add",width=10,command=self.CallAdd)
button1.grid(row=2,column=5)
button2=Button(text="View",width=10,state=DISABLED)
button2.grid(row=3,column=5)
button3=Button(text="Next",width=10,state=DISABLED)
button3.grid(row=4,column=5)

def menubuttons(self):
menubutton=Menubutton(text="Options",width=10,relief="raised")
menubutton.grid(row=5,column=5)
menubutton.menu=Menu(menubutton)
menubutton["menu"]=menubutton.menu
menubutton.menu.add_command(label="Modify")
menubutton.menu.add_command(label="Delete")

def scrollandcanvas(self):
yscroll=Scrollbar()
yscroll.grid(row=1,column=4,rowspan=7,sticky=N+S)
canva=Canvas(bg="#fff",yscrollcommand=yscroll.set)
canva.grid(row=1,column=0,rowspan=7,columnspan=4,sticky=N+E+S
+W)

def CallAdd(self):
AddKlass.root=Tk()
AddKlass.AddKlas()
AddKlass.root.focus_force()
AddKlass.root.geometry("275x250")
AddKlass.root.title("Add Class Information")
AddKlass.root.resizable(width=False,height=False)
AddKlass.root.mainloop()

root=Tk()
app = Klass()
root.geometry("960x300")
root.title("Class Information")
root.resizable(width=False,height=False)
root.mainloop()




#2nd file
#AddKlass.py
from Tkinter import *

class AddKlas(Frame):
#root=None
def __init__(self):
self.labels()
self.buttons()
self.entry()

def labels(self):
label1=Label(relief='flat',text=" Class
Id :",height=3,width=20)
label1.grid()
label2=Label(relief='flat',text=" Class
Name :",height=3,width=20)
label2.grid()
label3=Label(relief='flat',text=" Class Room
No. :",height=3,width=20)
label3.grid()
label4=Label(relief='flat',text=" Category
Id :",height=3,width=20)
label4.grid()

def buttons(self):
button1=Button(text="Add",width=10,state=DISABLED)
button1.grid(row=5,column=0)
button2=Button(text="Cancel",width=10,command=self.quit)
button2.grid(row=5,column=1)

def entry(self):
entry1=Entry()   #by default width =20
entry1.grid(row=0,column=1)
entry2=Entry()
entry2.grid(row=1,column=1)
entry3=Entry()
entry3.grid(row=2,column=1)
entry4=Entry()
entry4.grid(row=3,column=1)

#root=Tk()
#app = AddKlas()
#root.geometry("275x250")
#root.title("Add Class Information")
#root.resizable(width=False,height=False)
#root.mainloop()


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


Naruto 407, One Piece 506, Bleach 329 Hot manga Download

2008-07-01 Thread mangaboy001
Naruto 407, One Piece 506, Bleach 329 Hot manga Download

The hottest mangas and the latest chapters

Manga news, Most popular mangas, Latest mangas, Latest chapters

http://english1.isoshu.com/?recommid=1023

http://emanga1.isoshu.com/?recommid=1023

A New Wonderful Manga: Maken-ki!

http://english1.isoshu.com/search/Maken-ki/all-1?recommid=1023


Hi, my friends!!! Have you read the manga named Maken-ki? This manga
series is as nice as To-Love-ru!!! The illustrator is Hiromitsu
Takeda
and his girls are incredibly gorgeous.


The story is described as an "ecchi love comedy with battle action."
Oyama Takeshi happily enrolls in a co-ed school that didn't required
any entrance exams and has hostels to book... Only to find out that
there's more to the school than he thought!


It is very good that Takeda-san likes to draw his girls with very big
eyes. Have only read a bit so far but many of the girls have an item
called "Maken" - each are different and have varying powers when used
in battle. And as with all good school girl battles, their clothes
easily explode. And there are characters for folks who like loli's
too.


Maken Ki has been an entertaining read so far and look forward to
more!!! I am sure that you must be love it at the first glance!!!


http://english1.isoshu.com/search/Maken-ki/all-1?recommid=1023




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


Re: PyPy questions

2008-07-01 Thread Dave
On 1 Jul, 04:09, Allen <[EMAIL PROTECTED]> wrote:
> I read the website of some information about PyPy, and how a translator
> translates the RPython code to C/CLI/Java/etc to be compiled to a native
> executable or something like that.  Would it be possible, in PyPy, to
> write such an extension that could easily be compiled to native code
> from Python code?  Is this functionality planned in a future release of
> it?  Also, how is the source distributed (If I opt to use it I will end
> up compiling it on a system without an initial python install (a scratch
> linux system)), so does the source include the generated C code?
>
> B. Vanderburg II

Were you thinking of something like this?
http://www.enthought.com/~ischnell/compdec.html

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


Create a sex site

2008-07-01 Thread jinole
Asian porn sites! Not the best, only better.
To join our team, we do together.URL: http://www.loioi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Having problems using Tkinter

2008-07-01 Thread Marc 'BlackJack' Rintsch
On Tue, 01 Jul 2008 03:13:42 -0700, viv1tyagi wrote:

> Hi everyone ! ! !
> 
> I'm just a month old in the world of Python and trying to develop an
> application using Tkinter in which a new window pops out on a
> particular button press.The code for this new window is in
> "AddKlas.py" file.
> The  problem is  all the content of the new window is overwritten on
> the previous window.
> Below is the code of the two files

There can be only one `Tkinter.Tk` instance per running program.  Other
top level windows have to be `Tkinter.Toplevel` instances.

And you should reconsider your usage of classes.  You are just abusing
them as containers for functions without using `self` really.  And you
should pass the instance of the parent widget as first argument to
constructors of widgets.  Otherwise the very first, i.e. the `Tk` instance,
is assumed, which is not true for the widgets that should appear in the
`Toplevel` instance.

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


Re: Implementing an 8 bit fixed point register

2008-07-01 Thread moogyd
On 1 Jul, 08:57, nickola <[EMAIL PROTECTED]> wrote:
> Hello to all
> I'm about to write a simulator for a microcontroller in python
> (why python? because I love it!!!)
>
> but I have a problem.
>
> The registry of this processor are all 8 bit long (and 10 bit for some
> other strange register)
> and I need to simulate the fixed point behaviour of the register,
> and to access the single bit.
>
> f.x. (this is a pseudo python session, only for understanding)
>
> >>> reg1 = fixed_int(8)
> >>> reg2 = fixed_int(10)
> >>> reg1[0].set()
> or
> >>> reg1[0] = 1 # or True? how to rapresent a binary bit
> >>> reg1[0]
> 1
> >>> reg1[1]
> 0
> >>> reg1[9]
>
> >>> reg2 = 0x7FE   # in binary  
> 110 , or 11 bit long
> >>> reg2
>
> 0x7FE
> #or 10, the memorization truncate the upper bits ( or perhaps
> generate an exception?)>>> reg2 += 0x02 #the result is 100, again not 
> contained in 10 bit
> >>> reg2
>
> 0x00
> # truncated again>>> myprocessor.flags['z']
>
> 1
> # or True? Z flag indicated an overflow in arithmetic operations
>
> Is possibile to do so in python?
>
> thanks

I am not sure if it is exactly what you are looking for (it may be a
bit low level), but myHDL may be interesting. It provides low level H/
W simulation capabilities.

http://myhdl.jandecaluwe.com/doku.php


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


problem with exec and locals()

2008-07-01 Thread rocksportrocker

Hi,

the following code does not work until I ommit the "a=0" statement.


   def test():
   exec "a=3" in locals()
   print a
   a=0

test()

print raises:
 UnboundLocalError: local variable 'a' referenced before
assignment

Can anybody explain what is going wrong here ?

Greetings, Uwe
--
http://mail.python.org/mailman/listinfo/python-list


Re: How make regex that means "contains regex#1 but NOT regex#2" ??

2008-07-01 Thread Vlastimil Brom
2008/7/1, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
>
> I'm looking over the docs for the re module and can't find how to
> "NOT" an entire regex.
>
> For example.
>
> How make regex that means "contains regex#1 but NOT regex#2" ?
>
> Chris
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Maybe I'm missing something, but the negative lookahead seems to do roughly
that (at least for simpler cases); the usual form is the check the text
after the match, but it can also be used at the beginning of the pattern.

ie. (?!regex#2)regex#1

e.g. the following should search for "words" discarding some very frequent
ones; the important part seems to be keeping the excluding regexp2
compatible with the matching regex#1.

(?!\b(?:an?|the|is|are|of|in|to|and)\b)\b\w+\b

(without the checks for word boundaries \b, this pattern would also exclude
"words" only partly containing the stopwords)

regards

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

Disabling the magic "last expression" _ variable

2008-07-01 Thread Koen Vossen
A project I'm currently working on uses Turbogears as a framework. I'd 
like to interact with it using the tg-admin shell. We also use gettext's 
_() function for internationalization. Now, this function is overwritten 
in interactive mode, which causes annoying exceptions. Is it possible to 
disable this behavior?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Disabling the magic "last expression" _ variable

2008-07-01 Thread Peter Otten
Koen Vossen wrote:

> A project I'm currently working on uses Turbogears as a framework. I'd
> like to interact with it using the tg-admin shell. We also use gettext's
> _() function for internationalization. Now, this function is overwritten
> in interactive mode, which causes annoying exceptions. Is it possible to
> disable this behavior?

>>> import sys
>>> def displayhook(result):
... if result is not None:
... __builtins__._last = result
... print result
...
>>> "yadda"
yadda
>>> _
Traceback (most recent call last):
  File "", line 1, in 
NameError: name '_' is not defined
>>> _last
yadda

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


Re: Disabling the magic "last expression" _ variable

2008-07-01 Thread Peter Otten
Koen Vossen wrote:

> A project I'm currently working on uses Turbogears as a framework. I'd
> like to interact with it using the tg-admin shell. We also use gettext's
> _() function for internationalization. Now, this function is overwritten
> in interactive mode, which causes annoying exceptions. Is it possible to
> disable this behavior?

[correct overzealous snip]

>>> import sys
>>> def displayhook(result):
... if result is not None:
... __builtins__._last = result
... print result
...
>>> sys.displayhook = displayhook
>>> _
Traceback (most recent call last):
  File "", line 1, in 
NameError: name '_' is not defined
>>> "yadda"
yadda
>>> _
Traceback (most recent call last):
  File "", line 1, in 
NameError: name '_' is not defined
>>> _last
yadda


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


Scope and program structure problems

2008-07-01 Thread John Dann
Trying to learn Python here, but getting tangled up with variable
scope across functions, modules etc and associated problems. Can
anyone advise please?

Learning project is a GUI-based (wxPython) Python program that needs
to access external data across a serial port. 

The first thing that I need the program to do when it starts up is to
check that it can see the serial port, the first step of which is to
check that it can import the pySerial module, and display an
appropriate message in the statusbar of the main frame. (I know there
may be other ways of doing this but this is what I'm trying to do
currently and I'd like to understand how to make this approach work
robustly even if there are other options.)

So it seems that if I want to write to the frame's statusbar, I can't
do anything re serial import until the frame is initialising. And I
can't put any serial import code after the app.Mainloop() code line
because it won't run until the frame closes. 

In other words, I seem to be stuck with importing the serial library
either in the __init__ function or - if implemented slightly
differently - in a separate function of the wxPython Frame class, ie a
code structure of:

---
# Can't put serial import code here because there's no GUI yet to send
messages to.

Class Frame(wx.Frame)
def __init__()
etc
#code to check and use serial port has to go below??
def CheckSerial() # eg triggered by appropriate menu click event
Try:
import serial
etc
ser = Serial.etc  # set ser object as handle to serial port
def UseSerial():
# Code to perform serial IO

app=App(wx.App)
app.MainLoop()

# Can't put serial import code here because it won't execute until
frame closes?
---

But then I hit another problem. If I set the object ser to point to
the serial port in the CheckSerial function, then it's just got local
scope within the function and can't be seen from the UseSerial
function.

So I've got 2 questions. The main one is whether there's any way of
explicitly giving the ser object global scope in the code line:

ser = Serial.etc  # set ser object as handle to serial port

And, second, does my overall description above reveal any serious
misunderstanding about how best to handle this sort of problem in
Python?

Apologies for the long post and hope that my description is clear
enough to make sense.

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


wrong md5 checksum

2008-07-01 Thread kkwweett

Hi,

the download page (http://www.python.org/download/releases/3.0/) for 
Python 3000 shows :


9119625244b17aa35ed94b655a2b2135  13491200  python-3.0b1.msi

but I got

9119625244a57aa35ed94b655a2b2135  13491200  python-3.0b1.msi

(44a57 rather than 44b17 )

with several md5 checkers ( MdChecker (http://getmd5checker.com/) or a C 
 prog I've written)


what's wrong ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is recursion so slow?

2008-07-01 Thread Antoon Pardon
On 2008-06-29, slix <[EMAIL PROTECTED]> wrote:
> Recursion is awesome for writing some functions, like searching trees
> etc but wow how can it be THAT much slower for computing fibonacci-
> numbers?

Try the following recursive function:

def fib(n):

  def gfib(a, b , n):
if n == 0:
  return a
else:
  return gfib(b, a + b, n - 1)

  return gfib(0, 1, n)

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


Re: perl + python tutorial available for download

2008-07-01 Thread Ben Bullock
On Mon, 30 Jun 2008 17:44:13 +, Jürgen Exner wrote:

> Xah <[EMAIL PROTECTED]> wrote:
>>my perl and python tutorial
>>
>>http://xahlee.org/perl-python/index.html
>>
>>is now available for download for offline reading.
> 
> Why anyone would have the idea to mix two different langauges in one
> tutorial is beyond me.

It's an interesting idea to present two or more languages in parallel - 
it would assist someone going "sideways" from one language to another.

> And calling that web page a tutorial is a large stretch of imagination.
> It is a random collection of primitve code samples, organized roughly by
> area. No learning goals, no explanation of concepts, ...

I'm a big fan of code samples - most of my code starts as other people's 
code samples.

> Apparently you changed your ID to escape all the filters you have been a
> permanent guest to. This 'tutorial' confirms that this is the best place
> for you. So back you go again.

I'm not interested in Xah Lee's tutorials enough to check whether they're 
any good or not, but he does have some interesting things to say about 
Emacs.
--
http://mail.python.org/mailman/listinfo/python-list

Re: PyPy questions

2008-07-01 Thread Stephan Diehl
Allen schrieb:
> I read the website of some information about PyPy, and how a translator
> translates the RPython code to C/CLI/Java/etc to be compiled to a native
> executable or something like that.  Would it be possible, in PyPy, to
> write such an extension that could easily be compiled to native code
> from Python code?  Is this functionality planned in a future release of
> it?  Also, how is the source distributed (If I opt to use it I will end
> up compiling it on a system without an initial python install (a scratch
> linux system)), so does the source include the generated C code?
> 
> B. Vanderburg II

these kind of questions are better asked on pypy-dev.
Anyway, at the moment you need a working python installation in order to
run the pypy chain. I have to admit that I didn't understand your
question, but you should read the pypy documentation on codespeak.net as
it will probably answer all of your questions. Alternativly, you might
want to join the #pypy channel on freenode
Stephan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scope and program structure problems

2008-07-01 Thread Bruno Desthuilliers

John Dann a écrit :

Trying to learn Python here, but getting tangled up with variable
scope across functions, modules etc and associated problems. Can
anyone advise please?

Learning project is a GUI-based (wxPython) Python program that needs
to access external data across a serial port. 


The first thing that I need the program to do when it starts up is to
check that it can see the serial port, the first step of which is to
check that it can import the pySerial module, and display an
appropriate message in the statusbar of the main frame. (I know there
may be other ways of doing this but this is what I'm trying to do
currently and I'd like to understand how to make this approach work
robustly even if there are other options.)


(snip)


---
# Can't put serial import code here because there's no GUI yet to send
messages to.

Class Frame(wx.Frame)
def __init__()
etc
#code to check and use serial port has to go below??
def CheckSerial() # eg triggered by appropriate menu click event
Try:
import serial
etc
ser = Serial.etc  # set ser object as handle to serial port
def UseSerial():
# Code to perform serial IO

app=App(wx.App)
app.MainLoop()

# Can't put serial import code here because it won't execute until
frame closes?
---

But then I hit another problem. If I set the object ser to point to
the serial port in the CheckSerial function, then it's just got local
scope within the function and can't be seen from the UseSerial
function.

So I've got 2 questions. The main one is whether there's any way of
explicitly giving the ser object global scope in the code line:

ser = Serial.etc  # set ser object as handle to serial port


It is possible - for the python definition of 'global' being 
'module-global' - but it's not necessarily the best solution. Look up 
the doc for the 'global' statement to learn more.


Another solution would be to make ser an attribute of your Frame object:

class Frame(wx.Frame):
def __init__(self):
self.serial = None

#code to check and use serial port has to go below??
def setup_serial(self) # eg triggered by appropriate menu click event
try:
import serial
except ImportError, e:
# display an error message and either crash
# or return

else:
 # set self.serial object as handle to serial port
 self.serial = serial.etc()


def use_serial(self):
# Code to perform serial IO
# won't work if setupSerial failed


And, second, does my overall description above reveal any serious
misunderstanding about how best to handle this sort of problem in
Python?


Well... You'd get a very similar result by doing your import at the 
top-level but within a try/except block, then when you have a gui setup 
takes appropriate actions.


try:
import serial
serial_import_error = None
except ImportError, e:
serial = None
serial_import_error = e


class Frame(wx.Frame):
def __init__(self):
self.serial = None

def setup_serial(self):
if serial is None:
# display an error message and either crash
# or return
else:
self.serial = serial.whatever()





But anyway: I have no real (read : anything requiring any brain-cell) 
experience writing rich GUI apps in Python, and I haven't done rich GUI 
programming for four last years at least, so there may be better 
solutions here.


So : Any wxPython guru around ?-)


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


Re: Embedding Python

2008-07-01 Thread Pau Freixes
Hi

If PyImport_ExecCodeModule have a two parameteres and second parameter is
PyObject type  why you are make a call with a unsigned char value ?

If you search this function name into Google you will can found some
examples, use for example PyMarshal_ReadObjectFromString or
PyMarshal_ReadObjectFromFile

Bye

On Tue, Jul 1, 2008 at 11:36 AM, Marcin Krol <[EMAIL PROTECTED]> wrote:

> Hello everyone,
>
> I'm trying to embed Python interpreter in C code, but in a specific way:
> loading compiled bytecode into a memory location and executing it (don't
> ask why, complicated reasons).
>
> PyImport_ExecCodeModule seems like obvious candidate, docs say:
>
> "Given a module name (possibly of the form package.module) and a code
> object read from a Python bytecode file or obtained from the built-in
> function compile(), load the module."
>
> Code:
>
> ---cut---
> #include 
> #include 
> #include 
> #include 
> #include 
>
>
> int load_file(char *fname, unsigned char** result)
> {
>  int size = 0;
>  FILE *f = fopen(fname, "rb");
>  if (f == NULL)
>  {
>  *result = NULL;
>  return -1;
>  }
>  fseek(f, 0, SEEK_END);
>  size = ftell(f);
>  *result = (unsigned char *) malloc(size+1);
>  fseek(f, 0, SEEK_SET);
>  size = fread(*result, sizeof(unsigned char), size, f);
>  return size;
> }
>
> int main(int argc, char **argv)
> {
>int size;
>unsigned char *python_code;
>PyObject *mainobj;
>size = load_file("multiply.pyc", &python_code);
>
>Py_Initialize();
>mainobj = PyImport_ExecCodeModule("multiply", (PyObject *)
> python_code);
>Py_Finalize();
>
> }
> ---cut---
>
> Compiling it following way works fine:
>
> ${CC} testit.c -g -o testit -I/usr/include/python2.4 -lpython2.4 -lm
> -lutil -lpthread -ldl  -L/usr/lib/python2.4/config
>
>
> However, the damn thing crashes on this call:
>
> 33  mainobj = PyImport_ExecCodeModule("multiply", (PyObject
> *) python_code);
> (gdb) n
>
> Program received signal SIGSEGV, Segmentation fault.
> 0x0804e7f6 in PyImport_ExecCodeModuleEx ()
>
> The .pyc file woks just fine in Python interpreter:
>
>  import multiply
 multiply.multiply()

>>> The result of 12345 x 6789 : 83810205
> 83810205
>
>>

>
> What I am doing wrong? Please help.
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Pau Freixes
Linux GNU/User
--
http://mail.python.org/mailman/listinfo/python-list

Re: raw_input into Tkinter ?

2008-07-01 Thread Python.Arno


On 30 jun 2008, at 18:55, [EMAIL PROTECTED] wrote:


Is there any way to type into a Tkinter frame window?
I want to use raw_input() within a Tkinter frame.
--
http://mail.python.org/mailman/listinfo/python-list



You could use the Tkinter.Entry option from dialog windows...

http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm

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


Re: Implementing an 8 bit fixed point register

2008-07-01 Thread Mel
nickola wrote:

> Hello to all
> I'm about to write a simulator for a microcontroller in python
> (why python? because I love it!!!)
[...]
> The registry of this processor are all 8 bit long (and 10 bit for some
> other strange register)
> and I need to simulate the fixed point behaviour of the register,
> and to access the single bit.
> 
> f.x. (this is a pseudo python session, only for understanding)
> 
 reg1 = fixed_int(8)
 reg2 = fixed_int(10)
 reg1[0].set()
> or
 reg1[0] = 1 # or True? how to rapresent a binary bit
 reg1[0]
> 1
 reg1[1]
> 0
 reg1[9]
> 
 reg2 = 0x7FE   # in binary  110 , or 11 bit long
 reg2
> 0x7FE
> #or 10, the memorization truncate the upper bits ( or perhaps
> generate an exception?)
 reg2 += 0x02 #the result is 100, again not contained in 10 bit
 reg2
> 0x00
> # truncated again
 myprocessor.flags['z']
> 1
> # or True? Z flag indicated an overflow in arithmetic operations
> 
> Is possibile to do so in python?

I did this for a PIC, and generally just used brute force, e.g.

temp = reg2 + 0x02
reg2 = temp & 0xFF
if temp & 0x100:
flags |= CARRY_MASK
else:
flags &= ~CARRY_MASK
if temp & 0xFF:
flags &= ~ZERO_MASK
else:
flags |= ZERO_MASK

Since it was a PIC, and there were only a half-dozen arithmetic/logical
operations, the code stayed in this form.  With something bigger, it would
have been attractive to wrap these operations up in a class, as you
suggest.. (just a sketch) ..

class fixed_register (object):
def __init__ (self, size, val=0):
self.mask = ~(-1 << size)
self.ovfmask = 1 << size
self.val = val & self.mask

with appropriate __add__, __sub__, etc.  Perhaps __getitem__, __setitem__ to
manipulate bits.

Good Luck,  Mel.


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


pyparsing problem

2008-07-01 Thread name
Hi,

I try to parse a file with pyparsing and get this output:

['generic', 'host-01', 'host alias xyz', '10.0.0.1']
- alias: host alias xyz
- host_name: ['host-01']
- ip_address: ['10.0.0.1']
- use: ['generic']



  generic
  host-01
  host alias xyz
  10.0.0.1


['generic', 'host-01', 'host alias xyz', '10.0.0.1']

finished

What I don't understand is why I get the line

generic

and not 

generic

as there is an associated name in the dump() output.

Thank you very much in advance for any clue or help you could
provide.



The code:
-

#!/usr/bin/env python

from pyparsing import *

sample = """
define host{ 
  use   generic
  host_name host-01
  alias host alias xyz
  address   10.0.0.1
}
"""

# define tokens
LBRACE,RBRACE = map(Suppress, '{}')
ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3)
useTemplate = oneOf('generic user')

# define grammar

deviceName = Word(alphanums+'-')
hostDef = Literal('define').suppress() + Literal('host').suppress()
useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd))
host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo
(lineEnd))
aliasLine = Suppress('alias') + SkipTo(lineEnd)
aliasLine.setParseAction(lambda x: ' '.join(x[0].split()))
ip_addressLine = Suppress('address') + ipAddress

use = useLine.setResultsName('use')
host_name = host_nameLine.setResultsName('host_name')
alias = aliasLine.setResultsName('alias')
ip_address = ip_addressLine.setResultsName('ip_address')


host_stmt = (use + host_name + alias + ip_address)
host = hostDef + LBRACE + host_stmt  + RBRACE

test_file = OneOrMore(host) + stringEnd


# test
x = test_file.parseString(sample)
print x.dump()
print
print x.asXML('Hosts')
print
print x.asList()
print

print 'finished'

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


recursive import

2008-07-01 Thread oj
Hi, I'm just toying around with some ideas at the moment.

Is there an easy and safe way to recursivly import all modules under a
particular namespace?

Say, I had modules:

foo
foo.bar
foo.bar.baz
foo.baz
bar
bar.baz

I want to import all the modules in the foo namespace, so the first
four modules in that list.

Other then having those modules explicitly import their children, or
explicitly importing them all from where I want to use them, can I do
this? Should I do this?

The idea is that function decorates 'register' functions in those
modules, so they become available without having to have a list of all
the modules that contain them, and without all the modules necessarily
needing to know about each other.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Employment] New TurboGears Job in Eugene, OR

2008-07-01 Thread Aahz
In article <[EMAIL PROTECTED]>,
Tim Roberts  <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] (Aahz) wrote:
>>Paul McNett  <[EMAIL PROTECTED]> wrote:
>>>
>>>They want an expert for a maximum of $25 per hour? If they find someone, 
>>>it'll be a pretty good bullshitter looking for experience.
>>
>>Note that it's an "academic year" position -- lots and lots of vacation
>>time.  This would actually be a good job for e.g. a retired person who
>>doesn't need lots of money.  Also note that Eugene is not exactly an
>>area with a high cost of living.
>
>I take it you're not from Oregon.  Eugene is the second largest city.
>Prices are not quite up to the San Jose at its peak, but there are no
>bargains left in any of the urban sections of the state.  It's certainly
>far more expensive here than in the midwest or most of the south.

Depends where you look in the midwest, of course.  It's certainly cheaper
than Minneapolis or Chicago.  It's even cheaper than Cleveland or
Columbus.  It's cheaper than Atlanta.  So yeah, I stick by my comment.
It's all a matter of which perspective you're looking from.  ;-)

FYI, I'm pulling my info from
http://swz.salary.com/CostOfLivingWizard/layouthtmls/coll_metrodetail_58.html
which differs some from
http://www.eugenechamber.com/relo/facts_figures.htm
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with exec and locals()

2008-07-01 Thread Mel
rocksportrocker wrote:

> 
> Hi,
> 
> the following code does not work until I ommit the "a=0" statement.
> 
> 
>def test():
>exec "a=3" in locals()
>print a
>a=0
> 
> test()
> 
> print raises:
>  UnboundLocalError: local variable 'a' referenced before
> assignment
> 
> Can anybody explain what is going wrong here ?

AFAIK, local variables are implemented rather like __slots__ in new-style
classes.  This is a very valuable efficiency measure, but it can cause this
kind of trouble.  Without `a=0`, the bytecode compiler makes no slot for a,
and dis.dis shows the following bytecode for test:
>>> dis.dis (test)
  2   0 LOAD_CONST   1 ('a=3')
  3 LOAD_NAME0 (locals)
  6 CALL_FUNCTION0
  9 DUP_TOP
 10 EXEC_STMT

  3  11 LOAD_NAME1 (a)
 14 PRINT_ITEM
 15 PRINT_NEWLINE
 16 LOAD_CONST   0 (None)
 19 RETURN_VALUE

At address 11, LOAD_NAME 1(a) gets the value that was set by exec.

With a=0, the code is
>>> dis.dis(test2)
  2   0 LOAD_CONST   1 ('a=4')
  3 LOAD_NAME0 (locals)
  6 CALL_FUNCTION0
  9 DUP_TOP
 10 EXEC_STMT

  3  11 LOAD_FAST0 (a)
 14 PRINT_ITEM
 15 PRINT_NEWLINE

  4  16 LOAD_CONST   2 (0)
 19 STORE_FAST   0 (a)
 22 LOAD_CONST   0 (None)
 25 RETURN_VALUE

and here, the value of a is found in slot 0 via LOAD_FAST.  Slot 0 is used
because a=0 forced a to be a local variable.

Apparently, exec in locals() knows nothing about slots (because locals() is
the only dictionary in the universe where slots would be involved ? --
perhaps not, but close).

Mel.

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


Re: C++ or Python

2008-07-01 Thread Maria R
On Jun 28, 12:22 am, Kurda Yon <[EMAIL PROTECTED]> wrote:
> I would like to know what are advantages of Python in comparison with C
> ++? In which cases and why Python can be a better tool than C++?
>
> Thank you!

Back in 2002, we made a hard decision between c++ (well established
here) java (not as mature back then) and python (completely new to my
company).
The task was to do a complete rewrite of our control software running
our fully automatic pallet conveyor systems.
The architecture is three-tier; host (not our system), service with
GUI (com uppwards and downwards plus supporting the operators of the
plant) and PLC nearest the el-mech.

We decided to go for python since we always could fallback on ansi c
in case of performance issues.

We have today no regretted this!
We have extended the architecure since with handhelds and they are
programmed with java due to lack of proper python possibilities (at
the time).
We have further programmed code generatord for the PLC code.
and so on.. :o)

Sure, c++ could have been used but not at the effort(lessness) we now
experience.

Mu 2 cents//Maria
--
http://mail.python.org/mailman/listinfo/python-list


connecting to DBMS

2008-07-01 Thread varun chadha
i am a newbie to python and is working on an application which needs
to connect to the database. can anyone guide me through the DBMS that
i can use and the module to connect to it. currently i have MySQL
installed using the link on the python.org site but is unable to
connect to it through python. pls specify the link  to the tutorials
which can guide to connect and execute my query. hopes u understood
what i meant to say.
thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python

2008-07-01 Thread Carsten Haese

Marcin Krol wrote:

Hello everyone,

I'm trying to embed Python interpreter in C code, but in a specific way:
loading compiled bytecode into a memory location and executing it (don't
ask why, complicated reasons).

PyImport_ExecCodeModule seems like obvious candidate, docs say:

"Given a module name (possibly of the form package.module) and a code
object read from a Python bytecode file or obtained from the built-in
function compile(), load the module."
[...]
mainobj = PyImport_ExecCodeModule("multiply", (PyObject *)
python_code);
[...]


python_code is a C string containing the raw bytes from your pyc file. 
Casting that to a PyObject pointer will not magically transform it into 
a Python code object. A pyc file contains the following:


1) An 8 byte header containing a magic number.
2) A "marshal" serialization of the code object.

So, in order to transform those contents into a code object, you need to 
skip the 8 byte header and an unmarshal the rest. Basically, replace the 
line above with something like this:


codeobj = PyMarshal_ReadObjectFromString(python_code+8, size-8);
mainobj = PyImport_ExecCodeModule("multiply", codeobj);

where codeobj is of type (PyObject *).

Once that works, add magic number checking and exception handling to taste.

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looping-related Memory Leak

2008-07-01 Thread Tom Davis
On Jun 30, 3:12 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Mon, 30 Jun 2008 10:55:00 -0700, Tom Davis wrote:
> > To me, this seems illogical.  I can understand that the GC is
> > reluctant to reclaim objects that have many connections to other
> > objects and so forth, but once those objects' scopes are gone, why
> > doesn't it force a reclaim?  For instance, I can use timeit to create
> > an object instance, run a method of it, then `del` the variable used
> > to store the instance, but each loop thereafter continues to require
> > more memory and take more time. 1000 runs may take .27 usec/pass
> > whereas 10 takes 2 usec/pass (Average).
>
> `del` just removes the name and one reference to that object.  Objects are
> only deleted when there's no reference to them anymore.  Your example
> sounds like you keep references to objects somehow that are accumulating.
> Maybe by accident.  Any class level bound mutables or mutable default
> values in functions in that source code?  Would be my first guess.
>
> Ciao,
> Marc 'BlackJack' Rintsch

Marc,

Thanks for the tips.  A quick confirmation:

I took "class level bound mutables" to mean something like:

  Class A(object):
SOME_MUTABLE = [1,2]
  ...

And "mutable default values" to mean:

  ...
  def a(self, arg=[1,2]):
  ...

If this is correct, I have none of these.  I understand your point
about the references, but in my `timeit` example the statement is as
simple as this:

  import MyClass
  a = MyClass()
  del a

So, yes, it would seem that object references are piling up and not
being removed.  This is entirely by accident.  Is there some kind of
list somewhere that says "If your class has any of these attributes
(mutable defaults, class-level mutables, etc.) it may not be properly
dereferenced:"? My obvious hack around this is to only do X loops at a
time and make a cron to run the script over and over until all the
files have been processed, but I'd much prefer to make the code run as
intended. I ran a test overnight last night and found that at first a
few documents were handled per second, but when I woke up it had
slowed down so much that it took over an hour to process a single
document! The RAM usage went from 20mb at the start to over 300mb when
it should actually never use more than about 20mb because everything
is handled with local variables and new objects are instantiated for
each document. This is a serious problem.

Thanks,

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


Re: Scope and program structure problems

2008-07-01 Thread John Dann
Many thanks for the repsonse - much appreciated. 

And sorry - yes I was probably compounding two separate issues here -
the GUI one and the variable scope one. Maybe the wxPython list would
be the best place to ask more about the GUI side of things.

Then actually I can simplify my remaining question quite a lot - I
know you've partly answered this already but let me just rephrase
this:

It must be commonplace to first use a variable or object within one
function in a module and then want to use it again  - perhaps still
with the same value as in the first function - in a second function.

So what's the recommended Python way round this? If I was using .Net
then I'd be declaring the variables/objects explicitly and could set
their scope according to how/where they were declared. But if the
Python way is not to declare vars before use then this must create
some problems for cross-function use.

So it is best to declare such vars at the module level (ie outside of
a function) and set eg to Null/None or to assign them with a keyword
such as global or static (assuming that concept applies in Python) at
first use inside a function or what?

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


Re: Looping-related Memory Leak

2008-07-01 Thread Tom Davis
On Jun 30, 8:24 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Jun 30, 1:55 pm, Tom Davis <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 26, 5:38 am, Carl Banks <[EMAIL PROTECTED]> wrote:
>
> > > On Jun 26, 5:19 am, Tom Davis <[EMAIL PROTECTED]> wrote:
>
> > > > I am having a problem where a long-running function will cause a
> > > > memory leak / balloon for reasons I cannot figure out.  Essentially, I
> > > > loop through a directory of pickled files, load them, and run some
> > > > other functions on them.  In every case, each function uses only local
> > > > variables and I even made sure to use `del` on each variable at the
> > > > end of the loop.  However, as the loop progresses the amount of memory
> > > > used steadily increases.
>
> > > Do you happen to be using a single Unpickler instance?  If so, change
> > > it to use a different instance each time.  (If you just use the module-
> > > level load function you are already using a different instance each
> > > time.)
>
> > > Unpicklers hold a reference to everything they've seen, which prevents
> > > objects it unpickles from being garbage collected until it is
> > > collected itself.
>
> > > Carl Banks
>
> > Carl,
>
> > Yes, I was using the module-level unpickler.  I changed it with little
> > effect.  I guess perhaps this is my misunderstanding of how GC works.
> > For instance, if I have `a = Obj()` and run `a.some_method()` which
> > generates a highly-nested local variable that cannot be easily garbage
> > collected, it was my assumption that either (1) completing the method
> > call or (2) deleting the object instance itself would automatically
> > destroy any variables used by said method.  This does not appear to be
> > the case, however.  Even when a variable/object's scope is destroyed,
> > it would seem t hat variables/objects created within that scope cannot
> > always be reclaimed, depending on their complexity.
>
> > To me, this seems illogical.  I can understand that the GC is
> > reluctant to reclaim objects that have many connections to other
> > objects and so forth, but once those objects' scopes are gone, why
> > doesn't it force a reclaim?
>
> Are your objects involved in circular references, and do you have any
> objects with a __del__ method?  Normally objects are reclaimed when
> the reference count goes to zero, but if there are cycles then the
> reference count never reaches zero, and they remain alive until the
> generational garbage collector makes a pass to break the cycle.
> However, the generational collector doesn't break cycles that involve
> objects with a __del__method.

There are some circular references, but these are produced by objects
created by BeautifulSoup.  I  try to decompose all of them, but if
there's one part of the code to blame it's almost certainly this.  I
have no objects with __del__ methods, at least none that I wrote.

> Are you calling any C extensions that might be failing to decref an
> object?  There could be a memory leak.

Perhaps.  Yet another thing to look into.

> Are you keeping a reference around somewhere.  For example, appending
> results to a list, and the result keeps a reference to all of your
> unpickled data for some reason.

No.

> You know, we can throw out all these scenarios, but these suggestions
> are just common pitfalls.  If it doesn't look like one of these
> things, you're going to have to do your own legwork to help isolate
> what's causing the behavior.  Then if needed you can come back to us
> with more detailed information.
>
> Start with your original function, and slowly remove functionality
> from it until the bad behavior goes away.  That will give you a clue
> what's causing it.

I realize this and thank you folks for your patience.  I thought
perhaps there was something simple I was overlooking, but in this case
it would seem that there are dozens of things outside of my direct
control that could be causing this, most likely from third-party
libraries I am using. I will continue to try to debug this on my own
and see if I can figure anything out.  Memory leaks and failing GC and
so forth are all new concerns for me.

Thanks Again,

Tom

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


RE: How make regex that means "contains regex#1 but NOT regex#2" ??

2008-07-01 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: Tuesday, July 01, 2008 2:29 AM
> To: python-list@python.org
> Subject: How make regex that means "contains regex#1 but NOT regex#2"
> ??
> 
> I'm looking over the docs for the re module and can't find how to
> "NOT" an entire regex.
> 
> For example.
> 
> How make regex that means "contains regex#1 but NOT regex#2" ?
> 

Match 'foo.*bar', except when 'not' appears between foo and bar.


import re

s = 'fooAAABBBbar'
print "Should match:", s
m = re.match(r'(foo(.(?!not))*bar)', s);
if m:
print m.groups()

print

s = 'fooAAAnotBBBbar'
print "Should not match:", s
m = re.match(r'(foo(.(?!not))*bar)', s);
if m:
print m.groups()


== Output ==
Should match: fooAAABBBbar
('fooAAABBBbar', 'B')

Should not match: fooAAAnotBBBbar



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


Re: pyparsing problem

2008-07-01 Thread Paul McGuire
On Jul 1, 8:02 am, name <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I try to parse a file with pyparsing and get this output:
>
>     ['generic', 'host-01', 'host alias xyz', '10.0.0.1']
>     - alias: host alias xyz
>     - host_name: ['host-01']
>     - ip_address: ['10.0.0.1']
>     - use: ['generic']
>
>     
>       generic
>       host-01
>       host alias xyz
>       10.0.0.1
>     
>
>     ['generic', 'host-01', 'host alias xyz', '10.0.0.1']
>
>     finished
>
> What I don't understand is why I get the line
>
>     generic
>
> and not
>
>     generic
>
> as there is an associated name in the dump() output.
>
> Thank you very much in advance for any clue or help you could
> provide.
>
> The code:
> -
>
> #!/usr/bin/env python
>
> from pyparsing import *
>
> sample = """
> define host{
>   use                   generic
>   host_name             host-01
>   alias                 host alias xyz
>   address                       10.0.0.1}
>
> """
>
> # define tokens
> LBRACE,RBRACE = map(Suppress, '{}')
> ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3)
> useTemplate = oneOf('generic user')
>
> # define grammar
>
> deviceName = Word(alphanums+'-')
> hostDef = Literal('define').suppress() + Literal('host').suppress()
> useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd))
> host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo
> (lineEnd))
> aliasLine = Suppress('alias') + SkipTo(lineEnd)
> aliasLine.setParseAction(lambda x: ' '.join(x[0].split()))
> ip_addressLine = Suppress('address') + ipAddress
>
> use = useLine.setResultsName('use')
> host_name = host_nameLine.setResultsName('host_name')
> alias = aliasLine.setResultsName('alias')
> ip_address = ip_addressLine.setResultsName('ip_address')
>
> host_stmt = (use + host_name + alias + ip_address)
> host = hostDef + LBRACE + host_stmt  + RBRACE
>
> test_file = OneOrMore(host) + stringEnd
>
> # test
> x = test_file.parseString(sample)
> print x.dump()
> print
> print x.asXML('Hosts')
> print
> print x.asList()
> print
>
> print 'finished'

Looks like this is a bug in asXML().  Note that if I reverse the use
and host_name strings in the input and in your grammar, I get this XML
output:


  host-01
  generic
  host alias xyz
  10.0.0.1


Fortunately, you have provided a nice short test case, which should
allow me to track down the problem.

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


Re: frame grabber hardware

2008-07-01 Thread rubbishemail

> Do you mean something like this?
>
> Easy Cap Audio-Video Capturing Adapter 
> http://www.youtube.com/watch?v=3AvT8JQ7NzI

this would be suitable, if it had a documented driver, some sites said
it could only be used with the included
software. many bad comments, though:
http://forums.ebay.com/db1/thread.jspa?threadID=2000392978&start=40


I found this library
http://videocapture.sourceforge.net/
which may be useful to others



I will probably go for a TWAIN enabled grabber like
http://www.zarbeco.com/usb_videolink.htm
and use
twainmodule.sourceforge.net/

An alternative would be to use directshow, which seems to be supported
by many cameras:
http://directpython.sourceforge.net/index.html

thanks for your input

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


Re: Implementing an 8 bit fixed point register

2008-07-01 Thread Grant Edwards
On 2008-07-01, nickola <[EMAIL PROTECTED]> wrote:
> Hello to all
> I'm about to write a simulator for a microcontroller in python
> (why python? because I love it!!!)
>
> but I have a problem.
>
> The registry of this processor are all 8 bit long (and 10 bit
> for some other strange register) and I need to simulate the
> fixed point behaviour of the register,

Somebody posted a class that impliments fixed-width integer
types a while back.

> and to access the single bit.

The bitwise operators &, |, ~, ^ all work just like they do in C.

You can write methods to dip those in syntactic sugar if you
want.

> f.x. (this is a pseudo python session, only for understanding)
>
 reg1 = fixed_int(8)
 reg2 = fixed_int(10)
 reg1[0].set()
> or
 reg1[0] = 1 # or True? how to rapresent a binary bit
 reg1[0]
> 1
 reg1[1]
> 0
 reg1[9]
>
 reg2 = 0x7FE   # in binary  110 , or 11 bit long
 reg2
> 0x7FE
> #or 10, the memorization truncate the upper bits ( or perhaps
> generate an exception?)
 reg2 += 0x02 #the result is 100, again not contained in 10 bit
 reg2
> 0x00
> # truncated again
 myprocessor.flags['z']
> 1
> # or True? Z flag indicated an overflow in arithmetic operations
>
> Is possibile to do so in python?

Yes.  Everything shown above is possible.  If you really want
to get clever, you'll want to read up on the __setattr__,
__getattr__, __getitem__, and __setitem__ object methods.

They'll allow you to define special handling for the semantics
below:

  foo.something = x  # calls foo.__setattr___('something',x)
  x = foo.something  # calls foo.__getattr___('something,)

  foo[n] = x # calls foo.__setitem__(n,x)
  x = foo[n] # calls foo.__getitme__(n)
  
In the latter two cases, you can support slicing if you want.
That could allows you to grab a "bitfield" out of a register:

  x = processor.regA[4:7]   # get bits 4,5,6
  
  processor.regA[4:7]   # set bits 4,5,6
  
Just remember that in Python slices are traditionally half-open
intervals -- they don't include the "right" endpoint.  That's
going to confuse people who are more used to reading processor
data sheets where bit-ranges are traditionally closed
intervals.  You _could_ implment your __[sg]etitem__ slice
handling so that they're treated as closed intervals. That will
be a lot more intuitive to people used to dealing with
microprocessor register definitions, but could confuse an
experienced Python programmer.

Writing methods for __setattr__ and __getattr__ is a little
tricky. It's very easy to end up with infinite recursion.  It's
not that hard to fix/avoid, but it takes a while to get the
hang of it.

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


Installing paramiko and pycrypto

2008-07-01 Thread cokofreedom
I am really stuck presently, trying to install these on my Windows XP.
I have downloaded easy_install and it is now in Python25\Scripts but
none of the commands I have read in either program folder have worked
to install them.

I was hoping someone could give me a step by step guide to installing
these so I can use paramiko to perform SSH. Or at least point me in
the right direction...

Thanks

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


Re: Disabling the magic "last expression" _ variable

2008-07-01 Thread Ben Finney
Peter Otten <[EMAIL PROTECTED]> writes:

> >>> import sys
> >>> def displayhook(result):
> ... if result is not None:
> ... __builtins__._last = result
> ... print result
> ...

Better is to explicitly import the name '__builtin__'
http://www.python.org/doc/lib/module-builtin>. The name
'__builtins__' is an implementation detail not guaranteed to be
present in any particular implementation.

import __builtin__
import sys
def displayhook(result):
if result is not None:
__builtin__._last = result
print result

-- 
 \“If you continue running Windows, your system may become |
  `\   unstable.” —Microsoft, Windows 95 error message |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: pyparsing problem

2008-07-01 Thread name
Paul McGuire <[EMAIL PROTECTED]> wrote in news:be7af822-70d7-44fb-96fa-
[EMAIL PROTECTED]:

> 
> Looks like this is a bug in asXML().  Note that if I reverse the use
> and host_name strings in the input and in your grammar, I get this XML
> output:
> 
> 
>   host-01
>   generic
>   host alias xyz
>   10.0.0.1
> 
> 
> Fortunately, you have provided a nice short test case, which should
> allow me to track down the problem.
> 
> Thanks,
> -- Paul
> 

You are welcome! And I would like to thank you for this outstanding tool!

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


RE: How make regex that means "contains regex#1 but NOT regex#2" ??

2008-07-01 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Reedick, Andrew
> Sent: Tuesday, July 01, 2008 10:07 AM
> To: [EMAIL PROTECTED]; python-list@python.org
> Subject: RE: How make regex that means "contains regex#1 but NOT
> regex#2" ??
>  
> Match 'foo.*bar', except when 'not' appears between foo and bar.
> 
> 
> import re
> 
> s = 'fooAAABBBbar'
> print "Should match:", s
> m = re.match(r'(foo(.(?!not))*bar)', s);
> if m:
>   print m.groups()
> 
> print
> 
> s = 'fooAAAnotBBBbar'
> print "Should not match:", s
> m = re.match(r'(foo(.(?!not))*bar)', s);
> if m:
>   print m.groups()
> 
> 
> == Output ==
> Should match: fooAAABBBbar
> ('fooAAABBBbar', 'B')
> 
> Should not match: fooAAAnotBBBbar
> 


Fixed a bug with 'foonotbar'.  Conceptually it breaks down into:

First_half_of_Regex#1(not
Regex#2)(any_char_Not_followed_by_Regex#2)*Second_half_of_Regex#1

However, if possible, I would make it a two pass regex.  Match on
Regex#1, throw away any matches that then match on Regex#2.  A two pass
is faster and easier to code and understand.  Easy to understand == less
chance of a bug.  If you're worried about performance, then a) a
complicated regex may or may not be faster than two simple regexes, and
b) if you're passing that much data through a regex, you're probably I/O
bound anyway.


import re

ss = ('foobar', 'fooAAABBBbar', 'fooAAAnotBBBbar', 'fooAAAnotbar',
'foonotBBBbar', 'foonotbar')

for s in ss:
print s,
m = re.match(r'(foo(?!not)(?:.(?!not))*bar)', s);
if m:
print m.groups()
else:
print


== output ==
foobar ('foobar',)
fooAAABBBbar ('fooAAABBBbar',)
fooAAAnotBBBbar
fooAAAnotbar
foonotBBBbar
foonotbar

*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


dynamically load from module import xxx

2008-07-01 Thread Neal Becker
What is a good way to emulate:

from module import xxx
where 'module' is a dynamically generated string?

__import__ ('modulename', fromlist=['xxx'])

seems to be what I want, but then it seems 'xxx' is not placed in globals()
(which makes me wonder, what exactly did fromlist do?)

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


Re: Scope and program structure problems

2008-07-01 Thread Bruno Desthuilliers

John Dann a écrit :
Many thanks for the repsonse - much appreciated. 


And sorry - yes I was probably compounding two separate issues here -
the GUI one and the variable scope one. Maybe the wxPython list would
be the best place to ask more about the GUI side of things.

Then actually I can simplify my remaining question quite a lot - I
know you've partly answered this already but let me just rephrase
this:

It must be commonplace to first use a variable or object


What difference do you make between a variable and an object in this 
context ?



within one
function in a module and then want to use it again  - perhaps still
with the same value


For which definition of "same value" ? Remember, Python has *no* 
primitive types. Everything is an object.



as in the first function - in a second function.
So what's the recommended Python way round this?


This is way too general to give a single straight answer - whatever the 
language FWIW. Are both function in the same module ? Are they methods 
of a same object ? Is the first function calling the second or are they 
totally unrelated ?



If I was using .Net
then I'd be declaring the variables/objects explicitly


I personnally find the assignment, import, class and def statements (all 
having a binding behaviour) to be rather explicit.



and could set
their scope according to how/where they were declared.


Names bound at the top-level are globals to the module. Names bound 
within a function (including arguments) are locals, unless there has 
been a global statement for them before in the same function's body. 
Names bound within a class statement lives in the class's namespace (IOW 
: they become class attributes, shared by all instances). And names 
bound as object attributes (using either obj.name = whatever or 
setattr(obj, "name", whatever)) become, well, object attributes.


Now there may be a couple points worth paying attention to :

1/ some types (numerics, strings and tuples at least) are immutable. 
When doing :


  i = 1
  i = 2

the second assignment doesnt mutate the integer object bound to i, but 
rebinds i to another integer object.


2/ the scope of a name isn't necessarily related to the scope of the 
object bound to that name.


As an example, function's parameters *names* are local to the function, 
but the actual arguments - the objects passed when calling the function 
- are not.


IOW, rebinding a parameter name withing a function body will rebind the 
name locally, but will not affect the object originally bound to that 
name. But *mutating* an object passed as argument *will* (off course) 
affect the object outside the function.




But if the
Python way is not to declare vars before use


For which definition of "var" and "use" ? Did you really try to use a 
name that didn't exist in the accessible namespace - I mean, "use" for 
anything else than binding ?


The first binding of a name in a namespace *is* the 'declaration'. If a 
name is not defined in the currently accessible namespace, and you try 
to do anything else than binding it, you'll get an exception.



then this must create
some problems for cross-function use.


If what you mean is that it makes it harder to litter you code with true 
global variables, then it's obviously a *very* good thing IMHO !-)


But no, there's no more problem with shared state in Python than in any 
other (imperative) language I know - usually less in fact since there's 
no "application global" namespace. Most of the time, the appropriate way 
to share state is to use classes - heck, that's what they were created 
for, isn't it ?-). Sharing state thru module-level variables is ok as 
long you only access it for reading (pseudo-constants etc).


Sometimes, it's ok to use a module-level variable read-write, but this 
should be restricted to this particular module's  implementation stuff 
(IOW : the name is not part of the API, and only functions / methods in 
this same module access it), and never done without a clear enough 
understanding of Python's namespaces and bindings.




So it is best to declare such vars at the module level (ie outside of
a function) and set eg to Null/None or to assign them with a keyword
such as global or static (assuming that concept applies in Python)


it doesnt.


at first use inside a function or what?


Usually, when you really need a module-level variable to be shared 
read-write between functions, it happens that you can bind it to a 
sensible default. Now what is a "sensible default" depends on the 
concrete use case. Anyway, by all means, explicitely bind this name at 
the top-level, before any code accessing it, and if possible with a 
comment about this name being shared read/write by functions x and y.


My 2 cents...

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


Re: dynamically load from module import xxx

2008-07-01 Thread Guilherme Polo
On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker <[EMAIL PROTECTED]> wrote:
> What is a good way to emulate:
>
> from module import xxx
> where 'module' is a dynamically generated string?
>
> __import__ ('modulename', fromlist=['xxx'])
>
> seems to be what I want, but then it seems 'xxx' is not placed in globals()
> (which makes me wonder, what exactly did fromlist do?)

fromlist is used for importing subpackages/submodules of the first arg
of __import__. Since you are using "modulename", I'm guessing it is
not a package, fromlist will do nothing for you.
To solve your problem you could do getattr(__import__('modulename'), 'xxx').

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



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


How to use gnu readline library in program?

2008-07-01 Thread Grant Edwards
I'm trying to figure out how to use the gnu readline library so
that when my program is prompting the user for input there is
line editing and history support.

I've read and re-read the documentation for the "readline"
module in the standard library and I still can't figure out how
to use the module or even if the module is intended to do what
I want.  The example code all seems to be about on how to
modify the behavior of an interactive Python interpreter
session so you have things like auto-completion of Python
identifiers.

What I want to do is replace sys.stdin.readline() with
something that will provide the user with line editing and
history recall.  In other languages, one uses the Gnu readline
library to do that, but my reading of the Python library
documentation is that's not what the Python readline module is
for. Am I wrong?

-- 
Grant Edwards   grante Yow! On the road, ZIPPY
  at   is a pinhead without a
   visi.compurpose, but never without
   a POINT.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Implementing an 8 bit fixed point register

2008-07-01 Thread nickooooola
Thanks to all for the responses!

to MEl: I also want to build a pic simulator, but I want to do this as
"python for big project" learning exercise, I have used python in the
past only for small script and now I want to use it for something more
"big".
do you have some code to share?

myhdl seems interesting, I think that I can take a blick on its source
code...I think that must have something like
the 8 bit register class that I need somewhere

I try what you people have said, and if it turns to be something
useful, I report it to the community.

Nicola

Ps
excuse me for my english...
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do web templates separate content and logic?

2008-07-01 Thread Kirk Strauser
At 2008-06-30T19:34:53Z, Mike <[EMAIL PROTECTED]> writes:

> I should have say "why embedding HTML into Python is not good enough?" ;=)

I'm a programmer and would be able to cope with embedding HTML in assembler
if the need arose.

Having said that, embedding HTML in anything but HTML tends to be a bad idea
in the long run.  Inevitably, you're going to want to move stuff around, and
find out that you can't just move

print ""
for item in itemlist:
print "%s" % item
print ""

up near the top because you don't actually define itemlist until near the
end of your function, because it's built on the results of a bunch of other
code.

So then you "solve" the problem by leaving that snippet where it is and
moving all the other HTML print commands after it.  Oh, crud!  You realize
too late that some of your print commands have side effects:

for item in deletelist:
print "Deleting %s: %s" % (str(item), mangle(item))

and if you run that code *after* you generate itemlist, the results will be
all screwed up.

So you go back and move all of your logic to the top of the function and all
of the HTML print statements to the bottom.  And then you realize you've
written your very own page template, and that it's ugly, and that you
should've used something different from the very beginning.

That's why you don't embed HTML in Python, at least not for anything more
complicated than "Hello, world".
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Error from zipfile

2008-07-01 Thread Wesley Brooks
Dear Users,

I'm having a problem when trying to move script from Linux to Windows.
A zipfile opperation is failing with the message:

"BadZipFile: File is not a zip file"

I have a simple scripts that reads a zip file in the same way as any
other file into a string, then sends it across to a network where it
is saved as perusual into a file, then read in and processed by
zipfile. I've tried adding the flag to allow 64 bit and even using
uncompressed zip files. Niether fixes the problem.

The zip file and contents were created on linux. To be certain that
was not the issue I have emptied the zip file, created a new one,
opend all the files in wordpad and saved them, then put the contents
into the new file. Still no joy.

Any help would be greatly appreciated. On linux I'm running python 2.5
and on windows it is 2.4.

Thanks,

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


Re: Installing paramiko and pycrypto

2008-07-01 Thread GHZ
I installed from here:

http://bazaar-vcs.org/WindowsInstall

first pycrypto-2.0.1.win32-py2.5.zip
then paramiko-1.7.1-ctypes.win32.exe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Error from zipfile

2008-07-01 Thread Marc 'BlackJack' Rintsch
On Tue, 01 Jul 2008 16:38:23 +0100, Wesley Brooks wrote:

> Dear Users,
> 
> I'm having a problem when trying to move script from Linux to Windows.
> A zipfile opperation is failing with the message:
> 
> "BadZipFile: File is not a zip file"
> 
> I have a simple scripts that reads a zip file in the same way as any
> other file into a string, then sends it across to a network where it
> is saved as perusual into a file, […]

Are you sure you read and save the file in binary mode, especially on
windows!?

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

Discover Islam - The Fastest Growing Religion in the World !

2008-07-01 Thread ah
Correct your information about Islam
,
The Misunderstood Religion

  When you are ready_ you can enter this place!!!
 http://sultan.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: wrong md5 checksum

2008-07-01 Thread kkwweett

kkwweett a écrit :

Hi,

the download page (http://www.python.org/download/releases/3.0/) for 
Python 3000 shows :


9119625244b17aa35ed94b655a2b2135  13491200  python-3.0b1.msi

but I got

9119625244a57aa35ed94b655a2b2135  13491200  python-3.0b1.msi

(44a57 rather than 44b17 )

with several md5 checkers ( MdChecker (http://getmd5checker.com/) or a C 
 prog I've written)


Wrong md5 checksum even with Python2.5 :


import md5
m=md5.new()
message=open("python-3.0b1.msi","rb").read()
m.update(message)
m.hexdigest()

Answer : '9119625244a57aa35ed94b655a2b2135'


Does anyone know what can be done to decide wether the file is corrupted 
or the checksum given is wrong ?

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


Re: dynamically load from module import xxx

2008-07-01 Thread Neal Becker
Guilherme Polo wrote:

> On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker <[EMAIL PROTECTED]> wrote:
>> What is a good way to emulate:
>>
>> from module import xxx
>> where 'module' is a dynamically generated string?
>>
>> __import__ ('modulename', fromlist=['xxx'])
>>
>> seems to be what I want, but then it seems 'xxx' is not placed in
>> globals() (which makes me wonder, what exactly did fromlist do?)
> 
> fromlist is used for importing subpackages/submodules of the first arg
> of __import__. Since you are using "modulename", I'm guessing it is
> not a package, fromlist will do nothing for you.
> To solve your problem you could do getattr(__import__('modulename'),
> 'xxx').

This seems to be what I want, don't know if there is a simpler way:

stuff =['A','B'] 
module = __import__ (modulename)
for e in stuff:
  globals().update({e :  module.__dict__[e]})



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


Re: How to use gnu readline library in program?

2008-07-01 Thread Peter Otten
Grant Edwards wrote:

> I'm trying to figure out how to use the gnu readline library so
> that when my program is prompting the user for input there is
> line editing and history support.
> 
> I've read and re-read the documentation for the "readline"
> module in the standard library and I still can't figure out how
> to use the module or even if the module is intended to do what
> I want.  The example code all seems to be about on how to
> modify the behavior of an interactive Python interpreter
> session so you have things like auto-completion of Python
> identifiers.
> 
> What I want to do is replace sys.stdin.readline() with
> something that will provide the user with line editing and
> history recall.  In other languages, one uses the Gnu readline
> library to do that, but my reading of the Python library
> documentation is that's not what the Python readline module is
> for. Am I wrong?

Here's a simple example:
 
import readline

for s in "alpha beta gamma".split():
readline.add_history(s)

candidates = "red yellow pink blue black".split()

def completer(word, index):
matches = [c for c in candidates if c.startswith(word)]
try:
return matches[index] + " "
except IndexError:
pass


readline.set_completer(completer)
readline.parse_and_bind("tab: complete")

while 1:
print raw_input("$ ")

You may also consider using the cmd module.

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


Re: Embedding Python

2008-07-01 Thread Marcin Krol

Pau Freixes wrote:
If you search this function name into Google you will can found some 
examples, use for example PyMarshal_ReadObjectFromString or 
PyMarshal_ReadObjectFromFile


Rest assured I looked at a lot of code, but none of it was reading
in the .pyc file. I had no idea about the 8-byte header in the .pyc 
file, Carsten was so kind to show it.


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


Re: Embedding Python

2008-07-01 Thread Marcin Krol

Carsten Haese wrote:

python_code is a C string containing the raw bytes from your pyc file. 
Casting that to a PyObject pointer will not magically transform it into 
a Python code object. 


 well yeah, I kind of didn't think that through..


A pyc file contains the following:


1) An 8 byte header containing a magic number.
2) A "marshal" serialization of the code object.

So, in order to transform those contents into a code object, you need to 
skip the 8 byte header and an unmarshal the rest. Basically, replace the 
line above with something like this:


codeobj = PyMarshal_ReadObjectFromString(python_code+8, size-8);
mainobj = PyImport_ExecCodeModule("multiply", codeobj);

where codeobj is of type (PyObject *).

Once that works, add magic number checking and exception handling to taste.



Thanks. That's exactly what I was looking for.

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


Re: Embedding Python

2008-07-01 Thread Marcin Krol

Hello everyone,

In the meantime I managed to work out another solution, mainly thanks to 
reading the source code of some OSS projects. I post it here so somebody

else looking for solution to this problem had the example available:

cut
#include 
#include 
#include 
#include 
#include 

static FILE *read_module(const char *cpathname, long mtime)
{
  FILE *fp;
  long magic;
  long pyc_mtime;

  fp = fopen (cpathname, "rb");
  if (fp == NULL)
return NULL;

  magic = PyMarshal_ReadLongFromFile (fp);
  if (magic != PyImport_GetMagicNumber())
{
  fclose(fp);
  return NULL;
}

  pyc_mtime = PyMarshal_ReadLongFromFile (fp);
  if (mtime && pyc_mtime != mtime)
{
  fclose(fp);
  return NULL;
}

  return fp;
}


int main(int argc, char **argv)
{
int size;

Py_Initialize();
PyCodeObject *mainobj, *pycode;
PyObject *result, *mainmodule, *maindict;
mainmodule = PyImport_AddModule("__main__");
maindict = PyModule_GetDict(mainmodule);

FILE *f = read_module("multiply.pyc", 0L);
pycode = (PyCodeObject *) PyMarshal_ReadObjectFromFile(f);
printf("pointer: %d\n", pycode);

PyEval_EvalCode(pycode, maindict, maindict);
Py_Finalize();

}

cut

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


Classes for processing/parsing Wiki Markup text

2008-07-01 Thread Michael Mabin
Does anyone know if there are any generally available classes for parsing
various wiki markup formats?

-- 
| _ | * | _ |
| _ | _ | * |
| * | * | * |
--
http://mail.python.org/mailman/listinfo/python-list

Re: wrong md5 checksum

2008-07-01 Thread Peter Pearson
On Tue, 01 Jul 2008 17:54:05 +0200, kkwweett <[EMAIL PROTECTED]> wrote:
> kkwweett a écrit :
>> Hi,
>> 
>> the download page (http://www.python.org/download/releases/3.0/) for 
>> Python 3000 shows :
>> 
>> 9119625244b17aa35ed94b655a2b2135  13491200  python-3.0b1.msi
>> 
>> but I got
>> 
>> 9119625244a57aa35ed94b655a2b2135  13491200  python-3.0b1.msi
>> 
>> (44a57 rather than 44b17 )
>> 
[snip]
> Does anyone know what can be done to decide wether the file is corrupted 
> or the checksum given is wrong ?

For what it's worth, md5sum (GNU coreutils) 5.93 agrees with
your result.

This interesting almost-agreement could result from

 A. an error in the software that computed the value for the web page,
 B. a transcription error in putting the checksum on the web page,
 C. accidental corruption of the file, or
 D. a deliberate attempt to substitute a file with a similar MD5 sum.

Possibility C is unlikely, but would be the most exciting
development in cryptology this year.  If C turns out to be the
explanation, I hope someone will make sure sci.crypt gets told.
Possibility D would be awfully interesting, too.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: dynamically load from module import xxx

2008-07-01 Thread Guilherme Polo
On Tue, Jul 1, 2008 at 12:55 PM, Neal Becker <[EMAIL PROTECTED]> wrote:
> Guilherme Polo wrote:
>
>> On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker <[EMAIL PROTECTED]> wrote:
>>> What is a good way to emulate:
>>>
>>> from module import xxx
>>> where 'module' is a dynamically generated string?
>>>
>>> __import__ ('modulename', fromlist=['xxx'])
>>>
>>> seems to be what I want, but then it seems 'xxx' is not placed in
>>> globals() (which makes me wonder, what exactly did fromlist do?)
>>
>> fromlist is used for importing subpackages/submodules of the first arg
>> of __import__. Since you are using "modulename", I'm guessing it is
>> not a package, fromlist will do nothing for you.
>> To solve your problem you could do getattr(__import__('modulename'),
>> 'xxx').
>
> This seems to be what I want, don't know if there is a simpler way:
>
> stuff =['A','B']
> module = __import__ (modulename)
> for e in stuff:
>  globals().update({e :  module.__dict__[e]})
>

You could change that line to: globals()[e] = getattr(module, e)

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



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: ask for a RE pattern to match TABLE in html

2008-07-01 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 Jonathan Gardner <[EMAIL PROTECTED]> wrote:

> On Jun 27, 10:32 am, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
> > (ii) The regexes in languages like Python and Perl include
> > features that are not part of the formal CS notion of
> > "regular expression". Do they include something that
> > does allow parsing nested delimiters properly?
> >
> 
> In perl, there are some pretty wild extensions to the regex syntax,
> features that make it much more than a regular expression engine.
> 
> Yes, it is possible to match parentheses and other nested structures
> (such as HTML), and the regex to do so isn't incredibly difficult.
> Note that Python doesn't support this extension.

Huh. My evidently misinformed impression was that the regexes
in P and P were essentially equivalent. (I hope nobody takes
that as a complaint...)

> See http://www.perl.com/pub/a/2003/08/21/perlcookbook.html

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list

Re: How to use gnu readline library in program?

2008-07-01 Thread Grant Edwards
>> What I want to do is replace sys.stdin.readline() with
>> something that will provide the user with line editing and
>> history recall.  In other languages, one uses the Gnu readline
>> library to do that, but my reading of the Python library
>> documentation is that's not what the Python readline module is
>> for. Am I wrong?
>
> Here's a simple example:
>  
> import readline
>
> for s in "alpha beta gamma".split():
> readline.add_history(s)
>
> candidates = "red yellow pink blue black".split()
>
> def completer(word, index):
> matches = [c for c in candidates if c.startswith(word)]
> try:
> return matches[index] + " "
> except IndexError:
> pass
>
>
> readline.set_completer(completer)
> readline.parse_and_bind("tab: complete")
>
> while 1:
> print raw_input("$ ")

Ah, thanks.  It was far too simple.  What I was looking for was
simply:

  import readline

then replace sys.stdin.readline() with raw_input()

> You may also consider using the cmd module.

I'll have to keep the cmd module in mind for other applications
(where the user is entering commands).  Rather than commands,
the user of this application is entering data that changes
little (if any) from one line to the next, so raw_input() is
exactly what I needed.

-- 
Grant Edwards   grante Yow! I'm young ... I'm
  at   HEALTHY ... I can HIKE
   visi.comTHRU CAPT GROGAN'S LUMBAR
   REGIONS!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Classes for processing/parsing Wiki Markup text

2008-07-01 Thread Joshua Kugler
Michael Mabin wrote:

> Does anyone know if there are any generally available classes for parsing
> various wiki markup formats?

Several here:

http://pypi.python.org/pypi?%3Aaction=search&term=wiki&submit=search

I'm sure you could find a good one, and add your own markup if needed.

j

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


convert unicode characters to visibly similar ascii characters

2008-07-01 Thread Peter Bulychev
Hello.

I want to convert unicode character into ascii one.
The method ".encode('ASCII') " can convert only those unicode characters,
which fit into 0..128 range.

But there are still lots of characters beyond this range, which can be
manually converted to some visibly similar ascii characters. For instance,
there are several quotation marks in unicode, which can be converted into
ascii quotation mark.

Can this conversion be performed in automatic manner? After googling I've
only found that there exists Unicode database, which stores human-readable
information on notation of all unicode characters (
ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also exists
the Python adapter for this database (
http://docs.python.org/lib/module-unicodedata.html). Using this database I
can do something like `if notation.find('QUOTATION')!=-1:\n\treturn "'"`. I
believe there is more elegant way. Am I right?

Thanks.

-- 
Best regards,
Peter Bulychev.
--
http://mail.python.org/mailman/listinfo/python-list

Re: convert unicode characters to visibly similar ascii characters

2008-07-01 Thread Laszlo Nagy

Peter Bulychev wrote:

Hello.

I want to convert unicode character into ascii one.
The method ".encode('ASCII') " can convert only those unicode 
characters, which fit into 0..128 range.


But there are still lots of characters beyond this range, which can be 
manually converted to some visibly similar ascii characters. For 
instance, there are several quotation marks in unicode, which can be 
converted into ascii quotation mark.
Please be more specific. There is no general solution. Unicode can 
handle latin, cyrilic (russian), chinese, japanese and arabic characters 
in the same string. There are thousands of possible non-ascii characters 
and many of them are not similar to any ascii character.


If you only want this to work for a subset, please define that subset.

  Laszlo

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


Convert string to char array

2008-07-01 Thread Brandon
How do I convert a string to a char array?  I am doing this so I can edit 
the string received from an sql query so I can remove unnecessary 
characters. 


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


Re: convert unicode characters to visibly similar ascii characters

2008-07-01 Thread Peter Bulychev
Thank you for you answer.

If you only want this to work for a subset, please define that subset.

Actually, I want to convert only punctuations (dots, commas, hyphens and so
on).

-- 
Best regards,
Peter Bulychev.
--
http://mail.python.org/mailman/listinfo/python-list

Re: connecting to DBMS

2008-07-01 Thread teebes
On Jul 1, 9:35 am, varun chadha <[EMAIL PROTECTED]> wrote:
> i am a newbie to python and is working on an application which needs
> to connect to the database. can anyone guide me through the DBMS that
> i can use and the module to connect to it. currently i have MySQL
> installed using the link on the python.org site but is unable to
> connect to it through python. pls specify the link  to the tutorials
> which can guide to connect and execute my query. hopes u understood
> what i meant to say.
> thanks in advance

mysql-python is probably your best bet for MySQL databases
http://sourceforge.net/projects/mysql-python/

As far as tutorials are concerned, the presentation linked in this
page is very good, given by the creator of the interface Andy Dustman:
http://bogdan.org.ua/2007/09/07/mysql-python-good-mysqldb-tutorial-examples.html
(scroll down to page 7 for the stuff on MySQL).

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


Re: Convert string to char array

2008-07-01 Thread Larry Bates

Brandon wrote:
How do I convert a string to a char array?  I am doing this so I can edit 
the string received from an sql query so I can remove unnecessary 
characters. 




The precise answer is:

>>> s = 'abcdefghi'
>>> l = list(s)
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>>

But quite often you can just to the replace without doing the conversion

>>> s = 'abc,de,fghi'
>>> s2 = s.replace(',','')
>>> s2 = s.replace(',','')
'abcdefghi'
>>>

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


Re: Convert string to char array

2008-07-01 Thread Mike Kent
On Jul 1, 2:49 pm, "Brandon" <[EMAIL PROTECTED]> wrote:
> How do I convert a string to a char array?  I am doing this so I can edit
> the string received from an sql query so I can remove unnecessary
> characters.

Answering your specific question:

Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'hello'
>>> l = list(s)
>>> l
['h', 'e', 'l', 'l', 'o']
>>>

But more generally, you might want to read up on the string methods
available to you, such as replace():
http://docs.python.org/lib/string-methods.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Implementing an 8 bit fixed point register

2008-07-01 Thread Terry Reedy



nickola wrote:

Hello to all
I'm about to write a simulator for a microcontroller in python
(why python? because I love it!!!)

but I have a problem.

The registry of this processor are all 8 bit long (and 10 bit for some
other strange register)
and I need to simulate the fixed point behaviour of the register,
and to access the single bit.


In Python3, I would use a (mutable) bytearray.

IDLE 3.0b1
>>> reg1 = bytearray((0,)*8) # or *10 for 10 bits
>>> reg1
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
>>> reg1[1]=1
>>> reg1[1]
1
>>> tuple(reg1)
(0, 1, 0, 0, 0, 0, 0, 0)

A bytearray subclass could enforce that all 'bits' (stored as bytes) are 
0 or 1, have a customized representation to your taste, and add methods 
like .flipall().


The overhead of using 8 bytes instead of 1 to hold the object value is 
actually small compared to the minimum object size of 16 bytes (on Win32XP).


>>> sys.getsizeof(reg1)
24

In Python2.x, you can use the array module to make equivalent mutable 
arrays of chars.


Terry Jan Reedy

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


Re: convert unicode characters to visibly similar ascii characters

2008-07-01 Thread Laszlo Nagy

Peter Bulychev wrote:

Thank you for you answer.

If you only want this to work for a subset, please define that subset.

Actually, I want to convert only punctuations (dots, commas, hyphens 
and so on).

Then make your translation table manually and apply this method:

unicode.translate

Finally

print s.encode('ascii')

If you get an UnicodeEncodeError then it means you had other (not 
translated, non-ascii) characters in the original string.


Best,

  Laszlo

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


Re: Getting sorting order

2008-07-01 Thread Tobiah

 master,slave1,slave2=zip(*x)

What does the asterisk do here?

Thanks
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to char array

2008-07-01 Thread Brandon
Thank you both for your help.

"Mike Kent" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On Jul 1, 2:49 pm, "Brandon" <[EMAIL PROTECTED]> wrote:
> How do I convert a string to a char array? I am doing this so I can edit
> the string received from an sql query so I can remove unnecessary
> characters.

Answering your specific question:

Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'hello'
>>> l = list(s)
>>> l
['h', 'e', 'l', 'l', 'o']
>>>

But more generally, you might want to read up on the string methods
available to you, such as replace():
http://docs.python.org/lib/string-methods.html 


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


Please check my understanding...

2008-07-01 Thread Tobiah
list.append([1,2]) will add the two element list as the next
element of the list.

list.extend([1,2]) is equivalent to list = list + [1, 2]
and the result is that each element of the added list
becomes it's own new element in the original list.

Is that the only difference?

>From the manual:

s.extend(x)  |  same as s[len(s):len(s)] = x

But: (python 2.5.2)

>>> a
[1, 2, 3]
>>> a[len(a):len(a)] = 4
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only assign an iterable
>>> 

Also, what is the difference between list[x:x] and list[x]?

>>> a[3:3] = [4]
>>> a
[1, 2, 3, 4]
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Implementing an 8 bit fixed point register

2008-07-01 Thread Grant Edwards
On 2008-07-01, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
>
> nickola wrote:
>> Hello to all
>> I'm about to write a simulator for a microcontroller in python
>> (why python? because I love it!!!)
>> 
>> but I have a problem.
>> 
>> The registry of this processor are all 8 bit long (and 10 bit for some
>> other strange register)
>> and I need to simulate the fixed point behaviour of the register,
>> and to access the single bit.
>
> In Python3, I would use a (mutable) bytearray.
>
> IDLE 3.0b1
> >>> reg1 = bytearray((0,)*8) # or *10 for 10 bits
> >>> reg1
> bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
> >>> reg1[1]=1
> >>> reg1[1]
> 1
> >>> tuple(reg1)
> (0, 1, 0, 0, 0, 0, 0, 0)
>
> A bytearray subclass could enforce that all 'bits' (stored as bytes) are 
> 0 or 1, have a customized representation to your taste, and add methods 
> like .flipall().

It seems like implementing ALU operations on such arrays would
be a lot more work than implementing bit-indexing on a type
derived on a more "integer" like base. I'm pretty fuzzy on how
one sub-classes basic things like integers, so maybe I'm all
wet, and adding __getitem__ and __setitem__ to an integer type
isn't even possible.

-- 
Grant Edwards   grante Yow! Do you guys know we
  at   just passed thru a BLACK
   visi.comHOLE in space?
--
http://mail.python.org/mailman/listinfo/python-list


Re: convert unicode characters to visibly similar ascii characters

2008-07-01 Thread Terry Reedy



Peter Bulychev wrote:

Hello.

I want to convert unicode character into ascii one.
The method ".encode('ASCII') " can convert only those unicode 
characters, which fit into 0..128 range.


But there are still lots of characters beyond this range, which can be 
manually converted to some visibly similar ascii characters. For 
instance, there are several quotation marks in unicode, which can be 
converted into ascii quotation mark.


Can this conversion be performed in automatic manner? After googling 
I've only found that there exists Unicode database, which stores 
human-readable information on notation of all unicode characters 
(ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also 
exists the Python adapter for this database 
(http://docs.python.org/lib/module-unicodedata.html). Using this 
database I can do something like `if 
notation.find('QUOTATION')!=-1:\n\treturn "'"`. I believe there is more 
elegant way. Am I right?


I believe you will have to make up your own translation dictionary for 
the translations *you* want.  You should then be able to use that with 
the .translate() method.


tjr

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


Re: ImportError: No module named _md5

2008-07-01 Thread Robert Kern

[EMAIL PROTECTED] wrote:

Hello,

Does anyone know how to fix this error when trying to build MySQL-
python-1.2.2:

python setup.py build
Traceback (most recent call last):
  File "setup.py", line 5, in 
import ez_setup; ez_setup.use_setuptools()
  File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py",
line 83, in use_setuptools
egg = download_setuptools(version, download_base, to_dir,
download_delay)
  File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py",
line 111, in download_setuptools
import urllib2, shutil
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/
lib/python2.5/urllib2.py", line 91, in 
import hashlib
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/
lib/python2.5/hashlib.py", line 133, in 
md5 = __get_builtin_constructor('md5')
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/
lib/python2.5/hashlib.py", line 60, in __get_builtin_constructor
import _md5
ImportError: No module named _md5

I then tried installing py25-hashlib via macports, which never
completes:

sudo port install py25-hashlib
Password:
Waiting for lock on /opt/local/var/macports/build/
_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25-
hashlib/work/.macports.py25-hashlib.state

Do I need to completely reinstall python? I'm using 2.5.2 which
shipped with Leopard.


Delete the directory

/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25-hashlib/

and try building py25-hashlib again.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Please check my understanding...

2008-07-01 Thread Matimus
On Jul 1, 12:35 pm, Tobiah <[EMAIL PROTECTED]> wrote:
> list.append([1,2]) will add the two element list as the next
> element of the list.
>
> list.extend([1,2]) is equivalent to list = list + [1, 2]
> and the result is that each element of the added list
> becomes it's own new element in the original list.
>
> Is that the only difference?
>
> From the manual:
>
> s.extend(x)  |  same as s[len(s):len(s)] = x
>
> But: (python 2.5.2)
>
> >>> a
> [1, 2, 3]
> >>> a[len(a):len(a)] = 4
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: can only assign an iterable
>
>
>
> Also, what is the difference between list[x:x] and list[x]?
>
> >>> a[3:3] = [4]
> >>> a
>
> [1, 2, 3, 4]
> ** Posted fromhttp://www.teranews.com**

In this example:
> s.extend(x)  |  same as s[len(s):len(s)] = x

x _must_ be iterable. As the error states, `4` is not iterable.

the s[start:stop] notation is called slicing:

>>> x = range(10)
>>> x[0]
0
>>> x[1]
1
>>> x[0:1]
[0]
>>> x[0:2]
[0, 1]
>>> x[0:3]
[0, 1, 2]
>>> x[1:3]
[1, 2]
>>> x[5:-1]
[5, 6, 7, 8]
>>> x[5:]
[5, 6, 7, 8, 9]


In general `x[len(x):len(x)] = seq` is a stupid way to extend a list,
just use .extend or +=.

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


How to make a function associated with a class?

2008-07-01 Thread Kurda Yon
Hi,

I have a class called "vector". And I would like to define a function
"dot" which would return a dot product of any two  "vectors". I want
to call this function as follow: dot(x,y).

Well, I can define a functions "dot" outside the class and it works
exactly as I want. However, the problem is that this function is not
associated with the class (like methods a method of the class).

For example, if I call "x.calc()" or "y.calc()", python will execute
different methods if "x" and "y" belongs to different classes. I want
to have the same with my "dot" function. I.e. I want it calculates the
dot product ONLY IF the both arguments of that function belong to the
"vector" class.

Is it possible?

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


Re: Please check my understanding...

2008-07-01 Thread [EMAIL PROTECTED]
On 1 juil, 21:35, Tobiah <[EMAIL PROTECTED]> wrote:
> list.append([1,2]) will add the two element list as the next
> element of the list.

list.append(obj) will add obj as the last element of list, whatever
type(obj) is.

> list.extend([1,2]) is equivalent to list = list + [1, 2]

Not quite. The second statement rebinds the name list (a very bad name
BTW but anyway...) to a new list object composed of elements of the
list object previously bound to the name list and the elements of the
anonymous list object [1, 2], while the first expression modifies the
original list object in place. The results will compare equal (same
type, same content), but won't be identical (not the same object).

A better definition for list.extend(iterable) is that it is equivalent
to:

for item in iterable:
   list.append(item)

The difference is important if list is bound to other names. A couple
examples:

a = [1, 2, 3}
b = a
# b and a points to the same list object
b is a
=> True

a.append(4)
print b
=> [1, 2, 3, 4]

b.extend([5, 6])
print a
=> [1, 2, 3, 4, 5, 6]

a = a + [7, 8]
print b
=> [1, 2, 3, 4, 5, 6]

print a
=> [1, 2, 3, 4, 5, 6, 7, 8]

a is b
=> False

def func1(lst):
lst.extend([9, 10])
print lst

def func2(lst):
lst = lst + [11, 12]
print lst

func1(a)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func2(a)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


> Is that the only difference?

cf above.

> From the manual:
>
> s.extend(x)  |  same as s[len(s):len(s)] = x
>
> But: (python 2.5.2)
>
> >>> a
> [1, 2, 3]
> >>> a[len(a):len(a)] = 4
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: can only assign an iterable

And if you try with extend, you'll also have a TypeError:

a.extend(4)
=> Traceback (most recent call last):
 File "", line 1, in 
TypeError: 'int' object is not iterable


list.extend expects an iterable, and so does slice assignment.

You want:

a[len(a):len(a)] = [4]

>
> Also, what is the difference between list[x:x] and list[x]?

The first expression refers to the *sublist* starting at x and ending
one element before x. Of course, if x == x, then it refers to an empty
list !-)

>>> a[3:3]
[]
>>> a[1:3]
[2, 3]
>>> a[0:2]
[1, 2]
>>> a[0:1]
[1]
>>>

The second expression refers to the *element* at index x.

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


Re: Why is recursion so slow?

2008-07-01 Thread Nick Craig-Wood
Luis Zarrabeitia <[EMAIL PROTECTED]> wrote:
> > is that what lazy evaluation in functional languages avoids thus
> > making recursive versions much faster?
> 
>  Not exactly... Functional languages are (or should be) optimized for 
> recursion,
>  but if the algorithm you write is still exponential, it will still
>  take a long time.

Actually I think functional language are likely to perform
memoization.  By definition any function in a functional language will
always produce the same result if given the same arguments, so you can
memoize any function.

See here for a python memoize which makes the recursive algorithm run
fast...

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201

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


Re: raw_input into Tkinter ?

2008-07-01 Thread Sebastian "lunar" Wiesner
Matimus <[EMAIL PROTECTED]>:

> On Jun 30, 9:55 am, [EMAIL PROTECTED] wrote:
>> Is there any way to type into a Tkinter frame window?
>> I want to use raw_input() within a Tkinter frame.
> 
> `raw_input(prompt)` just calls `sys.stdout.write(prompt)` and returns
> `sys.stdin.readline()`.
It does more like providing readline support, if readline is loaded.



-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list

Re: Please check my understanding...

2008-07-01 Thread Marc 'BlackJack' Rintsch
On Tue, 01 Jul 2008 12:35:01 -0700, Tobiah wrote:

> list.append([1,2]) will add the two element list as the next
> element of the list.
> 
> list.extend([1,2]) is equivalent to list = list + [1, 2]
> and the result is that each element of the added list
> becomes it's own new element in the original list.

It's not 100% equivalent because `list.extend()` mutates the original list
while ``+`` creates a new list object:

In [8]: a = [1, 2, 3]

In [9]: b = a

In [10]: b.extend([4, 5])

In [11]: b
Out[11]: [1, 2, 3, 4, 5]

In [12]: a
Out[12]: [1, 2, 3, 4, 5]

In [13]: b = b + [6, 7]

In [14]: b
Out[14]: [1, 2, 3, 4, 5, 6, 7]

In [15]: a
Out[15]: [1, 2, 3, 4, 5]

> Is that the only difference?
> 
> From the manual:
> 
> s.extend(x)  |same as s[len(s):len(s)] = x
> 
> But: (python 2.5.2)
> 
 a
> [1, 2, 3]
 a[len(a):len(a)] = 4
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: can only assign an iterable
 

Have you tried `extend()` with the same value?

In [15]: a
Out[15]: [1, 2, 3, 4, 5]

In [16]: a.extend(6)
---
 Traceback (most recent call last)

/home/bj/ in ()

: 'int' object is not iterable

See, both ways need something iterable.

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


Re: Why is recursion so slow?

2008-07-01 Thread [EMAIL PROTECTED]
On 1 juil, 22:46, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
(snip)

>  By definition any function in a functional language will
> always produce the same result if given the same arguments,

This is only true for pure functional languages.

I know you know it, but someone might think it also applies to unpure
FPLs like Common Lisp.

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


Re: How to make a function associated with a class?

2008-07-01 Thread [EMAIL PROTECTED]
On 1 juil, 22:43, Kurda Yon <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a class called "vector". And I would like to define a function
> "dot" which would return a dot product of any two  "vectors". I want
> to call this function as follow: dot(x,y).
>
> Well, I can define a functions "dot" outside the class and it works
> exactly as I want. However, the problem is that this function is not
> associated with the class (like methods a method of the class).
>
> For example, if I call "x.calc()" or "y.calc()", python will execute
> different methods if "x" and "y" belongs to different classes. I want
> to have the same with my "dot" function. I.e. I want it calculates the
> dot product ONLY IF the both arguments of that function belong to the
> "vector" class.
>
> Is it possible?

You don't need to make dot() a method of your Vector class to have
this behaviour, and making it a method of the Vector class isn't
enough to have this behaviour.

The simplest solution would be:

class Vector(object):
def dot(self, other):
if not isinstance(other, type(self)):
raise TypeError("can only calculate the dot product of two
vectors")
# do the job here and return what's appropriate

Now since it's a binary operator, you might as well implement it as
such:

class Vector(object):
def __mul__(self, other):
if not isinstance(other, type(self)):
raise TypeError("can only calculate the dot product of two
vectors")
# do the job here and return what's appropriate

Then use it as doproduct = vector1 * vector2


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


Attribute reference design

2008-07-01 Thread chamalulu
Hello.
I think I'm aware of how attribute access is resolved in python. When
referencing a class instance attribute which is not defined in the
scope of the instance, Python looks for a class attribute with the
same name. (For assignment or deletion this is not the case,
thankfully.)
I've been trying to understand why? What is the reason behind, or
practical purpose of, this design decision? Anyone, please enlighten
me.

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


Re: Attribute reference design

2008-07-01 Thread Diez B. Roggisch

chamalulu schrieb:

Hello.
I think I'm aware of how attribute access is resolved in python. When
referencing a class instance attribute which is not defined in the
scope of the instance, Python looks for a class attribute with the
same name. (For assignment or deletion this is not the case,
thankfully.)
I've been trying to understand why? What is the reason behind, or
practical purpose of, this design decision? Anyone, please enlighten
me.


How else would you resolve methods which are of course defined on the 
class but invoked through the instance?


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


Re: How to make a function associated with a class?

2008-07-01 Thread Kurda Yon
On Jul 1, 5:01 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On 1 juil, 22:43, Kurda Yon <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
>
> > I have a class called "vector". And I would like to define a function
> > "dot" which would return a dot product of any two  "vectors". I want
> > to call this function as follow: dot(x,y).
>
> > Well, I can define a functions "dot" outside the class and it works
> > exactly as I want. However, the problem is that this function is not
> > associated with the class (like methods a method of the class).
>
> > For example, if I call "x.calc()" or "y.calc()", python will execute
> > different methods if "x" and "y" belongs to different classes. I want
> > to have the same with my "dot" function. I.e. I want it calculates the
> > dot product ONLY IF the both arguments of that function belong to the
> > "vector" class.
>
> > Is it possible?
>
> You don't need to make dot() a method of your Vector class to have
> this behaviour, and making it a method of the Vector class isn't
> enough to have this behaviour.
>
> The simplest solution would be:
>
> class Vector(object):
> def dot(self, other):
> if not isinstance(other, type(self)):
> raise TypeError("can only calculate the dot product of two
> vectors")
> # do the job here and return what's appropriate
>
> Now since it's a binary operator, you might as well implement it as
> such:
>
> class Vector(object):
> def __mul__(self, other):
> if not isinstance(other, type(self)):
> raise TypeError("can only calculate the dot product of two
> vectors")
> # do the job here and return what's appropriate
>
> Then use it as doproduct = vector1 * vector2
>
> HTH

As far as I understood, In the first case, you gave,  I need to call
the function as follows "x.dot(y)". In the second case I need to call
the function as follows "x*y". But I want to call the function as
follows "dot(x,y)".

By the way, "type(self)" returns the name of the class to which the
"self" belongs?
Does "instance" return "true" if the first argument belongs to the
class whose name is given in the second argument?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting sorting order

2008-07-01 Thread Nick Craig-Wood
Tobiah <[EMAIL PROTECTED]> wrote:
>  master,slave1,slave2=zip(*x)
> 
>  What does the asterisk do here?
> 
>  Thanks
>  ** Posted from http://www.teranews.com **

Instead of passing a single argument x to zip() you can think of it
unpacking the list x and passing len(x) arguments to zip.

So if x = [1,2,3,4]

zip(*x) == zip(1,2,3,4)

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


Re: Why is recursion so slow?

2008-07-01 Thread Rich Harkins

Nick Craig-Wood wrote:
[snip]

By definition any function in a functional language will
always produce the same result if given the same arguments, so you can
memoize any function.



Ah, so that's why time.time() seems to be stuck...  ;)

Rich

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


Re: How to make a function associated with a class?

2008-07-01 Thread Victor Noagbodji
>
> Hi,
>
> I have a class called "vector". And I would like to define a function
> "dot" which would return a dot product of any two  "vectors". I want
> to call this function as follow: dot(x,y).
>
> Well, I can define a functions "dot" outside the class and it works
> exactly as I want. However, the problem is that this function is not
> associated with the class (like methods a method of the class).
>
> For example, if I call "x.calc()" or "y.calc()", python will execute
> different methods if "x" and "y" belongs to different classes. I want
> to have the same with my "dot" function. I.e. I want it calculates the
> dot product ONLY IF the both arguments of that function belong to the
> "vector" class.
>
> Is it possible?
>
> Thank you in advance.
>
> Do you think a static method will do the thing?
>

Well you can define the function inside the class.
Then create a name outside the class that references it. Is is.

dot = Class.dot.

By the way, why do you want to tie this function to the class?


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

Combination of element-wise and matrix multiplication

2008-07-01 Thread Jonno
I have two 2x2 arrays a & b.
a=(([c,d],[e,f]))
b=(([g,h],[i,j]))
Each of c,d,e,f,g,h,i,j are all 1xN arrays
I want to matrix multiply a & b to create a 2x2 array x, where the elements
of x are created with element-wise math and result in the following:
x[0,0] = c*g+d*i
x[0,1] = c*h+d*j
x[1,0] = e*g+f*i
x[1,1] = e*h+f*j

What is the simplest way to do this? I ended up doing the matrix
multiplication manually as above but this doesn't scale very nicely if a & b
become larger size.

Cheers,

Jonno.
-- 
"If a theory can't produce hypotheses, can't be tested, can't be disproven,
and can't make predictions, then it's not a theory and certainly not
science." by spisska on Slashdot, Monday April 21, 2008
--
http://mail.python.org/mailman/listinfo/python-list

AttributeError with embedded Python

2008-07-01 Thread PlayDough
I've embedded Python in an extension for a program we are using here
at work.  And I'm a bit stumped as to why I am getting an
AttributeError only in the embedded Python.

First, a bit of what I am doing.  We use a simulator for a
microprocessor we are using in our systems.  Our simulator allows for
extensions that can be loaded as shared libraries.  Rather than code
the entire extension in C/C++, I would like to make use of Python to
script the extension.

So, I first initialize Python (examples below leave out the error
checking, but it is there):

Py_Initialize();

And then I make sure the script directory is in the path with
Py_GetPath() and PySys_SetPath().

Finally, I import the script (say it is in a local file 'script.py'):

pName = PyString_FromString("script");
pModule = PyImport_Import(pName);

Once the module is imported, I get objects to the functions in the
script I want to call later, which I do with:

pName = PyString_FromString("foo");
pFunc  = PyObject_GetAttr(pModule, pName);

Later, I come back and call the function:

pResult = PyObject_CallObject(pFunc, NULL);

And it always fails whenever I iterate of a list.  Say for example my
Python function is:

def foo():
  a = ['cat', 'window', 'defenstrate']
  for x in a:
print x, len(x)

Now, the function runs, i.e. I see the output ("cat 3\nwindow
6\ndefenstrate 11\n"), but I always get the following error message:

Traceback (most recent call last):
  File "./script.py", line 3, in foo
for x in a:
AttributeError: 'module' object has no attribute 'reset'

Now, if I run this exact same script using Python standalone, i.e.:

Python 2.3.4 (#1, Nov 20 2007, 15:18:15)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import script
>>> script.foo()
cat 3
window 6
defenstrate 11
>>>

(I know, and old version of Python.  But we are stuck with it because
our processes require us to validate a newer version if we change.)

This works great.  What is the difference?  Why does it work in one
context but not the other?

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


  1   2   >