Instance

2008-07-17 Thread karthikbalaguru
Hi,

I am new to python. I am trying to use the python files given to me
for bringing up a setup.
I get the following error while trying to use a python file -
AttributeError : Classroom instance has no attribute 'desk_offset'

How to resolve this ?
Should i need to define desk_offset to zero in the python file ?

Any ideas ..

Thx in advans,
Karthik Balaguru
--
http://mail.python.org/mailman/listinfo/python-list


Getting a unknown word out of a list with no spaces

2008-07-17 Thread Alexnb

Hello

Lets say I have a string:

--a href="/browse/brick"--brick--/a--

The -- needs to be replaced with < or > where applicable. 

and I want the "brick" out of that string (the second brick that is). How
can I get just the "brick" out of that string?
-- 
View this message in context: 
http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18502758.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread Alexandr N Zamaraev

s = '--a href="/browse/brick"--brick--/a--'
s

'--a href="/browse/brick"--brick--/a--'
''.join('<%s>' % l if i % 2 == 1 else l for i, l in 

enumerate(s.split('--')))
'brick'

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


Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread Alexnb



Alexandr N Zamaraev wrote:
> 
 s = '--a href="/browse/brick"--brick--/a--'
 s
> '--a href="/browse/brick"--brick--/a--'
 ''.join('<%s>' % l if i % 2 == 1 else l for i, l in 
> enumerate(s.split('--')))
> ' /browse/brick brick '
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

I'm sorry, I don't think I was being clear. I replaced the <'s with -- so it
would post online w/o actually making a link. I just need to know how to get
the "brick" out.

-- 
View this message in context: 
http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503144.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread Alexandr N Zamaraev

Alexnb wrote:

s = '--a href="/browse/brick"--brick--/a--'
s

'--a href="/browse/brick"--brick--/a--'
''.join('<%s>' % l if i % 2 == 1 else l for i, l in 

enumerate(s.split('--')))
' /browse/brick brick '


I'm sorry, I don't think I was being clear. I replaced the <'s with -- so it
would post online w/o actually making a link. I just need to know how to get
the "brick" out.

1) if string really '--a href="/browse/brick"--brick--/a--'
>>> s.split('--', 3)[2]
brick
2) if string 'brick'
>>> s.split('>', 1)[1].split('<')[0]
brick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Instance

2008-07-17 Thread Jeroen Ruigrok van der Werven
-On [20080717 09:01], karthikbalaguru ([EMAIL PROTECTED]) wrote:
>AttributeError : Classroom instance has no attribute 'desk_offset'

You are using a Classroom instance and probably assigning something to the
instance's variable/attribute 'desk_offset'. Except that the class Classroom
has no self.desk_offset.

So in your class definition you would need to add something to __init__()
like:

self.desk_offset = None # or 0 or...

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
A frightened mental vortex we will be, a Sun we seek, a Sun we flee...
--
http://mail.python.org/mailman/listinfo/python-list

Handling events using pycairo

2008-07-17 Thread Mr SZ
Hi,



I'm trying to create a rectangle when the user presses or releases the
mouse over a cairo object.I'm using the eventBox to capture the mouse
events.

Now the problem is the shapes is beng drawn when I call it from the
expose_event event handler and nothing happens when I call the same
from the mouse release event handler.



Here is my code :



#!/usr/bin/env python



import sys

import cairo

import gtk





start = None #Starting co-ords

stop = None #Ending co-ords

box = None  #Tuple of co-ords for drawing rect

ctx = None #Cairo Widget

def button_press(widget, event, surface):

    global start

    start = (int(event.x),int(event.y))

def motion_notify(widget, event, surface):

    pass

def button_release(widget, event, surface):

    global stop,ctx

    ctx = None

    ctx = widget.window.cairo_create()

    ctx.set_source_surface(surface, 0,0)

    ctx.paint()

    print ctx

    stop =  (int(event.x),int(event.y))

    box = (start[0],start[1])

    draw_dotrect(ctx,box)

    print "Released" + str(box)



def draw_dotrect(ctx,box):

    ctx.set_source_rgba(0, 0, 0,0.5)

    ctx.save()

    ctx.new_path()

    ctx.translate(3*20, 0)

    square(ctx,box)

    ctx.fill()

    ctx.restore()

    ctx.set_line_width(20 / 16)

    ctx.set_tolerance(0.1)

    ctx.set_line_join(cairo.LINE_JOIN_MITER)

    ctx.set_dash([20/2.0, 20/2.0], 8)

    ctx.save()

    ctx.new_path()

    ctx.set_source_rgb(0,0 ,0 )

    ctx.translate(3*20, 0)

    square(ctx,box)

    ctx.stroke_preserve()

    ctx.restore()

    

def expose_event(widget, event, surface):

    global ctx

    ctx = widget.window.cairo_create()

    ctx.set_source_surface(surface, 0,0)

    ctx.paint()

    

    #draw_dotrect(ctx,(20,20)) # If called from here,it works

    

    

def square(ctx,box):

    ctx.move_to(0, 0)

    ctx.rel_line_to(2*50, 0)

    ctx.rel_line_to(0, 2*50)

    ctx.rel_line_to(-2*50, 0)

    ctx.close_path()

    

    if len(sys.argv) != 2:

        raise SystemExit('usage: png_view.py png_file')



filename = sys.argv[1]



surface = cairo.ImageSurface.create_from_png(filename)

Width  = surface.get_width()

Height = surface.get_height()



win = gtk.Window()

win.connect('destroy', gtk.main_quit)



event_box = gtk.EventBox()

win.add(event_box)



drawingarea = gtk.DrawingArea()

event_box.add(drawingarea)



drawingarea.connect('expose_event', expose_event, surface)

event_box.connect('button_press_event',button_press,surface)

event_box.connect('button_release_event',button_release,surface)

event_box.connect('motion_notify_event',motion_notify,surface)



drawingarea.set_size_request(Width,Height)



win.show_all()

gtk.main()



It doesn't throw me any error.I hardcoded the box to simplify things
.    I also create a new ctx in the release event handler else it
throws an error:CAIRO_STATUS_SURFACE_FINISHED




Any ideas why ?

" life isn't heavy enough,it flies away and floats far above action"


  Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au--
http://mail.python.org/mailman/listinfo/python-list

how to do -vv for very verbose?

2008-07-17 Thread Thomaye
Create something else.  There is no such thing as "very" 
verbose!!!  There is only verbose or not verbose.



**Get the scoop on last night's hottest shows and the live music 
scene in your area - Check out TourTracker.com!  
(http://www.tourtracker.com?NCID=aolmus0005000112)
--
http://mail.python.org/mailman/listinfo/python-list

Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread Alexnb



Alexandr N Zamaraev wrote:
> 
> Alexnb wrote:
>> s = '--a href="/browse/brick"--brick--/a--'
>> s
>>> '--a href="/browse/brick"--brick--/a--'
>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in 
>>> enumerate(s.split('--')))
>>> ' /browse/brick brick '
>> 
>> I'm sorry, I don't think I was being clear. I replaced the <'s with -- so
>> it
>> would post online w/o actually making a link. I just need to know how to
>> get
>> the "brick" out.
> 1) if string really '--a href="/browse/brick"--brick--/a--'
>  >>> s.split('--', 3)[2]
> brick
> 2) if string ' /browse/brick brick '
>  >>> s.split('>', 1)[1].split('<')[0]
> brick
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Excellent! it works. But I have one more question. How can I test to see if
the first character of a string is what I want, for example, how can I test
to see if  the first char of a string is "<"?

-- 
View this message in context: 
http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503367.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Rotating a cube

2008-07-17 Thread Fredrik Lundh

J-Burns wrote:


Is there a built in Python function for this?


for answering questions that have nothing to do with programming, and 
looks quite a bit like homework?  don't think they've added that one yet.


maybe you should look for a geometry newsgroup/forum?



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


Re: how to debug python's extend module written in c/c++ on windows

2008-07-17 Thread Diez B. Roggisch

[EMAIL PROTECTED] schrieb:

dear Diez:

   I need step into c function in extending module(DLL) when debugging
the script. and I want Single-step debugging the extend module itself,
but python script Launched The whole process.


That is exactly what attaching a C-debugger to python will give you. Did 
you actually try it? Do you know how to debug C-programs?


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


Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-17 Thread Fredrik Lundh

Stefan Scholl wrote:


Django isn't ready.


That's a remarkably ignorant statement.


The 1.0 release will be in September.


So?  "1.0" will be done then, yes.  In what way does that mean that 
Django itself isn't ready, in any sane sense of that word?


(For bystanders, Django's 0.91 release in early 1996 was what most
people would have called "1.0".  0.95 was a "2.0" release, and the
upcoming 1.0 release is pretty much a "3.0".  Or if you use Micro-
soft's numbering system, 0.91 was "3.0", 0.95 is "5.0" and 1.0 is,
what, "8.0"?)



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


How to process a very large (4Gb) tarfile from python?

2008-07-17 Thread Terry Carroll
I am trying to do something with a very large tarfile from within
Python, and am running into memory constraints.  The tarfile in
question is a 4-gigabyte datafile from freedb.org,
http://ftp.freedb.org/pub/freedb/ , and has about 2.5 million members
in it.

Here's a simple toy program that just goes through and counts the
number of members in the tarfile, printing a status message every N
records (N=10,000 for the smaller file; N=100,000 for the larger). 

I'm finding that memory usage goes through the roof, simply iterating
over the tarfile.  I'm using over 2G when I'm barely halfway through
the file. This surprises me; I'd expect the memory associated with
each iteration to be released at the end of the iteration; but
something's obviously building up.

On one system, this ends with a MemoryError exception.  On another
system, it just hangs, bringing the system to its knees, to the point
that it takes a minute or so to do simple task switching.

Any suggestions to process this beast?  I suppose I could just untar
the file, and process 2.5 million individual files, but I'm thinking
I'd rather process it directly if that's possible.

Here's the toy code.  (One explanation about the "import tarfilex as
tarfile" statement. I'm running Activestate Python 2.5.0, and the
tarfile.py module of that vintage was buggy, to the point that it
couldn't read these files at all.  I brought down the most recent
tarfile.py from http://svn.python.org/view/python/trunk/Lib/tarfile.py
and saved it as tarfilex.py.  It works, at least until I start
processing some very large files, anyway.)

import tarfilex as tarfile
import os, time
SOURCEDIR = "F:/Installs/FreeDB/"
smallfile = "freedb-update-20080601-20080708.tar" # 63M file
smallint = 1
bigfile   = "freedb-complete-20080708.tar"  # 4,329M file
bigiTnt = 10

TARFILENAME, INTERVAL = smallfile, smallint
# TARFILENAME, INTERVAL = bigfile, bigint


def filetype(filename):
return os.path.splitext(filename)[1]

def memusage(units="M"):
import win32process
current_process = win32process.GetCurrentProcess()
memory_info = win32process.GetProcessMemoryInfo(current_process)
bytes = 1
Kbytes = 1024*bytes
Mbytes = 1024*Kbytes
Gbytes = 1024*Mbytes
unitfactors = {'B':1, 'K':Kbytes, 'M':Mbytes, 'G':Gbytes}
return memory_info["WorkingSetSize"]//unitfactors[units]

def opentar(filename):
modes = {".tar":"r", ".gz":"r:gz", ".bz2":"r:bz2"}
openmode = modes[filetype(filename)]
openedfile = tarfile.open(filename, openmode)
return openedfile


TFPATH=SOURCEDIR+'/'+TARFILENAME
assert os.path.exists(TFPATH)
assert tarfile.is_tarfile(TFPATH)
tf = opentar(TFPATH)
count = 0
print "%s memory: %sM count: %s (starting)" % (time.asctime(),
memusage(), count)
for tarinfo in tf:
count += 1
if count % INTERVAL == 0:
print "%s memory: %sM count: %s" % (time.asctime(),
memusage(), count)
print "%s memory: %sM count: %s (completed)" % (time.asctime(),
memusage(), count)


Results with the smaller (63M) file:

Thu Jul 17 00:18:21 2008 memory: 4M count: 0 (starting)
Thu Jul 17 00:18:23 2008 memory: 18M count: 1
Thu Jul 17 00:18:26 2008 memory: 32M count: 2
Thu Jul 17 00:18:28 2008 memory: 46M count: 3
Thu Jul 17 00:18:30 2008 memory: 55M count: 36128 (completed)


Results with the larger (4.3G) file:

Thu Jul 17 00:18:47 2008 memory: 4M count: 0 (starting)
Thu Jul 17 00:19:40 2008 memory: 146M count: 10
Thu Jul 17 00:20:41 2008 memory: 289M count: 20
Thu Jul 17 00:21:41 2008 memory: 432M count: 30
Thu Jul 17 00:22:42 2008 memory: 574M count: 40
Thu Jul 17 00:23:47 2008 memory: 717M count: 50
Thu Jul 17 00:24:49 2008 memory: 860M count: 60
Thu Jul 17 00:25:51 2008 memory: 1002M count: 70
Thu Jul 17 00:26:54 2008 memory: 1145M count: 80
Thu Jul 17 00:27:59 2008 memory: 1288M count: 90
Thu Jul 17 00:29:03 2008 memory: 1430M count: 100
Thu Jul 17 00:30:07 2008 memory: 1573M count: 110
Thu Jul 17 00:31:11 2008 memory: 1716M count: 120
Thu Jul 17 00:32:15 2008 memory: 1859M count: 130
Thu Jul 17 00:33:23 2008 memory: 2001M count: 140
Traceback (most recent call last):
  File "C:\test\freedb\tardemo.py", line 40, in 
