RE: A fast way to read last line of gzip archive ?

2009-05-23 Thread Barak, Ron
 

> -Original Message-
> From: MRAB [mailto:goo...@mrabarnett.plus.com] 
> Sent: Thursday, May 21, 2009 19:02
> To: 'python-list@python.org'
> Subject: Re: A fast way to read last line of gzip archive ?
> 
> Barak, Ron wrote:
> > Hi,
> >  
> > I need to read the end of a 20 MB gzip archives (To extract 
> the date 
> > from the last line of a a gzipped log file).
> > The solution I have below takes noticeable time to reach the end of 
> > the gzip archive.
> >  
> > Does anyone have a faster solution to read the last line of 
> a gzip archive ?
> >  
> > Thanks,
> > Ron.
> >  
> > #!/usr/bin/env python
> >  
> > import gzip
> >  
> > path = "./a/20/mb/file.tgz"
> >  
> > in_file = gzip.open(path, "r")
> > first_line = in_file.readline()
> > print "first_line ==",first_line
> > in_file.seek(-500)
> > last_line = in_file.readlines()[-1]
> > print "last_line ==",last_line
> > 
> It takes a noticeable time to reach the end because, well, 
> the data is compressed! The compression method used requires 
> the preceding data to be read first.

I thought maybe someone has a way to unzip just the end portion of the archive 
(instead of the whole archive), as only the last part is needed for reading the 
last line.

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


Need Help

2009-05-23 Thread abosalim

#Gui
import re, collections
from Tkinter import *
from nltk_lite import tokenize

def words(text): return re.findall('[a-z]+', text.lower())
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
NWORDS = train(words(file('big1.txt').read()))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in s if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in s if len(b)>1]
replaces = [a + c + b[1:] for a, b in s for c in alphabet if b]
inserts = [a + c + b for a, b in s for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in
NWORDS)
def known(words):
return set(w for w in words if w in NWORDS)
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2
(word) or [word]
return max(candidates, key=lambda w: NWORDS[w])
def textcorrect(str):
s=[]
for i in tokenize.whitespace(str):
s.append(correct(i))
result= " ".join(s)
return result

GUI
Part#
class Ex3:
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
self.field = Entry(self.frame)
self.field.pack(side=TOP)
self.contents = StringVar()
self.field.config(text=self.contents)
self.stop = Button(self.frame, text="Exit", fg="red",
command=self.frame.quit)
self.stop.pack(side=RIGHT)
self.enter = Button(self.frame, text="Correct", fg="black",
command=self.new)
self.enter.pack(side=LEFT)

def new(self):
self.string = self.contents.get()
#pass contents of textfield to words()method above
self.res=  words(self.string)
self.frame2 = Frame()
self.frame2.pack()
self.words = Label(self.frame2, text=self.res, fg="blue", font=
("Arial", 16))
self.words.pack()
root = Tk()
Ex3 = Ex3(root)
root.mainloop()



It print text without correction.I think it didn't enter the method or
any method above the gui.
Please if you have any information,inform me















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


Re: Problems with sys.stout.flush()

2009-05-23 Thread AK

Joel Ross wrote:

Rhodri James wrote:

On Sat, 23 May 2009 18:19:11 +0100, Joel Ross  wrote:


Now I can move onto next one.


Except that you still have the interesting issue that your environment
isn't responding to '\r' correctly, which worries me rather.  Or did
you never test that?

Yeah I gave the "\r" a go and it kept printing out on a new line I will 
look into it.


Thanks for the heads up


What happens when you run this little program:

import time, sys

print "ONE",
sys.stdout.flush()
time.sleep(0.5)
print "\rTWO",
sys.stdout.flush()
time.sleep(0.5)


The idea is that it should print ONE, flush it, sleep .5 sec so 
that you can see 'ONE', then return to start of line, print TWO, 
flush it so you can read it, and sleep another 0.5 sec.


NOTE comma after print statement.

Does that work for you?

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


Extending C++ class in python

2009-05-23 Thread nazia
Hi all,
I'm a newbie in Python and need help. Can anyone help me by explaining
the steps of extending a C++ class in Python with a simple example?
I'm not interested to use SWIG like tools.
Thanks for your time.

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


[Announcement] PyISAPIe version 1.1.0 Release Candidate 2

2009-05-23 Thread Phillip Sitbon
Hello all,

I've recently revived the Python ISAPI Extension (PyISAPIe) project
and thought I'd share the newest release with you, version 1.1.0-rc2.

Development in bringing Python to Windows servers has been slow these
days, so hopefully this project can continue to fill a niche for those
who need good performance and stable functionality.

http://pyisapie.sourceforge.net/

I know there's a good number of folks that have used it or are
currently using it, so any feedback is appreciated in order to make
1.1.0 come around faster.

Thanks for all your support so far!

Cheers,

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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Joel Ross

Mel wrote:

Joel Ross wrote:

Rhodri James wrote:

[ ... ]

Except that you still have the interesting issue that your environment
isn't responding to '\r' correctly, which worries me rather.  Or did
you never test that?



Yeah I gave the "\r" a go and it kept printing out on a new line I will
look into it.


Are you running an Apple computer?

Mel.



No running a Linux fedora 9 box
--
http://mail.python.org/mailman/listinfo/python-list


Re: from __future__ import absolute_import issue

2009-05-23 Thread Gabriel Genellina
En Sat, 23 May 2009 12:32:24 -0300, LittleGrasshopper  
 escribió:



On May 22, 12:42 am, "Gabriel Genellina" 
wrote:

En Wed, 20 May 2009 20:18:02 -0300, LittleGrasshopper  
 escribió:

> It appears that either absolute imports (or my brain) aren't working.
> Given a module string.py which is in the same directory as a.py:

> #File a.py
> from __future__ import absolute_import
> import string
> print string # Module imported is string.py in current directory, not
> standard library module

absolute_import helps with imports inside a package (those are  
"relative"  
imports, relative to the package). If a module is located in a  
directory  
listed in sys.path, an absolute import will find it. I don't think  
there  

is a way to avoid shadowing a standard module (other than ensuring the  
standard directories come first in sys.path).


You are right. If you have a directory in your PYTHONPATH before the
standard library directories that has a string module, for example,
absolute_import will not help you. I was getting confused by the fact
that when I print sys.path from the python shell, the first entry is
an empty string.
This empty string must denote the current directory though, because:

['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/ ...]

When I have this sys.path, doing an "import string" from a module
where I have absolute imports enabled will still import the string
module in the package (which also means it is in the same directory in
this case.)


Mmm, I don't understand this. Do you mean that the current directory is a  
package (that is, it contains an __init__.py file? And the main script is  
there? Then, from Python's POV, it is NOT a package; packages are  
recognized only at import time; if you execute a script that happens to be  
inside a package directory, Python is not aware of the "packageness" of  
such directory.

In that case, all imports are absolute.
The current directory should not be a package (at least, not a package  
accessible from sys.path), nasty things may happen.



So I think my string.py is being imported not because it
is in the same package, but because the home directory is searched
first.


Yes.


The empty string doesn't make much sense though (at least in a
Unix system, you would imagine it would be something like './') but I
guess that synce Python is platform independent, the empty string is
taken to denote the current directory.


Maybe you're surprised, but I don't think it's strange at all. Nobody  
writes open("./foo.txt") instead of open("foo.txt"), and  
os.path.normpath("./foo.txt") is actually "foo.txt". Having no path  
specification means "use the current directory" (at least in all OS that I  
know of, where "process' current directory" makes any sense)


--
Gabriel Genellina

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


Re: When does the escape character work within raw strings?

2009-05-23 Thread Steven D'Aprano
On Sat, 23 May 2009 14:05:10 -0700, walterbyrd wrote:

> On May 22, 12:22 pm, "Rhodri James"
>> How do you know how a string object is going to be treated by any given
>> function?  Read the Fine Manual for that function.
> 
> So am I to understand that there is no consistency in string handling
> throughout the standard modules/objects/methods?

No, you have completely misunderstood.


> Seems to make python a lot more complicated than it needs to be, but
> okay.

No, you are imagining complexity that doesn't exist.

To the Python compiler, a string is a string is a string. The rules are 
very simple: you write a string literal using quotation marks to tell the 
compiler "the text between these delimiters are a literal string". Here 
are the delimiters understood by Python:


Regular strings, must be on a single line:
'  '  or  "  "

Regular strings, allowed to include multiple lines:
'''  '''  or  """  """

Raw strings, must be on a single line:
r'  '  or  r"  "

Raw strings, allowed to include multiple lines:
r'''  '''  or  r"""  """

Regular strings interpret backslash escapes specially: \c has special 
meaning depending on what c is. For example, \t is interpreted by the 
compiler as a tab, and \n is interpreted as a newline. Raw strings 
*don't* interpret backslashes specially (except that you can't end the 
raw string with an odd number of backslashes).

That is how you *create* string literals. It is 100% consistent all 
through Python: the rules apply in every module, in every function, 
everywhere, because the compiler creates the string before the function 
or module gets a chance to see the string.

Having been created, how the string is *used* depends on the application, 
and Python modules and functions are no different. Inside a calculator 
application, the meaning of the literal string "x/y" would be very 
different than it would be inside an application dealing with file names. 
Python modules are no different:

- the os module interprets many strings as file names according to the 
rules for your operating system: e.g. on Linux '/' separates parts of the 
pathname into sub-directories. On Windows, either forward or backslashes 
are used to separate directories, and ':' is used to separate drive 
letters from the path.

- the glob module interprets strings according to the rules for shell 
globbing: e.g. '*' means 'match any number of any character', '?' means 
'match a single of any character'.

