Re: [Tutor] Equivalent of PHP's __FUNCTION__ ?

2004-12-02 Thread Kent Johnson
Here is one way to do it, based on this Python Cookbook recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062
def debug(msg):
import sys
frame = sys._getframe(1)
name = frame.f_code.co_name
line_number = frame.f_lineno
filename = frame.f_code.co_filename
return 'File "%s", line %d, in %s: %s' % (filename, line_number, name, msg)
def test():
print debug("Invalid arguments")
test()
Kent
Mohamed Lrhazi wrote:
Hello all,
In php one can produce nice debugging and logging use code like:
print __FUNCTION__ . ": Invalid arguments\n";
__FUNCTION__ will be replaced by the name of the function to which that 
line belongs, same with __LINE__ and __FILE__ I believe.

How do I get the current method's name? and class?
Thanks.
Mohamed~
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent of PHP's __FUNCTION__ ?

2004-12-02 Thread Kent Johnson
Kent Johnson wrote:
Here is one way to do it, based on this Python Cookbook recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062
Use of sys._getframe() is generally considered something of a skanky hack. (Though it is often done 
anyway.) Here is another solution that only uses supported public interfaces:

def debug(msg):
import traceback
frame = traceback.extract_stack(limit=1)[0]
filename, line_number, name, text = frame
return 'File "%s", line %d, in %s: %s' % (filename, line_number, name, msg)

def debug(msg):
import sys
frame = sys._getframe(1)
name = frame.f_code.co_name
line_number = frame.f_lineno
filename = frame.f_code.co_filename
return 'File "%s", line %d, in %s: %s' % (filename, line_number, 
name, msg)

def test():
print debug("Invalid arguments")
test()
Kent
Mohamed Lrhazi wrote:
Hello all,
In php one can produce nice debugging and logging use code like:
print __FUNCTION__ . ": Invalid arguments\n";
__FUNCTION__ will be replaced by the name of the function to which 
that line belongs, same with __LINE__ and __FILE__ I believe.

How do I get the current method's name? and class?
Thanks.
Mohamed~
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittest.makeSuite question

2004-12-02 Thread Kent Johnson
makeSuite() creates a TestSuite object that consolidates all the test methods of the class named by 
the first argument. Test methods are identified by having names starting with the second argument. 
'test' is the default value so you could omit it; in fact the most recent documentation does omit 
this argument. If you wanted to name your test methods something different you could use this 
argument to change it.

The basic pattern shown in the first page of the tutorial will work for most unit testing. It also 
shows a use of makeSuite(), but you can easily get by without using makeSuite().
http://docs.python.org/lib/node160.html

The page on "Organizing Test Code" is, IMO, more confusing than helpful. It shows some of the 
building blocks of tests and some ways of using unittest that I have never seen in practice.

HTH
Kent
Guillermo Fernandez Castellanos wrote:
Hi,
I've been through the unittest tutorial page and I've seen this function:
suite = unittest.makeSuite(Testname,'test')
In the python 2.4 Python Library Reference I have find no reference to
such a fucntion (there is an example, exactly the same but without the
'test' parameter).
I could not really understand the sources neither...
What is the 'test' parameter? Is there another possible values? Any
reference of the function?
Thanks!
Guille
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating & Handling lots of objects

2004-12-03 Thread Kent Johnson
If you want to be able to access the objects by name, you can put them in a 
dict. For example,
MyObjects={}
l=["a","b","c"]
for i in l:
MyObjects[i] = MyClass(i)
Then you can refer to MyObjects["a"]
If all the operations on the objects are done to all objects in a batch, putting them in a list 
might work. Then you can use list iteration to access all of them:
MyObjects=[]
l=["a","b","c"]
for i in l:
	MyObjects.add(MyClass(i))

then to process all the objects:
for myObj in MyObjects:
# do something with myObj
Kent
Matt Williams wrote:
Dear Tutor-list,
I'm sorry for this appallingly dumb question, but I'm having a little
problem with objects.
I've written a class, with some methods. I then want to be able to call
the class repeatedly, to create some objects. The number of objects, and
some of their initialisation parameters need to be specified later (i.e.
at run-time).
When I generate all these objects, how do I keep track of them. For a
finite (and small) number I can do this:
a=MyClass("a")
b=MyClass("b")
but this is obviously not scaleable. If I use a list, I can do:
MyObjects=[]
l=["a","b","c"]
for i in l:
MyObjects.add(MyClass(i))
but then I have to search the list (MyObjects) for the object where
Object.name="a".
The only other option seems to be finding objects via their hash codes,
which I'm sure isn't right
I'd like to be able to automate something closer to the a=MyClass("a")
but don't know how to do itIt may be that I'm trying to do it very
badly, which is Python seems to make it hard for me.
Thanks,
Matt

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global presets ?

2004-12-04 Thread Kent Johnson
You are on the right track. Put your common definitions in a configuration 
module like this:
# Config.py
arch_data_dir='/home/dave/mygg/gg1.3/arch_data'
data_dir='/home/dave/mygg/gg1.3/data'
Then in client code, import Config. When you use the names defined in Config you have to prefix them 
with the module name like this:

import Config
print Config.data_dir
Alternately you can use either of these forms:
# Get a couple of names from Config into our global namespace
from Config import arch_data_dir, data_dir
or this:
# Get *all* names defined in Config into our global namespace
from Config import *
to make the bare names available in the client.
Kent
Dave S wrote:
Hi there,
I have some common data directories, like
/home/dave/mygg/gg1.3/logs
/home/dave/mygg/gg1.3/data
/home/dave/mygg/gg1.3/datacore
/home/dave/mygg/gg1.3/arch_data
which increasing numbers of scripts are accessing. At the begining of 
each script
I end up putting in declarations like

arch_data_dir='/home/dave/mygg/gg1.3/arch_data'
data_dir='/home/dave/mygg/gg1.3/data'

over & over. This is OK until I want to move a directory
Somewhere I read about importing a script to define common globals for 
all the scripts that import it.

I tried this, and failed - the variable was only valid for the module, 
to be expected really :)

Can anyone make a suggestion howto set up common global presets.
Cheers
Dave

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-04 Thread Kent Johnson
I didn't get the attachment, can you try again?
Thanks,
Kent
Just Incase wrote:
Hi Tutors,
 
I am new to programming and so don't know "anything" much, yet. I am 
having problem with implementing a simple RPN calculator in python. I 
have tried editing some other programs I have been referenced to earlier 
and I was able to play around with hoping to get something out of it but 
the problem I have is that I don't know how to make it request for 
input(s) of say a simple math like  "1 2 3 4 5 + - * /".
 
Help please with any suggestions or any other better and easier way of 
implementing a RPN calculator.
 
Thank you,
 
Justice
 
The following is what I have:
 
 


Do you Yahoo!?
The all-new My Yahoo!  – What will yours do?

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to select particular lines from a text

2004-12-04 Thread Kent Johnson
kumar,
Here is a solution for you. The makeSections() function will iterate through blocks in the file and 
return each one in turn to the caller.

makeSections() is a generator function - the use of yield makes it one. That means that it returns 
an iterator that can be used in a for loop. Each time yield is executed it returns a new value to 
the loop. In this case, the values returned are the contents of each section.

The loop in makeSections just walks through the lines of the input file. It accumulates the lines 
into a list and looks for special markers. The markers are, a 'Name:' line, to start a new section, 
and a blank line, to end a section. When it finds a marker it outputs the current section, if there 
is one, and starts a new one.

Kent
PS this question is much better asked than the last - you clearly stated what 
you want in a simple form.
data = '''
Name:
City:




Name:
City:


'''
import cStringIO# just for test
def makeSections(f):
''' This is a generator function. It will return successive sections
of f until EOF.
Sections are every line from a 'Name:' line to the first blank line.
Sections are returned as a list of lines with line endings stripped.
'''
currSection = []
for line in f:
line = line.strip()
if line == 'Name:':
# Start of a new section
if currSection:
yield currSection
currSection = []
currSection.append(line)
elif not line:
# Blank line ends a section
if currSection:
yield currSection
currSection = []
else:
# Accumulate into a section
currSection.append(line)
# Yield the last section
if currSection:
yield currSection
f = cStringIO.StringIO(data)
for section in makeSections(f):
print 'Section'
for line in section:
print '   ', line
print
kumar s wrote:
Dear group, 
 This is continuation to my previous email with
sugject line "Python regular expression".  My text
file although, looks like .ini file, but it is not. It
is a chip definition file from Gene chip.  it is a
huge file with over 340,000 lines.

I have particular set of question in general not
related to that file:
Exmple text:
Name:
City:




Name:
City:


Characterstics of this text:
1. This text is divided into blocks and every block
start with 'Name'.  The number of lines after this
identifier is random. 

In this particular case how a particular logic I can
think of to extract some of these blocks is:
1.write a reg.exp to identify the Name identifier one
need.
2. based on the this, ask the program to select all
lines after that until it hits either a new line OR
another name identifier:
My question:
How can I tell my program these 2 conditions:
1. mark the identifier i need and select all the lines
after that identifier until it hits a new line or
another name identifier. 

please englihten me with your suggestions. 

thank you. 

kumar
		
__ 
Do you Yahoo!? 
Read only the mail you want - Yahoo! Mail SpamGuard. 
http://promotions.yahoo.com/new_mail 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Broblem with exiting a Tkinter app

2004-12-04 Thread Kent Johnson
Mark Kels wrote:
Hi all ,
I got 2 questions for you guys.
The fist question:
I wrote small Tkinter app while laerning about the Radiobutton widget,
and I added a "Quit" button, like this:
bb=Button(root, text="Quit", fg="BLUE", command=root.quit).pack()
When I pressed the button the app crashed and I got an error message (
program is not responding ) from windows.
I tried to add a frame to the program and then exit the frame, like this:
bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack()
But the result is the same...
Here is the full source code of the app:
from Tkinter import *
import sys
root=Tk()
f=Frame(root)
text=Label(root, text="how old are you?").pack()
v = IntVar(root)
Radiobutton(f, text="less than 13", variable=v, value=1).pack(side=LEFT)
Radiobutton(f, text="13-20", variable=v, value=2).pack(side=LEFT)
Radiobutton(f, text="20-40", variable=v, value=3).pack(side=LEFT)
Radiobutton(f, text="40+", variable=v, value=4).pack(side=LEFT)
bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack()
f.pack()
root.mainloop()
This program works fine for me on Win2K. How are you running the program?
The second question:
I dont understand how to get the input fron the radio buttons...
It doesnt returns any value, so how can the app know what the user chose?
Read the value from the variable associated with the buttons - v. For 
example if you define
def quit():
print 'You chose button', v.get()
f.quit()
and change the command on bb to command=quit, the program will print the 
selection value on exit.
(You have to define quit before bb or you will get a NameError.)
Kent
Thanks!!
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and exec

2004-12-04 Thread Kent Johnson
Marilyn Davis wrote:
Thank you.  You guys are great.
I was trying to eval("import %s" % something).  

exec("import %s" % something) works just fine and now I understand why.
But, why is this so extremely dangerous?
The danger is in exec'ing code whose source is not trusted.
Using exec to import a module or create a name in your own code is fine. Using exec to run code from 
a untrusted source such as user input is opening yourself to any kind of mischief. For example you 
wouldn't want to
exec("import os; os.system('del /f /q *')")

Kent
Marilyn

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-05 Thread Kent Johnson
RPN reverses the order of operator and operand, it doesn't reverse the whole string. So in Polish 
Notation 2 + 3 is +23 and (2 + 3) - 1 is -+231; in RPN they become 23+ and 23+1-

Kent
Brian van den Broek wrote:
By analogy, I had always assumed that Polish Arithmetic would read
(2 + 3) - 1 and
2 + (3 - 1)
as:
-+231 and
+2-31
I further assumed that RPN would simply reverse this. If that isn't 
true, I think I need to go investigate the origins of the name.

Best to all,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unicode help (COM)

2004-12-05 Thread Kent Johnson
Rene Bourgoin wrote:
Thanks for the responses. i'm a non-programmer and was learning/playing with 
some pyhton COM .
I'm trying to get my resluts from an excel spreadsheet to be saved or printed or stored as a python string. when i run this the results are in  unicode.
What problem are the unicode strings causing? If you want to convert them to normal strings you can 
use the encode method:

>>> s=u'abc'
>>> s
u'abc'
>>> s.encode('ascii')
'abc'
Now it's a plain string. If the unicode string includes characters that aren't available in the 
selected encoding you will get an error:

>>> s=u'ä'
>>> s.encode('ascii')
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in 
range(128)

You can change the handling of unknown characters by passing a second 'error' 
parameter:
>>> s.encode('ascii', 'replace')
'?'
or pick a different encoding:
>>> s.encode('utf-8')
'\xc3\xa4'
You can find a list of supported encodings in the docs for the 'codecs' module.
Kent

from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible = 0
xlApp.Workbooks.Open("c:\sheet.xls")
excelout = ()
excelout = xlApp.ActiveSheet.Range("C4:D10").Value
for item in excelout:
   print item
___
No banners. No pop-ups. No kidding.
Make My Way your home on the Web - http://www.myway.com
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] psyco 1.3 is out, with support for Python 2.4

2004-12-06 Thread Kent Johnson
Dick Moores wrote:
Here's what I learned from Kent about installing psyco (for Windows):
Download psyco from http://psyco.sourceforge.net. Unzip the zip file. 
Copy the folder psyco-1.3/psyco into Python24/Lib/site-packages. (Create 
site-packages if you don't already have it.) Should be good to go then.
Then to actually _use_ psyco, the simplest thing is just to add these two 
lines to your main program:
import psyco
psyco.full()
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.3.5 out in January??

2004-12-07 Thread Kent Johnson
I think the idea is to back-port bugfixes from 2.4 to 2.3. Then that is the end 
of the line for 2.3.
Kent
Dick Moores wrote:
Just saw this on comp.lang.python.announce.

I don't understand this. Why is a new version of 2.3 being worked on 
after 2.4 has been released?

I see Tim Peters has said this on python-list:
===begin Tim Peters' post===
[Brett C]
 >> Anthony Baxter, our ever-diligent release manager, mentioned this 
past week
 >> that Python 2.3.5 will most likely come to fruition some time in 
January
 >> (this is not guaranteed date).

[Roy Smith]
 > Interesting.  Does that mean that 2.3 and 2.4 will be maintained in
 > parallel for a while?  That would be awesome.
They'll be maintained in parallel through 2.3.5 in January, which is
all Brett said.  If history is a guide, after 2.3.5 nobody will
volunteer to work on a 2.3.6, and 2.3.5 will be the last release in
the 2.3 line.  It's *possible* that volunteers for 2.3.6 will appear.
That would be unprecedented, but not impossible ...
end TP's post
I ask here because I'm sure it's a newbie question. It's got me 
wondering if Microsoft is still working on Windows 3.1..  ;-)

Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String matching?