for tarinfo in tf:
  File "C:\test\freedb\tarfilex.py", line 2406, in next
tarinfo = self.tarfile.next()
  File "C:\test\freedb\tarfilex.py", line 2311, in next
tarinfo = self.tarinfo.fromtarfile(self)
  File "C:\test\freedb\tarfilex.py", line 1235, in fromtarfile
obj = cls.frombuf(buf)
  File "C:\test\freedb\tarfilex.py", line 1193, in frombuf
if chksum not in calc_chksums(buf):
  File "C:\test\freedb\tarfilex.py", line 261, in calc_chksums
unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) +
struct.unpack("356B", buf[156:512]))
MemoryError


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


Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-17 Thread Stefan Scholl
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 17 Jul 2008 05:41:11 +0200, Stefan Scholl wrote:
>> Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>>> Stefan Scholl wrote:
>>> 
 Django isn't ready.
>>> 
>>> That's a remarkably ignorant statement.
>> 
>> The 1.0 release will be in September.
> 
> So what?  It's not the version number that matters but features and
> stability.  It's not uncommon in open source projects to have very usable
> software with a version number below 1.0.

The book is about the development version, which was current at
the time the book was written. See page 4.


Nobody says something about "Book after feature freeze" (or
similar). Instead I get "ignorant statement" and "usable
software".

My conclusion: This book isn't about a stable release and not
about a future stable release. (And even if it was about the last
stable relase, too much has changed and will change until
September 2008. IMHO.)


And by the way: The quote was changed by deleting something on
the same line:

"June 2008 is a bit too early. Django isn't ready."

vs.

"Django isn't ready."


-- 
Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/
--
http://mail.python.org/mailman/listinfo/python-list


Good HTML Parser

2008-07-17 Thread Chris
Can anyone recommend a good HTML/XHTML parser, similar to
HTMLParser.HTMLParser or htmllib.HTMLParser, but able to intelligently
know that certain tags, like , are implicitly closed? I need to
iterate through the entire DOM, building up a DOM path, but the stdlib
parsers aren't calling handle_endtag() for any implicitly closed tags.
I looked at BeautifulSoup, but it only seems to work by first parsing
the entire document, then allowing you to query the document
afterwards. I need something like a SAX parser.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rotating a cube

2008-07-17 Thread J-Burns
On Jul 17, 12:53 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> J-Burns wrote:
> > Is there a built in Python function for this?
>
> for answering questions that have nothing to do with programming, and
> looks quite a bit like homework?  don't think they've added that one yet.
>
> maybe you should look for a geometry newsgroup/forum?
>
> 

I meant to ask how would you do this in Python... :S
--
http://mail.python.org/mailman/listinfo/python-list


Remove some characters from a string

2008-07-17 Thread Julien
Hi,

I can't seem to find the right regular expression to achieve what I
want. I'd like to remove all characters from a string that are not
numbers, letters or underscores.

For example:

>>> magic_function('[EMAIL PROTECTED]')
str: 'si_98udasgf'

Would you have any hint?

Thanks a lot!

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


Re: Need help getting BeautifulSoup contents

2008-07-17 Thread dusans
I dont quite understand what u want. U should paste the html here
http://pastebin.com/ also provide the result that u want.

If u dont take the time to write what u wont, nobody will take the
time to help u

On Jul 17, 7:38 am, Alexnb <[EMAIL PROTECTED]> wrote:
> The trick to this one is that the html looks something like this:
>
> 
> american,
> a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage
> cream "
>
> My question is I want everything inside, the contents of each   ad the
> regular text of the .
> I know I can do like a.contents, but it only gives me the first one, in this
> case being "blue". I want the contents of each of those and the regular
> contents of the .
>
> P.S. notice the things inbetween the 
> Can anyone help?
>
> --
> View this message in 
> context:http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp1850...
> Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread bearophileHUGS
On Jul 17, 9:50 am, Alexnb:
> how can I test to see if  the first char of a string is "<"?

I suggest you to try the interactive shell:

>>> "hello"[0]
'h'
>>> "hello"[0] == "<"
False
>>> "hello"[0] == "h"
True
>>> "hello".startswith("h")
True

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


Re: About wmi

2008-07-17 Thread Tim Golden

patrol wrote:

I will try to modify the wmi.py ,however I'm a novice.It will take a
long time. You can give it up temporarily. If you don't mind ,can you
tell me where needs modifying and how? Just unicode? Or Other?


OK. Thanks for your patience on this one, Patrol. What I propose
to do is to dig into the pywin32 sources to determine what's going
on when the error messages are fetched. Then I'll be better placed
to decide what to do when they come out. On the surface, the current
module should be handling things correctly; but I've obviously missed
an encode/decode somewhere.

If I can think of an (even hackish) workaround for you in the meantime,
I'll let you know. Until then...

TJG

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


Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread Alexnb



bearophileHUGS wrote:
> 
> On Jul 17, 9:50 am, Alexnb:
>> how can I test to see if  the first char of a string is "<"?
> 
> I suggest you to try the interactive shell:
> 
 "hello"[0]
> 'h'
 "hello"[0] == "<"
> False
 "hello"[0] == "h"
> True
 "hello".startswith("h")
> True
> 
> Bye,
> bearophile
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

really? That's just like C. I thought that it would fail because of the way
lists work. Thanks!

-- 
View this message in context: 
http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503830.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


common elements between list of lists and lists

2008-07-17 Thread antar2
Hello,

I am a beginner in python.
following program prints the second element in list of lists 4 for the
first elements in list 4 that are common with the elements in list 5


list4 = [['1', 'a'],['4', 'd'],['8', 'g']]
list5 = ['1', '2', '3']

for j in list4:
for k in list5:
if j[0] == k:
print j[1]

Result: a

I would like to do the same thing starting with following lists, where
the numbers in list 5 are without ''. Is there a way to convert
integers in a list to integers in '' ? This is based on a situation
where I want to find common numbers between a list and a list of lists
where the numbers in the list are without '' and the numbers in the
list of lists are with ''


list4 = [['1', 'a'],['4', 'd'],['8', 'g']]
list5 = [1, 2, 3]

This might be a stupid question, but anyway, thanks for your answer
It is not my first post on this site. In some way it is not possible
to react on the messages that I receive to thank the persons that
react. Anyway, thanks a lot


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


Re: common elements between list of lists and lists

2008-07-17 Thread Alexandr N Zamaraev

>>> list4 = [['1', 'a'],['4', 'd'],['8', 'g']]
>>> list5 = [1, 2, 3]
>>> set5 = set(list5)
>>> [x for n, x in list4 if int(n) in set5]
['a']

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


Re: Remove some characters from a string

2008-07-17 Thread Chris
On Jul 17, 10:13 am, Julien <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I can't seem to find the right regular expression to achieve what I
> want. I'd like to remove all characters from a string that are not
> numbers, letters or underscores.
>
> For example:
>
> >>> magic_function('[EMAIL PROTECTED]')
>
> str: 'si_98udasgf'
>
> Would you have any hint?
>
> Thanks a lot!
>
> Julien

One quick and dirty way would be...

import string
safe_chars = string.ascii_letters + string.digits + '_'
test_string = '[EMAIL PROTECTED]'
''.join([char if char in safe_chars else '' for char in test_string])

you could also use a translation table, see string.translate (the
table it uses can be made with string.maketrans)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-17 Thread Fredrik Lundh

Stefan Scholl wrote:


And by the way: The quote was changed by deleting something on
the same line:

"June 2008 is a bit too early. Django isn't ready."

vs.

"Django isn't ready."


Is this a language issue?  That you meant to write "django 1.0 isn't 
done" (as in "completed; finished") but accidentally wrote "django isn't 
ready" (where "ready" is usually read as "completely prepared or in fit 
condition for immediate action or use")?


(and the "stable release" and "much will change" stuff is pure FUD, of 
course.  what competing project will I find if I google your name?)




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


Re: Remove some characters from a string

2008-07-17 Thread Paul Hankin
On Jul 17, 9:13 am, Julien <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I can't seem to find the right regular expression to achieve what I
> want. I'd like to remove all characters from a string that are not
> numbers, letters or underscores.
>
> For example:
>
> >>> magic_function('[EMAIL PROTECTED]')
>
> str: 'si_98udasgf'

For speed, you can use 'string.translate', but simplest is to use a
comprehension:

import string

def magic_function(s, keep=string.ascii_letters + string.digits +
'_'):
return ''.join(c for c in s if c in keep)

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


Re: Remove some characters from a string

2008-07-17 Thread Fredrik Lundh

Julien wrote:


I can't seem to find the right regular expression to achieve what I
want. I'd like to remove all characters from a string that are not
numbers, letters or underscores.

For example:


magic_function('[EMAIL PROTECTED]')

str: 'si_98udasgf'


the easiest way is to replace the things you don't want with an empty 
string:


>>> re.sub("\W", "", "[EMAIL PROTECTED]")
'si_98udasgf'

("\W" matches everything that is "not numbers, letters, or underscores", 
where the alphabet defaults to ASCII.  to include non-ASCII letters, add 
"(?u)" in front of the expression, and pass in a Unicode string).




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


Re: common elements between list of lists and lists

2008-07-17 Thread Bighead
On Jul 17, 4:30 pm, antar2 <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am a beginner in python.
> following program prints the second element in list of lists 4 for the
> first elements in list 4 that are common with the elements in list 5
>
> list4 = [['1', 'a'],['4', 'd'],['8', 'g']]
> list5 = ['1', '2', '3']
>
> for j in list4:
> for k in list5:
> if j[0] == k:
> print j[1]
>
> Result: a
>
> I would like to do the same thing starting with following lists, where
> the numbers in list 5 are without ''. Is there a way to convert
> integers in a list to integers in '' ? This is based on a situation
> where I want to find common numbers between a list and a list of lists
> where the numbers in the list are without '' and the numbers in the
> list of lists are with ''
>
> list4 = [['1', 'a'],['4', 'd'],['8', 'g']]
> list5 = [1, 2, 3]
>
> This might be a stupid question, but anyway, thanks for your answer
> It is not my first post on this site. In some way it is not possible
> to react on the messages that I receive to thank the persons that
> react. Anyway, thanks a lot

By "integer without ''" you mean integers not embraced by single
quotes, right?

Actually, '1' is a string,  not an integer. If you want to normalize
the first elements of all the lists in list4, just use int() to
convert them.

That is:

list4 = [['1', 'a'],['4', 'd'],['8', 'g']]
list5 = ['1', '2', '3']

set5 = set(map(int, list5))
list4 = [[int(i[0]), i[1]] for i in list4]

for j in list4:
  if j[0] in set5: print j[1]

You can have a try :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread Fredrik Lundh

Alexnb wrote:


"hello"[0]

'h'

"hello"[0] == "<"

False

"hello"[0] == "h"

True

"hello".startswith("h")

True



really? That's just like C. I thought that it would fail because of the way
lists work. Thanks!


what way?

the first three will fail if the string is empty.

>>> ""[0]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: string index out of range

if you may end up doing this on an empty string, use slicing instead:

>>> "hello"[:1] == "<"
False
>>> ""[:1] == "<"
False

(startswith is perhaps more convenient, but method calls are rather 
expensive in Python, so if you're in a hurry, it's often better to use 
operators.  when in doubt, benchmark the alternatives.)




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


Question about properties

2008-07-17 Thread Frank Millman
Hi all

I have started experimenting with properties.

The example in the 2.5 docs uses an inconsistent mixture of single and
double underscores for the internal representation of the attribute. I
was going to file a documentation bug, but then I checked the 2.6 docs
online, and I see it has been fixed, by using single underscores
throughout.

IMHO, it would make more sense to use double underscores throughout. I
thought that the main point of using property was to prevent direct
access to the attribute. With a single underscore you can access it if
you prefix the attribute name with a single underscore, thus bypassing
the logic in 'property'.

Is this a valid comment, or does it come under the category of 'we are
all adults here'?

While experimenting, I came across the following curiosity.

I know that prefixing a class attribute with a double-underscore makes
it difficult to access the attribute externally. Here is a simple
example -

>>>class Test(object):
...def __init__(self,x):
...self.x = x
...self.__y = 123
...def get_y(self):
...return self.__y

>>>t = Test(99)
>>>t.x
99
>>>t.get_y()
123
>>>t.__y
AttributeError: 'Test' object has no attribute '__y'

I was surprised that I could do the following -

>>>t.__y = 456
>>>t.__y
456
>>>t.get_y()
123