- the re module interprets strings according to the rules for regular 
expressions: e.g. '.*' means 'match any number of any character (except 
newline by default)' and '\d' (backslash-d) means 'match a single decimal 
digit'.

- the urllib and urllib2 modules interpret strings according to the rules 
of dealing with URLs.


In every case, you construct the string literals using the same rules, 
but the *meaning* of them differs according to the application. Because 
regular expressions give special meanings to literal backslashes, it is 
inconvenient to create many regexes using regular strings, because you 
need to escape the backslashes. That's where raw strings are more useful.





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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Mel
Joel Ross wrote:
> Rhodri James wrote:
[ ... ]
>> Except that you still have the interesting issue that your environment
>> isn't responding to '\r' correctly, which worries me rather.  Or did
>> you never test that?

> Yeah I gave the "\r" a go and it kept printing out on a new line I will
> look into it.

Are you running an Apple computer?

Mel.


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


Re: wxpython and zoom/pan image

2009-05-23 Thread Dave Angel

rzzzwil...@gmail.com wrote:

Hi,

I've googled for this, but can only find things like openlayers that
is a web-based javascript solution.

I need to display an image at various zoom levels and want to allow
the user to pan around in the Google maps style, that is, left-click
hold and drag.  The code should also action double-clicks on the image
(but that's easy).

There are no 'standard' wxpython widgets that allow this.  Can anyone
point me to information on how to implement such a thing, or maybe
some working code?

Thanks,
Ross

  
These are all (?) of the pieces in my working image display program.  It 
rotates and scales.  It's an exercise to the reader to divide it up.  
For example, you don't want to rerun all of this every time the mouse
drags a little.  So these are in two different places, where the first 
group only happens when you change the image file, or rotate by an angle 
other than 90 degrees

   self._img = wx.Image(self.fname, wx.BITMAP_TYPE_ANY)
   self._img = wx.EmptyImage(42, 42, True)  #create a plain 
black image, 42 x 42 pixels

   self._img = self._img.Rotate90()
   self._img = self._img.Rotate(-radians, center)

   img2 = img1.Scale(self.imageW()*scale/1000, 
self.imageH()*scale/1000)#this is where image is scaled to final bit 
dimensions.  It's clipped during drawBitmap()

   tracer("drawStuff  Scale", "draw")
   bmp = wx.BitmapFromImage(img2)

   w, h = self.GetClientSize() #self is a 
subclass of Panel

   self.buffer = wx.EmptyBitmap(w, h)
   dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
   dc.DrawBitmap(bmp, cornerX, cornerY, False)

Hope this helps.  I tied the scaling to the mousewheel, and used drag to 
move the cornerX and cornerY.  Notice they can go negative, as well as 
positive.



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


Re: wxPython gurus, please help

2009-05-23 Thread Benjamin Kaplan
On Sat, May 23, 2009 at 6:55 PM, Jive Dadson  wrote:

>   I have an application that opens an image file of the user's choice.  I
> have an exception handler for the case that the user selected a bad or
> unsupported image file.  My code is catching the exception, but
> unfortunately for me, after I exit the except-clause, wxPython is popping up
> its own message dialog from somewhere in deepest, darkest __core__.
>
>   How do I make it not do that?
>

Hard to tell without seeing the relevant code. Try stripping down the
program until you get to the smallest program that still shows the error (
http://wiki.wxpython.org/MakingSampleApps). If you can't figure it out from
that, try asking on the wxPython mailing list (
http://lists.wxwidgets.org/mailman/listinfo/wxpython-users). You'll probably
get better advice there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with sys.stout.flush()

2009-05-23 Thread Joel Ross

Dennis Lee Bieber wrote:

flush() is working perfectly fine -- it says transmit any data still
held within internal buffers. It is NOT a "clear screen", "clear line"
terminal command.


I was mistaken about the sys.stout.flush(). I understand it a little 
more now thanks

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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Joel Ross

Rhodri James wrote:

On Sat, 23 May 2009 18:19:11 +0100, Joel Ross  wrote:


Now I can move onto next one.


Except that you still have the interesting issue that your environment
isn't responding to '\r' correctly, which worries me rather.  Or did
you never test that?

Yeah I gave the "\r" a go and it kept printing out on a new line I will 
look into it.


Thanks for the heads up
--
http://mail.python.org/mailman/listinfo/python-list


wxpython and zoom/pan image

2009-05-23 Thread rzzzwilson
Hi,

I've googled for this, but can only find things like openlayers that
is a web-based javascript solution.

I need to display an image at various zoom levels and want to allow
the user to pan around in the Google maps style, that is, left-click
hold and drag.  The code should also action double-clicks on the image
(but that's easy).

There are no 'standard' wxpython widgets that allow this.  Can anyone
point me to information on how to implement such a thing, or maybe
some working code?

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


wxPython gurus, please help

2009-05-23 Thread Jive Dadson
   I have an application that opens an image file of the user's choice. 
  I have an exception handler for the case that the user selected a bad 
or unsupported image file.  My code is catching the exception, but 
unfortunately for me, after I exit the except-clause, wxPython is 
popping up its own message dialog from somewhere in deepest, darkest 
__core__.


   How do I make it not do that?

   Thankee much,
   Jive
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cursor movement question

2009-05-23 Thread Jive Dadson

Aahz wrote:

In article ,
Jive Dadson   wrote:

Gosh, you guys are slow. :-) I figured it out.


Perhaps you could post the solution for posterity's sake?


The double secret magic encantation is "WarpPointer."  Unfortunately, it 
does not work in a plain vanilla ScrolledWindow. ScrolledWindow captures 
the event and scrolls by the default scroll amount of 20 pixels. I think 
I can figure out a work-around, but I have not yet done so.


self.bmp.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

def OnKeyDown(self, event):
# Use direction keys to move cursor one pixel

x,y = event.GetPosition()
keycode = event.GetKeyCode()
X = 0
Y = 0
if keycode == wx.WXK_LEFT:
X = -1
elif keycode == wx.WXK_RIGHT:
X = 1
elif keycode == wx.WXK_UP:
Y = -1
elif keycode == wx.WXK_DOWN:
Y = 1
else:
return

x = max(0,min(self.size[0]-1,x+X))
y = max(0,min(self.size[1]-1,y+Y))
self.bmp.WarpPointer(x, y)
self.bmp.SetFocus()
--
http://mail.python.org/mailman/listinfo/python-list


Re: When does the escape character work within raw strings?

2009-05-23 Thread Stephen Hansen
>
> > How do you know how a string object is going to be treated by any
> > given function?  Read the Fine Manual for that function.
>
> So am I to understand that there is no consistency in string handling
> throughout the standard modules/objects/methods?
>
> Seems to make python a lot more complicated than it needs to be, but
> okay.
>

What it seems like you're not understanding here is that regular expressions
are a special case.

\b means something in Python literals. It maps to a single character, \x08.
It _is_ a single character.

r"\b" is two characters, a slash followed by a b.

Regular expressions have an _entire_ range of their own special characters
that have nothing to do with Python special characters. For regular
expressions, \b -- that is, a slash followed by a b -- are TWO characters
(not one, like "\b" is to Python) that have special meaning.

Raw strings really exist SO you can do this. So you can do r"\b" and have
the slash-followed-by-b be encoded into two characters, which the re library
can then threat as a test for the blank string. Otherwise, you'd have to do
"\\b" and similar a LOT when building up regular expressions...

The re library just has its own rules for how it interprets strings. Its not
"no consistency". Its that regular expressions have meaning outside of
Python and Python's implementation follows that general meaning (some,
mostly, or to some other definition of how much).

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


Re: When does the escape character work within raw strings?

2009-05-23 Thread Rhodri James
On Sat, 23 May 2009 22:05:10 +0100, walterbyrd   
wrote:



On May 22, 12:22 pm, "Rhodri James"

How do you know how a string object is going to be treated by any
given function?  Read the Fine Manual for that function.


So am I to understand that there is no consistency in string handling
throughout the standard modules/objects/methods?


How can there be?  They all have different requirements, after all.
In C, for example, you wouldn't expect "^\\s*[qwerty]+" to be remotely
useful as a printf() format, but it might be exactly what you want for
some regular expression library.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with sys.stout.flush()

2009-05-23 Thread Rhodri James

On Sat, 23 May 2009 18:19:11 +0100, Joel Ross  wrote:


Now I can move onto next one.


Except that you still have the interesting issue that your environment
isn't responding to '\r' correctly, which worries me rather.  Or did
you never test that?

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Abstract Classes

2009-05-23 Thread Rhodri James
On Sat, 23 May 2009 12:02:00 +0100, Tim Cook   
wrote:



I am implementing a set of specifications that were designed to be OO
language neutral.

Several classes are specified as being abstract; so therefore there
should be no instances of them, correct?

However in the classes that are subclasses what is the correct way in
Python to implement them?


That very much depends on the classes, and how much the abstract classes
do.  With the very simple examples you give which have no methods even,
I'd be strongly tempted not to implement the classes at all.  But let's
assume that's not a good idea (and there are plenty of reasons for it
not to be a good idea, to be fair).

Caution: I am not in the slightest bit familiar with the zope.interface
module, which does make your IA and IB classes look exceptionally
pointless.  Again, it's fairly safe to presume that I'm wrong there :-)


I am using the zope.interface module as well.

For example:

class IA(Interface):
   m = Int()
   p = TextLine()

class IB(Interface):

   x = Bool()
   s = Text()



class A(object):
""" This is an abstract class with attributes m is an int and p is a
string"""

   implements(IA)
   pass

class B(A):
  implements(IB)

  def __init__(self,m,p,x,s):
m=m
p=p
x=x
s=s