2004-12-07 Thread Kent Johnson
Regular expressions are a bit tricky to understand but well worth the trouble - they are a powerful 
tool. The Regex HOW-TO is one place to start:
http://www.amk.ca/python/howto/regex/

Of course, Jamie Zawinsky famously said, "Some people, when confronted with a problem, think 'I 
know, I'll use regular expressions.'  Now they have two problems."

You can do a lot of cleanup with a few simple string substitutions:
test = ''' 
test2 = test.replace('=\n', '')
test2 = test2.replace('=3D"', '="')
print test2
prints =>
 
This is probably a good first step even if you want to use regular expressions to parse out the rest 
of the data from the applet tag.

OK, here is a brute-force regex that will find the text 'applet' with '=\n' perhaps between any pair 
of characters:

appRe = r'(=\n)?'.join(list('applet'))
print appRe
=> a(=\n)?p(=\n)?p(=\n)?l(=\n)?e(=\n)?t
The (=\n)? between each pair of letters means, optionally match =\n here.
You can use re.finditer to show all the matches:
import re
for match in re.finditer(appRe, test):
print
print match.group(0)
=>
app=
let
applet
ap=
plet
A couple other options:
elementtidy reads HTML, cleans it up and creates a tree model of the source. You can easily modify 
the tree model and write it out again. This has the bonus of giving you well-formed XHTML at the end 
of the process. It is based on HTML Tidy and Fredrik Lundh's elementtree package which is very easy 
to use.
http://www.effbot.org/zone/element-tidylib.htm

Beautiful Soup is an HTML parser that is designed to read bad HTML and give access to the tags. I'm 
not sure if it gives you any help for rewriting, though.
http://www.crummy.com/software/BeautifulSoup/

HTH
Kent
Liam Clarke wrote:
Hi all, 

I have a large amount of HTML that a previous person has liberally
sprinkled a huge amount of applets through, instead of html links,
which kills my browser to open.
So, want to go through and replace all applets with nice simple links,
and want to use Python to find the applet, extract a name and an URL,
and create the link.
My problem is, somewhere in my copying and pasting into the text file
that the HTMl currently resides in, it got all messed up it would
seem, and there's a bunch of strange '=' all through it. (Someone said
that the code had been generated in Frontpage. Is that a good thing or
bad thing?)
So, I want to search for 


or 
or 
plet 

etc. etc. (Full example of yuck here
http://www.rafb.net/paste/results/WcKPCy64.html)
So, I want to be write a search that will match 
I was thinking the re module is for this sort of stuff? Truth is, I
wouldn't know where to begin with it, it seems somewhat powerful.
Or, there's a much easier way, which I'm missing totally. If there is,
I'd be very grateful for pointers.
Thanks for any help you can offer.
Liam Clarke
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing two elements in a list

2004-12-07 Thread Kent Johnson
kumar s wrote:
Dear group, 
 I have two lists names x and seq. 

I am trying to find element of x in element of seq. I
find them. However, I want to print element in seq
that contains element of x and also the next element
in seq. 

So I tried this piece of code and get and error that
str and int cannot be concatenated
for ele1 in x:
for ele2 in seq:
if ele1 in ele2:
print (seq[ele1+1])
You are confusing the elements themselves with their indices. The problem here is that ele1 is a 
string - an element of x - not a number, which is what you need for an index.

for ele1 in x:
for ele2 in seq:
if ele2 in range(len(seq)):
if ele1 in ele2:
print seq[ele2+1]
Now ele2 is a number, so 'if ele1 in ele2' is never true.
3. TRIAL 3:
I just asked to print the element in seq that matched
element 1 in X.  It prints only that element, however
I want to print the next element too and I cannot get
it. 

for ele1 in x:
for ele2 in seq:
if ele1 in ele2:
print ele2
The enumerate function is useful here. enumerate(seq) returns a sequence of (index, element) pairs. 
So you could write

for ele1 in x:
for index, ele2 in enumerate(seq):
if ele1 in ele2:
print ele2
print seq[index+1]
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing two elements in a list

2004-12-07 Thread Kent Johnson
kumar,
Looking at the quantity and structure of your data I think the search you are doing is going to be 
pretty slow - you will be doing 4504 * 398169 = 1,793,353,176 string searches.

Where does the seq data come from? Could you consolidate the pairs of lines into a single record? If 
you do that and extract the '399:559' portion, you could build a dict that maps '399:559' to the 
full record. Looking up '399:559' in the dictionary would be much, much faster than searching the 
entire list.

If you have multiple entries for '399:559' you could have the dict map to a 
list.
Kent
kumar s wrote:

len(x)
4504
x[1:10]
['454:494', '319:607', '319:608', '322:289',
'322:290', '183:330', '183:329', '364:95', '364:96']
len(seq)
398169
seq[0:4]
['>probe:HG-U95Av2:1000_at:399:559;
Interrogation_Position=1367; Antisense;',
'TCTCCTTTGCTGAGGCCTCCAGCTT',
'>probe:HG-U95Av2:1000_at:544:185;
Interrogation_Position=1379; Antisense;',
'AGGCCTCCAGCTTCAGGCAGGCCAA']

for ele1 in x:
for ele2 in seq:
if ele1 in ele2:
print ele2

probe:HG-U95Av2:31358_at:454:493;
Interrogation_Position=132; Antisense;
probe:HG-U95Av2:31358_at:319:607;
Interrogation_Position=144; Antisense;


How Do I WANT:
I want to print get an output like this:

probe:HG-U95Av2:1000_at:399:559;
Interrogation_Position=1367; Antisense;'
TCTCCTTTGCTGAGGCCTCCAGCTT

probe:HG-U95Av2:1000_at:544:185;
Interrogation_Position=1379; Antisense;
AGGCCTCCAGCTTCAGGCAGGCCAA
can any one please suggest what is going wrong in my
statements and how can I get it. 

Thank you.
Kumar
		
__ 
Do you Yahoo!? 
Yahoo! Mail - 250MB free storage. Do more. Manage less. 
http://info.mail.yahoo.com/mail_250
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String matching?

2004-12-07 Thread Kent Johnson
Liam Clarke wrote:
And thanks for the re, hopefully I won't have to use it, but it gives
me a starting point to poke the re module from.
BTW Python comes with a nice tool for experimenting with regular expressions. Try running 
Python23\Tools\Scripts\redemo.py

Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import Statement Failing With IDLE?

2004-12-07 Thread Kent Johnson
I don't know why you are getting different results, but I do know that you aren't supposed to put 
the whole psyco-1.3 folder inside site-packages. Just put the psyco folder (from inside psyco-1.3) 
into site-packages.

Also the os.chdir() doesn't have any effect on import.
You could compare sys.path in the two different environments and see what is different between them.
>>> import sys
>>> sys.path
['', 'C:\\Python24\\python24.zip', 'D:\\Projects', 'C:\\Python24\\DLLs', 'C:\\Python24\\lib', 
'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-t
k', 'C:\\Python24', 'C:\\Python24\\lib\\site-packages', 'C:\\Python24\\lib\\site-packages\\win32', 
'C:\\Python24\\lib\\site-packages\\win32\\lib', 'C:
\\Python24\\lib\\site-packages\\Pythonwin']

You can also find out where psyco is being found by printing the module's 
__file__ attribute:
>>> import psyco
>>> psyco.__file__
'C:\\Python24\\lib\\site-packages\\psyco\\__init__.py'
Kent
Orri Ganel wrote:
Hello all, 
I recently downloaded Psyco and put it in the site-packages folder. 
Now, when i tried to use it to optimize a program, IDLE says it can't
find it:

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.1  

import os
os.chdir(r"c:\python24\lib\site-packes\psyco-1.3")
import psyco

Traceback (most recent call last):
  File "", line 1, in -toplevel-
import psyco
ImportError: No module named psyco
... However, when using the Command Prompt:
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
import os
os.getcwd()
'C:\\Python24'
os.chdir(r"c:\python24\lib\site-packages\psyco-1.3")
import psyco

Anyone know why this is? . . . 

Thanks in advance,
Orri
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Removing/Handing large blocks of text

2004-12-08 Thread Kent Johnson
I would use a loop with a flag to indicate whether you are in the  block or not. If the tags 
are always  and  on a line by themselves you don't need an re:

lines = []
appending = True
f = open('foobar.txt', 'r')
for line in f:
  if appending:
lines.append(line)
if line.strip() == '':
  appending = False
  elif line.strip() == '':
appending = True
lines.append(line)
f.close()
At the end of this loop lines will have the lines you want to write back.
Kent
Jesse Noller wrote:
Hello,
I'm trying to do some text processing with python on a farily large
text file (actually, XML, but I am handling it as plaintext as all I
need to do is find/replace/move) and I am having problems with trying
to identify two lines in the text file, and remove everything in
between those two lines (but not the two lines) and then write the
file back (I know the file IO part).
I'm trying to do this with the re module - the two tags looks like:

...
a bunch of text (~1500 lines)
...

I need to identify the first tag, and the second, and unconditionally
strip out everything in between those two tags, making it look like:


I'm familiar with using read/readlines to pull the file into memory
and alter the contents via string.replace(str, newstr) but I am not
sure where to begin with this other than the typical open/readlines.
I'd start with something like:
re1 = re.compile('^\')
re2 = re.compile('^\<\/foo\>')
f = open('foobar.txt', 'r')
for lines in f.readlines()
match = re.match(re1, line)
But I'm lost after this point really, as I can identify the two lines,
but I am not sure how to do the processing.
thank you
-jesse
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-08 Thread Kent Johnson
A callable is something that can be called with functional notation. It can be a function, a class, 
or in some cases a class instance. In general, any object that has a __call__() special method is 
callable. The callable() built-in tells you if an object is callable, though you can also just try 
it. For example,

the built-in len is callable and has a __call__ attribute:
>>> callable(len)
True
>>> dir(len)
['__call__', ... ]
1 is not callable and does not have a __call__ attribute:
>>> callable(1)
False
>>> dir(1)
[ ]
As you discovered, trying to call 1 as a function doesn't work:
>>> 1()
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'int' object is not callable
A user-defined function is callable and has a __call__ attribute:
>>> def f(): pass
...
>>> callable(f)
True
>>> dir(f)
['__call__', ... ]
>>>
A class is callable (you call it to create an instance):
>>> class C:
...   pass
...
>>> callable(C)
True
Instances of a class, in general, are not callable:
>>> c=C()
>>> callable(c)
False
You can make a class whose instances are callable by defining a __call__ method on the class. This 
allows you to make a class whose instances behave like functions, which is sometimes handy. (This 
behaviour is built-in to Python - __call__() is called a special method. There are many special 
methods that let you customize the behaviour of a class.)

>>> class D:
...   def __call__(self, x):
... print 'x =', x
...
>>> d=D()  # Calling the class creates an instance
>>> callable(d)
True
>>> d(3)  # Calling the instance ends up in the __call__() method of the class
x = 3
Kent
Dick Moores wrote:
I got this error msg for this line of code:
n = -(2(a**3.0)/27.0 - a*b/3.0 + c)
(where a = 1, b = 2, c = 3)
And was baffled until I realized the line should be
n = -(2*(a**3.0)/27.0 - a*b/3.0 + c)
But I still don't understand what "callable" means. Can someone help?
Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-09 Thread Kent Johnson
Liam Clarke wrote:
Hi Brian and Dick, 

I for one have learnt a lot from this combined poke around the
workings of datetime. The datetime.year thing never occurred to me,
yet it was so obvious when I saw it being used.
I give you, my python alarm clock timing mechanism, final version!
http://www.rafb.net/paste/results/qur2Pw95.html
Excuse me for butting in at the last minute, but you can use datetime for the date comparison as 
well. If you create desiredTime first, you can directly compare it with nowTime and increment it if 
necessary. Also note you can give better names to the hour and minute strings by using tuple assignment:

ja=sys.argv[1]
hh, mm=ja.split(':')
nowTime=datetime.datetime.now()
desiredTime=nowTime.replace(hour=int(hh), minute=int(mm),second=0)
if desiredTime <= nowTime:
desiredTime += datetime.timedelta(days=1)
Kent
It works on the cmd line - 

python alarm.py 17:30 

Sets the alarm for the next occurrence of 17:30, using nothing  but
datetime.datetime objects, and one timedelta (maybe).
'Twas a good discussion. : )
Liam Clarke
On Thu, 09 Dec 2004 00:12:04 -0500, Brian van den Broek
<[EMAIL PROTECTED]> wrote:
Brian van den Broek said unto the world upon 2004-12-07 23:57:
Dick Moores said unto the world upon 2004-12-07 12:04:


The note you reference:
date2 is moved forward in time if timedelta.days > 0, or backward if
timedelta.days < 0. Afterward date2 - date1 == timedelta.days.
timedelta.seconds and timedelta.microseconds are ignored. OverflowError
is raised if date2.year would be smaller than MINYEAR or larger than
MAXYEAR.
presupposes you are adding a timedelta to a datetime as in Tim's
suggestion. It makes no promises if you were doing something goofy like
I was. (If that is what you were trying to get me to see, sorry, but I
missed it.)
Hey Dick and all,
I've taken a look at your code and finally seen what you meant, Dick.
You were trusting datetime (along the same lines that Tim suggested to
me) and thus weren't facing the problems I'd caused for myself. Sorry
for missing your point before. Thanks,
Brian vdB

I hope this clarifies things some :-)
Ah, irony!

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-09 Thread Kent Johnson
Liam,
I'm sorry to hear you so discouraged.
It sourds like your program has gotten too big for you to clearly understand what it is doing. An 
earlier poster suggested that you break your program up into functions. This is a very good idea, 
especially if you do it from the start.

A very powerful technique for developing a complex program is to start with small pieces and build 
up from them. The pieces can be coded *and tested* independently. Because they are known to work, 
you can confidently build larger pieces by hooking together the small ones.

In your case, a very simple place to start would be a function to get rid of the '=\n' and '=3D' 
strings:

def cleanup(codeSt):
codeSt=codeSt.replace("=\n",'')
codeSt=codeSt.replace('=3D','=')
return codeSt
Using the unittest module you could write a test like this:
import unittest
class CodeFixTest(unittest.TestCase):
def test_cleanup(self):
self.assertEquals('', cleanup(''))

if __name__ == '__main__':
unittest.main()
That's pretty simple. Now move on to a function that, given an applet tag, figures out the 
corresponding link tag. Write tests for that function using examples from your actual data.

You could have another function that finds the applet tags. Finally a function that puts it all 
together. Still you can have unit tests that make sure it is working correctly.

When you are done you have a working, well-tested program and a suite of unit tests for it. Keep the 
tests - they will be handy if you ever want to make a change.

HTH
Kent
Liam Clarke wrote:
Well, I figured out the memory error relatively easily once I poked
some stuff, I was using codeSt.find instead of codeSt.index, so it was
returning no matches as -1, index raises an error for me, and I wasn't
catering for that -1. The MemoryError occurred when Python wanted to
slice from 160,000 to -1 or 0.
Was quite funny watching 1 Gb of paging file disappear in seconds.
But, I give up. Now, I've got several more bugs pop up. I've got an
index of integers that has the occasional index stored as a string. I
have indexes that start pointing at the right place, but when it comes
time to slice, the right place has moved. Unsure why, I'm specifically
moving from highest to lowest to avoid messing with the index values.
Even if nothing changes, my stored indexes go off course. This is
yuck.
So, I'm going to throw caution to the wind, and try an re approach. It
can't be any more unwieldy and ugly than what I've got going at the
moment.
Thanks for all the help, I'm off to get myself another problem.
Regards,
Liam Clarke
On Wed, 08 Dec 2004 15:25:30 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
Liam Clarke wrote:

I'm not sure why you're getting the MemoryError, but it'd be easier to
figure out if you posted the entire text of the traceback.
Traceback: 
Line 39: seg=codeSt[element:endInd+len(endStr]
MemoryError
Hehe. Helpful, no?
Actually, it was the "usual bit about in module" that might *be*
helpful. ;)  Often, something can be determined by the sequence of
function calls listed there.  Though I suppose, now that I think of
it, that since your code is all module-level, there wouldn't be any
function stack in this case...   Still, in general, when asking for
help with something that throws an exception, it's always best to copy
& paste the entire text of the exception.
One thing that I've noticed, which I thought was just a typo in your
original email but which is duplicated again here (it's not present on
the web page you linked to) -- you have a mismatched parenthesis in
your len() call.  It's "[ ... len(endstr]" -- there's no ')' to close
the function call.  Given that this typo isn't on the web page, I'm
not sure whether it's actually there in the code you're running or
not.  I'd have *thought*, however, that if it *is* present, you'd get
a syntax error rather than a memory error, so it's probably not there
but you should check it anyhow.  :)

Jeff Shannon
Technician/Programmer
Credit International
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sorting a list of dictionaries

2004-12-09 Thread Kent Johnson
If you can use Python 2.4 it is very simple using the new key= parameter to sort and 
operator.itemgetter:

>>> import operator
>>> ds = [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':36}]
>>> ds.sort(key=operator.itemgetter('name'))
>>> ds
[{'name': 'bar.txt', 'size': 36}, {'name': 'foo.txt', 'size': 35}]
>>> ds.sort(key=operator.itemgetter('size'))
>>> ds
[{'name': 'foo.txt', 'size': 35}, {'name': 'bar.txt', 'size': 36}]
Otherwise you should use decorate - sort - undecorate. The idea here is to make a new list whose 
values are pairs of (key, item) for each data item in the original list. The new list is sorted, 
then a final list is extracted containing only the items in the desired order:

>>> d2 = [ (d['name'], d) for d in ds ]
>>> d2.sort()
>>> ds = [ d for (name, d) in d2 ]
>>> ds
[{'name': 'bar.txt', 'size': 36}, {'name': 'foo.txt', 'size': 35}]
Kent
Larry Holish wrote:
Hello,
I have a list of dictionaries, each representing info about a file,
something like:
[{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
I want to present a sorted list of all the files' data, sorting on the
keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping)
across all the dictionaries. Can someone point me towards an efficient
solution for accomplishing the sort? (The list has 1000s of files).
Thanks in advance,
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sorting a list of dictionaries

2004-12-09 Thread Kent Johnson
Using sort() with a user compare function is not recommended when you care about performance. The 
problem is that the sort function has to call back into Python code for every compare, of which 
there are many. The decorate - sort - undecorate idiom is the preferred way to do this in Python < 
2.4. Python 2.4 adds the key= parameter to sort() and does the DSU internally.

Ironically, the best way to speed up Python code is often to eliminate it - the more work you can do 
in the C runtime, the faster your code will run. Sometimes an approach that seems to do more work - 
like DSU, which builds two extra lists - is actually faster because it does more in C code.

Here is a program to time the three methods. On my machine, the ratio of times of sort1 : sort2 : 
sort3 is pretty consistently about 1 : 2 : 6-7, i.e. sort with key parameter is twice as fast as DSU 
which is three times faster than sort with cmp.

A couple of interesting observations:
- The ratio of sort times is independent of the length of the list. I expected that the performance 
of sort3 would get progressively worse as the list got longer because I expect that the cmp function 
would be called a number of times that is O(n*logn). Apparently this is not the case.

- If the list is large and already sorted, sort3 is significantly faster than sort2 - it takes about 
2/3 the time of sort2. You can try this by taking out the call to random.shuffle().

Kent
import operator, random, timeit
a = range(1)
random.shuffle(a)
dlist = [ {'name':str(i), 'size':i} for i in a ]
def sort1(ds):
''' Sort using Python 2.4 key argument '''
ds.sort(key=operator.itemgetter('size'))
def sort2(ds):
''' Sort using DSU '''
d2 = [ (d['size'], d) for d in ds ]
d2.sort()
ds[:] = [ d for (name, d) in d2 ]
def sort3(ds):
''' Sort using cmp argument to sort '''
ds.sort(lambda m, n: cmp(m['size'], n['size']))
def timeOne(fn):
setup = "from __main__ import " + fn.__name__ + ',dlist'
stmt = fn.__name__ + '(dlist[:])'
t = timeit.Timer(stmt, setup)
secs = min(t.repeat(3, 10))
print '%s: %f secs' % (fn.__name__, secs)
# Make sure they all give the same answer
a1=dlist[:]
sort1(a1)
a2=dlist[:]
sort2(a2)
a3=dlist[:]
sort3(a3)
assert a1 == a2
assert a3 == a2
timeOne(sort1)
timeOne(sort2)
timeOne(sort3)
Karl Pflästerer wrote:
On  9 Dez 2004, [EMAIL PROTECTED] wrote:

I have a list of dictionaries, each representing info about a file,
something like:
[{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
I want to present a sorted list of all the files' data, sorting on the
keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping)
across all the dictionaries. Can someone point me towards an efficient
solution for accomplishing the sort? (The list has 1000s of files).

That's easy to achieve, since sort takes a custom sort function as
optional argument.  Now you need only a function which takes the values
of the fileds and compares them.
E.g.
lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
where field is either 'name' or 'size'.
As a function:
def sort_it (lst, field):
lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
   Karl
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-09 Thread Kent Johnson
Liam,
Here's a nifty re trick for you. The sub() method can take a function as the replacement parameter. 
Instead of replacing with a fixed string, the function is called with the match object. Whatever 
string the function returns, is substituted for the match. So you can simplify your code a bit, 
something like this:

def replaceTag(item):   # item is a match object
# This is exactly your code
text=gettextFunc(item.group()) #Will try and stick to string method
 for this, but I'll see.
if not text:
   text="Default" #Will give a text value for the href, so some
 lucky human can change it
url=geturlFunc(item.group()) # The simpler the better, and so far
 re has been the simplest
if not url:
  href = '"" #This will delete the applet, as there are applet's
 acting as placeholders
else:
  href='%s' % (url, text)
# Now return href
return href
now your loop and replacements get replaced by the single line
codeSt = reObj.sub(replaceTag, codeSt)
:-)
Kent
Liam Clarke wrote:
Hi all, 

Yeah, I should've written this in functions from the get go, but I
thought it would be a simple script. :/
I'll come back to that script when I've had some sleep, my son was
recently born and it's amazing how dramatically lack of sleep affects
my acuity. But, I want to figure out what's going wrong.
That said, the re path is bearing fruit. I love the method finditer(),
 as I can reduce my overly complicated string methods from my original
code to
x=file("toolkit.txt",'r')
s=x.read() 
x.close()
appList=[]

regExIter=reObj.finditer(s) #Here's a re obj I compiled earlier. 

for item in regExIter:
   text=gettextFunc(item.group()) #Will try and stick to string method
for this, but I'll see.
   if not text:
  text="Default" #Will give a text value for the href, so some
lucky human can change it
   url=geturlFunc(item.group()) # The simpler the better, and so far
re has been the simplest
   if not url:
 href = '"" #This will delete the applet, as there are applet's
acting as placeholders
   else:
 href='%s' % (url, text)
   appList.append(item.span(), href)
appList.reverse()
for ((start, end), href) in appList:
 codeSt=codeSt.replace(codeSt[start:end], href)
Of course, that's just a rought draft, but it seems a whole lot
simpler to me. S'pose code needs a modicum of planning.
Oh, and I d/led BeautifulSoup, but I couldn't work it right, so I
tried re, and it suits my needs.
Thanks for all the help.
Regards,
Liam Clarke
On Thu, 09 Dec 2004 11:53:46 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
Liam Clarke wrote:

So, I'm going to throw caution to the wind, and try an re approach. It
can't be any more unwieldy and ugly than what I've got going at the
moment.
If you're going to try a new approach, I'd strongly suggest using a
proper html/xml parser instead of re's.  You'll almost certainly have
an easier time using a tool that's designed for your specific problem
domain than you will trying to force a more general tool to work.
Since you're specifically trying to find (and replace) certain html
tags and attributes, and that's exactly what html parsers *do*, well,
the conclusions seems obvious (to me at least). ;)
There are lots of html parsing tools available in Python (though I've
never needed one myself). I've heard lots of good things about
BeautifulSoup...

Jeff Shannon
Technician/Programmer
Credit International
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PDF and Python

2004-12-09 Thread Kent Johnson
The reportlab toolkit is frequently recommended, though I haven't tried it 
myself.
http://www.reportlab.org/
Kent
Jason Child wrote:
Hey there. Does anyone know of a way to output PDFs with python? I have some
data that I have processed from a series of textfiles that I would like to
provide PDF format reports for..
Jason Christopher Child
Computer Network Services Professionals
Tech Support
505-986-1669
1-877-321-9165
[EMAIL PROTECTED]
VOZ Online
VOIP Install Tech
505-428-7500
1-877-428-7550
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-10 Thread Kent Johnson
Well, that's a regex only a mother could love. :-) I can see why you were happy to find the 
(?P) form of grouping.

You should compile textObj and urlObj outside of getVals. You could just pull the four lines that 
create textObj and urlObj outside of the function (into global scope). You just have to compile a 
regex once, then you can use it multiple times. Compiling is relatively slow so pulling it out of 
the loop is an optimization.

Congrats on getting this working!
Kent
Liam Clarke wrote:
Hi Kent, 

Thanks for the help, it worked third time around!
The final product is here if you have an interest  - 
http://www.rafb.net/paste/results/XCYthC70.html

But, I think I found a new best friend for this sort of thing - 
(?P.*?)

Being able to label stuff is brilliant.
But yeah, thanks for the help, especially that sub method.
Regards,
Liam Clarke
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.listdir fn

2004-12-10 Thread Kent Johnson
Have you looked at the glob module?
>>> import glob
>>> glob.glob('src/*.properties')
['src\\jdbc.properties', 'src\\jdbc_local.properties', 'src\\jdbc_qa.properties', 
'src\\jdbc_test.properties', 'src\\log4j.jnlp.properties', 'src\\log4j.properties', 
'src\\version.properties']

Kent
Nandan wrote:
Hello
I need to get the equivalent of 'ls script.icons/*.script'
I looked around in the os module but can't find anything appropriate.
That is, filename globbing doesn't seem to work. Looks like I'll have to
use map/filter to do this.  Is there a better way?
Thanks,
N
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.listdir fn

2004-12-11 Thread Kent Johnson
Are you sure this does what you want? You compute 'scripts' and 'filenames' and throw them away. I 
think this function will return the base name of all the files *and folders* in ./icon.scripts/opname.

If you are trying to return the base name of every file or directory whose extension is '.script', 
you can use a list comprehension to filter the list:

def createaproposjlist(opname):
filelist=os.listdir('./icon.scripts/'+opname)
spltnames=map(os.path.splitext,filelist)
return [ name for name, ext in spltnames if ext == '.script' ]
If you are concerned about directories with names ending in '.script' then add another filter using 
os.path.isdir:

def createaproposjlist(opname):
basedir = './icon.scripts/'+opname
filelist=os.listdir(basedir)
filelist = [ f for f in filelist if os.path.isfile(os.path.join(basedir, 
f)) ]
spltnames=map(os.path.splitext,filelist)
return [ name for name, ext in spltnames if ext == '.script' ]
Kent
Nandan wrote:
It does if you use the glob module :-)
Python, with batteries included.
But sometimes finding the right battery can be challenging...

Muttering 'globbing is a Perl concept, listing dirs must be in file ops' I
turned first to the Files section of the Nutshell book :-) But I came up with
this code, which I'm happy with for several reasons:
def createaproposjlist(opname):
filelist=os.listdir('./icon.scripts/'+opname)
spltnames=map(os.path.splitext,filelist)
scripts=filter(lambda x: x[1]=='.script', spltnames)
filenames=map(''.join,scripts)
filebases=map(lambda x: x[0], spltnames)
return filebases;
Cheers,
Nandan

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-11 Thread Kent Johnson
Liam Clarke wrote:
As far as I know, you'll either have to - run Python 2.3 or - run
Python 2.3 until they release a new version of Pygame,
Yes, any Python addon that uses .pyd or .dll files has to be recompiled for Python2.4. Pygame has 
many .pyd files so you have to use Python 2.3.

Here is a thread on comp.lang.python that explains why...
http://tinyurl.com/659mk
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function that returns a fn

2004-12-11 Thread Kent Johnson
Yes, it really is that simple. :-)
A common example is a function that makes a function which adds a constant to 
its argument:
>>> def makeadder(n):
...   def adder(x):
... return x + n
...   return adder
...
Make a function that adds 3 to its argument...note there is no special syntax for the return, just 
assign to a name
>>> add3 = makeadder(3)

add3 is a function:
>>> add3

>>> add3(4)
7
Make another function to add 5:
>>> add5 = makeadder(5)
>>> add5(10)
15
add3 still works, it is a separate function with its own binding of n:
>>> add3(2)
5
Kent
Nandan wrote:
I'm looking for resources to help me with a fn that returns a fn after
binding one of its arguments (aka currying, like the bind1st of C++)
Considering Python syntax is quite straightforward, this is my first try:
def getjlistrenderer(opname):
def listrender():
# use opname, eg ops=getlist(opname)
# or set local fn variable
return renderer;
return listrender;
#?or f=listrender(); return f;
Is it really as simple as this? Or will I always return the same function
definition? I need it to return a 'new' function for each call to
getjlistrender() .. do I need to create a new fn with f=listrender() ?
No, this is a call to listrender, it will return the renderer object not a 
function.
Any pointers to pages/books etc. appreciated. I am looking through my
books too, but thought I'd get some more pointers as well. Web searching
so far only shows lambda, which is one-liner, and that won't do.
There are several currying recipes in the Python Cookbook:
http://aspn.activestate.com/ASPN/search?query=curry&x=0&y=0§ion=PYTHONCKBK&type=Subsection
Searching the cookbook for 'closure' also gives some recipes that might be of 
interest.
Kent
Thanks!
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using a function as a dictionary value?

2004-12-13 Thread Kent Johnson
Liam Clarke wrote:
Hey Justin,
Tricky one this..
as far as I know, and I'm a beginner myself, a dictionary stores a
reference to the function, not the actual function.
Yes. In fact this is a good way to think about all variables in Python. A variable stores a 
reference to a value, not the value itself. I think of variables as somehow pointing at the value. 
Some people like to think of the variable as a sticky note stuck on the value with its name. 
Pythonistas say that the name is 'bound' to the value; the assignment 'x = 2' binds the name 'x' to 
the value '2'.

The *wrong* way to think about variables in Python is to think of them as containers that hold a 
value. This is appropriate for some languages but it is not a helpful model for Python.

So - 


command = {'1': spam(),
   '2': breakfast(),
   '3': bridgekeeper()
   }

Try this instead - 

command = {'1': spam, '2':breakfast, '3': bridgekeeper}
Yes. The difference is, you are storing a reference to the actual function object, rather than the 
result of calling the function.

>>> def foo():
...   return 3
...
The function name is actually a variable which is bound to a function object. When you use the bare 
variable name, you are referring to this object:
>>> foo


On the other hand when you use the function name with parentheses, you call the function. The value 
of this expression is the return value of the function.

>>> foo()
3
Here is a dictionary with both usages:
>>> d = { 'foo':foo, 'value':foo() }
>>> d
{'foo': , 'value': 3}
If you put foo in the dict, you have access to the function. If you put foo() in the dict, you have 
access to the result of calling the function. If I store a reference to the function, I can retrieve 
it and call it like this:
>>> d['foo']()
3

Kent
if select in options:
   command[select]

change this to - 

select = raw_input('Chose an option [1|2|3]: ')
if select in command.keys():
 command[select]()

That one had me going round in circles when I first met it.
AFAIK, everything is stored in dictionaries apparently. If you have a
function called 'dude()' you could probably call it as a dictionary of
'dude' from the namespace...
Yes, under the hood, binding a name to a value turns into adding a mapping to a special dictionary. 
For variables with global scope, you can access this dictionary with the globals function. Both the 
dict d and the function foo are in my globals:

>>> globals()
{'__builtins__': , '__name__': '__main__', 'foo': , '__doc__': None, 'd': {'foo': 
on foo at 0x008D6670>, 'value': 3}}
>>> globals()['d']
{'foo': , 'value': 3}

Standard disclaimer - 

Someone more knowledgable would probably be along shortly to point out
a simpler, elegant way to do it, but my way works. Mostly.
Actually you got the code right :-) I just thought the explanation needed a 
little fleshing out.
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems with unsigned integers

2004-12-13 Thread Kent Johnson
It seems that ntohl doesn't understand about unsigned values, at least on Win32:
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from struct import pack, unpack
>>> pack('L', -1)
'\xff\xff\xff\xff'
>>> unpack('L', '\xff\xff\xff\xff')
(4294967295L,)
>>> from socket import ntohl
>>> ntohl(4294967295L)
-1
Kent
Loptr Chaote wrote:
Hello everyone! 

I'm having problems with signed/unsigned (32bit) integers in python.
Example code:
  seq = 0L
  seq = socket.ntohl(struct.unpack("L", data[38:42])[0])
  print seq
This sometimes produces a negative output, how is that possible since
I booth initialized seq with "0L" and also specified "L" in unpack()?
-L.C
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cgi with system calls

2004-12-13 Thread Kent Johnson
Nik wrote:
hi,
I'm trying to write a python cgi script that can control certain 
processes on my server, but I'm having some trouble.
The script is;

#!/usr/bin/python
import cgitb; cgitb.enable()
print "Content-type: text/plain\n\n"
You may need explicit \r\n here, I'm not sure:
print "Content-type: text/plain\r\n\r\n"
Kent
import os
cmd = "/bin/ps"
status = os.system(cmd)
print status
which seems straight forward, but I get a server error, and
malformed header from script. Bad header=  PID TTY  TIME CMD:
appears in the apache logs. The PID TTY etc indicates it's getting the 
ps response, but why won't it display (even with text/plain)?

Ultimately I'll have the content type as html, and I'm going to 
preprocess the output of ps so it probably won't cause any problems, but 
I just don't understand why this isn't working in its simple form?

btw, the final idea is to list the processes corresponding to a certain 
name, and allow users to stop them or create new ones. I'm assuming this 
should be do-able?

nik
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regexp Not Matching on Numbers?

2004-12-14 Thread Kent Johnson
I'm not too sure what you are trying to do here, but the re in your code matches the names in your 
example data:
>>> import re
>>> name = 'partners80_access_log.1102723200'
>>> re.compile(r"([\w]+)").match( name ).groups()
('partners80_access_log',)

One thing that may be tripping you up is that re.match() only matches at the *start* of a string, as 
if the regex starts with '^'. For matching anywhere in the string use re.search() instead.

Another possible problem is that you are defining regexp but not using it - have you been trying to 
change the value of regexp and wondering why the program doesn't change?

If you are looking for file names that end in log.ddd then try
re.search(r'log\.\d+$', name)
If this doesn't help please be more specific about the format of the names you want to match and 
exclude.

Kent
Gooch, John wrote:
This is weird. I have a script that checks walks through directories, checks
to see if their name matches a certain format ( regular expression ), and
then prints out what it finds. However, it refuses to ever match on numbers
unless the regexp is ".*". So far I have tried the following regular
expressions:
"\d+"
"\d*"
"\W+"
"\W*"
"[1-9]+"
and more...
Here is an example of the output:
No Match on partners80_access_log.1102723200
Checking on type= Name = some_access_log.1102896000
Here is the code:
import os,sys
import re
#define the file mask to identify web log files
regexp = re.compile( r"\." )
startdir = "C:/Documents and Settings/John.Gooch/My Documents/chaser/"
#define global functions
def delFile(arg, dirname, names):
found = 0
for name in names:
print "Checking on type="+str(type( name ) )+" Name = "+str(name)
matches = re.compile(r"([\w]+)").match( name )
if matches:
print "Match on "+str(matches.groups()) 
found = 1
else:
print "No Match on "+name
if not found:
print "No matches found in "+dirname
else:
print "Match found in "+dirname
os.path.walk( startdir, delFile, "" )


Any thoughts?
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regexp Not Matching on Numbers?

2004-12-14 Thread Kent Johnson
Max Noel wrote:
On Dec 14, 2004, at 18:15, Gooch, John wrote:
So far I have tried the following regular
expressions:
"\d+"
"\d*"
"\W+"
"\W*"
"[1-9]+"
and more...

I think you have to escape the backslashes.
or use raw strings like r"\d+" which is what is in the sample code...
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] check_range

2004-12-14 Thread Kent Johnson
You misunderstand what range() does. It returns a list of numbers starting with the lower one and up 
to but not including the upper one:
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(5, 10)
[5, 6, 7, 8, 9]

To test for a number in a range you can use 10 < n < 90:
>>> x = 1
>>> 10 < x < 90
False
>>> x = 15
>>> 10 < x < 90
True
>>> x = 100
>>> 10 < x < 90
False
Kent
Marc Gartler wrote:
Hi all,
I am fairly new to both Python & programming, and am attempting to 
create a function that will test whether some user input is an integer 
between 10 and 89, but the check isn't happening...

def check_range(myrange):
if range(myrange) != range(10,89):
return "False"
else:
return "True"
...this gets called later via:
if check_range(input):
done = "True"
return int(input)
What am I doing wrong?
Thanks!
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] check_range

2004-12-15 Thread Kent Johnson
Brian van den Broek wrote:
DogWalker said unto the world upon 2004-12-15 00:32:
"Brian van den Broek" <[EMAIL PROTECTED]> said:
I have a some style suggestions for you, too.
Try it this way:
def check_in_range(value):
   in_range = False
   if 9 < value < 90:
   in_range = True
   return in_range
Shorter:
def check_in_range(value):
return 9 < value < 90

Indeed. Good one. I never seem to think of such very direct ways, but 
there you have it. It might say more about my psychology than anything 
else, but I think I'd be tempted to put a brief comment on that code. 
(Such as # returns True if the test, False otherwise.) My guess is that 
if I had to read it more than twice, the time spent writing the comment 
would be more than regained in spending less time scratching my head. 
This might also be a matter of little experience, too.
Of course put a comment if you like, but this is very concise, idiomatic code and I hope you will 
get used to it so the comment is not needed.

The value of the expression '9 < value < 90' is actually a boolean True or False, so testing the 
expression and explicitly returning True or False is redundant. You are using four lines of code to 
do the work of one.

In general, Python's flexibility with boolean values is a strength of the language and I recommend 
you try to get comfortable with it.

At any rate, I certainly would agree that yours is bound to be better in 
any situation where speed of execution mattered a lot.
Or readability, IMO.
Kent
Best,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dbcp module

2004-12-15 Thread Kent Johnson
Googling for 'python dbcp' turns up this recipe, is this what you are looking 
for?
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189
Kent
Rene Bourgoin wrote:
Anyone know where I can download the dbcp module for Python


___
No banners. No pop-ups. No kidding.
Make My Way your home on the Web - http://www.myway.com
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A simpler mousetrap

2004-12-16 Thread Kent Johnson
As Wolfram pointed out, os.path.splitext() is a good way to do this. It is also more robust than the 
other solutions because it does the right thing if there is no extension on the original file name. 
I just want to say that your first solution can be written much more simply as
x=a[:a.rfind('.')] + '.bak'

Kent
Liam Clarke wrote:
Hi all, 

I'm writing some code, and I want to take a given path + filename, and
change the file extension to *.bak.
In doing so, (entirely internal this function), I am assuming -
That the file will always have an extension
Thathe extension will vary
But, it will follow the general DOS format of name.ext
So, I came up with this -
a="./tc/arc/gab.pct"
x=a.replace(a[a.rfind('.'):len(a)],'.bak')
x="./tc/arc/gab.bak"
So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
as using an regex though ; )
I thought about 

a="./tc/arc/gab.pct"
aList=a.split('.')
aList[-1]='bak'
a=".".join(aList)
but I'm wondering if there's a simpler way, as there usually seems to
be, and it's always so obvious once I'm shown it, like 6 down - Six on
vehicle live in the manse (VI + car). Obvious once you know.
Regards,
Liam Clarke
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Multiple returns in a function

2004-12-16 Thread Kent Johnson
Brian van den Broek wrote:
Kent Johnson said unto the world upon 2004-12-15 20:16:
 > I would write
 > def is_leap_year(year):
 > try:
 > datetime.date(year, 2, 29)
 > return True
 > except ValueError:
 > return False
Not an adherent of the "only one exit point" doctrine then, hey? I spent 
a while a few weeks ago with a bug in a function that happened because 
I'd not noticed that I had two return statements, so I'm leery of this 
at the moment. (I concede if the function was long enough to hide that 
from me, it was probably too long.) I also like the conceptual purity of 
one way in and one way out. But, in my code above, that is indeed 
purchased at the cost of the ugly and a bit anomalous assignment of True.
Right you are. I wondered if anyone would notice :-)
I find multiple returns very handy. They can often reduce the indentation of a block or eliminate 
the need for flag variables. And I don't see any benefit from having a single return.

One simple use of multiple returns is to handle different conditions in a function. Especially for 
error conditions. I like to handle special cases early in a function. (This is the GuardClause idiom 
from the web page you cited: http://c2.com/cgi/wiki?GuardClause) For example something like

def fn(a, b):
  if not a:
return None
  if b == 0:
return 0
  # Calculate result from a and b
  return result
Without the multiple returns this might look like
def fn(a, b):
  if not a:
result = None
  elif b == 0:
result = 0
  else:
# Calculate result
  return result
To me the first version is cleaner and clearer. The exceptional cases are handled unambiguously at 
the start of the fn, the rest of the code just handles the normal case.

Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Kent Johnson
It's probably worth pointing out that these two functions are not entirely 
equivalent:
def t1():
  if condition:
return True
  return False
def t2():
  return condition
because 'condition' does not have to evaluate to a boolean value, it can be any 
Python value.
Here is a simple example where 'condition' is just the value of a parameter:
>>> def t1(a):
...   if a:
... return True
...   return False
...
>>> def t2(a):
...   return a
...
If a is actually True or False these two functions return the same value:
>>> a=True; print t1(a), t2(a)
True True
>>> a=False; print t1(a), t2(a)
False False
For other values of a they return different values; t1 will always return True or False, while t2, 
obviously, returns a:
>>> a=1; print t1(a), t2(a)
True 1
>>> a=None; print t1(a), t2(a)
False None
>>> a=[]; print t1(a), t2(a)
False []

Usually this is fine; code such as
if t1(a): print 'a is True'
will work the same with t1 or t2. OTOH, if you explicitly test the return value (which is *not* 
recommended practice), you will get different results:
>>> if t1(100) == True: print '100 is True'
...
100 is True

>>> if t2(100) == True: print '100 is True'
...
(nothing prints)
I recommend *not* testing explicitly for True, and I recommend the t2() form. Then Python will do 
what you expect. But I thought it was worth pointing out the difference.

Kent
Gregor Lingl wrote:

Brian van den Broek schrieb:
If my original bit of code, the structure was like:
output_value = False
if condition:
output_value = True
return output_value
Mine would be like yours if transformed to:
if condition:
return True
return False
Hi Brian!
Do you mean, that condition is something which is
True od False?
And if condition is True you want to return True?
And if condition is False you want to return False?
So why not simlpy:
return condition
?
Regards,
Gregor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python structure advice ?

2004-12-16 Thread Kent Johnson
Dave S wrote:
Dave S wrote:
The 'remembering where is was' seems a continuous stumbling block for 
me. I have though of coding each module as a class but this seems like 
a cheat. I could declare copious globals, this seems messy, I could 
define each module as a thread & get them talking via queues, given 
this serious thought but heeded warning in previous posts. I have 
thought about returning an list of saved 'pointers' which would be 
re-submitted when the function is called. I don't know which way to turn.

Having written this email, it has put my thoughts in order, though it 
seems a bit cheaty, wouldn't defining all modules that have to remember 
their internal state as classes be the best bet ?

Dave
Why do you say this is 'cheaty'? A class is basically a collection of data (state) and functions to 
operate on that state.

You might be interested in this essay:
http://www.pycs.net/users/323/stories/15.html
It might well make sense to organize your program as a collection of cooperating classes, or maybe a 
collection of classes with a top-level function that stitches them all together.

You might also want to learn about iterator classes and generator functions, they are a technique 
for returning a bit of data at a time while maintaining state. You might be able to structure your 
input stage as an iterator or generator.
http://docs.python.org/tut/node11.html#SECTION001190
http://docs.python.org/lib/typeiter.html

Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-17 Thread Kent Johnson
Jacob S. wrote:
Ha! That's what I was looking for! The builtin apply function! The only way
I could send the *args to the function was through a list, and function
calls see a list as one argument. The apply argument doesn't! Thanks Bob.
apply() is deprecated; it has been replaced by 'extended call syntax'. 
Instead of
  apply(fn, args, kwds)
you can now write
  fn(*args, **kwds)
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dbcp module

2004-12-17 Thread Kent Johnson
Please describe what you are looking for. A python version of the Jakarta 
Database Connection Pool?
Kent
Rene Bourgoin wrote:
Yah i came across that site and was trying to learn from that code.
I just cant seem to find a download for a python version.

i came across this site while searching.

http://jakarta.apache.org/






 --- On Wed 12/15, Kent Johnson < [EMAIL PROTECTED] > wrote:
From: Kent Johnson [mailto: [EMAIL PROTECTED]
To: 

 Cc: [EMAIL PROTECTED]
Date: Wed, 15 Dec 2004 20:19:22 -0500
Subject: Re: [Tutor] dbcp module

Googling for 'python dbcp' turns up this recipe, is this what you are looking for?http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189KentRene Bourgoin wrote:> Anyone know where I can 
download the dbcp module for Python> > > > > > > ___> No banners. No pop-ups. No kidding.> Make My 
Way your home on the Web - http://www.myway.com> ___> Tutor maillist  -  [EMAIL PROTECTED]> http://mail.python.org/mailman/listinfo/tutor> 
___Tutor maillist  -  [EMAIL PROTECTED]http://mail.python.org/mailman/listinfo/tutor
___
No banners. No pop-ups. No kidding.
Make My Way your home on the Web - http://www.myway.com
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python structure advice ?

2004-12-17 Thread Kent Johnson
Dave S wrote:
Separate modules is good. Separate directories for anything
other than big programs (say 20 or more files?) is more hassle
than its worth. The files are better kept in a single directory
IMHO. The exception being modules designed for reuse...
It just makes life simpler!
 

Ive tried to be hyper organized and added my dirs in
/usr/lib/python2.3/site-packages/mypath.pth
/home/dave/mygg/gg1.3/live_datad
/home/dave/mygg/gg1.3/logger
/home/dave/mygg/gg1.3/utils
/home/dave/mygg/gg1.3/datacore
/home/dave/mygg/gg1.3
/home/dave/mygg/gg1.3/configs
This works OK but I sometimes have to search around a bit to find where 
the modules are.

Probarby part of the problem is I tend to write lots of small modules, 
debug them & then import them into one controlling script, It works OK 
but I start to drown in files, eg my live_datad contains ...

exact_sleep.py   garbage_collect.py   gg ftsed.e3p  html_strip.py   
live_datad.py  valid_day.pyc
exact_sleep.pyc  garbage_collect.pyc  gg ftsed.e3s  html_strip.pyc  
valid_day.py

When I get more experienced I will try & write fewer, bigger modules :-)
It's just a guess from the filenames, but it looks like your live_datad package (directory) contains 
everything needed by live_datad.py. I would like to suggest a different organization.

I tend to organize packages around a single functional area, and by looking at the dependencies of 
the modules in the package on other packages.

For example, in my current project some of the packages are:
- common.util - this is a catchall for modules that are not specific to this application, and don't 
depend on any other packages
- common.db - low-level database access modules
- cb.data - application-specific database access - the data objects and data access objects that the 
application works with
- cb.import - modules that import legacy data into the application
- cb.writer - modules that generate files
- cb.gui - GUI components
- cb.app - application-level drivers and helpers

Anyway, the point is, if you organize your modules according to what they do, rather than by who 
uses them, you might make a structure that is less chaotic.

HTH
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-17 Thread Kent Johnson
Jacob S. wrote:
Hey, could you give an example?
I'll try...
Here is range with three explicit arguments
 >>> range(1, 10, 2)
[1, 3, 5, 7, 9]
Here is range with the arguments supplied in a list; it does the same thing
 >>> args = [1, 10, 2]
 >>> range(*args)
[1, 3, 5, 7, 9]
Here is an example with zip(). zip() normally takes multiple arguments, this makes it use elements 
of a single list:
 >>> l=[ [1,2], [3,4], [5,6] ]
 >>> zip(*l)
[(1, 3, 5), (2, 4, 6)]

Kent
Thanks,
Jacob

apply() is deprecated; it has been replaced by 'extended call syntax'.
Instead of
  apply(fn, args, kwds)
you can now write
  fn(*args, **kwds)
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-17 Thread Kent Johnson
Jacob S. wrote:
Thank you!
Wait, though.
How do I do this?
def differentnoofvars(*args,**kwargs):  ## By the way, is it **kwargs or
**kwds?
Call it what you like, it's an ordinary function parameter. kwds is commonly used but you can use 
kwargs.
print kwargs
another(kwargs)
Should be another(**kwargs). If you call another(kwargs) then kwargs will be an ordinary parameter 
of another and another would be defined as
def another(kwargs):
  ...

def another(**kwargs):
for x,y in kwagrs.items():
print "%s = %s" % (x,y)
a = ['a=2','f=3','t=[1,2,3]']  ## A list of kwargs that I want to send
Should be a dict, the **kwds parameter is a dict mapping keywords to values
a = {'a':2, 'f':3, 't':[1,2,3]}
There really are two different and complementary things going on here, at the point of call and at 
the point of function definition.

At the point of call, you can pass a dictionary instead of using explicit, named parameters. For 
example, given a function test() defined like this:
 >>> def test(a, b):
 ...  print a, b

you can call it with ordinary named arguments:
 >>> test(a='foo', b='bar')
foo bar
Or you can pass it a dictionary with the named arguments, using extended 
calling syntax:
 >>> d= {'a':'foo', 'b':'bar'}
 >>> test(**d)
foo bar
Inside the function, if you have a **kwds parameter, it will receive a dict containing any keyword 
arguments not explicitly declared. This allows you to pass keyword parameters that you don't 
anticipate when the function is defined. For example,

 >>> def test2(a, **kwds):
 ...   print a
 ...   for k,v in kwds.items():
 ... print k,v
 >>> test2(1)  # No keywords
1
 >>> test2(a=1)# a is a declared parameter so kwds is empty
1
 >>> test2(1, b=2, c=3) # b and c are passed in kwds
1
c 3
b 2
Kent
individually to differentnoofvars
differentnoofvars(a)

Hey, could you give an example?
Thanks,
Jacob

apply() is deprecated; it has been replaced by 'extended
call syntax'.
Instead of
  apply(fn, args, kwds)
you can now write
  fn(*args, **kwds)
Kent
Here is a quick example I came up with:

def spam(*args, **kwargs):
... print "Here are the args you supplied:"
... for item in args:
... print item
... print
... print "Here are the kwargs you supplied:"
... for key,value in kwargs.items():
... print key, '=', value
...
spam(1,'a','eggs',s=0, p=1, a=2, m=3)
Here are the args you supplied:
1
a
eggs
Here are the kwargs you supplied:
a = 2
p = 1
s = 0
m = 3
In the case of the spam() function, 1, 'a', and 'eggs' are all put into
the sequence args (not sure if it is a list or tuple).  The key/value
pairs are bundled into the dictionary kwargs.  The arguments have to be
given in the right order though:

spam(t=1, b=1, 'this', 'will', 'fail')
Traceback (SyntaxError: non-keyword arg after keyword arg
HTH!
Christian
http://www.dowski.com



___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dbcp module

2004-12-17 Thread Kent Johnson
The recipe you cite has the pp() function and an example of its use. It sounds like that is what you 
want.

Kent
Rene Bourgoin wrote:
Ive been learning to interact with databases using python and i was looking for 
ways to return a SELECT  query result in a plain format. what i mean by plain 
format is :

name numberaddress
Fred Smith   2125553243 1 main st 


All the pratices ive done return the results in tuples or tuples within tuples.
(('fred smith','2125553243','1 main st'))

I saw some examples on activestate that use the dbcp module and import the pp ( 
pretty print ) function and the results from the examples were in the format i 
was looking for. just straight strings in a tabular format. no tuples.


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

 --- On Fri 12/17, Danny Yoo < [EMAIL PROTECTED] > wrote:
From: Danny Yoo [mailto: [EMAIL PROTECTED]
To: [EMAIL PROTECTED]
 Cc: [EMAIL PROTECTED], [EMAIL PROTECTED]
Date: Fri, 17 Dec 2004 16:13:57 -0800 (PST)
Subject: Re: [Tutor] dbcp module

On Fri, 17 Dec 2004, Rene Bourgoin wrote:> Yes i believe im looking for the python version of the Jakarta databse> connection pool!!Hi Rene,I haven't looked at this too closely yet, but 
there are projects out therefor connection pools.  For example:http://sqlrelay.sourceforge.net/Some prominent Python projects, though, appear to use their own homebrewedconnection pools.  Zope appears to do 
this:http://zdp.zope.org/projects/zfaq/faq/DatabaseIntegration/954522163SQLObject maintains its own database pool:http://wiki.sqlobject.org/connectionsbut also refers to 'DBPool.py':
http://jonpy.sourceforge.net/dbpool.htmlI'm not sure if one database pooling solution has emerged as a dominantone yet, though.Good luck to you!
___
No banners. No pop-ups. No kidding.
Make My Way your home on the Web - http://www.myway.com
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] least squares

2004-12-17 Thread Kent Johnson
Have you tried contacting the author of the Scientific package? His email address is on the main web 
page.

Kent
mdcooper wrote:
Hi Danny,
Thanks for the reply - I was purposely vague just to see what people would ask 
for.

The code uses LinearAlgebra.py from Numeric and LeastSquares.py from 
Scientific.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] maximum value in a Numeric array

2004-12-10 Thread Kent Johnson
Are you using numarray? If so, there appears to be a max method of an array, so 
you can try
b = array([[1,2],[3,4]])
b.max()
Note that your method of finding the max row, then finding the max in the row, will not in general 
give the correct result. Sequences are compared lexicographically - the first elements are compared, 
and only if they match will the second elements be compared. Using plain lists:

>>> b=[ [3,2], [1,4] ]
>>> max(b)
[3, 2]
>>> max(max(b))
3
You can use a list comprehension to do what you want
>>> max([max(l) for l in b])
4
or in Python 2.4 you can use a generator expression and avoid creating the 
intermediate list:
>>> max(max(l) for l in b)
4
Kent
Ertl, John wrote:
All,
I am trying to get the maximum value in a 2-D array.  I can use max but it
returns the 1-D array that the max value is in and I then I need to do max
again on that array to get the single max value.
There has to be a more straightforward way...I have just not found it.

b = array([[1,2],[3,4]])
max(b)
array([3, 4])
c = max(b)
max(c)
4
I could also flatten the array to 1 D first then do max but the array I am
going to be working with is fairly large.
Thanks 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-15 Thread Kent Johnson
Brian van den Broek wrote:
I've begun to wonder if I am overlooking a 
improvement similar to that in DogWalker's suggestion. As an example of 
the sort of thing I have been doing:

import datetime
def is_leap_year(year):
'''-> boolean
Returns True or False as year is, or is not, a leap year.
'''
is_leap = True
try:
datetime.date(year, 2, 29)
except ValueError:
is_leap = False
return is_leap
I would write
def is_leap_year(year):
try:
datetime.date(year, 2, 29)
return True
except ValueError:
return False
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about function inside of function

2010-01-10 Thread Kent Johnson
On Sat, Jan 9, 2010 at 8:03 AM, spir  wrote:

> Do you realize the inner func will be redefined before each call? Meaning in 
> your case n calls x n outer loops x n inner loops.
>   def f() ...
> is actually a kind of masked assignment
>   f = function()...

That's true, but it is pretty inexpensive. The heavy lifting is at
compile time when a code object is created. Wrapping this as a
function is fast.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on "import foobar" vs "from foobar import *"

2010-01-10 Thread Kent Johnson
On Sat, Jan 9, 2010 at 3:50 AM, spir  wrote:
> Lie Ryan dixit:
>
>> only use "from module import *" if the
>> module was designed for such use
>
> In most cases, this translates to: the imported module defines __names__, 
> which holds the list of names (of the objects) to be exported. Check it.
> Below, a,b,c,f,g,X,Y are defined, but only c,g,Y are exported. This means 
> "from mod import *" will only import these names. Without __names__ defined, 
> it would import all.\

That should be __all__, not __names__

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] composing one test suite from two test cases

2010-01-11 Thread Kent Johnson
On Sun, Jan 10, 2010 at 10:44 PM, Tom Roche  wrote:
>
> How to create a single unittest test suite class that runs all methods
> from multiple TestCase classes? Why I ask:
>
> I'm trying to relearn TDD and learn Python by coding a simple app.
> Currently the app has 2 simple functional classes, Pid and TallyPid,
> and 2 very simple testcases, PidTests and TallyPidTests:
>
> http://www.unc.edu/~tr/courses/ENVR400/Pid.py
> http://www.unc.edu/~tr/courses/ENVR400/PidTests.py
> http://www.unc.edu/~tr/courses/ENVR400/Tally.py
> http://www.unc.edu/~tr/courses/ENVR400/TallyPidTests.py

> Before I continue, I'd like to create a single suite, in a separate
> cfile file/module (e.g. AllTests.py), that will run both testcases
> (PidTests.py and TallyPidTests.py). Unfortunately I have not been able
> to do this! which surprises me, since creating such a suite in JUnit
> is trivial.  Can someone show me how to create this suite in python?
> (FWIW the python version=2.5.2: downlevel, I know, but the box also
> needs to run ArcGIS.)

The supported way to do this is to create a test suite. There is an
example here:
http://docs.python.org/library/unittest.html#organizing-test-code

In your case I think AllTests.py would look something like

import unittest
from PidTests import PidTests
from TallyPidTests import TallyPidTests

class AllTests(unittest.TestCase):
  def suite():
suite1 = unittest.TestLoader().loadTestsFromTestCase(PidTests)
suite2 = unittest.TestLoader().loadTestsFromTestCase(TallyPidTests)
return unittest.TestSuite([suite1, suite2])


However I don't recommend this style of organizing tests. I prefer
using nose for test discovery, it saves the work of creating all the
aggregating suites. I think py.test also has a test discovery
component. In Python 2.7 the unittest module will finally have it's
own test discovery.
http://somethingaboutorange.com/mrl/projects/nose/0.11.1/finding_tests.html
http://docs.python.org/dev/library/unittest.html#test-discovery

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] what is the equivalent function to strtok() in c++

2010-01-11 Thread Kent Johnson
On Mon, Jan 11, 2010 at 2:33 AM, sudhir prasad  wrote:
> hi,
> what is the equivalent function to strtok() in c++,
> what i need to do is to divide a line into different strings and store them
> in different lists,and write them in to another file

To split on a single character or a fixed sequence of characters use
str.split(). To split on any one of a collection of characters use
re.split().

Note that if you pass multiple characters to str.split(), the string
is split on occurrences of the multiple character string, not on
occurrences of any character in the string. So for multiple character
arguments, str.split() is not equivalent to strtok().

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2010-01-11 Thread Kent Johnson
On Mon, Jan 11, 2010 at 12:33 AM, VacStudent  wrote:
> I would like to get a python book, how and where to get one?

Amazon.com? Or lots of free resources online.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] composing one test suite from two test cases

2010-01-11 Thread Kent Johnson
On Mon, Jan 11, 2010 at 8:53 AM, Tom Roche  wrote:

> Kent Johnson Mon, 11 Jan 2010 06:42:39 -0500

>> However I don't recommend this style of organizing tests. I prefer
>> using nose for test discovery, it saves the work of creating all the
>> aggregating suites.
>
> I've heard of Nose and am planning to try it, but for now I thought
> I'd "do the simplest thing that could possibly work."

That would be nose, IMO, because you don't have to write any code at
all beyond your individual tests.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numpy unexpected result: subtraction of cell values

2010-01-11 Thread Kent Johnson
On Mon, Jan 11, 2010 at 2:02 PM, Carnell, James E
 wrote:

>> I want to subtract the Red Value in an array cell from a neighboring
>> Red Value cell.
>>
>> >>> pictArray[39][4]    #pixel at 39 4
>> array([150, 140, 120], dtype=unint8)
>>
>> >>> pictArray[39][5]    #pixel at 39 5
>> array([160, 150, 120], dtype=unint8)
>>
>> >>> pictArray[39][4][0] #red pixel
>> 150
>>
>> >>> pictArray[39][5[0]  #neighboring red pixel
>> 160
>>
>> >>> pictArray[39][4][0] - pictArray[39][5][0]
>> 246  # <---  ???  vs -10
>>
>> How do I get the number -10? Does this have to do with the dtype?

>     - pictArray[39][4][0] - pictArray[39][5][0] = 246  is where I am
> getting stuck

I guess the subtraction is happening on unsigned values, which can't
represent -10. Try
int(pictArray[39][4][0]) - int(pictArray[39][5][0])

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] samples on sort method of sequence object.

2010-01-12 Thread Kent Johnson
On Tue, Jan 12, 2010 at 9:39 AM, Make Twilight  wrote:

>  I can understand how to use parameters of cmp and reverse,except the
> key parameter...
>  Would anyone give me an example of using sort method with key parameter?

http://personalpages.tds.net/~kent37/kk/7.html
Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] samples on sort method of sequence object.

2010-01-13 Thread Kent Johnson
On Wed, Jan 13, 2010 at 2:21 PM, Stefan Behnel  wrote:
> Hugo Arts, 13.01.2010 15:25:
>>
>> Here is my solution for the general case:
>>
>> from itertools import groupby
>> def alphanum_key(string):
>>    t = []
>>    for isdigit, group in groupby(string, str.isdigit):
>>        group = ''.join(group)
>>        t.append(int(group) if isdigit else group)
>>    return t
>
> Note that this won't work in Py3, where integers and strings are not
> ordered, i.e. not comparable w.r.t the < and > operators.

It will work fine if all the list items have the same format which I
would think is the most common case.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Keeping a list of attributes of a certain type

2010-01-14 Thread Kent Johnson
On Wed, Jan 13, 2010 at 9:24 PM, Guilherme P. de Freitas
 wrote:
> Hi everybody,
>
> Here is my problem. I have two classes, 'Body' and 'Member', and some
> attributes of 'Body' can be of type 'Member', but some may not. The
> precise attributes that 'Body' has depend from instance to instance,
> and they can be added or deleted. I need any instance of 'Body' to
> keep an up-to-date list of all its attributes that belong to the class
> 'Member'. How do I do this?

If you want to keep track of attributes as they are added and deleted,
you should override __setattr__() and __delattr__() in your Body
class.
http://docs.python.org/reference/datamodel.html#customizing-attribute-access
Here is a simple example:

In [4]: class LogAttributes(object):
   ...: def __setattr__(self, name, value):
   ...: print 'setting', name, 'to', value, type(value)
   ...: object.__setattr__(self, name, value)
   ...: def __delattr__(self, name):
   ...: print 'removing', name
   ...: object.__delattr__(self, name)

In [5]: l = LogAttributes()

In [6]: l.foo = 'bar'
setting foo to bar 

In [7]: l.foo
Out[7]: 'bar'

In [8]: del l.foo
removing foo

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Keeping a list of attributes of a certain type

2010-01-14 Thread Kent Johnson
On Wed, Jan 13, 2010 at 11:15 PM, Guilherme P. de Freitas
 wrote:
> Ok, I got something that seems to work for me. Any comments are welcome.
>
>
> class Member(object):
>    def __init__(self):
>        pass
>
>
> class Body(object):
>    def __init__(self):
>        self.members = []
>
>    def __setattr__(self, obj, value):
>        if isinstance(value, Member):
>            self.members.append(obj)
>            object.__setattr__(self, obj, value)
>        else:
>            object.__setattr__(self, obj, value)

That's fine but there is no need to duplicate the object.__setattr__() call:
   def __setattr__(self, obj, value):
   if isinstance(value, Member):
   self.members.append(obj)
   object.__setattr__(self, obj, value)

>    def __delattr__(self, obj):
>        if isinstance(getattr(self, obj), Member):
>            self.members.remove(obj)
>            object.__delattr__(self, obj)
>        else:
>            object.__delattr__(self, obj)

Same here.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching in a file

2010-01-15 Thread Kent Johnson
On Fri, Jan 15, 2010 at 4:24 AM, Paul Melvin
 wrote:
> Hi,
>
> Thanks very much to all your suggestions, I am looking into the suggestions
> of Hugo and Alan.
>
> The file is not very big, only 700KB (~2 lines), which I think should be
> fine to be loaded into memory?
>
> I have two further questions though please, the lines are like this:
>
>                                 src="/m/I/I/star.png" />
>                        Revenge
> (2011)
>
> 
> 
>                         class="ageVeryNew">5 days 
> 
> 
>                         class="ageVeryNew">65 minutes 
>
> Etc with a chunk (between each NEW) being about 60 lines, I need to extract
> info from these lines, e.g. /browse/post/5354361/ and Revenge (2011) to pass
> back to the output, is re the best option to get all these various bits,
> maybe a generic function that I pass the search strings too?

You might be better off using an HTML parser such as BeautifulSoup or lxml.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Keeping a list of attributes of a certain type

2010-01-15 Thread Kent Johnson
On Fri, Jan 15, 2010 at 3:43 PM, Guilherme P. de Freitas
 wrote:
> Ok, I checked the answers you all gave me, and the suggestions seem to be 2:
>
> a. Compute the list of members on the fly, with a list comprehension
> that looks up stuff on self.__dict___;
>
> b. Stay with my solution, but substituting the unnecessary "if-else"
> by a simple "if". In sum, maintain a list of members that is updated
> whenever a member is added or removed.
>
> Which one is better? I am new to all this, so please correct me if I
> am wrong. It seems that (a) is better if you do a lot of
> adding/removing members operations compared to the number of lookups
> to the "members" list. Otherwise, (b) is better. Right?

Personally (b) feels more direct and robust. There is no guarantee
that attributes are stored in self.__dict__, they can be in __slots__
or delegated to some other container. For example, here is a class
with no __dict__:

In [1]: class Foo(object):
   ...: __slots__ = ['bar']
   ...: def __setattr__(self, name, value):
   ...: print 'set', name, 'to', value
   ...: object.__setattr__(self, name, value)

In [2]: f=Foo()

In [3]: f.bar = 'baz'
set bar to baz

In [4]: f.__dict__
---
AttributeErrorTraceback (most recent call last)

C:\Project\(misc)\MangoDB\ in ()

AttributeError: 'Foo' object has no attribute '__dict__'

Granted if you have control over all the classes this won't happen but
still...relying on __dict__ makes me nervous.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smtp project

2010-01-17 Thread Kent Johnson
On Sun, Jan 17, 2010 at 3:45 PM, Kirk Z Bailey  wrote:
> I am writing a script that will send an email message. This will run in a
> windows XP box. The box does not have a smtp server, so the script must
> crete not merely a smtp client to talk to a MTA, it must BE one for the
> duration of sending the message- then shut off, we don't need no bloody
> op0en relays here!

Is there no SMTP server available on another machine? Can you send
email from a regular email client (e.g. Thunderbird)?

> I am RTFM and having some heavy sledding, can I get an Elmer on this?

An Elmer?

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smtp project

2010-01-18 Thread Kent Johnson
On Sun, Jan 17, 2010 at 9:57 PM, Kirk Z Bailey  wrote:

> There is no smtp server available, these are the cards I am delt; can you
> advise on how to play them?

A couple of possibilities:
- I'm no expert on SMTP but don't the MTAs talk SMTP to each other on
port 25? Could you use smtplib to talk to the remote MTA on port 25?

- The std lib contains a simple SMTP server in smtpd.py

- Lamson is a more robust SMTP server
http://lamsonproject.org/

- Twisted has SMTP support
http://twistedmatrix.com/trac/wiki/TwistedMail

Kent

PS Please Reply All to reply on list.

> Kent Johnson wrote:
>>
>> On Sun, Jan 17, 2010 at 3:45 PM, Kirk Z Bailey 
>> wrote:
>>>
>>> I am writing a script that will send an email message. This will run in a
>>> windows XP box. The box does not have a smtp server, so the script must
>>> crete not merely a smtp client to talk to a MTA, it must BE one for the
>>> duration of sending the message- then shut off, we don't need no bloody
>>> op0en relays here!
>>
>> Is there no SMTP server available on another machine? Can you send
>> email from a regular email client (e.g. Thunderbird)?
>>
>>> I am RTFM and having some heavy sledding, can I get an Elmer on this?
>>
>> An Elmer?
>>
>> Kent
>>
>>
>
> --
> end
>
> Very Truly yours,
>                 - Kirk Bailey,
>                   Largo Florida
>
>                       kniht
>                      +-+
>                      | BOX |
>                      +-+
>                       think
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python workspace - IDE and version control

2010-01-19 Thread Kent Johnson
On Mon, Jan 18, 2010 at 4:17 PM, Alan Gauld  wrote:

> I use plain old RCS for version control because its just me working on the
> code.

Wow. You should take a look at Mercurial. It is so easy to set up a
Mercurial repository for a local project - just
hg init # create a repository
hg st # show what will be checked in

hg add # mark new files as to be added
hg ci -m "Initial checkin" # the actual checkin

and voila! you have a version-controlled project!

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python workspace - IDE and version control

2010-01-19 Thread Kent Johnson
On Tue, Jan 19, 2010 at 9:12 AM, Andreas Kostyrka  wrote:

> The cool part about git that I've not yet replicated with hg is git add -p
> which allows you to seperate out
> different changes in the same file.

Sounds like the record and crecord extensions come close, anyway:
http://mercurial.selenic.com/wiki/RecordExtension
http://mercurial.selenic.com/wiki/CrecordExtension

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keeping track of the present line in a file

2010-01-21 Thread Kent Johnson
On Thu, Jan 21, 2010 at 1:57 AM, sudhir prasad  wrote:
> hi,
> is there any other way to keep track of line number in a file other than
> fileinput.filelineno()

With enumerate():

for line_number, line in enumerate(open('myfile.txt')):
  # etc

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Still searching in html files

2010-01-21 Thread Kent Johnson
On Thu, Jan 21, 2010 at 4:03 AM, Paul Melvin
 wrote:

> The code is at http://python.codepad.org/S1ul2bh7 and the bit I would like
> some advice on is how to get the sorted data and where to put it.

Generally the code seems a bit disorganized, consider breaking it into
functions. There is a fair amount of deadwood you could delete. Also
it will be more readable if you move the initialization of variables
closer to where they are used.

> Currently I use a temporary list to store the data before writing it to
> another, is this OK? (lines 45 onwards)

for chunk in u.split(searchText):
temp.append(chunk)

u.split() already returns a sequence, there is no need for this loop.
You could just write
temp = u.split(searchText)
though you might think of a more descriptive name.

for item in temp[1:]:
temp2 = []
temp2.append(findLink(item))
temp2.append(findTitle(item))
temp2.append(findSize(item))
cleaned.append(temp2)

This could be written more concisely without temp2:
  cleaned.append( [ findLink(item), findTitle(item), findSize(item) ] )

or even put the whole thing into a single list comprehension (though
this is perhaps too dense):
cleaned = [ [ findLink(item), findTitle(item), findSize(item) ] for
item in u.split(searchText)[1:] ]

I think I would write it as
items = u.split(searchText)[1:]
cleaned = [ [ findLink(item), findTitle(item), findSize(item) ] for
item in items ]

> I want to expand the program to give some output which the user can interact
> with, e.g. ‘which of this information do you want me to get?’ and the user
> would choose.  Does anyone have any tips on this? Can I just use things like
> raw_input and lists?

That's fine, just separate out the data acquisition from the user
input and processing.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] combinatorics problem: assembling array

2010-01-21 Thread Kent Johnson
On Thu, Jan 21, 2010 at 4:06 AM, markus kossner  wrote:
> Dear Pythonics,
> I have a rather algorithmic problem that obviously made a knot in my brain:
>
> Assume we have to build up all the arrays that are possible if we have a
> nested array
> containing an array of integers that are allowed for each single position.
> For example
> the nested array
> (
> (1,2,3,89),
> (3,5,8),
> (19,30,7,100,210,1,44)
> )
> would define all the arrays of length  3  that can be  enumerated  using the
> array of  possible numbers  for each position.

See itertools.product():
http://docs.python.org/library/itertools.html#itertools.product

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] combinatorics problem: assembling array

2010-01-21 Thread Kent Johnson
On Thu, Jan 21, 2010 at 8:07 AM, Kent Johnson  wrote:
> On Thu, Jan 21, 2010 at 4:06 AM, markus kossner  wrote:
>> Dear Pythonics,
>> I have a rather algorithmic problem that obviously made a knot in my brain:
>>
>> Assume we have to build up all the arrays that are possible if we have a
>> nested array
>> containing an array of integers that are allowed for each single position.
>> For example
>> the nested array
>> (
>> (1,2,3,89),
>> (3,5,8),
>> (19,30,7,100,210,1,44)
>> )
>> would define all the arrays of length  3  that can be  enumerated  using the
>> array of  possible numbers  for each position.
>
> See itertools.product():
> http://docs.python.org/library/itertools.html#itertools.product

Here is an example:
In [1]: values = (
   ...: (1,2,3,89),
   ...: (3,5,8),
   ...: (19,30,7,100,210,1,44)
   ...: )

In [2]: from itertools import product

In [3]: list(product(*values))
Out[3]:
[(1, 3, 19),
 (1, 3, 30),
 (1, 3, 7),
...
 (2, 3, 19),
 (2, 3, 30),
...
 (89, 8, 210),
 (89, 8, 1),
 (89, 8, 44)]

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The magic parentheses

2010-01-24 Thread Kent Johnson
On Sun, Jan 24, 2010 at 12:08 PM, Alan Gauld  wrote:
>
> "Hugo Arts"  wrote
>
> print "this is {0}".format("formatted")
>>
>> this is formatted
>
> Caveat:
> this style only works in Python 3.0 upwards  (or maybe in 2.6/2.7?)

It's in 2.6
http://docs.python.org/library/stdtypes.html#str.format

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] length of a string? Advice saught

2010-01-28 Thread Kent Johnson
On Wed, Jan 27, 2010 at 6:57 PM, Alan Gauld  wrote:
> read() functions usually have an optional buffersize parameter
> set to a "reasonable" size. If you try to read more than that it
> will be truncated. This is explained in the read() documentation
> for files.

?? files have a buffer size that sets how much is read from the disk
at once; I don't think it affects how much is read by file.read(). The
docs for that say,
"If the size argument is negative or omitted, read all data until EOF
is reached."

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] multiply and sum two lists with list comprehension?

2010-01-28 Thread Kent Johnson
On Thu, Jan 28, 2010 at 1:22 AM, Muhammad Ali  wrote:
>
> Hi,
>
> I am multipliying two lists so that each of list As elements get multiplied
> to the corresponding list Bs. Then I am summing the product.
>
> For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after
> multiplication and then sum it to get 12. I can do it using map like this:
>
> sum(map(lambda i,j:i*j, A, B))

You don't need a lambda, use operator.mul():
sum(map(operator.mul, A, B))

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hash value input

2010-01-29 Thread Kent Johnson
On Fri, Jan 29, 2010 at 8:03 AM, spir  wrote:

> I recently discovered that Lua uses the data's address (read: id) as input to 
> the hash func. This allows Lua tables (a kind of more versatile associative 
> array) to use _anything_ as key, since the id is guaranteed not to change, 
> per definition.
> [Aside this consideration, hashing addresses ensures a constant type as input 
> (so allows a specific efficient hash method) and the simplest possible one.]

This sounds like a bad idea to me. You generally want key lookup to be
based on value, not identity. For example, if I say

d = dict()
d['key'] = value

and later
print d['key']

I want this to print 'value' regardless of whether I use the same
instance of the string 'key' in both cases.

Maybe Lua has some mechanism for ensuring that this can't happen?

In general, for a hash table to work as expected, two keys that are
equal in value should have the same hash value. Here is an explanation
of why (for Java, but it pretty much applies to any hash table
implementation):
http://www.javaworld.com/javaqa/2002-06/01-qa-0621-hashtable.html

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hash value input

2010-01-29 Thread Kent Johnson
On Fri, Jan 29, 2010 at 1:20 PM, Rich Lovely  wrote:

> I've played with this a little.  The following class was quite handy for this:
>
> class BrokenHash(object):
>    def __init__(self, hashval):
>        self.hashval = hashval
>    def __hash__(self):
>        return self.hashval
>
> It basically implements the python hashable interface, but in a manner
> that is "broken" - it allows you control over what the object points
> to.
>
> From this, we can tell that chaning the value of an object's hash
> changes its "bucket":
>
 b = BrokenHash(1)
 d = {b:1}
 b.hashval=2
 d[b]
> Traceback (most recent call last):
>  File "", line 1, in 
> KeyError: <__main__.BrokenHash object at 0x657d70>
>
> But it's more than just the objects hash:
>
 b2 = BrokenHash(hash("foo"))
 hash(b2) == hash("foo")
> True
 d2 = {b2: "bar", "foo": "baz"}
 print d2
> {<__main__.BrokenHash object at 0x657e10>: 'bar', 'foo': 'baz'}
>
> (If they both fell into the same bucket, d2['foo'] would overwrite d2[b2]

Only if they compared equal. Placement and retrieval of items in hash
tables depends on both the hash value and equality comparisons. The
hash value determines the bucket, equality is used to disambiguate
keys with the same hash value.

> It appears to be some combination of identity and hash.  It is not,
> however, dependant on type:
>
 b3 = BrokenHash(hash("foo")) #same hash as b2

Same hash but not equal.

Kent

 d2[b3]
> Traceback (most recent call last):
>  File "", line 1, in 
> KeyError: <__main__.BrokenHash object at 0x657e90>
>
> Don't know if that's helped at all.
>
> --
> Rich "Roadie Rich" Lovely
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hash value input

2010-01-30 Thread Kent Johnson
On Sat, Jan 30, 2010 at 4:56 AM, spir  wrote:

> I'm surprised of this, for this should create as many indexes (in the 
> underlying array actually holding the values) as there are integer keys. With 
> possibly huge holes in the array. Actually, there will certainly be a 
> predefined number of indexes N, and the integers be further "modulo-ed" N. Or 
> what?
> I would love to know how to sensibly chose the number of indexes. Pointers 
> welcome (my searches did not bring any clues on the topic).

Wikipedia has an extensive article on hash tables.

For details of the Python implementation, there are many comments in the source:
http://svn.python.org/view/python/trunk/Objects/dictobject.c?view=markup

and more implementation notes here:
http://svn.python.org/view/python/trunk/Objects/dictnotes.txt?view=markup

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parse text file

2010-02-01 Thread Kent Johnson
On Mon, Feb 1, 2010 at 6:29 AM, Norman Khine  wrote:

> thanks, what about the whitespace problem?

\s* will match any amount of whitespace includin newlines.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parse text file

2010-02-02 Thread Kent Johnson
On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine  wrote:

> here are the changes:
>
> import re
> file=open('producers_google_map_code.txt', 'r')
> data =  repr( file.read().decode('utf-8') )

Why do you use repr() here?

> get_record = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""")
> get_title = re.compile(r"""(.*)<\/strong>""")
> get_url = re.compile(r"""a href=\"\/(.*)\">En savoir plus""")
> get_latlng = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""")
>
> records = get_record.findall(data)
> block_record = []
> for record in records:
>        namespace = {}
>        titles = get_title.findall(record)
>        for title in titles:
>                namespace['title'] = title


This is odd, you don't need a loop to get the last title, just use
  namespace['title'] = get_title.findall(html)[-1]

and similarly for url and latings.

Kent


>        urls = get_url.findall(record)
>        for url in urls:
>                namespace['url'] = url
>        latlngs = get_latlng.findall(record)
>        for latlng in latlngs:
>                namespace['latlng'] = latlng
>        block_record.append(namespace)
>
> print block_record
>>
>> The def of "namespace" would be clearer imo in a single line:
>>    namespace = {title:t, url:url, lat:g}
>
> i am not sure how this will fit into the code!
>
>> This also reveals a kind of name confusion, doesn't it?
>>
>>
>> Denis
>>
>>
>>
>>
>> 
>>
>> la vita e estrany
>>
>> http://spir.wikidot.com/
>> ___
>> Tutor maillist  -  tu...@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to pass data to aother function from a class?

2010-02-02 Thread Kent Johnson
On Tue, Feb 2, 2010 at 8:04 AM, Zheng Jiekai  wrote:
> I'm beginning my python learning. My python version is 3.1
>
> I‘v never learnt OOP before.
> So I'm confused by the HTMLParser
>
> Here's the code:
 from html.parser import HTMLParser
 class parser(HTMLParser):
> def handle_data(self, data):
>  print(data)
>
 p = parser()
 page = """TitleI'm a paragraph!"""
 p.feed(page)
> Title
> I'm a paragraph!
>
>
> I'm wondering if I can pass the data generated by ' handle_data' to a
> function instead of just print the data.

Sure. In fact print() is a function. Just replace print(data) with
my_function(data).

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parse text file

2010-02-02 Thread Kent Johnson
On Tue, Feb 2, 2010 at 9:33 AM, Norman Khine  wrote:
> On Tue, Feb 2, 2010 at 1:27 PM, Kent Johnson  wrote:
>> On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine  wrote:
>>
>>> here are the changes:
>>>
>>> import re
>>> file=open('producers_google_map_code.txt', 'r')
>>> data =  repr( file.read().decode('utf-8') )
>>
>> Why do you use repr() here?
>
> i have latin-1 chars in the producers_google_map_code.txt' file and
> this is the only way to get it to read the data.
>
> is this incorrect?

Well, the repr() call is after the file read. If your data is latin-1
you should decode it as latin-1, not utf-8:
data = file.read().decode('latin-1')

Though if the decode('utf-8') succeeds, and you do have non-ascii
characters in the data, they are probably encoded in utf-8, not
latin-1. Are you sure you have latin-1?

The repr() call converts back to ascii text, maybe that is what you want?

Perhaps you put in the repr because you were having trouble printing?

It smells of programming by guess rather than a correct solution to
some problem. What happens if you take it out?

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parse text file

2010-02-02 Thread Kent Johnson
On Tue, Feb 2, 2010 at 1:39 PM, Norman Khine  wrote:
> On Tue, Feb 2, 2010 at 4:19 PM, Kent Johnson  wrote:
>> On Tue, Feb 2, 2010 at 9:33 AM, Norman Khine  wrote:
>>> On Tue, Feb 2, 2010 at 1:27 PM, Kent Johnson  wrote:
>>>> On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine  wrote:

>>>> Why do you use repr() here?

>>
>> It smells of programming by guess rather than a correct solution to
>> some problem. What happens if you take it out?
>
> when i take it out, i get an empty list.
>
> whereas both
> data = repr( file.read().decode('latin-1') )
> and
> data = repr( file.read().decode('utf-8') )
>
> returns the full list.

Try this version:

data = file.read()

get_records = re.compile(r"""openInfoWindowHtml\(.*?\ticon:
myIcon\n""", re.DOTALL).findall
get_titles = re.compile(r"""(.*)<\/strong>""").findall
get_urls = re.compile(r"""a href=\"\/(.*)\">En savoir plus""").findall
get_latlngs = 
re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\n\s*(\-?\d+\.\d*)\)""").findall

then as before.

Your repr() call is essentially removing newlines from the input by
converting them to literal '\n' pairs. This allows your regex to work
without the DOTALL modifier.

Note you will get slightly different results with my version - it will
give you correct utf-8 text for the titles whereas yours gives \
escapes. For example one of the titles is "CGTSM (Satére Mawé)". Your
version returns

{'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804',
'-79.649735'), 'title': 'CGTSM (Sat\\xe9re Maw\\xe9)'}

Mine gives
{'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804',
'-79.649735'), 'title': 'CGTSM (Sat\xc3\xa9re Maw\xc3\xa9)'}

This is showing the repr() of the title so they both have \ but note
that yours has two \\ indicating that the \ is in the text; mine has
only one \.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parse text file

2010-02-02 Thread Kent Johnson
On Tue, Feb 2, 2010 at 4:56 PM, Norman Khine  wrote:
> On Tue, Feb 2, 2010 at 10:11 PM, Kent Johnson  wrote:

>> Try this version:
>>
>> data = file.read()
>>
>> get_records = re.compile(r"""openInfoWindowHtml\(.*?\ticon:
>> myIcon\n""", re.DOTALL).findall
>> get_titles = re.compile(r"""(.*)<\/strong>""").findall
>> get_urls = re.compile(r"""a href=\"\/(.*)\">En savoir plus""").findall
>> get_latlngs = 
>> re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\n\s*(\-?\d+\.\d*)\)""").findall
>>
>> then as before.
>>
>> Your repr() call is essentially removing newlines from the input by
>> converting them to literal '\n' pairs. This allows your regex to work
>> without the DOTALL modifier.
>>
>> Note you will get slightly different results with my version - it will
>> give you correct utf-8 text for the titles whereas yours gives \
>> escapes. For example one of the titles is "CGTSM (Satére Mawé)". Your
>> version returns
>>
>> {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804',
>> '-79.649735'), 'title': 'CGTSM (Sat\\xe9re Maw\\xe9)'}
>>
>> Mine gives
>> {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804',
>> '-79.649735'), 'title': 'CGTSM (Sat\xc3\xa9re Maw\xc3\xa9)'}
>>
>> This is showing the repr() of the title so they both have \ but note
>> that yours has two \\ indicating that the \ is in the text; mine has
>> only one \.
>
> i am no expert, but there seems to be a bigger difference.
>
> with repr(), i get:
> Sat\\xe9re Maw\\xe9
>
> where as you get
>
> Sat\xc3\xa9re Maw\xc3\xa9
>
> repr()'s
> é == \\xe9
> whereas on your version
> é == \xc3\xa9

Right. Your version has four actual characters in the result - \, x,
e, 9. This is the escaped representation of the unicode representation
of e-acute. (The \ is doubled in the repr display.)

My version has two bytes in the result, with the values c3 and a9.
This is the utf-8 representation of e-acute.

If you want to accurately represent (i.e. print) the title at some
later time you probably want the utf-8 represetation.
>
>>
>> Kent
>>
>
> also, i still get an empty list when i run the code as suggested.

You didn't change the regexes. You have to change \\t and \\n to \t
and \n because the source text now has actual tabs and newlines, not
the escaped representations.

I know this is confusing, I'm sorry I don't have time or patience to
explain more.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with strings

2010-02-03 Thread Kent Johnson
On Wed, Feb 3, 2010 at 8:19 AM, NISA BALAKRISHNAN
 wrote:
> hi
>
> I am very new to python.
> I have a string for example : 123B     new Project
> i want to separate 123B as a single string and new  project as another
> string .
> how can i do that.
> i tried using partition but couldnt do it

str.split() is the thing to use. By default it splits on any white space:

In [1]: s = "123B new Project"

In [2]: s.split()
Out[2]: ['123B', 'new', 'Project']

You can tell it to only split once (the None argument means "split on
white space"):
In [5]: s.split(None, 1)
Out[5]: ['123B', 'new Project']

The result is a list; you can assign each element to a variable:
In [6]: first, second = s.split(None, 1)

In [7]: first
Out[7]: '123B'

In [8]: second
Out[8]: 'new Project'

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] language aid

2010-02-04 Thread Kent Johnson
On Thu, Feb 4, 2010 at 5:43 AM, Owain Clarke  wrote:

> My question is, that if I proceed like this I will end up with a single list
> of potentially several hundred strings of the form "frword:engword". In
> terms of performance, is this a reasonable way to do it, or will the program
> increasingly slow down?

Python can easily handle lists of several hundred items.

You might be interested in googling "Python flash card" to see what
others have done.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Kent Johnson
On Thu, Feb 4, 2010 at 12:11 PM, Serdar Tumgoren  wrote:

> I just noticed, however, that in the comments section of the
> ActiveState recipe that someone is getting incorrect results for
> certain numbers (11 and 12, specifically).
>
> But when I use the code on my own machine it still works fine. So I
> was hoping that you all could help me "crowdsource" the issue. If you
> have the time and inclination, could you look at the code and tell me
> if and where I've gone wrong? And of course, if there's a simpler way
> to perform the conversion I'd be glad to update the recipe.  I
> certainly don't want something out in the wilds of the Web that's
> incorrect, inelegant or just plain confusing.
>
> Here's the link to the recipe:
>
> http://code.activestate.com/recipes/576888/

Perhaps the code on activestate is not a correct copy of what you are
running? The conditional at line 23 extends all the way to line 35 -
the end of the function - so if value % 100/10 == 1 no more code is
executed and None is returned.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Kent Johnson
On Thu, Feb 4, 2010 at 1:09 PM, Kent Johnson  wrote:
> On Thu, Feb 4, 2010 at 12:11 PM, Serdar Tumgoren  wrote:

>> Here's the link to the recipe:
>>
>> http://code.activestate.com/recipes/576888/
>
> Perhaps the code on activestate is not a correct copy of what you are
> running? The conditional at line 23 extends all the way to line 35 -
> the end of the function - so if value % 100/10 == 1 no more code is
> executed and None is returned.

If I delete line 33 and move lines 34 and 35 left to match line 23
then the tests pass.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with cursors please

2010-02-04 Thread Kent Johnson
On Thu, Feb 4, 2010 at 12:47 PM, Alan Harris-Reid
 wrote:
> Hi,
>
> I have a SQLite cursor which I want to traverse more than once, eg...
> for row in MyCursor:
>   method1(row)
>  then later...
> for row in MyCursor:
>   method2(row)
>  Method2 is never run, I guess because the pointer is at the bottom of the
> row 'stack' after the first 'for' loop
>
> How can I move the pointer back to the top of the stack?  Or do I have to
> reload the cursor first?

Either reload the cursor or use fetchall() to get the results into a
list and iterate the list.

rows = MyCursor.fetchall()
for row in rows;
  ...


Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Kent Johnson
On Thu, Feb 4, 2010 at 1:21 PM, Serdar Tumgoren  wrote:
>> Perhaps the code on activestate is not a correct copy of what you are
>> running? The conditional at line 23 extends all the way to line 35 -
>> the end of the function - so if value % 100/10 == 1 no more code is
>> executed and None is returned.
>>
>
> Here is the code that I'm running locally (hopefully the formatting
> doesn't get screwed up):
>
> def ordinal(value):
>    """
>    Converts an integer to it's ordinal as a string.
>    For example 1 to "1st", 2 to "2nd", 3 to "3rd", etc.
>    """
>    try:
>        value = int(value)
>    except ValueError:
>        return value
>
>    if value % 100/10 <> 1:
>        if value % 10 == 1:
>            ord = u"%d%s" % (value, "st")
>            return ord
>        elif value % 10 == 2:
>            ord = u"%d%s" % (value, "nd")
>            return ord
>        elif value % 10 == 3:
>            ord = u"%d%s" % (value, "rd")
>            return ord
>        else:
>            ord = u"%d%s" % (value, "th")
>            return ord
>    else:
>        ord = u"%d%s" % (value, "th")
>        return  ord

There is no need to duplicate the last 'else' clause. All the previous
cases return so just make it fall through to the general case:

   if value % 100/10 <> 1:
   if value % 10 == 1:
   ord = u"%d%s" % (value, "st")
   return ord
   elif value % 10 == 2:
   ord = u"%d%s" % (value, "nd")
   return ord
   elif value % 10 == 3:
   ord = u"%d%s" % (value, "rd")
   return ord

   ord = u"%d%s" % (value, "th")
   return  ord

If you want value % 100/10 to give the same result in Python 2.6 and
Python 3 you can use value % 100//10 which will always use integer
division.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variable: From input and output

2010-02-04 Thread Kent Johnson
On Thu, Feb 4, 2010 at 1:19 PM, ssiverling  wrote:

> So I have been working on this example for a little while.  I looked for the
> answer before posting.  I tried to use two raw inputs, then use
> sys.stdout.write, to add them together.  However I think I might need to use
> a variable.  Any help would be appreciated.  Thank you in advance.

What have you done so far? If you show us some code we can better help you.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variable: From input and output

2010-02-05 Thread Kent Johnson
On Thu, Feb 4, 2010 at 5:39 PM, ssiverling  wrote:
>
>
> I uploaded a file.  I know it's not very impressive.

Where did you upload it?

For short programs you can just include them in your email.

Also, please don't top-post, and please subscribe to the list.

Kent
>
>
> Kent Johnson wrote:
>>
>> On Thu, Feb 4, 2010 at 1:19 PM, ssiverling  wrote:
>>
>>> So I have been working on this example for a little while.  I looked for
>>> the
>>> answer before posting.  I tried to use two raw inputs, then use
>>> sys.stdout.write, to add them together.  However I think I might need to
>>> use
>>> a variable.  Any help would be appreciated.  Thank you in advance.
>>
>> What have you done so far? If you show us some code we can better help
>> you.
>>
>> Kent
>> ___
>> Tutor maillist  -  tu...@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> http://old.nabble.com/file/p27460922/psy psy
> --
> View this message in context: 
> http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27460922.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if item.find(extension)!= -1: -- what's the -1?

2010-02-06 Thread Kent Johnson
On Sat, Feb 6, 2010 at 11:35 AM, David  wrote:
> Hello again,
>
> in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes
> frequent use of the term -1 in his code, but doesn't tell to what aim. For
> want of search terms Google is not helpful. Could someone please enlighten
> me by means of a one-liner as a reply?
>
> Example Code:
>
> for item in filelist:
>        if item.find(extension)!= -1:
>            snaplist.append(item)

Wayne has explained the -1; I will add that a more idiomatic way to
write this is

for item in filelist:
  if extension in item:
snaplist.append(item)

or using a list comprehension (assuming snaplist starts out empty):

snaplist = [ item for item in filelist if extension in item ]

Assuming extension is a file extension, I would actually use
endswith() to filter the items:

snaplist = [ item for item in filelist if item.endswith(extension) ]

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rstrip in list?

2010-02-09 Thread Kent Johnson
On Tue, Feb 9, 2010 at 10:28 AM, Ken G.  wrote:
> I printed out some random numbers to a list and use 'print mylist' and
> they came out like this:
>
> ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n']

How are you generating this list? You should be able to create it
without the \n. That would be better than stripping them out.

> I was using 'print mylist.rstrip()' to strip off the '\n'
>
> but kept getting an error of :
>
> AttributeError: 'list' object has no attribute 'rstrip'
>
> My memory must be hazy but I thought I had it working several months ago.
>
> Any idea or suggestion?

Use a list comprehension or map():

In [1]: l = ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n']

In [2]: [ i.rstrip() for i in l ]
Out[2]: ['102', '231', '463', '487', '555', '961']

In [3]: map(str.rstrip, l)
Out[3]: ['102', '231', '463', '487', '555', '961']

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rstrip in list?

2010-02-09 Thread Kent Johnson
On Tue, Feb 9, 2010 at 11:09 AM, Ken G.  wrote:
>
> Kent Johnson wrote:
>
> On Tue, Feb 9, 2010 at 10:28 AM, Ken G.  wrote:
>
>
> I printed out some random numbers to a datafile and use 'print mylist' and
> they came out like this:
>
> ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n']
>
>
> How are you generating this list? You should be able to create it
> without the \n. That would be better than stripping them out.
>
>
> I inputting some random numbers into a database and then created a list
> and appended the list as it read the database.

If you show the code for this perhaps we can figure out where the
newlines are coming from.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] NameError: global name 'celsius' is not defined (actually, solved)

2010-02-10 Thread Kent Johnson
On Tue, Feb 9, 2010 at 10:00 PM, David  wrote:
> Hi guys,
>
> I just wrote this message, but after restarting ipython all worked fine.
> How is it to be explained that I first had a namespace error which, after a
> restart (and not merely a new "run Sande_celsius-main.py"), went away? I
> mean, surely the namespace should not be impacted by ipython at all!?

Python caches modules (in sys.modules). When you run inside of
ipython, you are not restarting the interpreter so you don't get a
clean module cache. This has implications for multi-module
development.

Suppose you have

# module.py
animls = ['cat', 'dog' ] # note the misspelling

# main.py
import module
print module.animals

If you "run main.py" you will get a NameError and the erroneous
module.py will be cached in the module cache. If you correct module.py
and again "run main.py" you will get the same error because module.py
has not been reloaded.

A couple of work-arounds-
- run main.py from a command line or some other way that gives it a
fresh interpreter
- from ipython command line, or in main.py
  import module
  reload(module)

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Error :Attempt to overwrite cell" while using xlwt to create excel sheets

2010-02-10 Thread Kent Johnson
On Wed, Feb 10, 2010 at 6:47 AM, nikunj badjatya
 wrote:

> I commented out the "raise Exception" statement in Row.py library
> module.
> Here's the (line no. 150 ) of Row.py which i have edited:
>
>   def insert_cell(self, col_index, cell_obj):
>         if col_index in self.__cells:
>             if not self.__parent._cell_overwrite_ok:
>                 msg = "Attempt to overwrite cell: sheetname=%r rowx=%d
> colx=%d" \
>                     % (self.__parent.name, self.__idx, col_index)
>                 #raise Exception(msg)
> #*commented to avoid error.
>             prev_cell_obj = self.__cells[col_index]
>             sst_idx = getattr(prev_cell_obj, 'sst_idx', None)
>             if sst_idx is not None:
>                 self.__parent_wb.del_str(sst_idx)
>         self.__cells[col_index] = cell_obj
>
> The excel sheet creation code now works fine.
>
> My question is, Instead of manually goin to /usr/lib/.../row.py and
> commenting out the line, Can this be done through few lines of code in
> my program itself. ??

Looking at the code above, you can see that the exception is raised
only if self.__parent._cell_overwrite_ok is False. So there is an
option to allow overwriting.

>From the error message it appears that self.__parent is a Worksheet.
Looking at the source code for Worksheet.py, the __init__() method
does have an optional cell_overwrite_ok= parameter. This parameter is
also available in Workbook.add_sheet(). So if you pass
cell_overwrite=True to add_sheet() you should be OK.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string to list

2010-02-10 Thread Kent Johnson
On Wed, Feb 10, 2010 at 6:26 AM, Owain Clarke  wrote:
> Please excuse the obviousness of my question (if it is), but I have searched
> the documentation for how to generate a list e.g. [(1,2), (3,4)] from a
> string "[(1,2), (3,4)]". I wonder if someone could point me in the right
> direction.

Python 2.6 and later contain the function ast.literal_eval() which is
the safe way to do this.
http://docs.python.org/library/ast.html#ast.literal_eval

In [15]: import ast

In [16]: ast.literal_eval("[(1,2), (3,4)]")
Out[16]: [(1, 2), (3, 4)]

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string to list

2010-02-10 Thread Kent Johnson
On Wed, Feb 10, 2010 at 8:32 AM, Owain Clarke  wrote:
> My son was doing a statistics project in which he had to sort some data by
> either one of two sets of numbers, representing armspan and height of a
> group of children - a boring and painstaking job.  I came across this piece
> of code:-
>
> li=[[2,6],[1,3],[5,4]]  # would also work with li=[(2,6),(1,3),(5,4)]
> li.sort(key=lambda x:x[1] )
> print li
>
> It occurred to me that I could adapt this so that he could input his data at
> the command line and then sort by x:x[0] or x:x[1].  And I have not
> discovered a way of inputting a list, only strings or various number types.

I would do this by reading the data from a file, that way the data
entry is simpler, easier to check and correct, easy to reuse, etc..
Create a file that looks like this:
2 6
1 3
5 4

Read it with code like

f = open('data.txt')
data = []
for line in f:
line_data = [ int(x) for x in line.split() ]
data.append(line_data)

or if you like map() and one-line list comprehensions:
data = [ map(int, line.split()) for line in open('data.txt') ]

Then you can sort & process data to your hearts content.

You could also just hard-code the data into your program as a literal list.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   6   7   8   9   10   >