It's not important, but I am curious to know what is going on
internally here.

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


Re: Question about properties

2008-07-17 Thread Fredrik Lundh

Frank Millman wrote:

> I thought that the main point of using property was to prevent direct
> access to the attribute.

Not "prevent access to" as much as "add behaviour to".


Is this a valid comment, or does it come under the category of 'we are
all adults here'?


The latter.  And the "__" doesn't provide much protection, really (as 
we'll see below).



While experimenting, I came across the following curiosity.

I know that prefixing a class attribute with a double-underscore makes
it difficult to access the attribute externally. Here is a simple
example -


class Test(object):

...def __init__(self,x):
...self.x = x
...self.__y = 123
...def get_y(self):
...return self.__y


t = Test(99)
t.x

99

t.get_y()

123

t.__y

AttributeError: 'Test' object has no attribute '__y'

I was surprised that I could do the following -


t.__y = 456
t.__y

456

t.get_y()

123

It's not important, but I am curious to know what is going on
internally here.


hint:

>>> dir(t)
['_Test__y', ..., '__y', 'get_y', 'x']
>>> t._Test__y
123
>>> t.__y
456



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


Fwd: Hello

2008-07-17 Thread spandana g
Hello ,

Traceback (most recent call last):
  File "C:\Python25\hadi_yahoo.py", line 12, in 
file_source.write(urllib2.urlopen(req).read())
  File "C:\Python25\lib\urllib2.py", line 124, in urlopen
return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 387, in open
response = meth(req, response)
  File "C:\Python25\lib\urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
  File "C:\Python25\lib\urllib2.py", line 425, in error
return self._call_chain(*args)
  File "C:\Python25\lib\urllib2.py", line 360, in _call_chain
result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 506, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 999: Unable to process request at this time -- error
999

Previously i got the error which I have attached below  when I use just
urlopen . But now when I use this http request
user_agent='Mozilla/3.0(compatible;MISE 5.5;Windows NT)'
headers={'User-Agent':user_agent}
req=urllib2.Request(url,None,headers)
file_source.write(urllib2.urlopen(req).read()

its still giving the error mentioned above .. Iam accessing the yahoo search
engine .. link is "http://search.yahoo.com/search?n=20&p=ipod";

I'm attaching the python file i have written just have a look and suggest me
something that works for this query

Thank You,
Spandana.




-- Forwarded message --
From: spandana g <[EMAIL PROTECTED]>
Date: Thu, Jul 3, 2008 at 2:52 PM
Subject: HTTP request error with urlopen
To: [email protected]


Hello ,

  I have written a code to get the page source of the google search
page .. this is working for other urls. I have this problem with

import re
from urllib2 import urlopen
string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search'
file_source=file("google_source.txt",'w')
file_source.write(urlopen(string).read())
page_content=file_source.readlines()

Traceback (most recent call last) :
File "C:/Python25/google.py", line 5,in 
file_source.write(urlopen(string).read())
File "C:\Python25\lib\urllib2.py", line 124 , in urlopen
return__opener.open(url,  data)
File "C:\Python25\lib\urllib2.py", line  387 , in open
   response =meth(req, response)
File "C:\Python25\lib\urllib2.py", line 498 , in http_response
   'http',   request,  response,  code,  msg,  hdrs)
File  "C:\Python25\lib\urllib2.py",  line 425,  in error
   return self._call_chain(*args)
File  "C:\Python25\lib\urllib2.py", line 360,  in __call_chain
   result = func(*args)
File "C:\Python25\lib\urllib2.py", line 506, in http_error_default
   raise HTTPError(req.get_full_url(),  code,  msg,  hdrs,  fp)
HTTPError:  HTTP Error 403: Forbidden

Actually urlopen is working for google labs sets page but not for the
google.com  and even I have same problem with wikipedia . Please let me know
.. If any one of have any idea about this .

Thank You,
Spandana.
import re
import urllib2
from urllib2 import urlopen
string1='http://search.yahoo.com/search?n=20&p='
string2=raw_input("Enter the string here")
user_agent='Mozilla/3.0(compatible;MISE 5.5;Windows NT)'
headers={'User-Agent':user_agent}
url=string1+string2
print url
req=urllib2.Request(url,None,headers)
file_source=file("yahoo_source.txt",'w')
file_source.write(urllib2.urlopen(req).read())
file_data=file("yahoo_source.txt",'r')
filename=string2+'_yahoo_hadi.txt'
output=file(filename,'w')
page_content=file_data.readlines()
--
http://mail.python.org/mailman/listinfo/python-list

Python Pmw ScrollListBox selectioncommand dblclickcommand

2008-07-17 Thread Guilhem Faure
Hello everybody,
I try to use Pmw library -> ScrollListBox. If I take the example of
the reference web site (see below, I just quote the minimal code to
launch, I note by <- the line which are not execute when I click)
It works, except selectioncommand and dblclickcommand: associate
function doesn't run when I click one or two time.
Could you have an idea about that ? Is it about my tried code ?

Thank,

Guilhem



from Tkinter import *
import Pmw
#from pymol import *

class Demo:
def __init__(self):
parent=Tk()
Pmw.initialise(parent)
# Create the ScrolledListBox.
self.box = Pmw.ScrolledListBox(parent,
items=('Sydney', 'Melbourne', 'Brisbane'),
labelpos='nw',
label_text='Cities',
listbox_height = 6,
selectioncommand=self.selectionCommand,
dblclickcommand=self.defCmd,
usehullsize = 1,
hull_width = 200,
hull_height = 200,
)

# Create a group widget to contain the scrollmode options.
w = Pmw.Group(parent, tag_text='Scroll mode')
w.pack(side = 'bottom', padx = 5, pady = 5)

hmode = Pmw.OptionMenu(w.interior(),
labelpos = 'w',
label_text = 'Horizontal:',
items = ['none', 'static', 'dynamic'],
command = self.sethscrollmode,
menubutton_width = 8,
)
hmode.pack(side = 'top', padx = 5, pady = 5)
hmode.invoke('dynamic')

vmode = Pmw.OptionMenu(w.interior(),
labelpos = 'w',
label_text = 'Vertical:',
items = ['none', 'static', 'dynamic'],
command = self.setvscrollmode,
menubutton_width = 8,
)
vmode.pack(side = 'top', padx = 5, pady = 5)
vmode.invoke('dynamic')

buttonBox = Pmw.ButtonBox(parent)
buttonBox.pack(side = 'bottom')
buttonBox.add('yview', text = 'Show\nyview', command = self.showYView)
buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown)
buttonBox.add('center', text = 'Center', command = self.centerPage)

# Pack this last so that the buttons do not get shrunk when
# the window is resized.
self.box.pack(fill = 'both', expand = 1, padx = 5, pady = 5)

# Do this after packing the scrolled list box, so that the
# window does not resize as soon as it appears (because
# alignlabels has to do an update_idletasks).
Pmw.alignlabels((hmode, vmode))


def sethscrollmode(self, tag):
self.box.configure(hscrollmode = tag)

def setvscrollmode(self, tag):
self.box.configure(vscrollmode = tag)

def selectionCommand(self):
print "toto"  # <--- doesn t run !!!
def defCmd(self):
print "toto2"   # <--- doen t run !!!

def showYView(self):
print self.box.yview()

def pageDown(self):
self.box.yview('scroll', 1, 'page')

def centerPage(self):
top, bottom = self.box.yview()
size = bottom - top
middle = 0.5 - size / 2
self.box.yview('moveto', middle)


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

Re: Python embedding question.

2008-07-17 Thread Thomas Troeger

Jan Claeys wrote:

I'd say that PyGame could be a solution.

Or otherwise you could do your own audio/graphics programming (you don't 
tell us which OS you use, but there exist python modules that allow you 
to do barebones graphics & sound programming on linux...).


Yes, I'm using a very small Linux system with busybox, running from a 
compact flash drive. I'll investigate PyGame, it sounds as if it is a 
good candidate :P


Thanks so far,
Thomas.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Hello

2008-07-17 Thread Fredrik Lundh

spandana g wrote:

HTTPError: HTTP Error 999: Unable to process request at this time -- 
error 999


Previously i got the error which I have attached below  when I use just 
urlopen . But now when I use this http request

user_agent='Mozilla/3.0(compatible;MISE 5.5;Windows NT)'
headers={'User-Agent':user_agent}
req=urllib2.Request(url,None,headers)
file_source.write(urllib2.urlopen(req).read()

its still giving the error mentioned above .. Iam accessing the yahoo 
search engine .. link is "http://search.yahoo.com/search?n=20&p=ipod 
"
 
I'm attaching the python file i have written just have a look and 
suggest me something that works for this query


they have an official API, you know:

http://developer.yahoo.com/search/boss/

here's an article showing how to install and use it:

http://lethain.com/entry/2008/jul/11/search-recipes-for-yahoo-s-boss-in-python/



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


Re: singletons

2008-07-17 Thread Craig Allen
On Jul 16, 7:01 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>, Craig
>
> Allen wrote:
> > ... the ideal is still that
>
> > tl = TehLibrary() would always return the same object.
> >> class TehLibrary(object) :
>
> ... @classmethod
> ... def __new__(self, cls) :
> ... return self
>
> >>> s = TehLibrary()
> >>> s == TehLibrary()
>
> True

That's great, I simply didn't find that when looking. Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Hello

2008-07-17 Thread Fredrik Lundh

> they have an official API, you know:
>
> http://developer.yahoo.com/search/boss/

and yes, there are other options too, including pYsearch which is 
available from their developer network:


http://developer.yahoo.com/python/python-pysearch.html

for more Python stuff from/for Yahoo, see the Yahoo Python Developer Center:

http://developer.yahoo.com/python/



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


Babelfish translation ...

2008-07-17 Thread Stef Mientki

hello,

I've build a translation tool, to translate all strings in a python 
source file.

As a extra gadget I added translation through Babel Fish,
using beautifulsoup.

Although it works functionally,
it can take lots of time waiting for the translation.

What I basically do is, after selecting a new string to be translated:

   kwds = { 'trtext' : line_to_be_translated, 'lp' :'en_nl'}
   soup = BeautifulSoup (urlopen(url, urlencode ( kwds ) ) )
   translation= soup.find ( 'div', style='padding:0.6em;' ).string
   self.Editor_Babel.SetLabel ( translation )

I'm using Python 2.5 and wxPython.

Probably I should use a separate thread, but that's above my knowledge.
I could also use a timer to check at regualr intervals when the 
translation is ready,

but I've no idea how to implement that with the above code.

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


Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-17 Thread alex23
On Jul 17, 6:04 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Django's 0.91 release in early 1996

While I totally agree with position, I'm pretty sure you mean 2006
here :)

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


Re: Good HTML Parser

2008-07-17 Thread Diez B. Roggisch
Chris wrote:

> Can anyone recommend a good HTML/XHTML parser, similar to
> HTMLParser.HTMLParser or htmllib.HTMLParser, but able to intelligently
> know that certain tags, like , are implicitly closed? I need to
> iterate through the entire DOM, building up a DOM path, but the stdlib
> parsers aren't calling handle_endtag() for any implicitly closed tags.
> I looked at BeautifulSoup, but it only seems to work by first parsing
> the entire document, then allowing you to query the document
> afterwards. I need something like a SAX parser.

This isn't possible. Your own example of arbitrarily closeable Tags needs
context that just a SAX-like parser can't provide.

I suggest you use BeautifulSoup, and if you must create your own
event-generation around that which you can attach consumers to.

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


storing references instead of copies in a dictionary

2008-07-17 Thread mk

Hello everyone,

I'm storing functions in a dictionary (this is basically for cooking up 
my own fancy schmancy callback scheme, mainly for learning purpose):


>>> def f2(arg):
... return "f2 " + arg
...
>>>
>>> def f1(arg):
... return "f1" + arg
...

>>> a={'1': f1, '2': f2}
>>>
>>> [ x[1](x[0]) for x in a.items() ]
['f11', 'f2 2']

Well, neat. Except if I change function definitions now, old functions 
are called. And rightly:


{'1': , '2': }
>>> f1

>>>
>>> def f1(arg):
... return "NEW f1 " + arg
...
>>> f1


The address of function f1 has obviously changed on redefinition.

Storing value copies in a dictionary on assignment is a reasonable 
default behaviour.


However, in this particular case I need to specifically store 
_references to objects_ (e.g. f1 function), or should I say _labels_ 
(leading to objects)?


Of course, I can basically update the dictionary with a new function 
definition.


But I wonder, is there not a way _in general_ to specifically store 
references to functions/variables/first-class objects instead of copies 
in a dictionary?




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


Re: Problem with MySQLdb and mod_python

2008-07-17 Thread Cyril Bazin
Thanks for your reply

The apache log contains lines like :