Presumably you mean
self.m = m
self.p = p
and so on?

This doesn't seem to be a consistent approach.  Class B enforces
initialisation of all its attributes, including the inherited ones,
but class A doesn't.


or should it be like:

class A(object):
""" This is an abstract class with attributes m is an int and p is a
string"""

   implements(IA)

   def __init__(self,m,p):
 m=m
 p=p


class B(A):
  implements(IB)

  def __init__(self,m,p,x,s):
A.__init__(m,p)
x=x
s=s


Modulo the "self." as before, this is more consistent.


or maybe even:

class B(A):
  implements(IB)

  def __init__(self,m,p,x,s):
super(A.__init__(m,p))
x=x
s=s


I have a bit of an allergy to super() because it works in slightly
unexpected ways.  Here in particular it doesn't gain you anything
and may cost you instead.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Problems with StaticBitmaps and events

2009-05-23 Thread Water Bottle
Hi, I'm new to wxpython and I created a test program. So far, it works, but
there are some problems with it.

For some reason, I get a small box in the top left corner. Not sure why
that's happening.

Also, I can't get my picture to bind to my Play().

Lastly, do you recommend using StaticBitmap as a button? I don't want to use
the wx.Button because I want to create my own custom buttons with its own
borders and such.



I've attached my png.





import wx

class Frame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition,
wx.Size(400,400))

self.sizer=wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(Box(self,-1).sizer,1,wx.EXPAND)
self.sizer.Add(Picture(self,-1).sizer,0,wx.EXPAND)

self.SetSizer(self.sizer)
self.SetAutoLayout(1)
self.Show(1)

class Picture(wx.Panel):
def __init__(self, parent, ID):
wx.Panel.__init__(self, parent, ID)

bitmap =
wx.Bitmap("/home/kevin/programming/python/media/data/arrow_blue.png",
wx.BITMAP_TYPE_PNG)
self.pic = wx.StaticBitmap(parent, ID, bitmap, wx.Point(30,120),
wx.Size(20,20), 0, "Name")

self.pic.Bind(wx.EVT_BUTTON, self.Play)

# Add more pictures later

# Layout
self.sizer = wx.GridSizer(1,10,0,0)
self.sizer.AddMany([(self.pic,1,wx.EXPAND),
])

def Play(self, event):
print "Hello"


class Box(wx.Panel):
def __init__(self, parent, ID):
wx.Panel.__init__(self, parent, ID)
self.control = wx.TextCtrl(parent, 1, style=wx.TE_MULTILINE)

# Layout
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.control, 1, wx.EXPAND)


class myApp(wx.App):
def OnInit(self):
frame = Frame(None, -1, "Test")
frame.Show()
self.SetTopWindow(frame)
return 1

app = myApp(0)
app.MainLoop()



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


Re: When does the escape character work within raw strings?

2009-05-23 Thread Robert Kern

On 2009-05-23 16:05, walterbyrd wrote:

On May 22, 12:22 pm, "Rhodri James"

How do you know how a string object is going to be treated by any
given function?  Read the Fine Manual for that function.


So am I to understand that there is no consistency in string handling
throughout the standard modules/objects/methods?

Seems to make python a lot more complicated than it needs to be, but
okay.


*Any* language would have such issues. Different functions do different things 
to its inputs. That's why you have different functions. I certainly wouldn't 
want my HTML parser to treat its inputs as if they were regular expressions.


--
Robert Kern

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

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


Re: Optimizing math functions

2009-05-23 Thread Robert Kern

On 2009-05-23 08:22, Esmail wrote:

Hello all,

I would like to maximize or minimize a given math function over a
specific set of values, in Python preferably.

I was checking out Wolfram Alpha (http://www70.wolframalpha.com/)
and it can do simple optimization problems in math, such as

maximize 15*x - x**2 over 0 to 15

(http://www70.wolframalpha.com/input/?i=maximize+15*x+-+x**2+over+0+to+15)

which finds the maximum value and input for x in the range 0 to 15.
Very cool. (This is of course a very simple example).

What it apparently can't do is for maximize (or minimize) functions
that contain two variables, x and y, or more. So for example a simple
example would be

maximize x**2 + y**2 over x:0 to 15, y:0-12 -- this does not work
-- though I'm unclear about
-- the correct syntax too.

Is there some sort of simple Python module that would allow me to
evaluate this type of function?

In this particular instance I am interested in the minimum of

x * sin(4*x) + 1.1 * sin(2*y), where x,y in range 0-10

though in other problems the range may not be identical for x and y.


We have several bounded optimization routines in scipy.

http://docs.scipy.org/doc/scipy/reference/optimize.html

--
Robert Kern

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

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


Re: When does the escape character work within raw strings?

2009-05-23 Thread walterbyrd
On May 22, 12:22 pm, "Rhodri James"
> How do you know how a string object is going to be treated by any
> given function?  Read the Fine Manual for that function.

So am I to understand that there is no consistency in string handling
throughout the standard modules/objects/methods?

Seems to make python a lot more complicated than it needs to be, but
okay.

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


Re: How to pass multiline flag to re.sub without using re.complie.

2009-05-23 Thread Tim Chase

I have a regex that needs multiline flag. Some where I read I
can pass multiline flag in regex string itself without using
re.compile. If anybody have any idea about how to do that
please reply.



As detailed at [1],

"""
(?iLmsux)

(One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) 
The group matches the empty string; the letters set the 
corresponding flags: re.I (ignore case), re.L (locale dependent), 
re.M (multi-line), re.S (dot matches all), re.U (Unicode 
dependent), and re.X (verbose), for the entire regular 
expression. (The flags are described in Module Contents.) This is 
useful if you wish to include the flags as part of the regular 
expression, instead of passing a flag argument to the compile() 
function.

"""

So you should be able to insert "(?m)" at the beginning of your 
regexp to make it multiline.


-tkc


[1]
http://docs.python.org/library/re.html




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


Re: How to pass multiline flag to re.sub without using re.complie.

2009-05-23 Thread MRAB

samba wrote:

I have a regex that needs multiline flag. Some where I read I can pass
multiline flag in regex string itself without using re.compile. If
anybody have any idea about how to do that please reply.


Include "(?m)" in the regular expression for multiline matching. It's 
best to put it at the start.

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


Re: need a help!

2009-05-23 Thread Dave Angel

Minh Doan wrote:

Hi,

I'm a newbie to python. I am having stuck with the following problem. I want
to download the info(price) from fromcity to tocity at a certain time from
kayak.com website. If we do it manually, we can go to the website, choose
the appropriate info we want to get and press SEARCH. How can i do it in
python ?

I hope someone could help me deal with the problem.
Thanks

Minh Doan

  

I'd start by researching the following two links.

http://www.kayak.com/labs/
http://www.programmableweb.com/api/kayak

You'll need to register with them to get an affiliate id, but this 
should get you started.


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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Carl Banks
On May 23, 8:20 am, Dave Angel  wrote:
> Incidentally, Carl's other suggestion, that you use a new variable
> instead of overwriting 'char', is a red herring.

Yeah, I dropped the ball on this one, I misread his code as being in a
loop instead of being called repeatedly.  And after criticizing him
for not running mine

Sorry bout that.


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


Re: need a help!

2009-05-23 Thread Esmail

Minh Doan wrote:

Hi,

I'm a newbie to python. I am having stuck with the following problem. I 
want to download the info(price) from fromcity to tocity at a certain 
time from kayak.com  website. If we do it manually, 
we can go to the website, choose the appropriate info we want to get and 
press SEARCH. How can i do it in python ?


I hope someone could help me deal with the problem.
Thanks

Minh Doan



For Kayak, see this page:

 http://www.kayak.com/labs/gateway/doc/air.vtl

and here's a sample query for 2 flights

#!/usr/bin/env python

#
# search for 2 flights on Kayak.com
#

import webbrowser

url1='http://www.kayak.com/s/search/air?l1=cid&d1=4/23/2009&l2=yyz&d2=4/26/2009'
url2='http://www.kayak.com/s/search/air?l1=cid&d1=6/22/2009&l2=fra&d2=3/17/2009'

webbrowser.open_new_tab(url1);
webbrowser.open_new_tab(url2);

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


Re: need a help!

2009-05-23 Thread Kushal Kumaran
On Sun, May 24, 2009 at 12:25 AM, Minh Doan  wrote:
> Hi,
>
> I'm a newbie to python. I am having stuck with the following problem. I want
> to download the info(price) from fromcity to tocity at a certain time from
> kayak.com website. If we do it manually, we can go to the website, choose
> the appropriate info we want to get and press SEARCH. How can i do it in
> python ?
>

You can automate interaction with web pages using the mechanize
library.  See http://wwwsearch.sourceforge.net/mechanize/

Or you can examine what data gets sent to the web server when you
click SEARCH, and send that data using the urllib2 module in the
standard library.  The library documentation has examples.

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


need a help!

2009-05-23 Thread Minh Doan
Hi,

I'm a newbie to python. I am having stuck with the following problem. I want
to download the info(price) from fromcity to tocity at a certain time from
kayak.com website. If we do it manually, we can go to the website, choose
the appropriate info we want to get and press SEARCH. How can i do it in
python ?

I hope someone could help me deal with the problem.
Thanks

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


How to pass multiline flag to re.sub without using re.complie.

2009-05-23 Thread samba
I have a regex that needs multiline flag. Some where I read I can pass
multiline flag in regex string itself without using re.compile. If
anybody have any idea about how to do that please reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Dave Angel

Vincent Davis wrote:

Thank you that makes sense to me. Much more clear then the tutorial, I think
so anyway. If you are learning about classes that you kinda expect MyClass
to have counter in it. I might be nice to show that x.counter = 1 creates an
instance that would look like (is this correct?)

class MyClass:
"""A simple example class"""
i = 12345
counter = 1
def f(self):
return 'hello world'

Thanks again

Vincent Davis


On Sat, May 23, 2009 at 8:24 AM, Benjamin Kaplan
wrote:

  

On Sat, May 23, 2009 at 9:13 AM, Vincent Davis wrote:



let me add that I see that this could be right if x.counter = 1 and
counter need not have anything to do with MyClass but this could be more
clear.
Thanks
Vincent Davis
720-301-3003


On Sat, May 23, 2009 at 7:08 AM, Vincent Davis wrote:

  

Section 9.3.3 says that given,
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'

and x = MyClass()
then this

x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter

will print 16

link,
http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes

I am reading this section so to learn about classes but if this is right
I think I need to start over.




The code given is correct, though the description in the tutorial could be
clearer. Basically, a class in Python is represented by a dict with strings
mapping to other stuff. Internally, x.counter = 1 is just a shortcut for
x.__dict__['counter'] = 1. This appears in the code as dynamically adding
the variable "counter" to the instance of MyClass. Unlike in static
languages, an instance variable in python doesn't need to be declared inside
the class for you to use it. It also doesn't need to appear in every
instance of the class.

The last line in the code (del x.counter) removes the "counter" key from x
so that the instance variable disappears. That's how the code works "without
leaving a trace".






Thanks
Vincent Davis
720-301-3003



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


  

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



(You accidentally top-posted.  That makes the context much harder for 
others to follow.)


No, the attribute 'counter' you demonstrated is an attribute of the 
class.  To duplicate what  x.counter=1 does, you have to add it to the 
instance.  Normally, this would be done in the __init__() method, but 
that would put it in each instance of the class, as it's being created.  
But this one is only in the 'x' instance.



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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Joel Ross

Thanks for all the help guys. I got it to work correctly with this

class progress:

def __init__(self):
   self.already = 0

def progressbar(self, number, total,  char):

   percentage = int(100 - round(number*100.0/total))
   if percentage > 0:
   xchar = char * (percentage-self.already)
   self.already = percentage
   sys.stdout.write(xchar)
   sys.stdout.flush()
   sleep(1)

Keeping track of the characters that had already been printed solved my 
main problem thanks Dave and everyone else for helping me out with this 
issue. Now I can move onto next one.


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


Re: error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Dave Angel

Vincent Davis wrote:

Section 9.3.3 says that given,
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'

and x = MyClass()
then this

x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter

will print 16

link,
http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes

I am reading this section so to learn about classes but if this is right I
think I need to start over.


Thanks
Vincent Davis
720-301-3003

  
Yes, this code will display 16, and it's not specific to 3.0, but works 
in earlier Pythons as well.


I'm not sure why you're puzzled;  it could be the question of why 16, 
but i suspect it's because you can't see who creates this x attribute.


Unlike languages like Java and C++, object attributes are not fixed at 
the time the class is compiled.  Some attributes are created by the 
placement of the code, for example the method name f.  But others are 
created in the code of the class (typically the __init__() method), and 
others can be created by anyone, at any time.


I don't know why the tutorial starts with this, but it illustrates that 
an object is really just a container for attributes, some of which are 
callable (methods), and some of which are data (what Java would call 
fields).  Anybody with an object reference can create, modify or delete 
those attributes.  If it's being done inside the class methods, you use 
the syntax  self.counter.  But it also works outside, as you see.

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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Steven D'Aprano
On Sun, 24 May 2009 00:44:21 +1000, Joel Ross wrote:

> Still having the same problem if I pass it 1000 lines it will printout
> 1000 asterisks when I say lines I mean the argument  for the
> progress() function. I only want to printout 100 asterisks no matter how
> many lines I pass to the progress() function, that's why I need the
> printout to overwrite the last printout instead of appending to the last
> printout. 

No, you're confusing two different problems:

(1) Scale the width of the progress bar to 100 characters;

(2) Make the progress bar appear on one line instead of multiple lines.


To solve the *second* problem, use the hint already given by Carl Banks.

To solve the *first* problem, use mathematics, then re-do your method, 
because your method is wrong. Before you can write code to solve this 
problem, you first have to get the mathematics right: you want to scale 
the width of the progress bar to be 100 asterisks no matter how many 
lines you have.

(a) If you have exactly 100 lines, and you draw one asterisk per line, 
then you get a progress bar of exactly 100 asterisks.

(b) If you have 50 lines, and you want a progress bar of exactly 100 
asterisks, you need to draw *two* asterisks per line.

(c) If you have 200 lines, and you want a progress bar of exactly 100 
asterisks, you need to draw *one half* an asterisk per line (or one 
asterisk per *two* lines).

(d) If you have N lines, and you want a progress bar of exactly 100 
asterisks, each line must be equivalent to [] asterisks.

Once you have filled in the blank, then go back to writing code.


Some further hints: I've added some commentary to your code:

def progressbar(self, number, total,  char):
percentage = float(number*100)/total
percentage = int(round(percentage))
percentage = int(100 - percentage)
# Why not combine all of the above into one line?
# percentage = int(100 - round(number*100.0/total))

self.f=sys.stdout
# Why are you storing stdout as an attribute to the method? Unless 
# you will need it again elsewhere, this is a waste.

if percentage > 0:
char = char * percentage
# Carl Banks has already pointed out the problem here.

self.f.write(char)
self.f.flush()
# Better written like this:
# sys.stdout.write(char)
# sys.stdout.flush()

sleep(0.2)


Finally, here's a function that should do what you ask for:

from __future__ import division
import sys

def progressbar(number, total, char='*', maxwidth=100):
done = number/total
if not 0 <= done <= 1:
raise ValueError('number or total out of range')
# Scale done=1 => maxwidth chars.
s = int(done*maxwidth)*char
sys.stdout.write(s + '\r')
sys.stdout.flush()
sleep(0.2)

This should work in "normal" terminal windows (tested on Linux, should 
work on Windows and Mac too) but some IDEs may mess it up.




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


Re: error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Benjamin Kaplan
On Sat, May 23, 2009 at 10:46 AM, Vincent Davis wrote:

> Thank you that makes sense to me. Much more clear then the tutorial, I
> think so anyway. If you are learning about classes that you kinda expect
> MyClass to have counter in it. I might be nice to show that x.counter = 1
> creates an instance that would look like (is this correct?)
>
> class MyClass:
> """A simple example class"""
> i = 12345
> counter = 1
> def f(self):
> return 'hello world'
>

That's how it would work in almost any language other than Python. In
Python, anything declared in that scope is a member of the class. For
something immutable like an int, it doesn't matter. If you can change it
however, you get problems. This is one of the biggest sources of problems
for python beginners (you get the same behavior with default method
arguments btw)

>>> class Foo :
...lst = []
...
>>> a = Foo()
>>> b = Foo()
>>> b.lst
[]
>>> a.lst.append(1)
>>> b.lst
[1]



In Python, if you want something to be a part of the instance, you have to
add it to the instance. That's what the "self" parameter in the method
argument list is. x.f() is just syntax sugar for MyClass.f(x). Dynamically
adding variables can get very confusing, so people usually declare
everything (or almost everything) they're going to use in the __init__
method discussed in section 9.3.2.


>
>

> Thanks again


> Vincent Davis
>
>
>
> On Sat, May 23, 2009 at 8:24 AM, Benjamin Kaplan  > wrote:
>
>>
>>
>> On Sat, May 23, 2009 at 9:13 AM, Vincent Davis 
>> wrote:
>>
>>> let me add that I see that this could be right if x.counter = 1 and
>>> counter need not have anything to do with MyClass but this could be more
>>> clear.
>>> Thanks
>>> Vincent Davis
>>> 720-301-3003
>>>
>>>
>>> On Sat, May 23, 2009 at 7:08 AM, Vincent Davis >> > wrote:
>>>
 Section 9.3.3 says that given,
 class MyClass:
 """A simple example class"""
 i = 12345
 def f(self):
 return 'hello world'

 and x = MyClass()
 then this

 x.counter = 1
 while x.counter < 10:
 x.counter = x.counter * 2
 print(x.counter)
 del x.counter

 will print 16

 link,
 http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes

 I am reading this section so to learn about classes but if this is right
 I think I need to start over.


>> The code given is correct, though the description in the tutorial could be
>> clearer. Basically, a class in Python is represented by a dict with strings
>> mapping to other stuff. Internally, x.counter = 1 is just a shortcut for
>> x.__dict__['counter'] = 1. This appears in the code as dynamically adding
>> the variable "counter" to the instance of MyClass. Unlike in static
>> languages, an instance variable in python doesn't need to be declared inside
>> the class for you to use it. It also doesn't need to appear in every
>> instance of the class.
>>
>> The last line in the code (del x.counter) removes the "counter" key from x
>> so that the instance variable disappears. That's how the code works "without
>> leaving a trace".
>>
>>
>>
>>
>>>
 Thanks
 Vincent Davis
 720-301-3003

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


Re: from __future__ import absolute_import issue

2009-05-23 Thread LittleGrasshopper
On May 22, 12:42 am, "Gabriel Genellina" 
wrote:
> En Wed, 20 May 2009 20:18:02 -0300, LittleGrasshopper  
>  escribió:
>
> > New to the group, this is my first post...
>
> > It appears that either absolute imports (or my brain) aren't working.
> > Given a module string.py which is in the same directory as a.py:
>
> > #File a.py
> > from __future__ import absolute_import
>
> > import string
>
> > print string # Module imported is string.py in current directory, not
> > standard library module
>
> absolute_import helps with imports inside a package (those are "relative"  
> imports, relative to the package). If a module is located in a directory  
> listed in sys.path, an absolute import will find it. I don't think there  
> is a way to avoid shadowing a standard module (other than ensuring the  
> standard directories come first in sys.path).
>
> --
> Gabriel Genellina

You are right. If you have a directory in your PYTHONPATH before the
standard library directories that has a string module, for example,
absolute_import will not help you. I was getting confused by the fact
that when I print sys.path from the python shell, the first entry is
an empty string.
This empty string must denote the current directory though, because:

['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/
python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/
python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/
usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/
Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/
site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/
lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/
python2.5/gtk-2.0']

When I have this sys.path, doing an "import string" from a module
where I have absolute imports enabled will still import the string
module in the package (which also means it is in the same directory in
this case.) So I think my string.py is being imported not because it
is in the same package, but because the home directory is searched
first. The empty string doesn't make much sense though (at least in a
Unix system, you would imagine it would be something like './') but I
guess that synce Python is platform independent, the empty string is
taken to denote the current directory.

Thanks for your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with sys.stout.flush()

2009-05-23 Thread Dave Angel

Joel Ross wrote:
Carl 
Banks wrote:

On May 23, 2:20 am, Joel Ross  wrote:

Carl Banks wrote:

On May 22, 10:33 pm, Joel Ross  wrote:

Hi all,
I'm using python 2.5 and trying to flush the sys.stout buffer with
sys.stout.flush(), but doesn't seem to work. Each time a line is 
printed
   it appends the one before it I need to clear the output and 
write a

new output without appending the previous one.

That's not how streams work, chief.  Once you output (and flush)
something you can't un-output it.
What you probably want to do is to write a carriage return ("\r")
which usually causes the cursor to return to the beginning of the
line, so that any new text you write overwrites the old text.
This has nothing to do with flushing; flushing doesn't erase or clear
the old input.  Flushing is usually needed for a different reason,
however, namely standard output doesn't actually get sent to the
console until it sees a newline ("\n") unless you flush the buffer.
Try to adapt this example to your problem:
for i in xrange(11):
sys.stdout.write('*'*(10-i) + ' '*i + '\r')
sys.stdout.flush()
time.sleep(2)

Your example prints a new line each time,


Did you run it and observe what happened, or did you just guess what
it actually did?  On my system it doesn't print new lines.



Doesn't help me with a
progress bar, do you know of anyway doing it with the print command? My
progress bars works fine this is the only problem im having with it at
the moment. any help would be appreciated.


Well, based on the code you posted it doesn't look like your progress
bar is fine.

Anyway, you haven't described the problem you are having very well,
and we can guess what might be wrong but if you want better help
you're going to have to describe your problem more coherently.  Give
us the

1. What code are you actually running (cut-and-paste, please, don't
retype).
2. What do you expect the code to output (type in actual output you
expect to see, not merely a description).
3. What does the code actually output when you run it (cut-and paste,
please, don't just describe).
4. Include any tracebacks if there are any.

In the meantime, I repeat my suggestion that you take my example and
adapt it to what you are doing.

One other note: the print statement is unsuitable for this task
because it always prints a trailing whitespace.  Use sys.stdout.write
for it.


Carl Banks

Hey,

The only reason I didn't supply full details is because I thought it 
may just be something simple I was missing. Sorry for the confusing. 
Well here's the full code.


import sys, os
from time import sleep


class progress:

def progressbar(self, number, total,  char):

percentage = float(number*100)/total
percentage = int(round(percentage))
percentage = int(100 - percentage)
self.f=sys.stdout
if percentage > 0:
char = char * percentage
self.f.write(char)
self.f.flush() 
sleep(0.2)



def countlines(self, file):

lineCount = 0
f = open(file)
it = iter(f)
try:
while it.next():
lineCount += 1
except StopIteration:
pass
return lineCount


def main():

p = progress()
lines = 5
#lines = p.countlines("/tmp/junk")
count = lines
for i in xrange(lines):
p.progressbar(count, lines, "*")
count -=1
print "Finished"

if __name__ == "__main__":
main()

For now we can ignore the countlines() function. I need a nice 
progress display e.g. ** continuing on til it 
reaches 100% I need this to print out on one line only. At the moment 
it does do this, only problem is its appends the print out from the 
last print out. I need it to clear the last print out and then print 
the new print out without appending the last.


So when it prints a progress at 50% it will print 50 (*) characters 
and if the next progress is 51% it will print 51 (*) characters 
including the last 50 (*) characters, so instead on ending up with 100 
(*) characters I end up with a shit load of them depending on how many 
lines I pass to the progressbar() function.


Needed Output:
***Finished 




Current Output:
Finished 



Note: As you can see I'm only sending 5 lines to the progressbar() 
function and It prints this many characters, so you could imagine if I 
have 1 lines I would end up with a heap of * characters.


Regards
jross


You don't tell your environment.  Like, what version of Python, and more 
importantly what operating system?  You also don't say how you're 
testing the system, nor where it's intended to finally run.


There is

Re: Problems with sys.stout.flush()

2009-05-23 Thread Peter Otten
Joel Ross wrote:

> class progress:
> 
>  def progressbar(self, number, total,  char):
> 
>  percentage = float(number*100)/total
>  percentage = int(round(percentage))
>  percentage = int(100 - percentage)
>  self.f=sys.stdout
>  if percentage > 0:
>  char = char * percentage

Carl probably overlooked that you didn't follow his advice. If you want to 
overwrite the current line you have to send a "\r" to the terminal. Change

>  self.f.write(char)

to
   self.f.write("\r" + char)

>  self.f.flush()
>  sleep(0.2)



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


Re: error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Michiel Overtoom


Vincent writes:

> you kinda expect MyClass to have counter in it.

Yeah, that makes sense. These instance variables are often initialized 
in the __init__ method:



class Counter(object):
def __init__(self,initialvalue):
self.value=initialvalue
def inc(self):
self.value+=1
def dec(self):
self.value-=1

beans=Counter(123)
beans.inc()
beans.inc()
beans.dec()
print beans.value

# the output of the program is: 124

Greetings,


--
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Valloppillil
http://www.catb.org/~esr/halloween/halloween4.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with sys.stout.flush()

2009-05-23 Thread Joel Ross

Carl Banks wrote:

On May 23, 3:49 am, Joel Ross  wrote:

 def progressbar(self, number, total,  char):

 percentage = float(number*100)/total
 percentage = int(round(percentage))
 percentage = int(100 - percentage)
 self.f=sys.stdout
 if percentage > 0:
 char = char * percentage
 self.f.write(char)
 self.f.flush()
 sleep(0.2)

[snip]

So when it prints a progress at 50% it will print 50 (*) characters and
if the next progress is 51% it will print 51 (*) characters including
the last 50 (*) characters, so instead on ending up with 100 (*)
characters I end up with a shit load of them depending on how many lines
I pass to the progressbar() function.


Here's why: when you write "char = char * percentage", you are setting
char to a string, so on the next iteration char is the string you
printed last time.  Thus char grows factorially with iterations.  Not
good.

Instead, change char to some other name so you don't ever overwrite
it; char should always be just one character.

 bar = char * percentage
 self.f.write(bar)


Carl Banks



Still having the same problem if I pass it 1000 lines it will printout 
1000 asterisks when I say lines I mean the argument  for the 
progress() function. I only want to printout 100 asterisks no matter how 
many lines I pass to the progress() function, that's why I need the 
printout to overwrite the last printout instead of appending to the last 
printout. I know there must be a way to do it. I'll keep trying and 
eventually get it. Any ideas would be helpful


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


Re: error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Vincent Davis
Thank you that makes sense to me. Much more clear then the tutorial, I think
so anyway. If you are learning about classes that you kinda expect MyClass
to have counter in it. I might be nice to show that x.counter = 1 creates an
instance that would look like (is this correct?)

class MyClass:
"""A simple example class"""
i = 12345
counter = 1
def f(self):
return 'hello world'

Thanks again

Vincent Davis


On Sat, May 23, 2009 at 8:24 AM, Benjamin Kaplan
wrote:

>
>
> On Sat, May 23, 2009 at 9:13 AM, Vincent Davis 
> wrote:
>
>> let me add that I see that this could be right if x.counter = 1 and
>> counter need not have anything to do with MyClass but this could be more
>> clear.
>> Thanks
>> Vincent Davis
>> 720-301-3003
>>
>>
>> On Sat, May 23, 2009 at 7:08 AM, Vincent Davis 
>> wrote:
>>
>>> Section 9.3.3 says that given,
>>> class MyClass:
>>> """A simple example class"""
>>> i = 12345
>>> def f(self):
>>> return 'hello world'
>>>
>>> and x = MyClass()
>>> then this
>>>
>>> x.counter = 1
>>> while x.counter < 10:
>>> x.counter = x.counter * 2
>>> print(x.counter)
>>> del x.counter
>>>
>>> will print 16
>>>
>>> link,
>>> http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes
>>>
>>> I am reading this section so to learn about classes but if this is right
>>> I think I need to start over.
>>>
>>>
> The code given is correct, though the description in the tutorial could be
> clearer. Basically, a class in Python is represented by a dict with strings
> mapping to other stuff. Internally, x.counter = 1 is just a shortcut for
> x.__dict__['counter'] = 1. This appears in the code as dynamically adding
> the variable "counter" to the instance of MyClass. Unlike in static
> languages, an instance variable in python doesn't need to be declared inside
> the class for you to use it. It also doesn't need to appear in every
> instance of the class.
>
> The last line in the code (del x.counter) removes the "counter" key from x
> so that the instance variable disappears. That's how the code works "without
> leaving a trace".
>
>
>
>
>>
>>> Thanks
>>> Vincent Davis
>>> 720-301-3003
>>>
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html ui + py background? any tut?

2009-05-23 Thread Stefaan Himpe

Or maybe you are looking for something like nufox?
http://nufox.berlios.de/
--
http://mail.python.org/mailman/listinfo/python-list


Re: error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Benjamin Kaplan
On Sat, May 23, 2009 at 9:13 AM, Vincent Davis wrote:

> let me add that I see that this could be right if x.counter = 1 and
> counter need not have anything to do with MyClass but this could be more
> clear.
> Thanks
> Vincent Davis
> 720-301-3003
>
>
> On Sat, May 23, 2009 at 7:08 AM, Vincent Davis 
> wrote:
>
>> Section 9.3.3 says that given,
>> class MyClass:
>> """A simple example class"""
>> i = 12345
>> def f(self):
>> return 'hello world'
>>
>> and x = MyClass()
>> then this
>>
>> x.counter = 1
>> while x.counter < 10:
>> x.counter = x.counter * 2
>> print(x.counter)
>> del x.counter
>>
>> will print 16
>>
>> link,
>> http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes
>>
>> I am reading this section so to learn about classes but if this is right I
>> think I need to start over.
>>
>>
The code given is correct, though the description in the tutorial could be
clearer. Basically, a class in Python is represented by a dict with strings
mapping to other stuff. Internally, x.counter = 1 is just a shortcut for
x.__dict__['counter'] = 1. This appears in the code as dynamically adding
the variable "counter" to the instance of MyClass. Unlike in static
languages, an instance variable in python doesn't need to be declared inside
the class for you to use it. It also doesn't need to appear in every
instance of the class.

The last line in the code (del x.counter) removes the "counter" key from x
so that the instance variable disappears. That's how the code works "without
leaving a trace".




>
>> Thanks
>> Vincent Davis
>> 720-301-3003
>>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Python -> R?

2009-05-23 Thread Esmail

Hello!

Anyone using Python scripts and accessing some of R's functionality?
If so, what are you using? I have read about RPy, is that a good
solution? Are there others that can be recommended or are preferred?

I would prefer to code in Python instead of R :-)

Thanks,
Esmail

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


Re: html ui + py background? any tut?

2009-05-23 Thread Stefaan Himpe

Perhaps you want to investigate
pyjamas[1] and pyjamas-desktop[2]

[1] http://pyjs.org/
[2] http://pyjd.sourceforge.net/

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


Re: Optimizing math functions

2009-05-23 Thread Esmail

Steven D'Aprano wrote:

On Sat, 23 May 2009 09:22:59 -0400, Esmail wrote:


Hello all,

I would like to maximize or minimize a given math function over a
specific set of values, in Python preferably.

...

What it apparently can't do is for maximize (or minimize) functions that
contain two variables, x and y, or more. 


Function minimization is a well-studied problem. You will find oodles of 
references to doing function minimization if you google. In fact, if you 
google for "python function minimization" you should find about 63,000 
links.


Hi Steven,

Right you are (63,700!) ... I don't know what search string I used
before, but clearly not this rather obvious one .. duh.


Minimizing functions of two variables is difficult, as a general rule. 
Nevertheless, there are tools for doing so. Check out SciPy.


I will - thanks. I have tools for 1D, I mostly am interested in 2D
optimization at this point, mostly as a way to verifying some results
I am calculating.

Hopefully SciPy will provide a nice simple interface to help me do
this.

Thanks,
Esmail

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


Re: Optimizing math functions

2009-05-23 Thread Steven D'Aprano
On Sat, 23 May 2009 09:22:59 -0400, Esmail wrote:

> Hello all,
> 
> I would like to maximize or minimize a given math function over a
> specific set of values, in Python preferably.
...
> What it apparently can't do is for maximize (or minimize) functions that
> contain two variables, x and y, or more. 

Function minimization is a well-studied problem. You will find oodles of 
references to doing function minimization if you google. In fact, if you 
google for "python function minimization" you should find about 63,000 
links.

Minimizing functions of two variables is difficult, as a general rule. 
Nevertheless, there are tools for doing so. Check out SciPy.



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


Re: Replacing module with a stub for unit testing

2009-05-23 Thread Ben Finney
pigmart...@gmail.com writes:

> 
> import ExpensiveModuleStub
> sys.modules['ExpensiveModule'] = ExpensiveModuleStub # Doesn't
> work
> 
> But, import statements in the IntermediateModule still access the real
> ExpensiveModule, not the stub.
> 
> The examples I can find of creating and using Mock or Stub objects
> seem to all follow a pattern where the fake objects are passed in as
> arguments to the code being tested. For example, see the "Example
> Usage" section here: http://python-mock.sourceforge.net. But that
> doesn't work in my case as the module I'm testing doesn't directly use
> the module that I want to replace.
> 
> Can anybody suggest something?

The ‘MiniMock’ library http://pypi.python.org/pypi/MiniMock>
addresses this by mocking objects via namespace.

If you know the code under test will import ‘spam.eggs.beans’, import
that yourself in your unit test module, then mock the object with
‘minimock.mock('spam.eggs.beans')’. Whatever object was at that name
will be mocked (until ‘minimock.restore()’), and other code referring to
that name will get the mocked object.

-- 
 \ “When I turned two I was really anxious, because I'd doubled my |
  `\   age in a year. I thought, if this keeps up, by the time I'm six |
_o__)  I'll be ninety.” —Steven Wright |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing module with a stub for unit testing

2009-05-23 Thread Steven D'Aprano
On Sat, 23 May 2009 06:00:15 -0700, pigmartian wrote:

> Hi,
> 
> I'm working on a unit test framework for a module.  The module I'm
> testing indirectly calls another module which is expensive to access ---
> CDLLs whose functions access a database.
...
> The examples I can find of creating and using Mock or Stub objects seem
> to all follow a pattern where the fake objects are passed in as
> arguments to the code being tested.  For example, see the "Example
> Usage" section here: http://python-mock.sourceforge.net.  But that
> doesn't work in my case as the module I'm testing doesn't directly use
> the module that I want to replace.
> 
> Can anybody suggest something?

Sounds like a job for monkey-patching!

Currently, you have this:

# inside test_MyModule:
import MyModule
test_code()


# inside MyModule:
import IntermediateModule


# inside IntermediateModule:
import ExpensiveModule


You want to leave MyModule and IntermediateModule as they are, but 
replace ExpensiveModule with MockExpensiveModule. Try this:

# inside test_MyModule:
import MyModule
import MockExpensiveModule
MyModule.IntermediateModule.ExpensiveModule = MockExpensiveModule
test_code()



That should work, unless IntermediateModule uses "from ExpensiveModule 
import functions" instead of "import ExpensiveModule". In that case, you 
will have to monkey-patch each individual object rather than the entire 
module:

MyModule.IntermediateModule.afunc = MockExpensiveModule.afunc
MyModule.IntermediateModule.bfunc = MockExpensiveModule.bfunc
MyModule.IntermediateModule.cfunc = MockExpensiveModule.cfunc
# etc...



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


Optimizing math functions

2009-05-23 Thread Esmail

Hello all,

I would like to maximize or minimize a given math function over a
specific set of values, in Python preferably.

I was checking out Wolfram Alpha (http://www70.wolframalpha.com/)
and it can do simple optimization problems in math, such as

maximize 15*x - x**2 over 0 to 15

(http://www70.wolframalpha.com/input/?i=maximize+15*x+-+x**2+over+0+to+15)

which finds the maximum value and input for x in the range 0 to 15.
Very cool. (This is of course a very simple example).

What it apparently can't do is for maximize (or minimize) functions
that contain two variables, x and y, or more. So for example a simple
example would be

   maximize x**2 + y**2 over x:0 to 15, y:0-12  -- this does not work
-- though I'm unclear about
-- the correct syntax too.

Is there some sort of simple Python module that would allow me to
evaluate this type of function?

In this particular instance I am interested in the minimum of

  x * sin(4*x) + 1.1 * sin(2*y), where x,y in range 0-10

though in other problems the range may not be identical for x and y.

Thanks,

Esmail

ps: Does anyone know if Octave or some other free Linux (or Windows)
program might also do this in a simple way? My preference would
still be a Python solution that would be simple to use, ie plug in
the function, the ranges and have it pop out the solution :-)

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


Re: error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Vincent Davis
let me add that I see that this could be right if x.counter = 1 and counter
need not have anything to do with MyClass but this could be more clear.
Thanks
Vincent Davis
720-301-3003


On Sat, May 23, 2009 at 7:08 AM, Vincent Davis wrote:

> Section 9.3.3 says that given,
> class MyClass:
> """A simple example class"""
> i = 12345
> def f(self):
> return 'hello world'
>
> and x = MyClass()
> then this
>
> x.counter = 1
> while x.counter < 10:
> x.counter = x.counter * 2
> print(x.counter)
> del x.counter
>
> will print 16
>
> link,
> http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes
>
> I am reading this section so to learn about classes but if this is right I
> think I need to start over.
>
>
> Thanks
> Vincent Davis
> 720-301-3003
>
-- 
http://mail.python.org/mailman/listinfo/python-list


error in tutorial for 3.0, section 9.3.3

2009-05-23 Thread Vincent Davis
Section 9.3.3 says that given,
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'

and x = MyClass()
then this

x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter

will print 16

link,
http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes

I am reading this section so to learn about classes but if this is right I
think I need to start over.


Thanks
Vincent Davis
720-301-3003
-- 
http://mail.python.org/mailman/listinfo/python-list


Replacing module with a stub for unit testing

2009-05-23 Thread pigmartian
Hi,

I'm working on a unit test framework for a module.  The module I'm
testing indirectly calls another module which is expensive to access
--- CDLLs whose functions access a database.

test_MyModule --->MyModule--->IntermediateModule---
>ExpensiveModule

I want to create a stub of ExpensiveModule and have that be accessed
by IntermediateModule instead of the real version

test_MyModule --->MyModule--->IntermediateModule---
>ExpensiveModuleStub

I tried the following in my unittest:

import ExpensiveModuleStub
sys.modules['ExpensiveModule'] = ExpensiveModuleStub # Doesn't
work

But, import statements in the IntermediateModule still access the real
ExpensiveModule, not the stub.

The examples I can find of creating and using Mock or Stub objects
seem to all follow a pattern where the fake objects are passed in as
arguments to the code being tested.  For example, see the "Example
Usage" section here: http://python-mock.sourceforge.net.  But that
doesn't work in my case as the module I'm testing doesn't directly use
the module that I want to replace.

Can anybody suggest something?

Thanks,

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


Re: html ui + py background? any tut?

2009-05-23 Thread Дамјан Георгиевски


> I have read for many times that the modern appliaction (not a web one,
> but desktop on) uses html + js for its UI, and python code is for the
> background work
> but I have never found event a simple (yet completed) article on how
> to develop such a thing from scrach in these advocacy thing.
> 
> Can anyone point out some simple, can-be-followed tutorial on such
> thing especially for windows os?

That's very very simple to do with PyQt and Qts Webkit. You can export 
Python objects to the HTML/JS application running in Webkit.

You'll just need to read the Qt Webkit documentation to see how it's all 
done.

This is actually a very good strategy for new apps, you can easily make 
them skinable with  html/js skins for ex.



-- 
дамјан ( http://softver.org.mk/damjan/ )

Well when _I_ was in school, I had to run Netscape on HP/UX, displayed 
on my local X Server running on a Windows 3.1 box. Displayed over a 2400 
baud modem. Uphill. Both ways. In the rain. With NOBODY to hold my 
hands. Because the life of the geek is a lonely life.
- aclarke on /.

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


PureData py/pyExt into standalone python

2009-05-23 Thread responsible7
Hi guys,

Short version:

I've written some python classes for py/pyExt extensions for the
"dataflow" graphical programming environment PureData. Here's an
example PureData screenshot for clarity:

see: http://i40.tinypic.com/2rrx6gy.jpg

My classes talk to eachother via the PureData system, and they talk to
the outside world via pyPortMIDI (which enables raw MIDI data
communication).

PureData encourages modularisation, so I've written several classes:
* some that receive raw MIDI data,
* some that parse this into human-readable tokens,
* some that just generate human-readable tokens,
* and some that parse human-readable tokens then send raw MIDI data

I want to join these together as a stand-alone python application,
using internal python communication instead of PureData...

...but I don't know how to do this. The only python I know comes from
writing using the pyExt API, and the PureData API (which is written in
C).


Long(er) version:

Miller Pukette's PureData: http://puredata.info/
Thomas Grill's Flext: http://puredata.info/Members/thomas/flext
Thomas Grill's Py/Pyext: http://puredata.info/Members/thomas/py/
John Harrison's PyPortMIDI: http://www.media.mit.edu/~harrison/code.html
CMU's PortMIDI: http://www.cs.cmu.edu/~music/portmusic/

PureData is a graphical "dataflow" programming environment that (among
many, many other things!) allows for very rapid development of Audio
and MIDI processing. Objects in PureData (and MaxMSP) communicate by
sending messages through "patch cords" that connect an "outlet" to an
"inlet" of another object.

Thomas Grill's py/pyExt allows python code to be embedded as a
PureData object. The benefit being that this python code can be
effortlessly ported across multiple platforms (win32/linux/osx) and
also to the highly related (but more commercial) Cycling'74 MaxMSP
system. (PureData object code is written in C and generally not easy
to port between platforms, nor between PD and MaxMSP - so writing
portable python objects is a boon!)

a pyExt object sends messages from its outlets using the line:


self._outlet(outlet_id,message_to_send)


a pyExt object performs actions when a message arrives at an inlet. An
integer arriving at inlet 1 could be attached to this method code:


def int_1(self,*arg):
print "received integer:",arg[0]

If these pieces of code were in separate python classes - how would I
connect two objects together such that an integer was passed between
the two?

If the first object sent 42, in puredata it would look like this:

http://i44.tinypic.com/15eh74p.gif

useless fact: the screenshot doubles up (i.e. "pyext sender sender")
due to the first word being the python file (i.e. sender.py), whilst
the second is the name of the object class (i.e class sender
(pyext._class)


Maybe a more tricky question is:

PureData supports "message busses" - messages sent to named busses can
be broadcast to multiple locations. How would I connect objects up in
this way using python?

a pyExt object registers to receive messages on a certain bus using:


self._bind(bus_name,self.method_to_call)

def method_to_call(self,*arg):
print "a message on", bus_name, "arrived"
print "the message was", len(arg), "long"
print "and had the values", arg, "inside"


a pyExt object sends messages to a particular bus by using:


self._send(bus_name,message_to_send)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Representing a Tree in Python

2009-05-23 Thread Albert van der Horst
In article <43289c33-04b9-4cbc-9823-d8a4ee86d...@y33g2000prg.googlegroups.com>,
godshorse   wrote:
>On May 13, 11:54=A0am, CTO  wrote:
>> On May 13, 12:10=A0am, godshorse  wrote:
>>
>> > Hello,
>>
>> > I want to find out the shortest path tree from a root to several nodes
>> > in a graph data structure. I found a Dijkstra code from internet that
>> > finds shortest path between only two nodes. How can i extend it to a
>> > tree?. And what is the best way to represent a tree in Python?.



>
>Thanks very much for your reply Geremy. That site was interesting.
>
>Actually the Graph building part is already completed now. I used a
>dictionary for that and it works fine. for Dijkstra shortest path
>problem your suggestion can be used.
>
>But let me clear the my problem again. I have a graph. and I want to
>find 'shortest path tree' from a root node to several nodes. as a
>example if we have a graph of 5 nodes from 1 to 5, I need to build the
>shortest path tree from node 1 to nodes 2,3,5. So my question is
>instead of keeping separate lists for each destination node's shortest
>path. How can I represent and store them in a tree structure using
>python. Then I can easily find out what are the common nodes in the
>path to each destination.

If I understand correctly, you want to know the path given
the end-node. Common sense dictates that you use back links
if that has to be done with decent efficiency.
The back links can be added as part of the algorithm.

>
>Thanks once again.

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- like all pyramid schemes -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Carl Banks
On May 23, 3:49 am, Joel Ross  wrote:
>      def progressbar(self, number, total,  char):
>
>          percentage = float(number*100)/total
>          percentage = int(round(percentage))
>          percentage = int(100 - percentage)
>          self.f=sys.stdout
>          if percentage > 0:
>              char = char * percentage
>              self.f.write(char)
>              self.f.flush()            
>              sleep(0.2)
[snip]
> So when it prints a progress at 50% it will print 50 (*) characters and
> if the next progress is 51% it will print 51 (*) characters including
> the last 50 (*) characters, so instead on ending up with 100 (*)
> characters I end up with a shit load of them depending on how many lines
> I pass to the progressbar() function.

Here's why: when you write "char = char * percentage", you are setting
char to a string, so on the next iteration char is the string you
printed last time.  Thus char grows factorially with iterations.  Not
good.

Instead, change char to some other name so you don't ever overwrite
it; char should always be just one character.

 bar = char * percentage
 self.f.write(bar)


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


Abstract Classes

2009-05-23 Thread Tim Cook
I am implementing a set of specifications that were designed to be OO
language neutral.

Several classes are specified as being abstract; so therefore there
should be no instances of them, correct?

However in the classes that are subclasses what is the correct way in
Python to implement them?
I am using the zope.interface module as well.

For example:

class IA(Interface):
   m = Int()
   p = TextLine()

class IB(Interface):

   x = Bool()
   s = Text()



class A(object):
""" This is an abstract class with attributes m is an int and p is a
string"""

   implements(IA)
   pass

class B(A):
  implements(IB)

  def __init__(self,m,p,x,s):
m=m
p=p
x=x
s=s


or should it be like:

class A(object):
""" This is an abstract class with attributes m is an int and p is a
string"""

   implements(IA)

   def __init__(self,m,p):
 m=m
 p=p


class B(A):
  implements(IB)

  def __init__(self,m,p,x,s):
A.__init__(m,p)
x=x
s=s


or maybe even:

class B(A):
  implements(IB)

  def __init__(self,m,p,x,s):
super(A.__init__(m,p))
x=x
s=s

Thanks for any pointers.

Tim


--
Timothy Cook, MSc
Health Informatics Research & Development Services
LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook
Skype ID == timothy.cook
**
*You may get my Public GPG key from  popular keyservers or   *
*from this link http://timothywayne.cook.googlepages.com/home*
**
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with sys.stout.flush()

2009-05-23 Thread Joel Ross

Carl Banks wrote:

On May 23, 2:20 am, Joel Ross  wrote:

Carl Banks wrote:

On May 22, 10:33 pm, Joel Ross  wrote:

Hi all,
I'm using python 2.5 and trying to flush the sys.stout buffer with
sys.stout.flush(), but doesn't seem to work. Each time a line is printed
   it appends the one before it I need to clear the output and write a
new output without appending the previous one.

That's not how streams work, chief.  Once you output (and flush)
something you can't un-output it.
What you probably want to do is to write a carriage return ("\r")
which usually causes the cursor to return to the beginning of the
line, so that any new text you write overwrites the old text.
This has nothing to do with flushing; flushing doesn't erase or clear
the old input.  Flushing is usually needed for a different reason,
however, namely standard output doesn't actually get sent to the
console until it sees a newline ("\n") unless you flush the buffer.
Try to adapt this example to your problem:
for i in xrange(11):
sys.stdout.write('*'*(10-i) + ' '*i + '\r')
sys.stdout.flush()
time.sleep(2)

Your example prints a new line each time,


Did you run it and observe what happened, or did you just guess what
it actually did?  On my system it doesn't print new lines.



Doesn't help me with a
progress bar, do you know of anyway doing it with the print command? My
progress bars works fine this is the only problem im having with it at
the moment. any help would be appreciated.


Well, based on the code you posted it doesn't look like your progress
bar is fine.

Anyway, you haven't described the problem you are having very well,
and we can guess what might be wrong but if you want better help
you're going to have to describe your problem more coherently.  Give
us the

1. What code are you actually running (cut-and-paste, please, don't
retype).
2. What do you expect the code to output (type in actual output you
expect to see, not merely a description).
3. What does the code actually output when you run it (cut-and paste,
please, don't just describe).
4. Include any tracebacks if there are any.

In the meantime, I repeat my suggestion that you take my example and
adapt it to what you are doing.

One other note: the print statement is unsuitable for this task
because it always prints a trailing whitespace.  Use sys.stdout.write
for it.


Carl Banks

Hey,

The only reason I didn't supply full details is because I thought it may 
just be something simple I was missing. Sorry for the confusing. Well 
here's the full code.


import sys, os
from time import sleep


class progress:

def progressbar(self, number, total,  char):

percentage = float(number*100)/total
percentage = int(round(percentage))
percentage = int(100 - percentage)
self.f=sys.stdout
if percentage > 0:
char = char * percentage
self.f.write(char)
self.f.flush()  
sleep(0.2)


def countlines(self, file):

lineCount = 0
f = open(file)
it = iter(f)
try:
while it.next():
lineCount += 1
except StopIteration:
pass
return lineCount


def main():

p = progress()
lines = 5
#lines = p.countlines("/tmp/junk")
count = lines
for i in xrange(lines):
p.progressbar(count, lines, "*")
count -=1
print "Finished"

if __name__ == "__main__":
main()

For now we can ignore the countlines() function. I need a nice progress 
display e.g. ** continuing on til it reaches 100% I 
need this to print out on one line only. At the moment it does do this, 
only problem is its appends the print out from the last print out. I 
need it to clear the last print out and then print the new print out 
without appending the last.


So when it prints a progress at 50% it will print 50 (*) characters and 
if the next progress is 51% it will print 51 (*) characters including 
the last 50 (*) characters, so instead on ending up with 100 (*) 
characters I end up with a shit load of them depending on how many lines 
I pass to the progressbar() function.


Needed Output:
***Finished


Current Output:
Finished

Note: As you can see I'm only sending 5 lines to the progressbar() 
function and It prints this many characters, so you could imagine if I 
have 1 lines I would end up with a heap of * characters.


Regards
jross






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


Re: Problems with sys.stout.flush()

2009-05-23 Thread Mohammed Mediani
Hi all,
Is anyone aware of a 3-d plotting tool for simple mathematical functions. It
seems that all the tools available have their problems with new versions.
None of matplotlib, nor PyX, nor mat3d, seems to work for 3d anymore.
Any suggestions???
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with sys.stout.flush()

2009-05-23 Thread Carl Banks
On May 23, 2:20 am, Joel Ross  wrote:
> Carl Banks wrote:
> > On May 22, 10:33 pm, Joel Ross  wrote:
> >> Hi all,
>
> >> I'm using python 2.5 and trying to flush the sys.stout buffer with
> >> sys.stout.flush(), but doesn't seem to work. Each time a line is printed
> >>    it appends the one before it I need to clear the output and write a
> >> new output without appending the previous one.
>
> > That's not how streams work, chief.  Once you output (and flush)
> > something you can't un-output it.
>
> > What you probably want to do is to write a carriage return ("\r")
> > which usually causes the cursor to return to the beginning of the
> > line, so that any new text you write overwrites the old text.
>
> > This has nothing to do with flushing; flushing doesn't erase or clear
> > the old input.  Flushing is usually needed for a different reason,
> > however, namely standard output doesn't actually get sent to the
> > console until it sees a newline ("\n") unless you flush the buffer.
>
> > Try to adapt this example to your problem:
>
> > for i in xrange(11):
> >     sys.stdout.write('*'*(10-i) + ' '*i + '\r')
> >     sys.stdout.flush()
> >     time.sleep(2)
>
> Your example prints a new line each time,

Did you run it and observe what happened, or did you just guess what
it actually did?  On my system it doesn't print new lines.


> Doesn't help me with a
> progress bar, do you know of anyway doing it with the print command? My
> progress bars works fine this is the only problem im having with it at
> the moment. any help would be appreciated.

Well, based on the code you posted it doesn't look like your progress
bar is fine.

Anyway, you haven't described the problem you are having very well,
and we can guess what might be wrong but if you want better help
you're going to have to describe your problem more coherently.  Give
us the

1. What code are you actually running (cut-and-paste, please, don't
retype).
2. What do you expect the code to output (type in actual output you
expect to see, not merely a description).
3. What does the code actually output when you run it (cut-and paste,
please, don't just describe).
4. Include any tracebacks if there are any.

In the meantime, I repeat my suggestion that you take my example and
adapt it to what you are doing.

One other note: the print statement is unsuitable for this task
because it always prints a trailing whitespace.  Use sys.stdout.write
for it.


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


Re: html ui + py background? any tut?

2009-05-23 Thread David Lyon

Hi,

I don't know any tutorial either...

At work, we have made gui apps using wxpython to make the gui...

wxpython has html viewer component...

you can use Cheetah or another template engine to make the
html...

It's pretty easy and effective...

David


On Sat, 23 May 2009 15:48:38 +0800, oyster  wrote:
> I have read for many times that the modern appliaction (not a web one,
> but desktop on) uses html + js for its UI, and python code is for the
> background work
> but I have never found event a simple (yet completed) article on how
> to develop such a thing from scrach in these advocacy thing.
> 
> Can anyone point out some simple, can-be-followed tutorial on such
> thing especially for windows os?
> 
> thanx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with sys.stout.flush()

2009-05-23 Thread Joel Ross

Carl Banks wrote:

On May 22, 10:33 pm, Joel Ross  wrote:

Hi all,

I'm using python 2.5 and trying to flush the sys.stout buffer with
sys.stout.flush(), but doesn't seem to work. Each time a line is printed
   it appends the one before it I need to clear the output and write a
new output without appending the previous one.


That's not how streams work, chief.  Once you output (and flush)
something you can't un-output it.

What you probably want to do is to write a carriage return ("\r")
which usually causes the cursor to return to the beginning of the
line, so that any new text you write overwrites the old text.

This has nothing to do with flushing; flushing doesn't erase or clear
the old input.  Flushing is usually needed for a different reason,
however, namely standard output doesn't actually get sent to the
console until it sees a newline ("\n") unless you flush the buffer.

Try to adapt this example to your problem:

for i in xrange(11):
sys.stdout.write('*'*(10-i) + ' '*i + '\r')
sys.stdout.flush()
time.sleep(2)

Your example prints a new line each time, Doesn't help me with a 
progress bar, do you know of anyway doing it with the print command? My 
progress bars works fine this is the only problem im having with it at 
the moment. any help would be appreciated.


cheers


Notice that you have to print out spaces as well, to overwrite the
previous characters on the line (well, it might not be strictly needed
for a progress bar that only grows, but it's normally a good idea.



I have tried the -u
(unbuffered) option for python and a few examples from this 
sitehttp://stackoverflow.com/questions/107705/python-output-buffering

Code:

import sys
from time import sleep

def progress(number, total,  char):

 percentage = float(number*100)/total
 percentage = int(round(percentage))
 percentage = int(100 - percentage)
 if percentage > 0:
 char = char * percentage
 sys.stdout.write(char)
 sys.stdout.flush()  #Not working correctly
 sleep(2)

progress(40, 50, "*")
progress(30, 50, "*")
progress(20, 50, "*")
progress(10, 50, "*")
progress(2, 50, "*")

Regards

jross




Carl Banks

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


Re: Ambiguous locale.strxfrm

2009-05-23 Thread Tuomas Vesterinen


Thanks. Bug report done, issue 6093.

Tuomas Vesterinen

Gabriel Genellina wrote:
En Fri, 22 May 2009 06:32:40 -0300, Tuomas Vesterinen 
 escribió:


This was fixed once in Python 2.5, but in Python 3.0 the bug 
celebrates its comeback. The tail of the strxfrm result is ambiguous.


Python 3.0.1 (r301:69556, Apr 14 2009, 14:30:31)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import locale
 >>> locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
'en_US.utf8'
 >>> key1=locale.strxfrm('maupassant guy')
  for i in range(10):
... print(locale.strxfrm('maupassant guy')==key1)
...
False
True
False
False
False
False
False
False
False
False


I could not reproduce the issue on Windows (I don't have any locale 
using utf8) but you should file a bug report at http://bugs.python.org/




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


html ui + py background? any tut?

2009-05-23 Thread oyster
I have read for many times that the modern appliaction (not a web one,
but desktop on) uses html + js for its UI, and python code is for the
background work
but I have never found event a simple (yet completed) article on how
to develop such a thing from scrach in these advocacy thing.

Can anyone point out some simple, can-be-followed tutorial on such
thing especially for windows os?

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