[Tue Jul 15 23:31:01 2008] [notice] mod_python (pid=11836,
interpreter='www.toto.fr'): Importing module
'/usr/local/apache2/htdocs/intranet/courrier/test.py'
[Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal
Segmentation fault (11)
[Tue Jul 15 23:31:19 2008] [notice] mod_python (pid=11764,
interpreter='www.toto.fr'): Importing module
'/usr/local/apache2/htdocs/intranet/courrier/test.py'
[Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal
Segmentation fault (11)

I think the problem comes from the MySQLdb module.
If I can't find another solution, I think I will downgrade the MySQLdb
version to 1.2.1

Cyril

On Thu, Jul 17, 2008 at 7:27 AM, Lawrence D'Oliveiro
<[EMAIL PROTECTED]> wrote:
> In message <[EMAIL PROTECTED]>, Cyril Bazin
> wrote:
>
>> But it seems, after many tests, that the script stops at the
>> instruction : "c.execute(requete)"
>
> What's the error message? This should be in Apache's error_log file.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing for connection to a website

2008-07-17 Thread Venky Shankar
ping the universal DNS ? (4.2.2.2)

-Venky

On Wed, Jul 16, 2008 at 1:17 AM, Jordan <[EMAIL PROTECTED]> wrote:

> On Jul 15, 3:43 pm, Alexnb <[EMAIL PROTECTED]> wrote:
> > Okay, I already made this post, but it kinda got lost. So anyway I need
> to
> > figure out how to test if the user is able to connect to a specific
> website.
> > Last time I got pointed to the urllib2 page, but if I do urlopen() and
> and
> > am not connected, the program stops. So I don't know if that was what you
> > guys wanted me to do, but I don't think so, you guys are smarter than
> that.
> > So, how can I test for connection to a website.
> > --
> > View this message in context:
> http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p...
> > Sent from the Python - python-list mailing list archive at Nabble.com.
>
> Ping it? ~_^
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Testing for Internet Connection

2008-07-17 Thread Venky Shankar
may be try to open a connection to 4.2.2.2 at port 53 ?

-vks

On Wed, Jul 16, 2008 at 12:13 AM, norseman <[EMAIL PROTECTED]> wrote:

>
> Grant Edwards wrote:
>
>> On 2008-07-15, Alexnb <[EMAIL PROTECTED]> wrote:
>>
>>  What exactly do you think will work? I am not sure what you
>>> think I should do? If I use urlopen("http://www.google.com";)
>>> and I am not connected, I am not going to get an exception,
>>> the program will fail.
>>>
>>
>> Bullshit.  You get an exception.  Here's my program:
>>
>>   import urllib2
>>   try:
>>   con = urllib2.urlopen("http://www.google.com/";)
>>   data = con.read()
>>   print data
>>   except:
>>   print "failed"
>>
>> If I run it with no internet connection, I get this:
>>
>>   $ python testit.py
>>   failed
>>
>> If I bring up the internet connection, then I get a bunch of
>> HTML.
>>
> =
> Yep -me two
>
> Process:
> copy/paste into afile
> slide lines left to create proper indent values
> save
> python afile
>
> I get same as Grant
>
>
> If one does a copy/paste into interactive Python, it does fail.
> (Lots of indent error messages.  After all, it is Python :)
>
>
> Steve
> [EMAIL PROTECTED]
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-17 Thread [EMAIL PROTECTED]
On 16 juil, 10:35, Stefan Scholl <[EMAIL PROTECTED]> wrote:
> Dave U. Random <[EMAIL PROTECTED]> wrote:
>
> >http://snipr.com/PracticalDjango
>
> June 2008 is a bit too early. Django isn't ready.

Oh, really ? Too bad. But, wait... If Django isn't ready, what's that
framework I've been using for almost three years now, then ???

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


Re: storing references instead of copies in a dictionary

2008-07-17 Thread Uwe Schmitt
On 17 Jul., 13:45, mk <[EMAIL PROTECTED]> wrote:
> Hello everyone,
>
> I'm storing functions in a dictionary (this is basically for cooking up
> my own fancy schmancy callback scheme, mainly for learning purpose):
>
>  >>> def f2(arg):
> ...     return "f2 " + arg
> ...
>  >>>
>  >>> def f1(arg):
> ...     return "f1" + arg
> ...
>
>  >>> a={'1': f1, '2': f2}
>  >>>
>  >>> [ x[1](x[0]) for x in a.items() ]
> ['f11', 'f2 2']
>
> Well, neat. Except if I change function definitions now, old functions
> are called. And rightly:
>
> {'1': , '2': }
>  >>> f1
> 
>  >>>
>  >>> def f1(arg):
> ...     return "NEW f1 " + arg
> ...
>  >>> f1
> 
>
> The address of function f1 has obviously changed on redefinition.
>
> Storing value copies in a dictionary on assignment is a reasonable
> default behaviour.
>
> However, in this particular case I need to specifically store
> _references to objects_ (e.g. f1 function), or should I say _labels_
> (leading to objects)?
>
> Of course, I can basically update the dictionary with a new function
> definition.
>
> But I wonder, is there not a way _in general_ to specifically store
> references to functions/variables/first-class objects instead of copies
> in a dictionary?

Python stores references in dictionaries and does not copy ! (unless
you explicitly use the copy module) !

In your case the entry in the dictionary is a reference to the same
object which f1 references, that is the object at 0xb7f0ba04.

If you now say "f1=...:" then f1 references a new object
at 0xb7f0b994, and the entry in your dictionary still references
the "old" object at 0xb7f0ba04.

I do not know any method to automatically update your dictionary
as there is no possibility to overload the assignement operator "=".
But may be somebody can teach me a new trick :-)

Greetings, Uwe




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


Re: How can i use a variable without define it ?

2008-07-17 Thread [EMAIL PROTECTED]
On 16 juil, 11:06, zhw <[EMAIL PROTECTED]> wrote:
> On 7月16日, 下午4时47分, Ben Finney <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > zhw <[EMAIL PROTECTED]> writes:
> > > How can i use a variable without define it ?
>
> > What do you mean by "use"? That's so vague I can think of many
> > possible interpretations.
>
> > What do you mean by "variable"? That term carries a lot of baggage
> > that doesn't apply in Python.
>
> > Can you give a small, complete example that demonstrates the issue
> > you're trying to solve?
>
> > --
> >  \  “The face of a child can say it all, especially the mouth part |
> >   `\of the face.” ―Jack Handey |
> > _o__)  |
> > Ben Finney
>
> Thank you! Sorry for my poor english!
>
> Here is a example that I want to complete:>>> import sys, new
> >>> context={"name":"david", "sex":"male"}
> >>> sys.modules["foo"] = new.module("foo")
> >>> import foo
> >>> for attr in context:
>
> setattr(foo, attr, context[attr])
>
> >>> def bar():
>
> # here is a error
> # import * only allowed at module level
> from foo import *
> print name, sex
>
> >>> bar()

Looks like a major WTF to me. What's wrong with:

class Person(object):
def __init__(self, name, sex):
self.name = name
self.sex = sex
def bar(self):
print self.name, self.sex

p = Person("david", "male")
p.bar()
--
http://mail.python.org/mailman/listinfo/python-list

Re: singletons

2008-07-17 Thread Uwe Schmitt
On 17 Jul., 00:20, Craig Allen <[EMAIL PROTECTED]> wrote:
>
> I have several classes in our system which need to act like
> singletons, they are libraries of data classifications, and other such
> libraries of configurations for the system which need to be global.
> ...
>
> Is it pythonic?

My approach in this situation is to use the Borg pattern instead
of singeltons. This is really pythonic, very simple and usefull.

Look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
The german wikipedia shows another solution using metaclasse:
http://de.wikipedia.org/wiki/Singleton_(Entwurfsmuster)#Das_Borg-Pattern

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


Re: how to debug python's extend module written in c/c++ on windows

2008-07-17 Thread fang
Dear Diez:

It is attaching a C-debugger to python. I can attach python-
debugger(for example:wingIDE) to c-debugger(for example:VS2008), but I
cannot attach VS2008 to wingIDE. I need both python statement and c
statement can be single-step debugged.

best regards

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


Re: bad recursion, still works

2008-07-17 Thread Jeff
Thanks, that made things very clear.  I like that technique for adding
memoization via the parameter.  That is clever.  It would be nice if
there were a way to have multiple functions close over a shared local
variable in Python, like let-binding in lisp.
--
http://mail.python.org/mailman/listinfo/python-list


Re: storing references instead of copies in a dictionary

2008-07-17 Thread John Machin
On Jul 17, 9:45 pm, mk <[EMAIL PROTECTED]> wrote:
> Hello everyone,
>
> I'm storing functions in a dictionary (this is basically for cooking up
> my own fancy schmancy callback scheme, mainly for learning purpose):
>
>  >>> def f2(arg):
> ... return "f2 " + arg
> ...
>  >>>
>  >>> def f1(arg):
> ... return "f1" + arg
> ...
>
>  >>> a={'1': f1, '2': f2}
>  >>>
>  >>> [ x[1](x[0]) for x in a.items() ]
> ['f11', 'f2 2']
>
> Well, neat. Except if I change function definitions now, old functions
> are called. And rightly:
>
> {'1': , '2': }
>  >>> f1
> 
>  >>>
>  >>> def f1(arg):
> ... return "NEW f1 " + arg
> ...
>  >>> f1
> 
>
> The address of function f1 has obviously changed on redefinition.

I wouldn't put it like that. You have created a new function, with a
different address to the original function, and bound the name "f1" to
that new function. The address of the old function is still stored in
the dictionary.

A function (or any other object) can have 0, 1, or many names:

>>> def foo():
... print "The function formerly known as foo"
...
>>> fred = foo # 2 names
>>> del foo # back to one name
>>> fred()
The function formerly known as foo
>>> L = [fred]
>>> del fred # 0 names
>>> L[0]() # You can't keep a good function down ...
The function formerly known as foo
>>>


> Of course, I can basically update the dictionary with a new function
> definition.

Uh-huh ...

>
> But I wonder, is there not a way _in general_ to specifically store
> references to functions/variables/first-class objects instead of copies
> in a dictionary?

Yup, and that's what happens all the time, unless you explicitly make
a copy ... some objects have a copy method, sequences can be copied by
taking a full slice (seq_copy = seq[:]), otherwise read up on the copy
module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: storing references instead of copies in a dictionary

2008-07-17 Thread Calvin Spealman
On Thu, Jul 17, 2008 at 7:45 AM, mk <[EMAIL PROTECTED]> wrote:
> Hello everyone,
>
> I'm storing functions in a dictionary (this is basically for cooking up my
> own fancy schmancy callback scheme, mainly for learning purpose):
>
 def f2(arg):
> ... return "f2 " + arg
> ...

 def f1(arg):
> ... return "f1" + arg
> ...
>
 a={'1': f1, '2': f2}

 [ x[1](x[0]) for x in a.items() ]
> ['f11', 'f2 2']
>
> Well, neat. Except if I change function definitions now, old functions are
> called. And rightly:
>
> {'1': , '2': }
 f1
> 

 def f1(arg):
> ... return "NEW f1 " + arg
> ...
 f1
> 
>
> The address of function f1 has obviously changed on redefinition.
>
> Storing value copies in a dictionary on assignment is a reasonable default
> behaviour.
>
> However, in this particular case I need to specifically store _references to
> objects_ (e.g. f1 function), or should I say _labels_ (leading to objects)?
>
> Of course, I can basically update the dictionary with a new function
> definition.
>
> But I wonder, is there not a way _in general_ to specifically store
> references to functions/variables/first-class objects instead of copies in a
> dictionary?

As was pointed out already, this is a basic misunderstanding of
assignment, which is common with people learning Python.

To your actual problem... Why do you wanna do this anyway? If you want
to change the function in the dictionary, why don't you simply define
the functions you'll want to use, and change the one you have bound to
the key in the dictionary when you want to change it? In other words,
define them all at once, and then just d['1'] = new_f1. What is wrong
with that?

For completeness:

def new_f1(arg):
return "NEW f1 " + arg
f1.func_code = new_f1.func_code

Don't use that unless you really have to and I nearly promise that you don't.

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Instance

2008-07-17 Thread Calvin Spealman
On Thu, Jul 17, 2008 at 2:56 AM, karthikbalaguru
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am new to python. I am trying to use the python files given to me
> for bringing up a setup.
> I get the following error while trying to use a python file -
> AttributeError : Classroom instance has no attribute 'desk_offset'
>
> How to resolve this ?
> Should i need to define desk_offset to zero in the python file ?
>
> Any ideas ..

This means you did something like this:

class Foo:
   def __init__(self):
   self.bar = 10

f = Foo()
print f.quu
...
AttributeError : Foo instance has no attribute 'quu'

See? You tried to use an attribute that simply doesn't exist. Look in
the traceback for where you used the desk_offset attribute, and figure
out why you thought the object had such an attribute and why it does
not.

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-17 Thread Torsten Bronger
Hallöchen!

[EMAIL PROTECTED] writes:

> On 16 juil, 10:35, Stefan Scholl <[EMAIL PROTECTED]> wrote:
>
>> Dave U. Random <[EMAIL PROTECTED]> wrote:
>>
>>> http://snipr.com/PracticalDjango
>>
>> June 2008 is a bit too early. Django isn't ready.
>
> Oh, really ? Too bad. But, wait... If Django isn't ready, what's
> that framework I've been using for almost three years now, then
> ???

Before writing sarcastic comments, reading the thread would be
really polite.

As far as versioning is concerned, Django's policy is that "1.0"
equals "API is frozen".  And I consider publishing a book four
months before the API is polished bad timing, too.  Especially
because Django is exquisitely documented on its webpage, so there is
no urgent need for it.

I thought about buying a Django book, too.  I'm happy to have
delayed it, for the same reason Stefan mentioned.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread Calvin Spealman
BeautifulSoup. You need a good html parsing, not some one-shot code to
handle one tiny unflexable pattern.

On Thu, Jul 17, 2008 at 3:07 AM, Alexnb <[EMAIL PROTECTED]> wrote:
>
> Hello
>
> Lets say I have a string:
>
> --a href="/browse/brick"--brick--/a--
>
> The -- needs to be replaced with < or > where applicable.
>
> and I want the "brick" out of that string (the second brick that is). How
> can I get just the "brick" out of that string?
> --
> View this message in context: 
> http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18502758.html
> Sent from the Python - python-list mailing list archive at Nabble.com.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pickle and wx.TextCtrl

2008-07-17 Thread DWebre


D. J. Webre, Jr. PE & PLS



   
 "Gabriel  
 Genellina"
 <[EMAIL PROTECTED]  To
 com.ar>   [email protected]  
 Sent by:   cc
 python-list-bounc 
 esSubject
 +djwebre=dotd.la. Re: Pickle and wx.TextCtrl
 [EMAIL PROTECTED]
   
   
 07/11/2008 10:51  
 PM
   


Thanks for the response.

En Fri, 11 Jul 2008 10:15:36 -0300, <[EMAIL PROTECTED]> escribió:

> Trying to read a pickled file and list contents.
>
> The attached program works using pprint, but I want to write to my frame.
> WriteText only produces half of the records.
> What is happening?

What do you mean by "only produces half of the records"?

Write Text list records from "Assignment" to "Report"
pprint list records from "Assignment" to "Report" and continues to
"TaskWeek", about twice as many records

Probably your problem has nothing to do with a TextCtrl - ensure you can
save and load your data with a simple, console-based script, and only then
write the GUI.
The way you read the file is rather strange -mixing calls to readline and
pickle.load- I'd write the data using pickle.dump calls *only* and then
read it using pickle.load calls *only*.

I used 13.1.7 Example of the Python Library Referencebut.  Got an error
message when I did not have the readline() statement.

Additional ideas will be appreciated.
--
Gabriel Genellina

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

Re: Javascript - Python RSA encryption interoperability

2008-07-17 Thread Evren Esat Ozkan
Hi,

Thank you very much. Your code is worked like a charm and saved my
honeymoon :)

Thanks again,
Evren


On Jul 4, 6:19 pm, [EMAIL PROTECTED] wrote:
> Evren Esat Ozkan napisa³(a):
>
>
>
>
>
> > Hello,
>
> > I'm trying to encrypt a string with RSA. But it needs to be compitable
> > with Dave's JavaScript RSA implementation*. I'm already read and tried
> > lots of different things about RSA and RSA in Python. But could not
> > produce the same result with the javascript library.
>
> > My experiments could be seen at:http://dpaste.com/hold/60741/
>
> > * JavaScript RSA Library:http://www.ohdave.com/rsa/
>
> > Python libraries which I tried;
> > * PyCrtypo:http://www.amk.ca/python/code/crypto.html
> > * rsa library fromhttp://www.stuvel.eu/rsa
>
> > How could I create the same results with the JS library in Python.
>
> > Any help would be appreciated
>
> > Evren,
>
> It seems that this Javascript is doing weird things to its input,
> namely processing it in reverse. Try encrypting ciphertext[::-1]
> instead of just ciphertext.
>
> public_modulus_hex = '9F2E..snip..4BC7'
> public_exponent_hex = '10001'
> public_modulus = int(public_modulus_hex, 16)
> public_exponent = int(public_exponent_hex, 16)
>
> def encrypt(plaintext_text):
>         # Beware, plaintext must be short enough to fit in a single block!
>         plaintext = int(plaintext_text.encode('hex'), 16)
>         ciphertext = pow(plaintext, public_exponent, public_modulus)
>         return '%X' % ciphertext # return hex representation
>
> print encrypt('12345')
> print encrypt('12345'[::-1]) # Will return the value compatible with
> JS output
>
> Regards,
> Marek

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


Re: How to process a very large (4Gb) tarfile from python?

2008-07-17 Thread Uwe Schmitt
On 17 Jul., 10:01, Terry Carroll <[EMAIL PROTECTED]> wrote:
> I am trying to do something with a very large tarfile from within
> Python, and am running into memory constraints.  The tarfile in
> question is a 4-gigabyte datafile from 
> freedb.org,http://ftp.freedb.org/pub/freedb/, and has about 2.5 million 
> members
> in it.
>
> Here's a simple toy program that just goes through and counts the
> number of members in the tarfile, printing a status message every N
> records (N=10,000 for the smaller file; N=100,000 for the larger).
>
> I'm finding that memory usage goes through the roof, simply iterating
> over the tarfile.  I'm using over 2G when I'm barely halfway through
> the file. This surprises me; I'd expect the memory associated with
> each iteration to be released at the end of the iteration; but
> something's obviously building up.
>
> On one system, this ends with a MemoryError exception.  On another
> system, it just hangs, bringing the system to its knees, to the point
> that it takes a minute or so to do simple task switching.
>
> Any suggestions to process this beast?  I suppose I could just untar
> the file, and process 2.5 million individual files, but I'm thinking
> I'd rather process it directly if that's possible.
>
> Here's the toy code.  (One explanation about the "import tarfilex as
> tarfile" statement. I'm running Activestate Python 2.5.0, and the
> tarfile.py module of that vintage was buggy, to the point that it
> couldn't read these files at all.  I brought down the most recent
> tarfile.py fromhttp://svn.python.org/view/python/trunk/Lib/tarfile.py
> and saved it as tarfilex.py.  It works, at least until I start
> processing some very large files, anyway.)
>
> import tarfilex as tarfile
> import os, time
> SOURCEDIR = "F:/Installs/FreeDB/"
> smallfile = "freedb-update-20080601-20080708.tar" # 63M file
> smallint = 1
> bigfile   = "freedb-complete-20080708.tar"  # 4,329M file
> bigiTnt = 10
>
> TARFILENAME, INTERVAL = smallfile, smallint
> # TARFILENAME, INTERVAL = bigfile, bigint
>
> def filetype(filename):
>     return os.path.splitext(filename)[1]
>
> def memusage(units="M"):
>     import win32process
>     current_process = win32process.GetCurrentProcess()
>     memory_info = win32process.GetProcessMemoryInfo(current_process)
>     bytes = 1
>     Kbytes = 1024*bytes
>     Mbytes = 1024*Kbytes
>     Gbytes = 1024*Mbytes
>     unitfactors = {'B':1, 'K':Kbytes, 'M':Mbytes, 'G':Gbytes}
>     return memory_info["WorkingSetSize"]//unitfactors[units]
>
> def opentar(filename):
>     modes = {".tar":"r", ".gz":"r:gz", ".bz2":"r:bz2"}
>     openmode = modes[filetype(filename)]
>     openedfile = tarfile.open(filename, openmode)
>     return openedfile
>
> TFPATH=SOURCEDIR+'/'+TARFILENAME
> assert os.path.exists(TFPATH)
> assert tarfile.is_tarfile(TFPATH)
> tf = opentar(TFPATH)
> count = 0
> print "%s memory: %sM count: %s (starting)" % (time.asctime(),
> memusage(), count)
> for tarinfo in tf:
>     count += 1
>     if count % INTERVAL == 0:
>         print "%s memory: %sM count: %s" % (time.asctime(),
> memusage(), count)
> print "%s memory: %sM count: %s (completed)" % (time.asctime(),
> memusage(), count)
>
> Results with the smaller (63M) file:
>
> Thu Jul 17 00:18:21 2008 memory: 4M count: 0 (starting)
> Thu Jul 17 00:18:23 2008 memory: 18M count: 1
> Thu Jul 17 00:18:26 2008 memory: 32M count: 2
> Thu Jul 17 00:18:28 2008 memory: 46M count: 3
> Thu Jul 17 00:18:30 2008 memory: 55M count: 36128 (completed)
>
> Results with the larger (4.3G) file:
>
> Thu Jul 17 00:18:47 2008 memory: 4M count: 0 (starting)
> Thu Jul 17 00:19:40 2008 memory: 146M count: 10
> Thu Jul 17 00:20:41 2008 memory: 289M count: 20
> Thu Jul 17 00:21:41 2008 memory: 432M count: 30
> Thu Jul 17 00:22:42 2008 memory: 574M count: 40
> Thu Jul 17 00:23:47 2008 memory: 717M count: 50
> Thu Jul 17 00:24:49 2008 memory: 860M count: 60
> Thu Jul 17 00:25:51 2008 memory: 1002M count: 70
> Thu Jul 17 00:26:54 2008 memory: 1145M count: 80
> Thu Jul 17 00:27:59 2008 memory: 1288M count: 90
> Thu Jul 17 00:29:03 2008 memory: 1430M count: 100
> Thu Jul 17 00:30:07 2008 memory: 1573M count: 110
> Thu Jul 17 00:31:11 2008 memory: 1716M count: 120
> Thu Jul 17 00:32:15 2008 memory: 1859M count: 130
> Thu Jul 17 00:33:23 2008 memory: 2001M count: 140
> Traceback (most recent call last):
>   File "C:\test\freedb\tardemo.py", line 40, in 
>     for tarinfo in tf:
>   File "C:\test\freedb\tarfilex.py", line 2406, in next
>     tarinfo = self.tarfile.next()
>   File "C:\test\freedb\tarfilex.py", line 2311, in next
>     tarinfo = self.tarinfo.fromtarfile(self)
>   File "C:\test\freedb\tarfilex.py", line 1235, in fromtarfile
>     obj = cls.frombuf(buf)
>   File "C:\test\freedb\tarfilex.py", line 1193, in frombuf
>     if chksum not in calc_chksums(buf):
>   File "C:\test\freedb\tarfilex.py", line 261, in calc_chksums
>     unsigned_chksum = 256 + sum(st

Re: storing references instead of copies in a dictionary

2008-07-17 Thread mk

Calvin Spealman wrote:

To your actual problem... Why do you wanna do this anyway? If you want
to change the function in the dictionary, why don't you simply define
the functions you'll want to use, and change the one you have bound to
the key in the dictionary when you want to change it? In other words,
define them all at once, and then just d['1'] = new_f1. What is wrong
with that?


Well, basically nothing except I need to remember I have to do that.

Suppose one does that frequently in a program. It becomes tedious. I 
think I will define some helper function then:


>>> def helper(fundict, newfun):
... fundict[newfun.func_name] = newfun
...

_If_ there were some shorter and still "proper" way to do it, I'd use 
it. If not, no big deal.



For completeness:

def new_f1(arg):
return "NEW f1 " + arg
f1.func_code = new_f1.func_code

Don't use that unless you really have to and I nearly promise that you don't.


I promise I won't use it. :-) It seems like a 'wrong thing to do'.


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


Re: Python embedding question (2).

2008-07-17 Thread Thomas Troeger

I'd say that PyGame could be a solution.

Or otherwise you could do your own audio/graphics programming (you don't 
tell us which OS you use, but there exist python modules that allow you 
to do barebones graphics & sound programming on linux...).


After some more reading I've stumbled over pyglet. Any experiences with 
it? It seems it does a lot of cool things, if anyone has used it more 
intensely I'd be happy to hear if the following things can be done:


- Linux framebuffer (16, 24 bpp) display of 2d graphics with overlays 
(i.e. menues, contextual areas that pop up etc.). I don't have X on the 
embedded device, just the regular framebuffer.

- alpha blending of several layers.
- rendering of TTF fonts and unicode, for example display of arabic text 
(which renders from right to left) and mixed text support like in the 
unicode bidirectional algorithm.
- hardware caching of bitmaps for faster graphics operations (needed for 
tool tips or similar tasks).


I'll try to find that out myself (I'm pretty excited about the thing 
already ^^), but I'd be happy to hear of people who have used it already.


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


Re: Babelfish translation ...

2008-07-17 Thread Stefan Behnel
Stef Mientki  gmail.com> writes:
> Although it works functionally,
> it can take lots of time waiting for the translation.
> 
> What I basically do is, after selecting a new string to be translated:
> 
> kwds = { 'trtext' : line_to_be_translated, 'lp' :'en_nl'}
> soup = BeautifulSoup (urlopen(url, urlencode ( kwds ) ) )
> translation= soup.find ( 'div', style='padding:0.6em;' ).string
> self.Editor_Babel.SetLabel ( translation )

You should give lxml.html a try.

http://codespeak.net/lxml/

It can parse directly from HTTP URLs (no need to go through urlopen), and it 
frees the GIL while parsing, so it will become efficient to create a little 
Thread that doesn't do more than parsing the web site, as in (untested):

  def read_bablefish(text, lang, result):
  url = BABLEFISH_URL + '?' + urlencode({'trtext':text, 'lp':lang})
  page = lxml.html.parse(url)
  for div in page.iter('div'):
   style = div.get('style')
   if style is not None and 'padding:0.6em;' in style:
   result.append(
  lxml.html.tostring(div, method="text", with_tail=False))

  result = []
  thread = threading.Thread(target=read_bablefish,
args=("...", "en_nl", result))
  thread.start()
  while thread.isAlive():
  # ... do other stuff
  if result:
  print result[0]

Stefan


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


% sign in python?

2008-07-17 Thread korean_dave
What does this operator do? Specifically in this context

test.log( "[[Log level %d: %s]]" % ( level, msg ), description )

(Tried googling and searching, but the "%" gets interpreted as an
operation and distorts the search results)
--
http://mail.python.org/mailman/listinfo/python-list


Re: % sign in python?

2008-07-17 Thread Robert Bossy

korean_dave wrote:

What does this operator do? Specifically in this context

test.log( "[[Log level %d: %s]]" % ( level, msg ), description )

(Tried googling and searching, but the "%" gets interpreted as an
operation and distorts the search results)
  

It's the string formatting operator:
   http://docs.python.org/lib/typesseq-strings.html


Btw, a good place to start searching would be:
   http://docs.python.org/lib/lib.html
especially:
   http://docs.python.org/lib/genindex.html

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


Re: how to debug python's extend module written in c/c++ on windows

2008-07-17 Thread Diez B. Roggisch
fang wrote:

> Dear Diez:
> 
> It is attaching a C-debugger to python. I can attach python-
> debugger(for example:wingIDE) to c-debugger(for example:VS2008), but I
> cannot attach VS2008 to wingIDE. I need both python statement and c
> statement can be single-step debugged.

AFAIK that's not possible. First of all, *don't* attach VS2008 to WingIDE,
use VS2008 to start a python-interpreter with commandline-args (at least
that's how it works for me in gdb)

And then write only small python-scripts that expose an actual error in the
DLL, and debug these.

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


Re: % sign in python?

2008-07-17 Thread Roy H. Han
The percent sign is a placeholder.

For example, if
level = 1
msg = 'look'

Then
'[[Log level %d: %s]]' % ( level, msg )
becomes
'[[Log level 1: look]]'

%d means insert an integer
%s means insert a string

You can also use dictionaries.
d = {'string1': 'hey', 'string2': 'you'}
Then
'%(string1)s %(string2)s' % d
becomes 'hey you'


On Thu, Jul 17, 2008 at 10:33 AM, korean_dave <[EMAIL PROTECTED]> wrote:
> What does this operator do? Specifically in this context
>
> test.log( "[[Log level %d: %s]]" % ( level, msg ), description )
>
> (Tried googling and searching, but the "%" gets interpreted as an
> operation and distorts the search results)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


twistedmatrix

2008-07-17 Thread Białystok
Hi.
I'm newbie in Twisted.
Can anyone explain how does twisted server work? What happens after
reactor.listenTCP running?

I've got many connections from one client (one connection-one socket),
each of them is served by class serve(Protocol).

every protocol owns transport
every transport owns socket

for me it's obvious that protocol returning data to client should use
it's own socket
but
transport.write(data) writes data into buffer
what happens then?

when my server handles two requests from one client (one by one) it
writes first data part to buffer, then second part ... and then writes
back to socket.
what more
it buffers data when I start many clients and sends it to last one.

help me? please?

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


Re: storing references instead of copies in a dictionary

2008-07-17 Thread bgeddy

mk wrote:

Calvin Spealman wrote:

To your actual problem... Why do you wanna do this anyway? If you want
to change the function in the dictionary, why don't you simply define
the functions you'll want to use, and change the one you have bound to
the key in the dictionary when you want to change it? In other words,
define them all at once, and then just d['1'] = new_f1. What is wrong
with that?


Well, basically nothing except I need to remember I have to do that.

Suppose one does that frequently in a program. It becomes tedious. I 
think I will define some helper function then:


 >>> def helper(fundict, newfun):
... fundict[newfun.func_name] = newfun
...

_If_ there were some shorter and still "proper" way to do it, I'd use 
it. If not, no big deal.



For completeness:

def new_f1(arg):
return "NEW f1 " + arg
f1.func_code = new_f1.func_code

Don't use that unless you really have to and I nearly promise that you 
don't.


I promise I won't use it. :-) It seems like a 'wrong thing to do'.




Well it's probably totally "non pythonic" but this does what you want:

def f2(arg):
return "f2 "+arg

def f1(arg):
return "f1 "+arg

a={"1":"f1","2":"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]

Don't know if this is any use to you..

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


Re: storing references instead of copies in a dictionary

2008-07-17 Thread mk

Uwe Schmitt wrote:

Python stores references in dictionaries and does not copy ! (unless
you explicitly use the copy module) !

In your case the entry in the dictionary is a reference to the same
object which f1 references, that is the object at 0xb7f0ba04.

If you now say "f1=...:" then f1 references a new object
at 0xb7f0b994, and the entry in your dictionary still references
the "old" object at 0xb7f0ba04.


Erm, I theoretically knews that, I guess I suffered temporary insanity 
when I wrote "copies" of objects. To me it seems that Python actually 
stores _labels_ referencing _objects_. Here, the problem was that the 
label in the dictionary led to the "old" object.



I do not know any method to automatically update your dictionary
as there is no possibility to overload the assignement operator "=".
But may be somebody can teach me a new trick :-)


Theoretically I could define a class inheriting from dictionary and 
define a property with a setter (and getter). But I would still have to 
update the attribute manually, so plain dictionary is just as good.


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


property getter with more than 1 argument?

2008-07-17 Thread mk


It seems like getter is defined in such way that it passes only 'self':


class FunDict(dict):
def __init__(self):
self.fundict = dict()

def fget(self, fun):
return fundict[fun.func_name]

def fset(self, newfun):
self.fundict[newfun.func_name] = newfun

newfun = property (fget, fset)


>>> a=FunDict()
>>>
>>> a.newfun=f1
>>>
>>> a.newfun('f1')

Traceback (most recent call last):
  File "", line 1, in 
a.newfun('f1')
TypeError: fget() takes exactly 2 arguments (1 given)



Is it possible to pass more than one argument to fget function?

I know: I can define a function with property name ('newfun' in the 
example) and call it with more arguments. But then I do not get the 
benefits of setter and property in general!


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


Re: Python embedding question (2).

2008-07-17 Thread Carl Banks
On Jul 17, 9:57 am, Thomas Troeger <[EMAIL PROTECTED]>
wrote:
> > I'd say that PyGame could be a solution.
>
> > Or otherwise you could do your own audio/graphics programming (you don't
> > tell us which OS you use, but there exist python modules that allow you
> > to do barebones graphics & sound programming on linux...).
>
> After some more reading I've stumbled over pyglet. Any experiences with
> it? It seems it does a lot of cool things, if anyone has used it more
> intensely I'd be happy to hear if the following things can be done:
>
> - Linux framebuffer (16, 24 bpp) display of 2d graphics with overlays
> (i.e. menues, contextual areas that pop up etc.). I don't have X on the
> embedded device, just the regular framebuffer.
> - alpha blending of several layers.
> - rendering of TTF fonts and unicode, for example display of arabic text
> (which renders from right to left) and mixed text support like in the
> unicode bidirectional algorithm.
> - hardware caching of bitmaps for faster graphics operations (needed for
> tool tips or similar tasks).
>
> I'll try to find that out myself (I'm pretty excited about the thing
> already ^^), but I'd be happy to hear of people who have used it already.

Pyglet runs on top of OpenGL, which might have performance problems on
an embedded device, if OpenGL or Mesa is even supported.  If it's
supported, I suspect performance will be adequate for 2D drawing.  It
almost certainly is the lightest solution you can find.


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


Re: how to debug python's extend module written in c/c++ on windows

2008-07-17 Thread fang
Dear Diez:

   I see. I appreciate your help really.


best regards


fang

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


Re: Good HTML Parser

2008-07-17 Thread Stefan Behnel
Chris wrote:
> Can anyone recommend a good HTML/XHTML parser, similar to
> HTMLParser.HTMLParser or htmllib.HTMLParser, but able to intelligently
> know that certain tags, like , are implicitly closed? I need to
> iterate through the entire DOM, building up a DOM path, but the stdlib
> parsers aren't calling handle_endtag() for any implicitly closed tags.
> I looked at BeautifulSoup, but it only seems to work by first parsing
> the entire document, then allowing you to query the document
> afterwards. I need something like a SAX parser.

Try lxml.html. It's very memory friendly and extremely fast, so you may end up
without any reason to use SAX anymore.

http://codespeak.net/lxml/

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


Re: storing references instead of copies in a dictionary

2008-07-17 Thread mk



def f2(arg):
return "f2 "+arg

def f1(arg):
return "f1 "+arg

a={"1":"f1","2":"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]


Neat trick, if probably dangerous in some circumstances. Anyway, thanks, 
I didn't think of that.



Don't know if this is any use to you..


At least I learned something. :-)




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


Re: Javascript - Python RSA encryption interoperability

2008-07-17 Thread Paul Rubin
Evren Esat Ozkan <[EMAIL PROTECTED]> writes:
> I'm trying to encrypt a string with RSA. But it needs to be compitable
> with Dave's JavaScript RSA implementation*. 

What exactly are you trying to do?  That Javascript implementation
looks like bad news.  If you're trying to secure a web page, use SSL,
don't mess around with trying to encrypt it with Javascript.
--
http://mail.python.org/mailman/listinfo/python-list


Unusual Exception Behaviour

2008-07-17 Thread Robert Rawlins
Hello Chaps,

 

I have an unusual situation with my application which I've also seen once or
twice in the past but never found a solution too. Basically the application
stops properly reporting Exceptions when they are thrown.

 

My application logs extensively to a file using the python logging module,
when an exception is throw all the log data starts being thrown to the
command prompt instead of the file, however, I don't get any actual
exception information output.

 

I have looked through the application for any unusual or bare try/except
blocks that don't actually do anything with the except just in case any of
them are causing the issue but can't seem to see any.

 

This little issue makes debugging my application VERY hard, when running the
app I can see it crash, but I get no information as to where the exception
is being thrown from, as you can imagine, quite frustrating.

 

Even when throwing my own exceptions just for testing like so:

 

Raise Exception, "This is a test exception."

 

In certain parts of the application it doesn't print the exception to
screen, but all subsequent requests to the logger seem to print out at the
command prompt.

 

I would really love some suggestions on what might be causing this.

 

Cheers,

 

Robert

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

Re: Unusual Exception Behaviour

2008-07-17 Thread mk
I have looked through the application for any unusual or bare try/except 
blocks that don’t actually do anything with the except just in case any 
of them are causing the issue but can’t seem to see any.


Why not capture exceptions themselves to a log file?

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



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


Re: How to process a very large (4Gb) tarfile from python?

2008-07-17 Thread Terry Carroll
On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt
<[EMAIL PROTECTED]> wrote:

>I had a look at tarfile.py in my current Python 2.5 installations
>lib path. The iterator caches TarInfo objects in a list
>tf.members . If you only want to iterate and you  are not interested
>in more functionallity, you could use "tf.members=[]" inside
>your loop. This is a dirty hack !

Thanks, Uwe.  That works fine for me.  It now reads through all 2.5
million members, in about 30 minutes, never going above a 4M working
set.


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


RE: Unusual Exception Behaviour

2008-07-17 Thread Robert Rawlins
Hi Mk,

> Why not capture exceptions themselves to a log file?
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466332

Thanks for the reply mate, I appreciate you getting back to me so quickly.

I certainly like that implementation for logging the exceptions, however, at
the moment I don't even know where the exceptions are occurring, or what
type they are, could I still use this method to log any and all exceptions
raised in the application? I'm a little confused as to how I can modify that
implementation to do so.

Robert

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


unpacking with default values

2008-07-17 Thread McA
Hi all,

probably a dumb question, but I didn't find something elegant for my
problem so far.
In perl you can unpack the element of a list to variables similar as
in python
(a, b, c = [0, 1, 2]), but the number of variables need not to fit the
number
of list elements.
That means, if you have less list elements variables are filled with
'undef' (None in python), if you have more list elements as necessary
the rest is ignored.

How can I achieve this behaviour with python in an elegant and fast
way?

Best regards
Andreas Mock
--
http://mail.python.org/mailman/listinfo/python-list


Python Behind a Squid Corporate Proxy on Windows

2008-07-17 Thread Larry Hale
Greetings, Pythonistas!

My employer has a Squid Proxy between my Python programs and The
Internet.

I've searched high-and-low, and can only find examples online of how
to do basic authentication to connect TO an external Web Server, but
not how to go THROUGH a (corporate) Proxy, thus my question here.
I've tried all sorts of permutations based on my findings, but
(obviously) nothing's working for me.  I've come across conflicting
information, including that urllib2 can't/won't do what I'm needing,
though this statement was a couple years old.

I'm running Python 2.5 on Windows XP SP2 64-bit.  The Proxy is Squid
(don't know what version, but can find out if this is relevant).

urllib2 grabs the Proxy info fine: 'http': 'http://webfilter.xyz.local:
3128' (.getproxies()).  There's the obvious necessity of telling
"something" my ID/pass *somehow*.

An example of one iteration:

##

import urllib2

proxy_handler = urllib2.ProxyHandler( { "http": "http://
myusername:@webfilter.xyz.local:3128" } )
opener= urllib2.build_opener( proxy_handler )

urllib2.install_opener( opener )

response = opener.open( "http://python.org"; )

print response

##

I've tried situations using HTTPPasswordMgrWithDefaultRealm and its
add_password method, also to no avail.  (Again, THIS sort of thing
seems related to the -external- Web Server, _not_ going *through* a
Proxy.  'Course, I could be wrong.  But if I am, I couldn't get this
to work, either.  ;)

I've looked at what's happening with Wireshark; Py/my program/urllib2
makes the initial page request, Proxy replies HTTP Error 407: Proxy
Authentication Required, and Py/my program/urllib2 simply stops at
that, reporting the message/error.

Please forgive me; I've been programming in Python for a few years
now, but never had to deal with Web Proxies.  I *have* tried to RTFMs,
but the "documentation" for non-basic stuffs with urllib2 is... uh...
well, I'm sure ye olde pro's know...  :)


Cheers, and *any* help would be appreciated!
-Larry
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unusual Exception Behaviour

2008-07-17 Thread mk

Robert Rawlins wrote:


I certainly like that implementation for logging the exceptions, however, at
the moment I don't even know where the exceptions are occurring, or what
type they are, could I still use this method to log any and all exceptions
raised in the application? 


Sure.

I'm a little confused as to how I can modify that

implementation to do so.


Remember, Google is your friend, here's the crux of the method without 
the fancy schmancy sugar coating:


http://linux.byexamples.com/archives/365/python-convey-the-exception-traceback-into-log-file/

if __name__=="__main__":
try:
main()
except:
print "Trigger Exception, traceback info forward to log file."
traceback.print_exc(file=open("errlog.txt","a"))
sys.exit(1)


This will obviously capture every exception happening in the main() 
function.


The drawback of this method is that you cannot capture the  error 
message / object accompanying the exception, as you normally can do 
while capturing specific exception:


>>> import sys
>>> import traceback

>>> def anindextoofar(alist):
print alist[10]


>>> shortlist=range(1,10)
>>>
>>> try:
anindextoofar(shortlist)
except IndexError, err:
print err
traceback.print_exc(file=sys.stdout)


list index out of range
Traceback (most recent call last):
  File "", line 2, in 
  File "", line 2, in anindextoofar
IndexError: list index out of range




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


properly delete item during "for item in..."

2008-07-17 Thread Ratko
Say you have something like this:

for item in myList:
   del item

Would this actually delete the item from the list or just decrement
the reference counter because the item in myList is not associated
with name "item" anymore (but still is with myList[itemIndex])? In
other words, is "item" a temporary reference to myList[itemIndex] or
is it actually that reference that myList has stored?

I am not sure if this question even makes any sense anymore. I've been
using python for years and never had any problems (and I don't now
either) but now that I had to revisit c++/STL, I had to deal about
these issues and was wondering how python does it.

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


Re: unpacking with default values

2008-07-17 Thread Gary Herron

McA wrote:

Hi all,

probably a dumb question, but I didn't find something elegant for my
problem so far.
In perl you can unpack the element of a list to variables similar as
in python
(a, b, c = [0, 1, 2]), but the number of variables need not to fit the
number
of list elements.
That means, if you have less list elements variables are filled with
'undef' (None in python), if you have more list elements as necessary
the rest is ignored.

How can I achieve this behaviour with python in an elegant and fast
way?

Best regards
Andreas Mock
--
http://mail.python.org/mailman/listinfo/python-list
  


Python 3.0 has something a bit like this.  Excess values can be bound 
(as a list) to the last variable:


 a,b,*c = [1,2,3,4,5]

will result in c containing [3,4,5].

In Python 2.x, you can't do that directly, but you should be able to 
create a function that lengthens or shortens an input tuple of arguments 
to the correct length so you can do:


 a,c,b = fix(1,2)
 d,e,f = fix(1,2,3,4)

However, the function won't know the length of the left hand side 
sequence, so it will have to be passed in as an extra parameter or hard 
coded.



Gary Herron

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


Re: Python Behind a Squid Corporate Proxy on Windows

2008-07-17 Thread Larry Hale
Err, the line above should be:

proxy_handler = urllib2.ProxyHandler( { "http": "http://
myusername:[EMAIL PROTECTED]:3128" } )

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


Re: properly delete item during "for item in..."

2008-07-17 Thread Marc 'BlackJack' Rintsch
On Thu, 17 Jul 2008 09:27:27 -0700, Ratko wrote:

> for item in myList:
>del item
> 
> Would this actually delete the item from the list or just decrement
> the reference counter because the item in myList is not associated
> with name "item" anymore (but still is with myList[itemIndex])? In
> other words, is "item" a temporary reference to myList[itemIndex] or
> is it actually that reference that myList has stored?

The latter.  Names are always bound to objects, you can't bind a name to
another name or reference in Python.

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


Re: properly delete item during "for item in..."

2008-07-17 Thread Gary Herron

Ratko wrote:

Say you have something like this:

for item in myList:
   del item

Would this actually delete the item from the list or just decrement
the reference counter because the item in myList is not associated
with name "item" anymore (but still is with myList[itemIndex])? In
other words, is "item" a temporary reference to myList[itemIndex] or
is it actually that reference that myList has stored?
  


The 'del' statement does not delete an object, it deletes a reference to 
an object.  In this case, the variable item is deleted from the scope, 
and the referred-to object will have its reference counter decremented 
by 1.  (But, as you surmise, not to zero, because the list will still 
reference it.)


You could remove the object from the list with
 del myList[i]
if you knew i.  HOWEVER, don't do that while looping through the list!  
Changing a list's length will interact badly with the for loop's 
indexing through the list, causing the loop to mis the element following 
the deleted item.


Gary Herron


I am not sure if this question even makes any sense anymore. I've been
using python for years and never had any problems (and I don't now
either) but now that I had to revisit c++/STL, I had to deal about
these issues and was wondering how python does it.

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


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


RE: Unusual Exception Behaviour

2008-07-17 Thread Robert Rawlins
Hi MK,

>>Robert Rawlins wrote:
>>
>> I certainly like that implementation for logging the exceptions, however,
at
>> the moment I don't even know where the exceptions are occurring, or what
>> type they are, could I still use this method to log any and all
exceptions
>> raised in the application? 

> Remember, Google is your friend, here's the crux of the method without 
> the fancy schmancy sugar coating:
>
>
http://linux.byexamples.com/archives/365/python-convey-the-exception-traceba
ck-into-log-file/
>
> if __name__=="__main__":
>  try:
>  main()
>  except:
>  print "Trigger Exception, traceback info forward to log file."
>  traceback.print_exc(file=open("errlog.txt","a"))
>  sys.exit(1)
>

I've just given this solution a shot but I still seem to get the same
result, it suddenly starts dumping the log data to the command line, and
nothing gets printed in error.txt apart from the keyboard interrupt from
when I kill the application.

For some reason the exceptions don't seem to be raised properly so obviously
aren't being caught at this higher level.

So confusing.

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


Re: properly delete item during "for item in..."

2008-07-17 Thread mk

Gary Herron wrote:

You could remove the object from the list with
 del myList[i]
if you knew i.  HOWEVER, don't do that while looping through the list!  
Changing a list's length will interact badly with the for loop's 
indexing through the list, causing the loop to mis the element following 
the deleted item.


Jumping into a thread, I know how not to do it, but not how to do it 
properly?


Iterating over a copy may _probably_ work:

>>> t=['a', 'c', 'b', 'd']
>>>
>>> for el in t[:]:
del t[t.index(el)]


>>> t
[]


However, is it really safe? Defining safe as "works reliably in every 
corner case for every indexable data type"?



Con: suppose the data structure t is really, really big. Just deleting 
some items from t temporarily doubles the memory consumption.


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


Re: properly delete item during "for item in..."

2008-07-17 Thread Ratko
On Jul 17, 9:57 am, mk <[EMAIL PROTECTED]> wrote:
> Gary Herron wrote:
> > You could remove the object from the list with
> >  del myList[i]
> > if you knew i.  HOWEVER, don't do that while looping through the list!
> > Changing a list's length will interact badly with the for loop's
> > indexing through the list, causing the loop to mis the element following
> > the deleted item.
>
> Jumping into a thread, I know how not to do it, but not how to do it
> properly?
>
> Iterating over a copy may _probably_ work:
>
>  >>> t=['a', 'c', 'b', 'd']
>  >>>
>  >>> for el in t[:]:
> del t[t.index(el)]
>
>  >>> t
> []
>
> However, is it really safe? Defining safe as "works reliably in every
> corner case for every indexable data type"?
>
> Con: suppose the data structure t is really, really big. Just deleting
> some items from t temporarily doubles the memory consumption.



Would this work (safely) then? It does in my test cases but that of
course doesn't prove it works in a general case...

for item in myList:
myList.remove(item)


For dictionaries we can just iterate over values() or items() as
opposed to itervalues() or iteritems() since that's technically a copy
of values or items in the dict, right?


R

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


Re: Unusual Exception Behaviour

2008-07-17 Thread mk

http://linux.byexamples.com/archives/365/python-convey-the-exception-traceba
ck-into-log-file/

if __name__=="__main__":
 try:
 main()
 except:
 print "Trigger Exception, traceback info forward to log file."
 traceback.print_exc(file=open("errlog.txt","a"))
 sys.exit(1)



I've just given this solution a shot but I still seem to get the same
result, it suddenly starts dumping the log data to the command line, and
nothing gets printed in error.txt apart from the keyboard interrupt from
when I kill the application.


That's seriously weird. What's your Python version and platform? On my 
Windows and Linux machines, with more recent Python versions the above 
trick works flawlessly.


Check your environment, namely PYTHON* variables. There may be something 
causing this behaviour. Unset them.


Check the first line of your scripts. If you're calling wrong Python 
interpreter (there may be more than one in the system for some reason), 
this may cause it.


You could also try setting up PYTHONINSPECT environment variable or run 
the python interpreter with -i option before program filename, which 
drops you into an interactive shell upon exception or termination of a 
program.



For some reason the exceptions don't seem to be raised properly so obviously
aren't being caught at this higher level.

So confusing.


This behavior is seriously unusual for Python. Maybe you have some old / 
buggy version?





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


RE: Unusual Exception Behaviour

2008-07-17 Thread Robert Rawlins
> That's seriously weird. What's your Python version and platform? On my 
> Windows and Linux machines, with more recent Python versions the above 
> trick works flawlessly.
>
> Check your environment, namely PYTHON* variables. There may be something 
> causing this behaviour. Unset them.
>
> Check the first line of your scripts. If you're calling wrong Python 
> interpreter (there may be more than one in the system for some reason), 
> this may cause it.
>
> You could also try setting up PYTHONINSPECT environment variable or run 
> the python interpreter with -i option before program filename, which 
> drops you into an interactive shell upon exception or termination of a 
> program.
>
> This behavior is seriously unusual for Python. Maybe you have some old / 
> buggy version?

Thanks for that MK. I'm using Debian with Python 2.5 from the stable apt
repository, installed but a couple of days ago. I'll be sure to look into
those other elements you suggested also. I'm not sure if it bares any
resemblance but this application runs a gobject mainloop and uses dbus quite
extensively.

Don't think this might have something to do with the way I have my loggers
configured do you? For some reason it sits in my mind that this issue
started when I moved my logging configuration from programmatic into a
config file, I can't be totally sure of that though.

I've attached the config file that I use, does it all look ok to you? I
wonder if the way I've not added any handles/formatters to my root logger
might be causing beef?

This is certainly a strange one.

Robert


simple_loggingconf.conf
Description: Binary data
--
http://mail.python.org/mailman/listinfo/python-list

Re: properly delete item during "for item in..."

2008-07-17 Thread Duncan Booth
mk <[EMAIL PROTECTED]> wrote:

> Iterating over a copy may _probably_ work:
> 
> >>> t=['a', 'c', 'b', 'd']
> >>>
> >>> for el in t[:]:
>  del t[t.index(el)]
> 
>  
> >>> t
> []
> 
> 
> However, is it really safe? Defining safe as "works reliably in every 
> corner case for every indexable data type"?

No, because you cannot necessarily copy every indexable data type using 
t[:], and not all types will support index. Also it is inefficient to 
delete from the start of the list.

If you are working with a list and deleting every object:

del t[:]

will suffice.

If you don't want to delete everything then you could do:

for index, el in enumerate(reversed(t)):
if not wewant(el):
   del t[index]

but the pythonic way is just:

 t[:] = [ el for el in t if wewant(el) ]

or if you just want the filtered list and don't care about updating the 
original:

 t = [ el for el in t if wewant(el) ]


> Con: suppose the data structure t is really, really big. Just deleting 
> some items from t temporarily doubles the memory consumption.

No it doesn't. Copying a list doesn't copy any of the elements in the list, 
it just copies the references to those element.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unpacking with default values

2008-07-17 Thread McA
On 17 Jul., 18:33, Gary Herron <[EMAIL PROTECTED]> wrote:
>
> In Python 2.x, you can't do that directly, but you should be able to
> create a function that lengthens or shortens an input tuple of arguments
> to the correct length so you can do:
>
>   a,c,b = fix(1,2)
>   d,e,f = fix(1,2,3,4)
>
> However, the function won't know the length of the left hand side
> sequence, so it will have to be passed in as an extra parameter or hard
> coded.

Hi Gary,

thank you for the answer.
Do you know the "protocol" used by python while unpacking?
Is it a direct assingnment? Or iterating?

Best regards
Andreas Mock
--
http://mail.python.org/mailman/listinfo/python-list


Re: property getter with more than 1 argument?

2008-07-17 Thread Roy H. Han
I don't understand what you're trying to do here.


On Thu, Jul 17, 2008 at 10:57 AM, mk <[EMAIL PROTECTED]> wrote:
>
> It seems like getter is defined in such way that it passes only 'self':
>
>
> class FunDict(dict):
>def __init__(self):
>self.fundict = dict()
>
>def fget(self, fun):
>return fundict[fun.func_name]
>
>def fset(self, newfun):
>self.fundict[newfun.func_name] = newfun
>
>newfun = property (fget, fset)
>
>
 a=FunDict()

 a.newfun=f1

 a.newfun('f1')
>
> Traceback (most recent call last):
>  File "", line 1, in 
>a.newfun('f1')
> TypeError: fget() takes exactly 2 arguments (1 given)
>
>
>
> Is it possible to pass more than one argument to fget function?
>
> I know: I can define a function with property name ('newfun' in the example)
> and call it with more arguments. But then I do not get the benefits of
> setter and property in general!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: bad recursion, still works

2008-07-17 Thread mdsherry
On Jul 17, 8:27 am, Jeff <[EMAIL PROTECTED]> wrote:
> Thanks, that made things very clear.  I like that technique for adding
> memoization via the parameter.  That is clever.  It would be nice if
> there were a way to have multiple functions close over a shared local
> variable in Python, like let-binding in lisp.

Is this something like what you're looking for?

>>> def functionmaker():
... shared = []
... def addnumber():
... shared.append(3)
... return shared
... def addletter():
... shared.append('f')
... return shared
... return addnumber, addletter
...
>>> addnumber, addletter = functionmaker()
>>> addnumber()
[3]
>>> addletter()
[3, 'f']
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to process a very large (4Gb) tarfile from python?

2008-07-17 Thread Uwe Schmitt
On 17 Jul., 17:55, Terry Carroll <[EMAIL PROTECTED]> wrote:
> On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt
>
> <[EMAIL PROTECTED]> wrote:
> >I had a look at tarfile.py in my current Python 2.5 installations
> >lib path. The iterator caches TarInfo objects in a list
> >tf.members . If you only want to iterate and you  are not interested
> >in more functionallity, you could use "tf.members=[]" inside
> >your loop. This is a dirty hack !
>
> Thanks, Uwe.  That works fine for me.  It now reads through all 2.5
> million members, in about 30 minutes, never going above a 4M working
> set.

Maybe we should post this issue to python-dev mailing list.
Parsing large tar-files is not uncommon.

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


RE: Unusual Exception Behaviour

2008-07-17 Thread Robert Rawlins
>> That's seriously weird. What's your Python version and platform? On my 
>> Windows and Linux machines, with more recent Python versions the above 
>> trick works flawlessly.
>>
>> Check your environment, namely PYTHON* variables. There may be 
>> something causing this behaviour. Unset them.
>>
>> Check the first line of your scripts. If you're calling wrong Python 
>> interpreter (there may be more than one in the system for some 
>> reason), this may cause it.
>>
>> You could also try setting up PYTHONINSPECT environment variable or 
>> run the python interpreter with -i option before program filename, 
>> which drops you into an interactive shell upon exception or 
>> termination of a program.
>>
>> This behavior is seriously unusual for Python. Maybe you have some old 
>> / buggy version?
> 
> Thanks for that MK. I'm using Debian with Python 2.5 from the stable apt
repository, installed > but a couple of days ago. I'll be sure to look into
those other elements you suggested also. > > I'm not sure if it bares any
resemblance but this application runs a gobject mainloop and uses > > dbus
quite extensively.
>
> Don't think this might have something to do with the way I have my loggers
configured do you? > > For some reason it sits in my mind that this issue
started when I moved my logging > > > >  > > > configuration from
programmatic into a config file, I can't be totally sure of that though.
>
> I've attached the config file that I use, does it all look ok to you? I
wonder if the way I've > not added any handles/formatters to my root logger
might be causing beef?
>
> This is certainly a strange one.

Ok, Just to add a little interest, when I comment out the configuration line
for my logging, like so:

#logging.config.fileConfig("/myapp/configuration/logging.conf")

It appears to throw the exceptions as normal :-) :-s

Sounds as if it's a conflict with my logging configuration, I wonder what
though.

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


Re: Converting from local -> UTC

2008-07-17 Thread M.-A. Lemburg

On 2008-07-16 20:00, Keith Hughitt wrote:

Thanks Gabriel!

That helps clear things up for me. The above method works very well. I
only have one remaining question:
How can I pass a datetime object to MySQL?'

So far, what I've been doing is building the query as a string, for
example:

query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas,
date, 'jpg')
cursor.execute(query)


Use binding parameters and it should work:

query = "INSERT INTO image VALUES(%d, %d, %s, '%s')"
cursor.execute(query, (id, meas, date, 'jpg'))

Database interfaces typically do not support timezones, so I'm not
sure why you are making things more complicated by adding a timezone
to the date/time value.


This works fine for regular datetime objects, which are passed as
strings similar
to: "2003-10-01 00:00:00." When incorporating a timezone, however, the
resulting string
is of the form "2003-10-01 00:00:00+00:00." Unfortunately, MySQL does
not recognize
the offset.

I know you said you don't use MySQL, but how would you do something
execute a similar query
on the database you normally interface with?




Thanks,
Keith


On Jul 15, 12:04 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
En Mon, 14 Jul 2008 12:06:30 -0300,KeithHughitt  
<[EMAIL PROTECTED]> escribió:





On Jul 12, 12:52 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
En Fri, 11 Jul 2008 15:42:37 -0300,KeithHughitt  
<[EMAIL PROTECTED]> escribió:

I am having a little trouble figuring out how to convert a python
datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would
like to create a UTC date so that when I send it to MySQL (which
treats all dates at local dates by default), it will already have
incorporated the proper UTC offset. I've tried looking through the
docshttp://python.active-venture.com/lib/datetime-datetime.html), but
have not had any luck.
You have to use a "timezone aware" datetime object. If all you want is  
to  
store an UTC date, the tzinfo demo classes that you can find in the  
Python  
docs at  may be enough.

Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved
it as
UTC.py and imported it. I'm still not exactly sure how to use it
though. It looks like
the file already creates an instance of the UTC tzinfo class (line 20:
"utc = UTC()"),
however, when I try to test it out in the interpreter, it cannot be
found. I'm new
to python, and there is probably something obvious I'm missing, but do
you have any ideas?
The import statement in Python doesn't behave the same way as similar  
statements in other languages - and it may be confusing you. I'll try to  
explain it using this example.

You have:
- a *file* UTC.py, containing the source code for the *module* UTC. It  
contains:

- a *class* definition (UTC) and
- an *instance* of that class, utc.

--- begin UTC.py ---If you pass a "timezone aware" datetime object as a SQL 
parameter
class UTC(tzinfo):
   ...
utc = UTC()
...
--- end UTC.py ---


Here is what I'm attempting:
 output begin =
Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import datetime, UTC
Here you have imported the *module* UTC. That is, the name UTC now refers  
to a newly created module just loaded from the UTC.py file.



t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC())

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'module' object is not callable
The error comes from UTC(): UTC is a module, UTC() is attempting to "call"  
it, and since modules are not callable objects, we get a TypeError.



utc

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'utc' is not defined
The *only* name we have imported so far is UTC - the module. Lowercase utc  
isn't defined.



utc = UTC()

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'module' object is not callable

Same as above...

Ok, how to solve it? We know that UTC refers to the *module* with the same  
name. To get the *class* inside that module, use UTC.UTC - try again in  
the interpreter. To create a new instance of that class, you can use  
UTC.UTC(). To obtain the instance already created in the UTC module, use  
UTC.utc


**OR**

Import those names explicitely:

py> from UTC import UTC

In this case the name UTC refers to the *class* inside the module.
In this particular example it may be confusing - both have the same name.  
Another example from the standard library: the poplib module contains a  
POP3 class, so after executing this line:


py> from poplib import POP3

the name POP3 refers to that class. The poplib module itself isn't  
directly available.

Back to the UTC module, you could use:

py> from UTC import utc

and now utc refers to the *instance* already created inside the module.  
This last form may be the most convenient in your case:


py> import datetime
p

Re: unpacking with default values

2008-07-17 Thread Gary Herron

McA wrote:

On 17 Jul., 18:33, Gary Herron <[EMAIL PROTECTED]> wrote:
  

In Python 2.x, you can't do that directly, but you should be able to
create a function that lengthens or shortens an input tuple of arguments
to the correct length so you can do:

  a,c,b = fix(1,2)
  d,e,f = fix(1,2,3,4)

However, the function won't know the length of the left hand side
sequence, so it will have to be passed in as an extra parameter or hard
coded.



Hi Gary,

thank you for the answer.
Do you know the "protocol" used by python while unpacking?
Is it a direct assingnment? Or iterating?
  


Both I think, but what do you mean by *direct* assignment?


Best regards
Andreas Mock
--
http://mail.python.org/mailman/listinfo/python-list
  


It RHS of such an assignment can be any iterable (I think).  Lets test:
(The nice thing about an interactive Python session, it that it's really 
easy to test.)



>>> L = [1,2,3]
>>> a,b,c=L
>>> a,b=L
Traceback (most recent call last):
 File "", line 1, in 
ValueError: too many values to unpack
>>> a,b,c,d=L
Traceback (most recent call last):
 File "", line 1, in 
ValueError: need more than 3 values to unpack

>>> G = (f for f in [1,2,3])   # A generator expression
>>> a,b,c = G
>>> G = (f for f in [1,2,3])   # A generator expression
>>> a,b = G
Traceback (most recent call last):
 File "", line 1, in 
ValueError: too many values to unpack
>>> G = (f for f in [1,2,3])   # A generator expression
>>> a,b,c,d = G
Traceback (most recent call last):
 File "", line 1, in 
ValueError: need more than 3 values to unpack


I'd call that direct assignment with values supplied by any iterable.

Gary Herron





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


Re: properly delete item during "for item in..."

2008-07-17 Thread Gary Herron

Ratko wrote:

On Jul 17, 9:57 am, mk <[EMAIL PROTECTED]> wrote:
  

Gary Herron wrote:


You could remove the object from the list with
 del myList[i]
if you knew i.  HOWEVER, don't do that while looping through the list!
Changing a list's length will interact badly with the for loop's
indexing through the list, causing the loop to mis the element following
the deleted item.
  

Jumping into a thread, I know how not to do it, but not how to do it
properly?

Iterating over a copy may _probably_ work:

 >>> t=['a', 'c', 'b', 'd']
 >>>
 >>> for el in t[:]:
del t[t.index(el)]

 >>> t
[]

However, is it really safe? Defining safe as "works reliably in every
corner case for every indexable data type"?

Con: suppose the data structure t is really, really big. Just deleting
some items from t temporarily doubles the memory consumption.





Would this work (safely) then? It does in my test cases but that of
course doesn't prove it works in a general case...

for item in myList:
myList.remove(item)
  


No.  Same problem,  The for loop iterates through the list by keeping 
and incrementing an internal index.  Any modification of the list does 
not change the index correspondingly.


One proper way:
newList = []
for item in myList:
 if ... whatever...
newList.append(item)
myList = newList

Another, using list comprehension (it's the same thing really as the above):
myList = [item for item in myList if ... whatever...]






For dictionaries we can just iterate over values() or items() as
opposed to itervalues() or iteritems() since that's technically a copy
of values or items in the dict, right?
  


No!  In fact the whole point of iteritems and itervalues and iterkeys is 
that they *DO NOT* make copies, so changing the dictionary out from 
under them is a programming error.


If you use dict.items(), dict.keys() or dict.values(), then you're OK, 
because these methods  *do* create new lists for both.


Gary Herron



R

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


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


  1   2   >