OT--Shuffling, was Re: invert or reverse a string... warning this is a rant

2006-10-19 Thread J. Clifford Dyer
Demel, Jeff wrote:

 > P.S.  How about a string.shuffle() method that splits the string in half
 > into two new strings str1 and str2, and then recompiles the string by
 > alternating one character from each str1 and str2 as it goes?  Like
 > shuffling cards.  ;)

Jeff,

To my mind that would be the exact opposite of shuffling a deck of 
cards.  In your case, each time, you know exactly which stack the card 
comes from, but not which card out of the stack.  When you shuffle 
cards, it's more like you know exactly which card is coming next off of 
each stack, you just don't know which stack it's pulling from next.

import random

def shuffle(seq):
midpoint = len(seq)/2
stack1 = seq[:midpoint]
stack2 = seq[midpoint:]
shuffled = []
while stack1 and stack2:
next = random.choice((stack1, stack2))
shuffled.append(next.pop())
if stack1:
shuffled.extend(stack1)
else:
shuffled.extend(stack2)
return shuffled
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default location while open an Excel file

2006-10-24 Thread J. Clifford Dyer
Try this:

 >>> import os
 >>> os.getcwd()
'C:\\Python24'

I ran it from the interpreter.  Dunno what it does from a script in an 
arbitrary location.  YMMV.

Cheers,
Cliff

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


Re: Simple python + html + from --> to python script

2006-10-24 Thread J. Clifford Dyer
A good starting place would be the documentation on python.org.

In this case, the python library reference would have been helpful:

http://docs.python.org/lib/lib.html

Cheers,
Cliff


flit wrote:
> Man
> Very thanks...
> I really try to find some source of good and simple and nothing..
> Many thanks you are a great help!
> 
> Steve Holden wrote:
>> flit wrote:
>>> Hello All,
>>>
>>> I am trying to get information from a form and send it to a python
>>> script without success..
>>> Here is my objective:
>>>
>>> User enters data in form --> form send variables to python script -->
>>> script runs and output result.
>>>
>>> the form code
>>>
>>> Entre com
>>> os dados 
>>>
>>> Entre com os dados 
>>> Vai magraum 
>>>
>>> In my script.py
>>>
>>> What I should have to print
>>> something like
>>>
>>> Hello the data1 + data 2 = 
>>>
>>> ?
>>>
>>> Maybe I am stumbling in something very simple, but I cannot find some
>>> working example, and I am totally confused...
>>> Thanks in advance
>>>
>> Untested, without error checking. Caveat emptor:
>>
>> import cgi
>> import cgitb; cgitb.enable() # optional error handling
>>
>> form = cgi.FieldStorage()
>>
>> d1 = form["data1"].value
>> d2 = form["data2"].value
>>
>> print """\
>> Content-type: text/plain
>>
>> Hello: the data were: %s and %s""" % (d1, d2)
>>
>> regards
>>   Steve
>> --
>> Steve Holden   +44 150 684 7255  +1 800 494 3119
>> Holden Web LLC/Ltd  http://www.holdenweb.com
>> Skype: holdenweb   http://holdenweb.blogspot.com
>> Recent Ramblings http://del.icio.us/steve.holden
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting by item_in_another_list

2006-10-25 Thread J. Clifford Dyer
ZeD wrote:
> Paul Rubin wrote:
> 
>>> A = [0,1,2,3,4,5,6,7,8,9,10]
>>> B = [2,3,7,8]
>>>
>>> desired_result = [2,3,7,8,0,1,4,5,6,9,10]
>> How about:
>>
>>   desired_result = B + sorted(x for x in A if x not in B)
> 
> this. is. cool.
> 

Cool, yes, but I'm not entirely sure it does what the OP wanted.  Partly 
because I'm not entirely sure what the OP wanted.  Counter example:

Given these variables:

A = [0,1,2,3,4,5,6,8,9,10]  # Note 7 is missing
B = [2,3,7,8]

which of the following should the function yield?

desired_result = [2,3,7,8,0,1,4,5,6,9,10]
desired_result2 = [2,3,8,0,1,4,5,6,9,10]

The fact that we are ostensibly sorting A makes me thing it should be 
the latter, but the example given was ambiguous.  If we are in fact 
looking for desired_result2, maybe we should use:

result = [ x for x in B if x in A ] + [ x for x in A if X not in B ]

or like the sibling post suggests: substitute set(A) and set(B) for the 
"in" argument in each comprehension.

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


Re: Simple python + html + from --> to python script

2006-10-25 Thread J. Clifford Dyer
Good point.  I forget sometimes, because that's how I learned, but I 
came in with some background in other scripting languages, so I guess I 
knew what I was looking for.

Thanks.

Cliff

flit wrote:
> Sorry but for a totally newbie the lib doccumentation doesnt help..
> The target audience for the docs are for "grown ups" programmers..
> I think I will do some tutorial, in baby steps...
> 
> J. Clifford Dyer wrote:
>> A good starting place would be the documentation on python.org.
>>
>> In this case, the python library reference would have been helpful:
>>
>> http://docs.python.org/lib/lib.html
>>
>> Cheers,
>> Cliff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting by item_in_another_list

2006-10-25 Thread J. Clifford Dyer
Right you are.  I was a bit hasty.

Many thanks.

Cliff


Paul McGuire wrote:
> 
> From the original post:
> 
> "I have two lists, A and B, such that B is a subset of A."
> 

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


Re: How to Split Chinese Character with backslash representation?

2006-10-27 Thread J. Clifford Dyer
Paul McGuire wrote:
> "Wijaya Edward" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> Hi all,
>>
>> I was trying to split a string that
>> represent chinese characters below:
>>
>>
> str = '\xc5\xeb\xc7\xd5\xbc'
> fields2 = split(r'\\',str)
> 
> There are no backslash characters in the string str, so split finds nothing 
> to split on.  I know it looks like there are, but the backslashes shown are 
> part of the \x escape sequence for defining characters when you can't or 
> don't want to use plain ASCII characters (such as in your example in which 
> the characters are all in the range 0x80 to 0xff). 

Moreover, you are not splitting on a backslash; since you used a 
r'raw_string', you are in fact splitting on TWO backslashes.  It looks 
like you want to treat str as a raw string to get at the slashes, but it 
isn't a raw string and I don't think you can directly convert it to one. 
  If you want the numeric values of each byte, you can do the following:

Py >>> char_values = [ ord(c) for c in str ]
Py >>> char_values
[ 197, 235, 199, 213, 188 ]
Py >>>

Note that those numbers are decimal equivalents of the hex values given 
in your string, but are now in integer format.

On the other hand, you may want to use str.encode('gbk') (or whatever 
your encoding is) so that you're actually dealing with characters rather 
than bytes:

Py >>> str.decode('gbk')

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 str.decode('gbk')
UnicodeDecodeError: 'gbk' codec can't decode byte 0xbc in position 4: 
incomplete multibyte sequence
Py >>> str[0:4].decode('gbk')
u'\u70f9\u94a6'

Py >>> print str[0:4].decode('gbk')
烹钦
Py >>> print str[0:4]
ÅëÇÕ

OK, so gbk choked on the odd character at the end.  Maybe you need a 
different encoding, or maybe your string got truncated somewhere along 
the line

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

Re: question about True values

2006-10-27 Thread J. Clifford Dyer
I do see how mapping to Truth/Falsehood is more natural, and I do 
believe that one of the great things about python is that it feels 
natural in so many ways, and hence makes it easy to produce code, but 
the one thing that Ms. Creighton points out that I can't get past is 
that Python, even with its bool type, *still* evaluates somethingness 
and nothingness, and True and False are just numbers with hats on.

 >>> True + 3
4
 >>> bool(True-1)
False
 >>> bool(True-2)
True
 >>> (10 > 5) + (10 < 5)
1

So when you say

 >>>if 10 > 5:
... print "Yes!"

Python is not evaluating the truth of the matter, but, as Ms. Creighton 
would say, the "somethingness" of that which 10 > 5 evaluates to.  (1 
aka True)

Furthermore, how do you explain this bizarreness in terms of "Truth" and 
"Falsehood?"  You have to go back to the fact that True=1 and that 
REALLY, Python is dealing with somethingness and nothingness.  It might 
not be as direct a mental connection as True/False, but it is certainly 
a more accurate one for understanding how Python works.

 >>> (1 > 0) < 1
False
 >>> 1 > 0 < 1
True
 >>> 1 > (0 < 1)
False
 >>> 10 > (0 < 1)
True

Finally, while True/False is a good mental mapping for numeric 
comparisons, take the following:

 >>> if "Cliff is a pillar of the open source community":
... print "thank you"
... else:
... print "bugger off"

bugger off

Clearly this is not true.  (Google Cliff/Dyer open source: only 11 
hits.), but the string is *something* so the if block gets evaluated.

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


Re: PROBLEM with MOD_PYTHON

2006-10-28 Thread J. Clifford Dyer
dan84 wrote:
> I don't understand this error , in the (Apache) errorlog I read this
> message :
> 
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import
> mod_python.apache.\n
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being
> used "['C:Python24python24.zip', '.DLLs', '.lib',
> '.libplat-win', '.liblib-tk',
> 'C:ProgrammiApache GroupApache2bin']".

The four backslashes look okay to me, since there are "s outside the 
list, viz:

 >>> mylist = [ r'C:\Python24' ]
 >>> mylist
['C:\\Python24']
 >>> repr(mylist)
"['C:Python24']"


Back to your question: Where is mod_python located?  Is it anywhere in 
this path?  Go to each directory/zip file, and see if you find 
mod_python.  If so, is your base directory where you think it is?  (use 
os.getcwd() to find out).  If mod_python is still not in there, where is 
it?  Now add THAT directory to your Python path.

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


Re: question about True values

2006-10-28 Thread J. Clifford Dyer
Georg Brandl wrote:
> J. Clifford Dyer wrote:
> 
>>  >>> (1 > 0) < 1
>> False
>>  >>> 1 > 0 < 1
>> True
>>  >>> 1 > (0 < 1)
>> False
>>  >>> 10 > (0 < 1)
>> True
> 
> I hope you know why this works the way it does.
> 
> Georg

Yes, I do understand why it works.  I couldn't have crafted it if I 
didn't, but my point is that the reason why it works is not explainable 
if you believe that you are dealing with booleans.  It's only 
explainable if you recognize that you are actually dealing with 
integers, and specifically, 1 and 0.  So the something/nothing dichotomy 
combined with an understanding of what the comparison operation REALLY 
does (yield a 1 or a 0) helps you understand where your result came 
from, while thinking in terms of true/false will mislead you.



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


Re: question about True values

2006-10-28 Thread J. Clifford Dyer
Steven D'Aprano wrote:
> On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote:
 >
>>> Finally, while True/False is a good mental mapping for numeric 
>>> comparisons, take the following:
>>>
>>>  >>> if "Cliff is a pillar of the open source community":
>>> print "thank you"
>>>  else:
>>> print "bugger off"
>>>
>>> bugger off
>>>

First off, even though nobody has called me on it, this example really 
prints "thank you", not "bugger off".  I got confused in my cutting and 
pasting.  Sorry about that.


>>> Clearly this is not true.  (Google Cliff/Dyer open source: only 11 
>>> hits.), but the string is *something* so the if block gets evaluated.
>>>
>>   >>> if "The above example was bollocks":
>>   ...   print "You don't know what you are talking about"
>>   ... else:
>>   ...   print "Sorry: of course you are perfectly correct"
>>   ...
>> You don't know what you are talking about
> 
> Cliff is making a point about semantics, and he's absolutely correct about
> it, although it is irrelevant since we're talking about two-value logic
> not semantics.
> 
> 
> 
> 

Thank you for the clarification Steven (D'Aprano).  To a certain level, 
I agree that semantics are important.  I hesitated about including that 
example in my post to begin with.  However, my point, and hopefully I'll 
be able to make it more clearly now, was that true/false is a useful way 
to think regarding logical statements like x == 3, but that when you are 
dealing with strings, or more accurately strings that represent 
language, you really aren't talking about truth any more, because in 
that context, truth cannot be divorced from semantics--somethingness, on 
the other hand, can.

Conceptually, you have to go through "'something' is true, and 'nothing' 
is false" before it makes sense.

On the other hand, (to play devil's advocate for a moment), when you are 
dealing with comparison operators, you have to go through "true 
statements yield something and false statements yield nothing" before it 
makes sense, or rather "yield a nothing value."  So either way you think 
about it, you have to, in some cases, mentally convert from truthiness 
to somethingness or vice versa.  I don't find it as odious to mentally 
convert the comparison operators as I do the declarative statements.  I 
don't think it's just a personal preference either, because that way 
your mental processes are in sync with the way python works.  It 
evaluates if the statement is true and yields a something value, and a 
nothing value if it's false.  You are working with the Tao of Python, if 
you'll forgive the analogy.  However thinking in terms of truth and then 
saying that all statements that exist are true works, but runs counter 
to what is going on behind the scenes.

Or maybe it doesn't, if everything's getting converted implicitly to 
bool anyway.  Maybe it is just personal preference after all.  But then 
bools are assigned "something" and "nothing" values

This stuff is tricky, but I'm enjoying trying to wrap my mind around it, 
and appreciating the comments and critiques.

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


Re: create global variables?

2006-10-30 Thread J. Clifford Dyer
Alistair King wrote:
> Hi,
> 
> is there a simple way of creating global variables within a function?
> 
> ive tried simply adding the variables in:
> 
> def function(atom, Xaa, Xab):
> Xaa = onefunction(atom)
> Xab = anotherfunction(atom)
> 
> if i can give something like:
> 
> function('C')#where atom = 'C' but not necessarly include Xaa or Xab
> 
> i would like to recieve:
> 
> Caa = a float
> Cab = another float
> 
> ive tried predefining Xaa and Xab before the function but they are
> global values and wont change within my function. Is there a simple way
> round this, even if i call the function with the variables ('C', Caa, Cab)?
> ...
> 
> some actual code:
> 
> # sample dictionaries
> DS1v = {'C': 6}
> pt = {'C': 12.0107}
> 
> def monoVarcalc(atom):
> a = atom + 'aa'
> Xaa = a.strip('\'')
> m = atom + 'ma'
> Xma = m.strip('\'')
> Xaa = DS1v.get(atom)
> Xma = pt.get(atom)
> print Xma
> print Xaa
> 
> monoVarcalc('C')
> 
> print Caa
> print Cma
> ...
> it seems to work but again i can only print the values of Xma and Xaa
> 
> ?
> 
> Alistair
> 

I suspect you are misusing the concept of a function.  In most basic 
cases, and I suspect your case applies just as well as most, a function 
should take arguments and return results, with no other communication 
between the calling code and the function itself.  When you are inside 
your function don't worry about the names of the variables outside.  I'm 
not sure exactly where your floats are coming from, but try something 
like this:

 >>> def monoVarCalc(relevant_data):
... float1 = relevant_data * 42.0
... float2 = relevant_data / 23.0
... return float1, float2

 >>> C = 2001
 >>> Caa, Cab = monoVarCalc(C)
 >>> Caa
84042.0
 >>> Cab
87.0

Notice that you don't need to use the variable C (or much less the 
string "C", inside monoVarCalc at all.  It gets bound to the name 
relevant_data instead.

Also, if you are going to have a lot of these little results lying 
around, (Cab, Cac ... Czy, Czz), you might consider making them a list 
or a dictionary instead.  I won't tell you how to do that, though.  The 
online tutorial has plenty of information on that.

http://docs.python.org/tut/tut.html


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


Re: scared about refrences...

2006-10-30 Thread J. Clifford Dyer
SpreadTooThin wrote:
> Steven D'Aprano wrote:
>> On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote:
>>
> How do I specify or create deep copies of objects that may contain
> other objects that may contain other object that may contain other
> objects
 See the `copy` module especially `copy.deepcopy()`.

>>> This appears to be the right thing to do to me.. (but what do I know?)
>> Yes, copy.deepcopy() is the thing you want.
>>
>> But remember Fredrik's advice that well-designed Python code should not
>> need to copy data structures often. I don't think I've ever needed to use
>> deepcopy, and rarely copy.copy().
>>
>> In general, functions should not modify their caller's data. So this is
>> bad practice:
>>
>> def print_list(alist):
>> """Print a sorted list"""
>> alist.sort()  # modifies the caller's data -- bad!
>> for index, value in enumerate:
>> print "Value %s at index %d" % (index, value)
>>
>> This is better:
>>
>> def print_list(alist):
>> """Print a sorted list"""
>> alist = alist[:]  # makes a local shallow copy of the list
>> alist.sort()  # safe to modify now
>> for index, value in enumerate:
>> print "Value %s at index %d" % (index, value)
>>
>> But notice that you only need a shallow copy, not a deep copy, because you
>> aren't modifying the objects within the list, only the list itself.
>>
>>
>>
>>> I tried this which more closely resembles my project but this doesn't
>>> work:
>> Unfortunately my crystal ball is back at the shop being repaired, so
>> you'll have to explain what "doesn't work" means in this case. Does it
>> raise an exception? If so, please post the exception. Does it do something
>> different from what you expected? Then what did you expect, and what did
>> it do?
>>
> I seems that some of the objects in the list don't get along well with
> deep copy..
> See my second example post that used deepcopy... When run blows up...
> 
When it blows up, is there a lot of shrapnel, or just smoke and fire? 
Is the shrapnel mostly metal, or is it plastic and glass?

In short, if we don't know what's happening, we can't help.
* Did the program spit out a bunch of text you didn't understand?
   If so, show us the text.  That text may be incomprehensible at first,
   but it contains crucial clues.

* Did it close your python window without a word?
   Tell us.

* Did your computer freeze up?
   Tell us.

If you don't tell us what went wrong *exactly*, you won't get a 
satisfactory answer.

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


Re: scared about refrences...

2006-10-30 Thread J. Clifford Dyer
SpreadTooThin wrote:
> J. Clifford Dyer wrote:
>> SpreadTooThin wrote:
>>> Steven D'Aprano wrote:
>>>> On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote:
>>>>
>>>>
>>> I seems that some of the objects in the list don't get along well with
>>> deep copy..
>>> See my second example post that used deepcopy... When run blows up...
>>>
>> When it blows up, is there a lot of shrapnel, or just smoke and fire?
>> Is the shrapnel mostly metal, or is it plastic and glass?
>>
>> In short, if we don't know what's happening, we can't help.
>> * Did the program spit out a bunch of text you didn't understand?
>>If so, show us the text.  That text may be incomprehensible at first,
>>but it contains crucial clues.
>>
>> * Did it close your python window without a word?
>>Tell us.
>>
>> * Did your computer freeze up?
>>Tell us.
>>
>> If you don't tell us what went wrong *exactly*, you won't get a
>> satisfactory answer.
>>
> 
> I would assume that looking at the code you should be able to tell..
> Silly me..  Here.. is the log.. If I were helping.. I would have cut
> and pasted the code myself and ran it.. instead of trying to interpret
> this...

I know it seems unnecessary to post the traceback when I could get the
same thing by running your code on my machine, but it's actually useful,
for a couple reasons:  First, when I run the code, I might not get an
error, or if I do, it might not be the same error you were getting, and
then we'd be on a wild goose chase.  This could be because your python
installation is goofy, or because you copied in your code incorrectly.
Shit happens, and I'd rather not even start down one of those blind
alleys.  Third, it provides a useful frame for how to look at your
code.  While a traceback might look like a big mess at first, it's
actually pretty easy to skim through once you get used to it, and it
tells me where to focus my attention in your code.

> 
> array('H', [1, 2, 3]) ['a', 'b', 'c']
> Traceback (most recent call last):
>   File
> "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
> line 1806, in runMain
> self.dbg.runfile(debug_args[0], debug_args)
>   File
> "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
> line 1529, in runfile
> h_execfile(file, args, module=main, tracer=self)
>   File
> "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
> line 590, in __init__
> execfile(file, globals, locals)
>   File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
> line 20, in __main__
> test(t)
>   File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
> line 16, in test
> t = copy.deepcopy(x)
>   File
> "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py",
> line 174, in deepcopy
> y = copier(x, memo)
>   File
> "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py",
> line 305, in _deepcopy_inst
> state = deepcopy(state, memo)
>   File
> "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py",
> line 174, in deepcopy
> y = copier(x, memo)
>   File
> "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py",
> line 268, in _deepcopy_dict
> y[deepcopy(key, memo)] = deepcopy(value, memo)
>   File
> "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py",
> line 185, in deepcopy
> y = copier(x, memo)
> TypeError: __deepcopy__() takes no arguments (1 given)
> 
> 
> 
>> Cheers,
>> Cliff
> 

Thanks, that's very helpful.  Playing with your code a bit, I narrowed 
the problem down to the array.array() structure.  Looking at 
help(array), there's a method defined called __deepcopy__, which, it 
seems, takes no arguments, while deepcopy is passing it one argument. 
Looks like a bug in the array module to me.  Maybe others with more 
experience using array will have some deeper insight.


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


Re: create global variables?-the full story

2006-11-02 Thread J. Clifford Dyer
> OK...
> 
> from the start.
> 
> im trying to develop a simple command line application for determining
> the degree of substitution (DS) on a polymer backbone from elemental
> analysis, i.e., the % weights of different elements in the
> monomer-substituent compound ( i want each element to give a result and
> heaviest atoms give the most accurate results).
> 
> most basic comp chem programs use input files but i dont know anything
> about file iteration yet and want the program to be as user friendly as
> possible..i.e. command line prompt. GUI would be great but too much for
> me at this stage
> 
> at the start of the script i have 2 dictionaries 1) containing every
> atom in the periodic table with associated isotopic average masses 2)
> containing the molecular forumla of the monomer unit...eg for cellulose
> AGU {'C': 6, 'H': 10, 'O': 5}.
> 
> the basic steps are
> 
> 1. calculate the weight percentage values for each atom in the monomer
> 2. iterate into dictionaries from DS=0 - DS=15 (0.5 step) the
> projected % values for the monomer plus substituent, for EACH atom in
> the compound.
> 3. find the (local) minimum from each dictionary/atom to give the
> appropriate DS value.
> 
> *Note* I have to iterate ALL the values as there is a non-linear
> relationship between % values and DS due to the different atomic weights
> The computer seems to cope with this in about 10 seconds with the above
> parameters and about 8 elements for the iteration step
> 

Since you have a parallel structure for each element, consider using a 
dictionary with the element names as keys:

 >>> atomicdata = {}
 >>> for element in 'C','H','U':
... atomicdata[element] = getAtomVars(element)
...
 >>> print atomicdata
{ 'C': (1, 2), 'H': (4, 5), 'U': (78, 20) }

The first value of each tuple will be your Xaa, and the second value 
will be Xma.  Do you really need to keep the names Caa, Cma, Haa, Hma 
around?  Instead of Caa, you have atomicdata['C'][0] and Cma becomes 
atomicdata['C'][1].  Completely unambiguous.  A bit more verbose, 
perhaps, but you don't have to try to sneak around the back side of the 
language to find the data you are looking for.  That's very much against 
the tao.  If you really want the names, nest dicts, but don't try to get 
the element name into the keys, because you already have that:

 >>> atomicdata = { 'C': { 'aa': 1,
...   'ma': 2},
...'H': { 'aa': 4
...   'ma': 5},
...'U': { 'aa': 78
...   'ma': 20} }

and to get from there to storing all your data for all however many 
steps, change the value of each entry in atomic data from a tuple (or 
dict) to a list of tuples (or dicts).


 >>> atomicdata = { 'C': [ (1,2), (4,6), (7,8), (20,19) ],
...'H': [ (5,7), (2,986), (3,4) ] }
 >>> atomicdata['H'].append((5,9))
 >>> atomicdata
{ 'C': [ (1, 2), (4, 6), (7, 8), (20, 19) ], 'H': [ (5, 7), (2, 986), 
(3, 4), (5, 9) ] }

You can build up those lists with nested for loops. (one tells you which 
element you're working on, the other which iteration).

The indexes of your lists, of course, will not correspond to the DS 
values, but to the step number.  To get back to the DS number, of 
course, let the index number be i, and calculate DS = i * 0.5

That should get you off and running now.  Happy pythoning!

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


Re: modules and generated code

2006-11-15 Thread J. Clifford Dyer
Nigel Rantor wrote:
> Peter Otten wrote:
>> Nigel Rantor wrote:
>>
>>> Peter Otten wrote:
 Nigel Rantor wrote:
>>
> So, if I have a tool that generates python code for me (in my case,
> CORBA stubs/skels) in a particular package is there a way of 
> placing my
> own code under the same package hierarchy without all the code 
> living in
> the same directory structure.
>>
 http://docs.python.org/lib/module-pkgutil.html
>>
>>> Yep, looks like that should work, but it doesn't. :-/
>>>
>>> Do you have any idea whether other __init__.py scripts from the same
>>> logical module will still be run in this case?
>>
>> I don't think it will.
> 
> Yeah, I am getting that impression. Gah!
> 
>>> The generated code uses its init script to pull in other code.
>>
>> You could invoke it explicitly via
>> execfile("/path/to/generated/package/__init__.py")
>> in the static package/__init__.py.
> 
> Hmm, yes, that works. It's not pretty though, it seems to be finding the 
> file relative to the current directory, I suppose writing a bit of code 
> that figures out where this package is located and modifying it won't be 
> too hard.
> 
> And, at the risk of being flamed or sounding like a troll, this seems 
> like something that should be easy to do...other languages manage it 
> quite neatly. Up until this point I was really liking my exposure to 
> Python :-/
> 
> I wonder if there is any more magic that I'm missing, the thing is the 
> pkgutil method looks exactly like what I want, except for not executing 
> the additional __init__.py files in the added directories.
> 
> Thanks for the help so far Peter, if anyone has a prettier solution then 
> I'm all ears.
> 
> Cheers,
> 
>   n
> 
> 
> 
> 
> 

Maybe I'm missing something obvious, but it sounds like you are 
over-complicating the idea of inheritance.  Do you just want to create a 
subclass of the other class?

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


Re: case insensitive dictionary

2006-11-27 Thread J. Clifford Dyer
John Henry wrote:
>print pets.keys()
> 
> should print:
> 
> "Cat", "Dog"

If you do:

Py> pets['Cat'] = 2
Py> pets['Dog'] = 3
Py> pets['DOG'] = 4
Py> pets['cat'] += 5
Py> pets.keys()

What should the result be?

"['Cat', 'Dog']" or "['cat', 'DOG']"?


That is to say, if you use a new case in redefining the values of your
case insensitive dictionary, does the key take on the new case, or will
it always and forever be the case originally given to it?

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


Re: Inheritance doesn't work

2006-12-04 Thread J. Clifford Dyer
Fredrik Lundh wrote:
> John Salerno wrote:
> 
>> How do you get that error with that code?
> 
> $ python
> 
 import os
 class foo(os):
>  pass
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: Error when calling the metaclass bases
> module.__init__() takes at most 2 arguments (3 given)
> 
> 
> 

Sure, but I think the question was more about how code that references
"MandelbrotImage could yield a stack that references MandelImage.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-19 Thread J. Clifford Dyer
Roy Smith wrote:
> In article <[EMAIL PROTECTED]>,
>  greg <[EMAIL PROTECTED]> wrote:
> 
>> Roy Smith wrote:
>>
>>> The struct does lookup by name, the tuple is inherently index based.
>> I was trying to help people understand the distinction
>> we're talking about by showing an example of the same
>> distinction in another language where it's much clearer.
>>
>> There are a great many ways in which C structs are
>> different from Python tuples, and C arrays are different
>> from Python lists. But they're not the aspects I'm
>> drawing an analogy between.
>>
>> --
>> Greg
> 
> Well, yeah, but it's kind of like saying "a tangerine and an orange are 
> very different things because one of them is like an apple and the other 
> one is like a pear" :-)

Actually, I found the distinction a bit more helpful than that--more
like saying, "a tangerine and a pear are very different things because
one of them is like an orange and the other is like an apple."  Still
not a precise definition, but a useful analogy in many ways.

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


Re: tuple.index()

2006-12-19 Thread J. Clifford Dyer
James Stroud wrote:
> Christoph Zwerschke wrote:
>> "Inhomogenous" in some meaning of the word --> tuple
> 
> I think that you have nailed it here. I don't think anyone on this list
> is capable of giving a "concrete" (as you have put it) operational
> definition of "inhomogenous". They will resort to use cases and thus
> cloud the definition with programming philosophy.
> 

How about: "A heterogenous sequence is one in which each element plays a
unique role, specific to its position in the sequence.  A homogenous
sequence is one in which position is determinative of nothing
significant other than (perhaps) order."

I'm not exactly sure what you mean by "programming philosophy."  I
suspect it does enter into the choice of which to use, (as programming
philosophy determines whether a database will have a "name" field, or
"lastname", "firstname", and "middlename" fields)  but I don't see that
this clouds the definitions, necessarily.

> So, programming philosophy, whether it will be admitted or not, is fully
> responsible for the exclusion of index() from the tuple interface.
> 

No.  Because as pointed out in another subthread, the exclusion of
index() from the tuple interface is in many ways orthogonal to the issue
of homogeneity/heterogeneity.  It's partly that, and partly that The
Maintainers have decreed that the workarounds (list(mytuple).index())
are trivial enough to obviate the need for making all the changes to the
source code, and hacking something ugly (a linear search has been
suggested) into all unsuspecting hand-rolled subscriptable objects.


> But perhaps we could take "not necessarily homogenous" to be the
> operational definition of "inhomogenous". Of course then we would have
> to define necessary...
> 
> James

I doubt the python interpreter will ever try to enforce
homogeneity/heterogeneity on lists/tuples, in part because there no good
ways of definining it syntactically, and in part because there are
certainly good reasons for breaking the rules.  As someone said: passing
lists to untrustworthy functions.  And as someone else said, *args
passes a tuple, even though it is frequently just a homogenous list of
more arguments.

Forgive me for referencing throughout the threads without proper
citation.  I've been ill all weekend, and I just don't feel like doing
it right.

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


Re: tuple.index()

2006-12-19 Thread J. Clifford Dyer
Nick Maclaren wrote:
> In article <[EMAIL PROTECTED]>,
> "J. Clifford Dyer" <[EMAIL PROTECTED]> writes:
> |> 
> |> How about: "A heterogenous sequence is one in which each element plays a
> |> unique role, specific to its position in the sequence.  A homogenous
> |> sequence is one in which position is determinative of nothing
> |> significant other than (perhaps) order."
> 
> Nope.  Sorry.  Consider the old model where an I/O list is an ordered
> sequence of strings and agents (effectively procedure calls), with no
> constraints on how those are ordered.  With your specification, that
> is neither heterogenous nor homogenous :-)

On the contrary, I think that example fits perfectly with my definition
of homogenous.  If there is no constraint on position, then what is the
position determinative of?  Order in the queue.  Nothing more.  By my
definition, homogeneous.  QED.

I'll grant, it's not exactly the most intuitive definition of
homogenous, but I think it is the most accurate for this situation.
Perhaps homogenous and heterogenous aren't the best possible words here,
but I think they work.


> 
> |> I doubt the python interpreter will ever try to enforce
> |> homogeneity/heterogeneity on lists/tuples, in part because there no good
> |> ways of definining it syntactically, and in part because there are
> |> certainly good reasons for breaking the rules.  As someone said: passing
> |> lists to untrustworthy functions.  And as someone else said, *args
> |> passes a tuple, even though it is frequently just a homogenous list of
> |> more arguments.
> 
> It's a complete delusion, because even the claimed assumption of list
> homogeneity is tantmount to saying that Python doesn't encourage (or,
> arguably, support) ANY way of using mutable heterogenous sequences
> (such as the example above).  To claim that they are inherently an
> undesirable programming practice is a clear descent into religion!
>
> I would be amused to know what Python type the "lists are intended to
> be homogenous" people use to implement mutable heterogenous sequences,
> or whether they claim that wanting such a feature is heresy :-)
> 

By my definition, how can it be mutable AND heterogenous?  If the first
element is a name, the second element is a phone number, and the third
element is an email address, and you insert an element in between the
first two elements, do you mean to tell me that the phone number, which
has moved to the third slot, is now an email address?  It doesn't make
sense.

Maybe the words are wrong.  I'm not sure.  But I think the distinction
is valid.  Furthermore, I think we "lists are intended to be homogenous"
people would say that you are perfectly welcome to use lists for other
purposes, if it suits you.  Just as you can use a string as a list.  We
don't have to be rigid to appreciate the difference.  :)


> 
> Regards,
> Nick Maclaren.
> 
> 

Blessings,
Cliff


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


Re: tuple.index()

2006-12-19 Thread J. Clifford Dyer
Nick Maclaren wrote:
> In article <[EMAIL PROTECTED]>,
> "J. Clifford Dyer" <[EMAIL PROTECTED]> writes:
> |> 
> |> On the contrary, I think that example fits perfectly with my definition
> |> of homogenous.  If there is no constraint on position, then what is the
> |> position determinative of?  Order in the queue.  Nothing more.  By my
> |> definition, homogeneous.  QED.
> |> 
> |> I'll grant, it's not exactly the most intuitive definition of
> |> homogenous, but I think it is the most accurate for this situation.
> |> Perhaps homogenous and heterogenous aren't the best possible words here,
> |> but I think they work.
> 
> Grrk.  I see what you mean.  The homogeneity is referring to the order
> and not to the types :-)

Thank you.  The more I tried to explain it, the more I was losing the
sense of the actual words "homogeneous" and "heterogenous" in this
context, but that helps me recapture it.  It made so much sense until I
tried to articulate it...

> 
> |> By my definition, how can it be mutable AND heterogenous?  If the first
> |> element is a name, the second element is a phone number, and the third
> |> element is an email address, and you insert an element in between the
> |> first two elements, do you mean to tell me that the phone number, which
> |> has moved to the third slot, is now an email address?  It doesn't make
> |> sense.
> 
> Well, I could provide an example, but they are a bit weird.  More
> seriously, consider changing a structure consisting of a name and
> telephone number, and then changing the value of the latter (not
> exactly an unreasonable requirement!)  With tuples that can't be done,
> but it makes perfect sense, and it is a mutable heterogeneous sequence
> with your definition.
>

Good example.  Of course, an immutable sequence can be made up of
mutable elements, but a string (which you'd probably use for a telephone
number or an email address) isn't one of those types.

> |> Maybe the words are wrong.  I'm not sure.  But I think the distinction
> |> is valid.  Furthermore, I think we "lists are intended to be homogenous"
> |> people would say that you are perfectly welcome to use lists for other
> |> purposes, if it suits you.  Just as you can use a string as a list.  We
> |> don't have to be rigid to appreciate the difference.  :)
> 
> Nope.  That is DEFINITELY wrong.  If you write code that abuses a
> language construct in a way that is discouraged but just happens to
> work, a couple of decades down the line it will stop working, because
> someone will change the feature.  Been there - been caught by that :-(
> 

Yeah, that could suck.  Personally, I can't picture such a basic
construct as a list or a tuple ever being given such a restrictive
meaning.  If you ask me what a list is (in python), I would never say "a
list is a homogeneous sequence."  I would say "a list is a mutable
sequence," as I believe the language reference defines it.  (No
citation).  If you then asked me why we have separate mutable and
immutable sequences, THAT's when I'd bring up homogeneity and
heterogeneity.  So I wouldn't say you were misusing the structure for
making a homogeneous tuple, as long as you didn't try to mutate it.  Or
that you were misusing a list if you really needed a mutable
heterogeneous sequence (like for changing phone numbers).  The mapping
from heterogeneous to immutable is helpful, but not perfect, nor
normative.  However, if more powerful minds disagree with me, that's
when you'd get in trouble.

Cheers,
Cliff

> 
> Regards,
> Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mod_python

2006-12-27 Thread J. Clifford Dyer
Lad wrote:
> Maxim Sloyko wrote:
>> Lad wrote:
>>> In my web application I use Apache and mod_python.
>>> I allow users to upload huge files( via HTTP FORM , using POST method)
>>> I would like to store the file directly on a hard disk and not to
>>> upload the WHOLE huge file into  server's memory first.
>>> Can anyone suggest a solution?
>> The only solution you need is Apache and mod_python :)
>> I mean,  Apache won't load a huge POST request into its memory no
>> matter what. All file uploads will be stored in temporary files. Under
>> mod_python (provided you use FieldStorage) you'll need to deal only
>> with 'file' objects.
> 
> 
>  Maxim ,
> Thank you for your reply.
> Here is an example:
> If a user uploads 100MB file ,
> what will be a consumption of memory, when the upload is complete?
> 
> Or does it mean that Apache will read a part of a file , store it in a
> temporary file, then read another part and adds this part to the
> temporary file and so on until the whole uploaded file is read?
> Thank you for the reply.
> Lad
> 

Are you working on *nix?  Try this from the shell on your server:

$ top

Then upload a 100MB file and watch the memory usage.

On Windows, I think you can do similar from Ctrl-Alt-Del, but
graphically.  Correct me if I'm wrong.

Cheers,
Cliff

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


Re: Unsubscribing from the list

2007-01-03 Thread J. Clifford Dyer
Nice move, using Perl/PHP for that.  It's always fun to piss people off
by apologizing. ;)

Cheers,
Cliff


Dotan Cohen wrote:
> On 03/01/07, Robert Kern <[EMAIL PROTECTED]> wrote:
>> He misunderstood you (as I nearly did, too). The way you phrased
>> "decided that
>> there was no futher interest on the page for me" is somewhat
>> ambiguous: it can
>> seem like it refers to the second time, not the first.
>>
> 
> Ah. Sorry. I'm getting better at confusing people :)
> 
> if ($you=="got_offended") {
>$dotan="sorry";
> }
> 
> Dotan Cohen
> 
> http://what-is-what.com/what_is/website.html
> http://lyricslist.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterate through list two items at a time

2007-01-03 Thread J. Clifford Dyer
Gabriel Genellina wrote:
> b=iter(a)
> for x in b:
>y=b.next()
>print x,y
> 

So as not to choke on odd-length lists, you could try

a = [1,2,3,4,5,6,7]
b = iter(a)
for x in b:
try:
 y=b.next()
except StopIteration:
 y=None
print x,y

Substitute in whatever for y=None that you like.

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


Re: encoding latin1 to utf-8

2007-09-10 Thread J. Clifford Dyer
On Mon, Sep 10, 2007 at 12:25:46PM -, Harshad Modi wrote regarding encoding 
latin1 to utf-8:
> Path: 
> news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!newsgate.cistron.nl!xs4all!news.glorb.com!postnews.google.com!22g2000hsm.googlegroups.com!not-for-mail
> 
> hello ,
>  I make one function for encoding latin1 to utf-8. but i think it is
> not work proper.
> plz guide me.
> 
> it is not get proper result . such that i got "Belgi???" using this
> method, (Belgium)  :
> 
> import codecs
> import sys
> # Encoding / decoding functions
> def encode(filename):
>  file = codecs.open(filename, encoding="latin-1")
>  data = file.read()
>  file = codecs.open(filename,"wb", encoding="utf-8")
>  file.write(data)
> 
> file_name=sys.argv[1]
> encode(file_name)

Some tips to help you out. 

1.  Close your filehandles when you're done with them.
2.  Don't shadow builtin names.  Python uses the name file, and binding it to 
your own function can have ugly side effects that manifest down the road.

So perhaps try the following:

import codecs

def encode(filename):
read_handle = codecs.open(filename, encoding='latin-1')
data = read_handle.read()
read_handle.close()
write_handle = codecs.open(filename, 'wb', encoding='utf-8')
write_handle.write(data)
write_handle.close()

For what it's worth though, I couldn't reproduce your problem with either your 
code or mine.  This is not too surprising as all the ascii characters are 
encoded identically in utf-8 and latin-1.  So your program should output 
exactly the same file as it reads, if the contents of the file just read 
"Belgium"

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


Re: Car-ac-systems

2007-09-11 Thread J. Clifford Dyer
On Tue, Sep 11, 2007 at 05:50:43PM +, Marc 'BlackJack' Rintsch wrote 
regarding Re: Car-ac-systems:
> 
> On Tue, 11 Sep 2007 17:42:53 +, Zentrader wrote:
> 
> > 
> > What is it about "please do not top-post" that you have difficulty
> > understanding? Or do "MVP"s feel that their time is so much more
> > valuable than anyone else's that they are free to ignore the norms?
> > 
> > Who made this the norm?
> 
> Common sense and (western) reading habits.
> 

More to the point, one or more of the mailing lists to which you are posting.  
When in Rome, do as the Romans do.  If you don't know what the Romans do, 
you're probably cross-posting too broadly.

Cheers,
Cliff

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


Re: Car-ac-systems

2007-09-11 Thread J. Clifford Dyer
On Tue, Sep 11, 2007 at 07:50:33PM +0100, John Timney (MVP) wrote regarding Re: 
Car-ac-systems:
> 
> "Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > On Tue, 11 Sep 2007 17:42:53 +, Zentrader wrote:
> >
> >> 
> >> What is it about "please do not top-post" that you have difficulty
> >> understanding? Or do "MVP"s feel that their time is so much more
> >> valuable than anyone else's that they are free to ignore the norms?
> >>
> >> Who made this the norm?
> >
> > Common sense and (western) reading habits.
> >
> >> In my travels through web-land, it appears to be the opposite.
> >
> > You must travel strange territories.  ;-)
> >
> >> Don't waste space repeating everything in every post, and it wastes
> >> everyone's time by have to go over the same thing again and again.
> >
> > That's why you trim the quoted part to the minimum to understand what one
> > is answering.  Top posting and full quoting wastes time for people who
> > want to see the context because context and answer are way apart and in 
> > the
> > wrong order so one has to scroll back and forth to keep track of the
> > discussion.
> >
> > Ciao,
> > Marc 'BlackJack' Rintsch
> 
> 
> I like top posted threads, its my preferred response method - and actually 
> also how I prefer to read a thread.  Normally, I and the thread followers 
> are familiar with a threads context - and don't need to read down to get the 
> context of a response.  Not much of a hardship really and just as I give my 
> time freely in answering a thread - everyone else can chose freely to read 
> it or ignore.
> 
> I don't though have no issues with people who chose to bottom post, or 
> respond with the full thread if its relevent, or trim it.  If the answer is 
> relevent, I'll gladly spend the time reading it from any direction.
> 
> Regards
> 
> John Timney (MVP)

Thank you for your courtesy in bottom posting that comment, in spite of your 
personal preference.  It makes the group easier to follow.  

Personally, I have nothing against top-posted comments.  What really gets my 
panties in a bunch, however, are threads in which some replies are top-posted 
and some bottom posted.  Then, in order to get the full story you end up 
bouncing back and forth through the message and trying to remember how deeply 
nested the last post was.  

Cheers, and welcome to c.l.py.

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread J. Clifford Dyer
On Wed, Sep 12, 2007 at 07:43:51AM -0700, Charles Fox wrote regarding Re: 
newbie: self.member syntax seems /really/ annoying:
> 
> Thanks guys -- yeah these two stategies (short s.varname; and explicit
> rescoping, a=self.a etc) are more or less what I was using.  That's
> still kind of annoying though.
> 
> The s.varname approach still makes numerical code much harder to read.
> 

For what it's worth, if you stick with python for a while, you will stop 
noticing the self, and be able to see what you're looking for quite clearly.  

Moreso if you use s.

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-13 Thread J. Clifford Dyer
On Thu, Sep 13, 2007 at 04:21:36PM -, Steven D'Aprano wrote regarding Re: 
newbie: self.member syntax seems /really/ annoying:
> 
> It's not just a matter of taste.
> 
> Reading comprehensibility is an objective, measurable quantity, and I 
> would bet that "(self.foo + self.bar) * self.baz" would be measurably 
> more readable on average than either of your two alternatives _even for 
> those people who claim to hate it_. 
> 

It may be measurable, but it is also contextual.  Depending on what you've been 
trained in, one way or the other might be more readable.  For a teenager in a 
major city, tagging is far more readable than a Fraktur font, but for Mad King 
Ludwig, it was certainly quite the opposite.  Objectively, measurably so, to be 
sure.  Also depending on what you are looking for in the source code.  
Readability can in most cases be enhanced by minimizing those things that serve 
only to distract from the meaning.  Hence the OP's desire to see his formulae, 
uncluttered by the word self.  Now will such a change make his code less 
readable for other python programmers who may look at it later?  Indubitably.  
But that's a different issue.

Moreover, it may be that the best solution is to stop trying for an 
object-oriented solution.  Why not use a functional programming style to 
represent mathematical functions?

Cheers,
Cliff

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


Re: plotting pixels in python

2007-09-13 Thread J. Clifford Dyer
On Thu, Sep 13, 2007 at 06:37:43PM -, [EMAIL PROTECTED] wrote regarding Re: 
plotting pixels in python:
> 
> On Sep 13, 11:22 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> > On Sep 13, 1:03 pm, [EMAIL PROTECTED] wrote:
> >
> > > hi to all
> > > I am just a beginner of python. I want to know how pixels are plotted
> > > in python. I am not intending to use PIL because I don't need to
> > > manipulate images. So is there a simple module for 2D graphics and
> > > plot pixels
> >
> > Here is a *very* simple-minded module for creating BMP files, that
> > supports drawing points, lines, and simple shapes.
> >
> > http://www.geocities.com/ptmcg/python/index.html#bmp
> >
> > -- Paul
> 
> No currently I am using a canvas from the Tkinter module
> What I actually want is to show how a line is plotted pixel by pixel
> using a delay loop. I want functions something like putpixel not
> draw_line
> 

The question to your answer can be found here:

http://catb.org/~esr/faqs/smart-questions.html

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


Re: Decimal formatting

2007-09-13 Thread J. Clifford Dyer
On Thu, Sep 13, 2007 at 01:50:51PM -0700, Harlin Seritt wrote regarding Decimal 
formatting:
> 
> Cant believe I have to post this and get help... and can't believe I
> couldnt Google it reasonably well enough... I need to take a float
> variable and have it display as a string to always have two decimal
> places:
> 
> 12. -> 12.33
> 1.0 -> 1.00
> etc...
> 
> Anyone willing to help with this one?
> 
> thanks,
> 
> Harlin
> 

f = 12.33
i = 10
f_output = "%0.2f" % f
i_output = "%0.2f" % i


Cheers,
Cliff

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


Re: recursion

2007-09-14 Thread J. Clifford Dyer

On Fri, Sep 14, 2007 at 01:40:17PM +0200, Gigs_ wrote regarding Re: recursion:
> 
> what i mean is how python knows to add all thing at the end of recursion
> 
>  >>> def f(l):
>  if l == []:
>  return []
>  else:
>  return f(l[1:]) + l[:1]
> 

The following script does exactly the same thing, except it creates print 
statements to help you figure out what's going on, and it binds f(L[1:]) to 
a variable so you can use it again.

def f(L):  # l capitalized to accentuate difference between l and 1.
print "L =", L
print "L[1:] =", L[1:]
print "L[:1] =", L[:1]
if L == []:
print "Return: ", []
return []
else:
next = f(L[1:])
print "Return: ", next, "+", L[:1], "=", next + L[:1]
return next + L[:1]

if __name__=='__main__':
print f(['A', 'B', 'C', 'D'])

Try it out.  See what happens.

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


Re: adodb with mysql - connection string syntax for filepath

2007-09-18 Thread J. Clifford Dyer
On Tue, Sep 18, 2007 at 09:32:45AM -0400, Steve Holden wrote regarding Re: 
adodb with mysql - connection string syntax for filepath:
> 
> Mridula Ramesh wrote:
> > Hi. Firstly, thank you both very much for the response!
> > 
> > Cliff, I did some more reading up about it after  you corrected me re 
> > MySQL not being a _language_  but another means of storing data (would 
> > you believe NONE of the connection tutorials actually said that?!) 
> > Anyway, now I have MySQL on my machine, and it's installed - if I say 
> > "import MySQLdb" in python prompt, it does that, but I can't see any exe 
> > in the program's folder itself: does that mean tables can only be 
> > created by code? *puzzled*
> > 
> > Steve, thank you too, I looked up the link you had given, but I do not 
> > yet know which part of that site may help me... And I am now going to 
> > struggle with Dive Into Python before attempting much else!
> > 
> > This is a nice, helpful mailing group!
> > 
> We try, though not everyone appreciates us :-)
> 
> You may find
> 
>http://www.connectionstrings.com/
> 
> more helpful.
> 
> regard
>   Steve

For non-programmatic (non-python) access, you might also look into the "MySQL 
GUI Tools" package, freely downloadable from mysql.com.

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


Re: RE Help

2007-09-21 Thread J. Clifford Dyer
On Fri, Sep 21, 2007 at 12:05:51PM -0700, [EMAIL PROTECTED] wrote regarding Re: 
RE Help:
> 
> >
> > x = re.compile('START(.*)END', re.DOTALL)
> 
> You'll want to use a non-greedy match:
> 
> x = re.compile(r"START(.*?)END", re.DOTALL)
> 
> Otherwise the . will match END as well.

The . will only consume END if there is another END to match later on in the 
string.  And then it's a question of desired fuctionality.  If the given string 
is: "abcdSTARTefgENDxyzENDhijk" do you want to match "STARTefgEND" (in which 
case you need a non-greedy match r".*?" )? or do you want to match 
"STARTefgENDxyzEND" (in which case you need a greedy match: r".*" )?

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


Re: getopt with negative numbers?

2007-09-27 Thread J. Clifford Dyer
If you can access the argument list manually, you could scan it for a negative 
integer, and then insert a '--' argument before that, if needed, before passing 
it to getopt/optparse.  Then you wouldn't have to worry about it on the command 
line. 

Cheers,
Cliff

On Thu, Sep 27, 2007 at 08:08:05PM +0200, Peter Otten wrote regarding Re: 
getopt with negative numbers?:
> 
> Casey wrote:
> 
> > On Sep 27, 1:34 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> >> optparse can handle options with a negative int value; "--" can be used
> >> to signal that no more options will follow:
> > 
> > Thanks, Peter.  getopt supports the POSIX "--" end of options indicator
> > as well, but that seems a little less elegant than being able to simply
> > set a value that tells the parser "I don't use any numeric values as
> > options, and I want to allow negative values as arguments".  At the
> > parser level implemening this would be trivial and I frankly was hoping
> > it had been implemented and it just wasn't mentioned in the spares
> > Python getopt library reference.
> 
> After a quick glance into the getopt and optparse modules I fear that both
> hardcode the "if it starts with '-' it must be an option" behaviour.
> 
> Peter
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ValueError: too many values to unpack,>>>

2007-09-27 Thread J. Clifford Dyer
On Thu, Sep 27, 2007 at 09:50:26PM +0200, Bruno Desthuilliers wrote regarding 
Re: ValueError: too many values to unpack,>>>:
> 
> Shawn Minisall a ?crit :
> > Fredrik Lundh wrote:
> > 
> >> Shawn Minisall wrote:
> >>
> >>  
> >>
> >>> Sorry, it looks like it's on the fourth line with the 3 values on 
> >>> line 4...its reading line 3 fine
> >>>
> >>> Traceback (most recent call last):
> >>>   File "", line 1, in 
> >>> main()
> >>>   File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 
> >>> 33, in main
> >>> deposit1, deposit2, deposit3 = string.split(line, "\t")
> >>> ValueError: too many values to unpack
> >>> 
> >>
> >>
> >> instead of fumbling around in the dark, try inserting a print 
> >> statement before the offending line, so you can see what you're trying 
> >> to unpack:
> >>
> >>  print string.split(line, "\t") # see what it is
> >>  deposit1, deposit2, deposit3 = string.split(line, "\t")
> >>
> >> 
> >>   
> > 
> > I did and it printed everything up until the 3rd line with 3 numbers for 
> > deposits.  I have since figured it out...the teacher put in an extra tab 
> > after the last value so python thought it was 4 values for three.  I 
> > went back into the file and deleted the extra tab after the 3rd number 
> > and saved it...now it's working fine.
> > I'm going to kill her...
> 
> You'd better learn how to deal with "this-cant-happen-here" situation, 
> because it's how it is in real-life.
> 

And preferably learn how to deal with it in your code, not in the data that's 
given to you.  I wouldn't be surprised if your teacher gave you that on 
purpose.  There's an old maxim which I think applies here: "Be liberal in what 
you accept and conservative in what you produce."

Note that you have *not* come up with code that handles the dataset given to 
you by your professor.  Do not expect full marks on this homework assignment, 
unless you go back and modify your code to handle extraneous tabs at the end of 
the line.

Cheers,
Cliff

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


Re: Select as dictionary...

2007-10-01 Thread J. Clifford Dyer
On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote regarding 
Select as dictionary...:
> 
> aia.execute("SELECT id, w from list")
> links=aia.fetchall()
> print links
> 
> and result
> [(1, 5), (2,5)...] (2 million result)
> 
> I want to see this result directly as a dictionary:
> 
> {1: 5, 2: 5 .}
> 
> How do i select in this format ?
> 
Try this:

aia.execute("SELECT id, w from list")
links=aia.fetchall()
linkdict = dict()
for k,v in links:
linkdict[k] = v
print linkdict


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


Re: Select as dictionary...

2007-10-01 Thread J. Clifford Dyer
On Mon, Oct 01, 2007 at 03:50:59PM +0200, Bruno Desthuilliers wrote regarding 
Re: Select as dictionary...:
> 
> IIRC, postgres' db-api connector (well, at least one of them - I don't 
> know which one you're using) has a DictCursor. You should find all you 
> want to know in the relevant doc.
> 

Correct me if I'm wrong, but I think the DictCursor would output the following:

[{'id': 1, 'value': 5}, {'id': 2, 'value': 5}, ...]

But the OP wanted one dict with IDs as keys:

{1: 5, 2: 5, ...}

As a side note to the OP, a better format might be:

{1: (5,), 2: (5,), ...}

Where each key keys into a tuple, in case you want to pull more than one value 
from the DB. Also, in this format, it is essential that the record used as a 
key be a primary key or uniquely indexed, in order to avoid collisions.  If you 
intend to make this code reusable, it might be worth explicitly checking for 
this, and raising an exception if it is not.

Cheers,
Cliff


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


Re: Select as dictionary...

2007-10-01 Thread J. Clifford Dyer
On Mon, Oct 01, 2007 at 10:12:04AM -0400, Carsten Haese wrote regarding Re: 
Select as dictionary...:
> 
> On Mon, 2007-10-01 at 09:57 -0400, J. Clifford Dyer wrote:
> > > 
> > Try this:
> > 
> > aia.execute("SELECT id, w from list")
> > links=aia.fetchall()
> > linkdict = dict()
> > for k,v in links:
> > linkdict[k] = v
> > print linkdict
> 
> Improvement 1: Use the fact that dict can be initialized from a sequence
> of key/value pairs:
> 
> aia.execute("SELECT id, w from list")
> linkdict = dict(aia.fetchall())
> 

This is only an improvement if the SQL query remains a list of 2-tuples.  If 
the OP wants to add more values, the more verbose version allows for easier 
extensibility.  

for k,v1,v2 in links:
linkdict[k] = (v1, v2)

Of course even better would be not to have to add variables, so maybe:

for link in links:
linkdict[link[0]] = link[1:],

which changes the output format somewhat, but keeps the access by dict keyed to 
the DB id.

> Improvement 2: Use an iterator instead of reading all rows into memory:
> 
> aia.execute("SELECT id, w from list")
> linkdict = dict(iter(aia.fetchone,None))
> 

Agreed.  A much better solution.

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


Re: problem with special built-in method __contains__,

2007-10-02 Thread J. Clifford Dyer
On Tue, Oct 02, 2007 at 11:14:38AM -, [EMAIL PROTECTED] wrote regarding 
problem with special built-in method   __contains__,:
> 
> if i have a dictionary  name number and i want toask the list
> whether a particular key already
> exists.
> 
> >>> print number
> {'octal': '1234567', 'binary': '10100101', 'decimal': '1234567890',
> 'hexadecimal': '1-9,a-f'}
> 
>  i got  error..after execute
> 
>  >>>number._contains_("test")
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> number._contains_("test")
> AttributeError: 'dict' object has no attribute '_contains_'
> 

First of all, the special methods contain a *double* underscore before and 
after the name, so it's not _contains_, it's __contains__.

Secondly, for most basic operations, you shouldn't have to use these special 
methods directly.  They are bound to other funtionality in Python.  So instead 
of:


number.__contains('test')

try the following:

'test' in number  

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-10-04 Thread J. Clifford Dyer
On Thu, Oct 04, 2007 at 04:49:50PM +0200, Wildemar Wildenburger wrote regarding 
Re: The Modernization of Emacs: terminology buffer and keybinding:
> 
> Steve Holden wrote:
> > Lawrence D'Oliveiro wrote:
> >> In message <[EMAIL PROTECTED]>, Steve
> >> Holden wrote:
> >>
> >>> Lawrence D'Oliveiro wrote:
> >>>
>  In message <[EMAIL PROTECTED]>, George Neuner
>  wrote:
> 
> > The Christian Bible says "In the beginning was the Word..."
>  Which is an English mistranslation from the Greek "logos".
> >>> So, now you're telling me that the Garden of Eden was actually a
> >>> *marketing campaign*?
> >>
> >> Different Bible book, different author, different original language.
> > 
> > So Genesis was written in Hebrew? I have no clue as to where the 
> > manuscripts were found.
> > 
> Am I missing a joke here? What are you talking about?
> 
I'm trying to figure that out myself...

> Different book? From what book would the first sentence in the Bible be, 
> if not from the first book (yeah yeah, from the publisher, haw-haw :-|)?
> 

Yeah, different book.  "In the beginning was the Word" is John's cosmology.  
Written in Greek long after Genesis, and a couple decades after Jesus was 
executed. 

Also, I wouldn't so much say that "word" is a mistranslation.  Logos does 
indeed mean "word" in common usage, it just also carries along the baggage of 
reason, "logic" (for a loose definintion of which), rationality, and so forth.  
So it's not so much inaccurate as inadequate.

> And Genesis and all other of Moe's books where written in Hebrew. No 
> doubt about that. Its (part of) the /Hebrew/ Bible, after all. 
> http://en.wikipedia.org/wiki/Torah>
> 
> I can't program with discussions like this going on ;)
> /W

For real.  Not much python in this thread.  And yet, here I am, sucked into 
posting to a thread that I've spent the past three or four days wishing would 
die

Sigh.

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


Re: RegEx question

2007-10-04 Thread J. Clifford Dyer
You *are* talking about python regular expressions, right?  There are a number 
of different dialects.  Also, there could be issues with the quoting method 
(are you using raw strings?)  

The more specific you can get, the more we can help you.

Cheers,
Cliff
On Thu, Oct 04, 2007 at 11:54:32AM -0500, Robert Dailey wrote regarding Re: 
RegEx question:
> 
>On 10/4/07, Adam Lanier <[EMAIL PROTECTED]> wrote:
> 
>  try @param\[(in|out)\] \w+
> 
>This didn't work either :(
>The tool using this regular expression (Comment Reflower for VS2005)
>May be broken...
> 
> References
> 
>1. mailto:[EMAIL PROTECTED]

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


Re: remove list elements..

2007-10-05 Thread J. Clifford Dyer
On Fri, Oct 05, 2007 at 07:27:39AM -0700, Abandoned wrote regarding remove list 
elements..:
> 
> Hi..
> I have a problem..
> list1=[11, 223, 334, 4223...] 1 million element
> list2=[22,223,4223,2355...] 500.000 element
> 
> I want to difference list1 to list2 but order very importent..
> 
> My result must be:
> list3=[11,334,...]
> 
> I do this use FOR easly but the speed very imported for me. I want to
> the fastest method please help me.
> 
> I'm sorry my bad english.
> 
> King regards..
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

If you're using a recent python, you can create a set from list2, and preserve 
order with list1 like so:

set2 = set(list2)
list3 = [ x for x in list1 if x not in set2 ]

That will speed up your access to list2 (for 500,000 scans) at the low cost of 
reading through the whole thing once.

You say order is very important, but if your order is known to be strictly 
increasing (as it appears from your sample code), you can speed up further by 
doing:

set1 = set(list1)
set2 = set(list2)
list3 = sorted(set1 - set2)


Though to tell the truth, I'm not sure this actually would be faster, since you 
access each element of list1 just once in the list comprehension version.  And 
I can't be bothered to try it out with timeit.

Cheers,
Cliff

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


Re: Python Magazine: Issue 1 Free!

2007-10-05 Thread J. Clifford Dyer
On Fri, Oct 05, 2007 at 04:11:07PM -, Grant Edwards wrote regarding Re: 
Python Magazine: Issue 1 Free!:
> 
> On 2007-10-05, Steve Holden <[EMAIL PROTECTED]> wrote:
> >>
> >>> I've just been told by the editors at Python Magazine that the
> >>> first issue is out.
> >> 
> >> The first issue is issue number 10?
> >> 
> >> That's a bit silly.
> >
> > It's the October edition. They obviously decided to make sure
> > the month numbering was consistent across the volumes.
> 
> I presumed that was the reasoning. It just seems
> counter-intuitive (and sort of un-Pythonic) to start numbering
> a sequence of objects at 10. ;)
> 

Well, it's also unpythonic to start numbering a sequence at 1, but it's clearly 
the right thing to do in this case.

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


Re: pytz has so many timezones!

2007-10-08 Thread J. Clifford Dyer
On Mon, Oct 08, 2007 at 10:41:03AM -0700, [EMAIL PROTECTED] wrote regarding Re: 
pytz has so many timezones!:
> 
> On Oct 8, 2:32 am, Sanjay <[EMAIL PROTECTED]> wrote:
> > Hi All,
> >
> > I am using pytz.common_timezones to populate the timezone combo box of
> > some user registration form. But as it has so many timezones (around
> > 400),
> 
> There are only 25 timezones: -12, -11, ... -1, 0 (GMT), +1, ... +11,
> +12.
> 
> A handful of countries set their clocks offset by a half hour,
> but those aren't timezones.
> 

I'm sorry.  By what even vaguely useful definition of "Timezone" is it not a 
timezone if it's offset by half an hour?  

> 
> The 400 you're seeing are duplications based on locality. Of the 86
> shown in Windows, all but 33 are dulplicate references to the same
> timezones.
> 
> For example, Windows has seperate listings for
> 
> Central America
> Central Time (US & Canada)
> Guadalahara, Mexico City, Monterry - New
> Guadalahara, Mexico City, Monterry - Old
> Saskatchewan
> 
> but they are all GMT-6
> 

Those are non-duplicate (and perhaps inaccurate, I'm not sure).  US time 
switches from standard to Daylight Savings earlier than Mexico, and switches 
back later, as of this year.  Reducing them to a single time zone will result 
in aberrant functionality in one or more locales.

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


Re: pytz has so many timezones!

2007-10-08 Thread J. Clifford Dyer
On Mon, Oct 08, 2007 at 01:12:32PM -0700, [EMAIL PROTECTED] wrote regarding Re: 
pytz has so many timezones!:
>  [ I wrote ]
> > Reducing them to a single time zone will result in aberrant functionality 
> > in one or more locales.
> 
> I would hardly think that's an issue on the user registration
> form the OP is trying to create.
> 

You don't think that it's an issue that the OPs users will complain about their 
time being inaccurate?  If I register in what we in the US call Eastern Time 
Zone, I don't want to have to switch to Atlantic time zone just because the 
form designer couldn't be bothered to include a time zone that actually matched 
the function of the clocks in my area.  

Pedantry about the definition of a time zone is not going to win you points 
with irate users.  

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


Re: pytz has so many timezones!

2007-10-08 Thread J. Clifford Dyer
On Mon, Oct 08, 2007 at 01:13:24PM -0700, [EMAIL PROTECTED] wrote regarding Re: 
pytz has so many timezones!:
> 
> On Oct 8, 1:03 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > On Mon, 2007-10-08 at 10:41 -0700, [EMAIL PROTECTED] wrote:
> > > For example, Windows has seperate listings for
> >
> > > Central America
> > > Central Time (US & Canada)
> > > Guadalahara, Mexico City, Monterry - New
> > > Guadalahara, Mexico City, Monterry - Old
> > > Saskatchewan
> >
> > > but they are all GMT-6
> >
> > But they could have different rules for Daylight Saving Time.
> 
> Which only matters if you're setting your clock.
> 

Maybe this is where I'm not understanding you:  Do you have another use for 
setting a timezone?  The only thing a time zone does, as far as I can tell, is 
set clocks relative to a shared conception of time.


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


Re: why did MIT drop scheme for python in intro to computing?

2007-10-09 Thread J. Clifford Dyer
On Tue, Oct 09, 2007 at 06:28:00AM -0500, Harold Ancell wrote regarding Re: why 
did MIT drop scheme for python in intro to computing?:
> 
> On Tue, 09 Oct 2007 03:28:53 -, [EMAIL PROTECTED] wrote:
> 
> >On Oct 8, 1:23 pm, [EMAIL PROTECTED] (Brian Harvey) wrote:
> 
> >> "Kjetil S. Matheussen" <[EMAIL PROTECTED]> writes:
> 
> >> >I don't think your speculations makes very much sence.
> 
> >> Amen.
> 
> >> And, in any case, there's no need to speculate.
> >> MIT has published, on their web site, pages and
> >> pages of rationale for the new curriculum.
> 
> >> The most important point, imho, is that the
> >> programming language was the /least/ important
> >> aspect of the decision.  The most important
> >> aspect was the move to an application-based
> >> (rather than topic-based) organization of the
> >> curriculum.  The details flow out of that big
> >> shift of focus.
> 
> >[ much snipped. ]
> 
> >Does scheme have a gui library?
> 
> >I really dont follow the logic.
> 
> I really REALLY hope that not a single GUI is
> constructed in 6.01-2; adding that to the load
> would be stark raving mad (look and you'll agree).
> 
> As Brian points out, languages are a means to the
> end of teaching stuff, and I wouldn't be surprised
> if not a single GUI is constructed in the entire
> required/restricted elective curriculum.  That's
> just not to the point of an EECS education that
> has to be squeezed into 4/5 years (most students
> take the combined MEng path, where the MS degree
> is terminal and leads straight to industry).
> 
> If any library was a consideration in choosing
> Python, it was the robots one for 6.01.  Note also
> that Hal helped design and teach 6.01, and fully
> supports the new curriculum.
> 
> As a total LISP/Scheme fanatic who finds parts of
> Python's syntax to be too hard for his brain (not
> the indentation, that's weird but useful and cool,
> much like S-expressions in LISP), I looked hard at
> the beginning of 6.01 where they're only teaching
> SICP.
> 
> For that purpose, Python is not "awful" (remember,
> I believe LISP is the One True Way of Computing).
> For that initial bit of SICP material, I do not
> believe the students will be handicapped.
> 
> Beyond that initial bit of material, I have no
> informed opinions.
> 
>   - Harold
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I, for one, (coming from the Python side) would be thrilled to see a rigorous 
SICP-like book published using Python as its basis.  But maybe with the new 
change of focus to application based, that won't be forthcoming.  We'll see.

Cheers,
Cliff


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


Re: pytz has so many timezones!

2007-10-09 Thread J. Clifford Dyer
On Tue, Oct 09, 2007 at 11:21:41AM -0700, [EMAIL PROTECTED] wrote regarding Re: 
pytz has so many timezones!:
> 
> The Earth says. It takes 24 hours to revolve.
> 
> > Why aren't they separated by 30minutes, or 20, or 10? Or 2 hours?
> 
> Why isn't an hour defined to be 30 minutes?
> 
> > Or why don't we have a global time?
> 
> Like UTC?
> 
> >
> > Your 25 timezones are an abstraction the same way
> 
> Not the same way at all. The 25 timezones I speak of are
> not merely an abstraction, but related to longitude.
> 
> > as are the 400 apparently in use by people all over the world
> 
> Where the correlation to longitude is much looser.
> Granted, it doesn't need to be for non-navigational
> purposes. And although governments can legislate things
> like DST, they can't legislate longitude.
> 
> > - and last time I checked, there was no
> > fundamental law in physics or such that limited the allowed or sensible
> > number of timezones...
> 
> Isn't there some law somewhere that says the circumference
> of a sphere is 360deg? Doesn't that same law mean that no two
> points on a sphere can be seperated by more than 180deg
> longitude? Doesn't that make GMT+13 non-sensible?
> 

You seem to be talking about time zones as if they are a scientific abstraction 
based on the physical layout of the earth.  They are not.  They are an 
abstraction away from true scientific (solar) time to give us regular 24 hour 
days, and to simplify calculation to make sure that trains don't run into one 
another for having left their respective stations at times based on locally 
defined solar noon.  Solar time is the only kind of time that doesn't have to 
take political considerations into account.  

GMT+13 is not non-sensible at all, if the major trade partners of the island in 
question are at GMT+12.  Imagine the confusion not being able to schedule 
meetings on monday or friday because your next door neighbor, one time zone 
away, is actually off-calendar from you by one day.  The IDL was arbitrarily 
placed in the middle of the pacific to limit this problem to as few people as 
possible, but the people of Kiribati have no reason to accept the disadvantage 
under which this (European) abstraction places them.  What would be 
non-sensible is for them to live 23 hours offset from their closest neighbors 
and family, while living a mere three hours offset from people that they have 
minimal contact with.  

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


Re: Problem with MySQL cursor

2007-10-11 Thread J. Clifford Dyer
On Thu, Oct 11, 2007 at 03:14:30PM +0200, Florian Lindner wrote regarding 
Problem with MySQL cursor:
> 
> Traceback (most recent call last):
>   File "manage.py", line 90, in ?
> addDomain(domainName)
>   File "manage.py", line 27, in addDomain
> executeSQL(sql,  DOMAIN_TABLE, DOMAIN_FIELD, domainname)
>   File "manage.py", line 22, in executeSQL
> cursor.execute(sql, args)
>   File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, in
> execute
> self.errorhandler(self, exc, value)
>   File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35,
> in defaulterrorhandler
> raise errorclass, errorvalue
> _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL
> syntax; check the manual that corresponds to your MySQL server version for
> the right syntax to use near ''domains' ('domain') VALUES ('xgm.de')' at
> line 1")
> 
> I see the error: 2 opening quotes but only 1 closing around domains. But
> where do they come from?
> 
> Note that there are no quotes at print sql % args.
> 

No, there are no double quote issues.  The first quote is provided by the error 
message, and is paired with the quote after the closed parenthesis in 
('xgm.de')'.  It is not part of your SQL.

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-18 Thread J. Clifford Dyer
On Thu, Oct 18, 2007 at 11:57:10AM -, Paul Hankin wrote regarding Re: 
Appending a list's elements to another list using a list comprehension:
> 
> Not to me: I can never remember which of a.append and a.extend is
> which. Falling back to a = a + b is exactly what you want. For
> instance:
> 
> a = (1, 2, 3)
> a += (4, 5, 6)
> 
> works, whereas:
> 
> a = (1, 2, 3)
> a.extend((4, 5, 6))
> 
> doesn't. So using += makes your code more general. There's no standard
> sequence type that has extend and not +=, so worrying that += is
> slower isn't a concern unless you're using a user-defined class. Even
> then, it's probably a mistake that should be fixed in the class rather
> than requiring .extend() to be used instead of +=.
> 

I was going to argue that in fact += is not more general, it just covers a 
different set of use cases, but then I tested my hypothesis...

>>> a = [1,2,3]
>>> b = a
>>> c = [4,5,6]
>>> d = c
>>> e = [7,8,9]
>>> a.extend(e)
>>> b
[1, 2, 3, 7, 8, 9]
>>> c += e
>>> d # I expected [4, 5, 6]
[4, 5, 6, 7, 8, 9]
>>> c = c + e # But += doesn't do the same as this
>>> c
[4, 5, 6, 7, 8, 9, 7, 8, 9]
>>> d
[4, 5, 6, 7, 8, 9]

So I learned something new.

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


Re: How can i protect text format ?

2007-10-23 Thread J. Clifford Dyer
On Tue, Oct 23, 2007 at 06:30:18AM -0700, Abandoned wrote regarding How can i 
protect text format ?:
> 
> Hi..
> I want to do a forum with python but i have a problem..
> 
> I have a  and i write:
> line 1 hi
> line 2 how r u
> 
> And then i save to this database ( colomn data type is text)
> And than it looks "line 1 hi line 2 how r u"..
> How can i protect \n characters ?
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Are you sure they're getting lost on the way into the DB?  Could they be 
getting lost on the way out?  Say... into an HTML page?

You need to pinpoint your problem more clearly to get a helpful response.

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


Re: New module for method level access modifiers

2007-10-23 Thread J. Clifford Dyer
On Tue, Oct 23, 2007 at 08:54:52PM +0200, Bruno Desthuilliers wrote regarding 
Re: New module for method level access modifiers:
> 
> TimeHorse a ?crit :
> > I have started work on a new module that would allow the decoration of
> > class methods to restrict access based on calling context.
> > Specifically, I have created 3 decorators named public, private and
> > protected.
> 
> Lord have mercy.
> 

I invented a new decorator too.  It gets rid of many of the limitations of 
python, including duck typing and hideously flat namespaces.  It's used kind of 
like this:

@java
def public_com.sun.lord.have.mercy():
pass

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


Re: Better writing in python

2007-10-24 Thread J. Clifford Dyer
On Wed, Oct 24, 2007 at 12:09:40PM -, Alexandre Badez wrote regarding 
Better writing in python:
> 
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
> 
> I think there is a better way, but I can't see how...
> 

I assume cls.dArguments is a dict, correct?

`for arg in cls.dArguments` takes each *key* for cls.dArguments and assigns it 
to arg, so the line 'if arg is True' will test the truth value of each key.  I 
assume (you haven't shown the details here) that your dict looks like this:

cls.dArguments = { 'a': True, 'b': False, 'c': True, 'd': False, '': True, 0: 
False }

and you want your for loop to do this:

lMandatory == [ 'a', 'c', '' ]
lOptional == [ 'b', 'd', 0 ]

in fact, since it's testing the truth value of the keys, not the values, you 
will get this:

lMandatory == [ 'a', 'b', 'c', 'd' ]
lOptional == [ '', 0 ]

In no particular order, of course.

Also, `if x is True:` should be written as `if x:`

Actually, come to think of it, what I said above is false, because the string 
'a' *is not* the boolean value True, per se: it is *equal to* True.  So if you 
change `if x is True:` to `if x == True:`  then everything I said above holds 
true, including that you should change `if x == True:` to `if x:`

As it stands, the only key in your dict that has a snowball's chance in key 
largo of being marked as mandatory is the boolean value True itself.

Cheers,
Cliff

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


Re: tuples within tuples

2007-10-26 Thread J. Clifford Dyer
On Fri, Oct 26, 2007 at 06:59:51AM -0700, [EMAIL PROTECTED] wrote regarding Re: 
tuples within tuples:
> 
> > Resolve *what*?  The problem isn't clear yet; at least to me.  Above you
> > say what you get.  What exactly do you want?  Examples please.
> >
> 
> 
> Sorry for my poor english, but I meant: how can I obtain a list of A
> and C starting from something like this?
> 
> (A,B,C,D)
> that could be
> ('tagA', None, [('tagB', None, ['bobloblaw], None)], None)
> but also
> ('tagA', None, description, None)
> when I don't know if C is a tuple or not?
> 
> I guess that, at least,  within the cicle I may test if C is a tuple
> or not.. And then apply the same cicle for C... and so on
> 
> Am i right?
> 
> 
> ciao
> korovev

So, to clarify the piece that you still haven't explicitly said, you want to 
keep the tag name and children of every element in your XML document.  (which 
is different from keeping (A, C) from tuple (A, B, C, D), because you want to 
modify C as well, and it's decendants.)

As a first solution, how about: 

def reduceXML(node):
if type(node) == str:
return node
else: 
return (node[0], reduceXML(node[2])

N.B. Beware of stack limitations.

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


Re: two file into a single file

2007-10-29 Thread J. Clifford Dyer
You will need to use the open() builtin for each input file, and again for the 
output file.  Documentation is available in the python tutorial here: 

http://docs.python.org/tut/node9.html#SECTION00920

You should read also the whole tutorial, and work with it until you understand 
it, but for now, that section should get you going.

Cheers,
Cliff


On Mon, Oct 29, 2007 at 09:02:30PM +0530, Beema shafreen wrote regarding two 
file into a single file:
> Delivered-To: [EMAIL PROTECTED]
> Date: Mon, 29 Oct 2007 21:02:30 +0530
> From: "Beema shafreen" <[EMAIL PROTECTED]>
> To: python-list@python.org
> Subject: two file into a single file
> Precedence: list
> List-Id: General discussion list for the Python programming language
>   
> List-Unsubscribe: ,
>   
> List-Archive: 
> List-Post: 
> List-Help: 
> List-Subscribe: ,
>   
> Errors-To: [EMAIL PROTECTED]
> 
>hi everybody,
>   I have a two file,
> file 1:
>17097
>17186
>1723
>17895
>17906
>18295
>18311
>1880
>19160
>19629
>file 2:
>17097
>17186
>1723
>17895
>17906
>18295
>18311
>1880
>19160
>19629
>how do i make into a single file..like this
>file 1 file 2
>17097  17097
>17186  17097
>17186   1880
>172317895
>17895  17895
>17906  17895
>18295  8311
>18311  188

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


Re: two files into an alternate list

2007-10-29 Thread J. Clifford Dyer
That depends:

What do you want when you have these two files:

file 1:
a
b
c

file 2:
1
2
3
4
5

Options: 
*['a',1,'b',2,'c',3,None,4,None,5]
*['a',1,'b',2,'c',3,4,5]
*['a',1,'b',2,'c',3]
*Throw an exception

And what if file 1 has more lines than file 2?

Cheers,
Cliff
1
On Mon, Oct 29, 2007 at 09:50:51PM +0530, Beema shafreen wrote regarding two 
files into an alternate list:
> Delivered-To: [EMAIL PROTECTED]
> Date: Mon, 29 Oct 2007 21:50:51 +0530
> From: "Beema shafreen" <[EMAIL PROTECTED]>
> To: python-list@python.org
> Subject: two files into an alternate list
> Precedence: list
> List-Id: General discussion list for the Python programming language
>   
> List-Unsubscribe: ,
>   
> List-Archive: 
> List-Post: 
> List-Help: 
> List-Subscribe: ,
>   
> Errors-To: [EMAIL PROTECTED]
> 
>hi everybody ,
>i have a file :
> file 1:
>1
>2
>3
>4
>5
>6
>file2:
>a
>b
>c
>d
>e
>f
>how do i make the two files into  list like this =
>[1,a,2,b,3,c,4,d,5,e,6,f]
>regards
>shafreen

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


Re: Built-in functions and keyword arguments

2007-10-29 Thread J. Clifford Dyer
On Mon, Oct 29, 2007 at 02:27:50PM +, Duncan Booth wrote regarding Re: 
Built-in functions and keyword arguments:
> 
> Bruno Desthuilliers <[EMAIL PROTECTED]> 
> wrote:
> 
> > In the second case, the name of the argument *is* 'object'. Which is not 
> > the case for the builtin len (which, fwiw, has type 
> > 'builtin_function_or_method', not 'function', so inspect.getargspec 
> > couldn't tell me more).
> > 
> >
> > While we're at it, you should avoid using builtin's names for 
> > identifiers - here, using 'object' as the arg name shadows the builtin 
> > 'object' class).
> >
> 
> I think you are being a little bit unfair here: help(len) says:
> 
> len(...)
> len(object) -> integer
> 
> Return the number of items of a sequence or mapping.
> 
> which implies that the argument to len has the name 'object' (although in 
> fact it doesn't have a name). The OP was simply asking about the difference 
> in calling conventions, not proposing to write code using 'object' as the 
> argument name.

Hmm  To my mind, that just implies that the *type* of the expected input is 
an object.  Just like the "-> integer" tells you that the type of the output is 
an integer.  If the documentation read "len(s=object) -> integer", then I would 
expect a keyword argument s typed as an object.

Now that might also be misleading, as not all objects have a length (integers, 
for example raise a TypeError).  But the documentation has to say something, 
which doesn't imply that every argument has to be a keyword.

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


Re: Built-in functions and keyword arguments

2007-10-29 Thread J. Clifford Dyer
On Mon, Oct 29, 2007 at 06:45:22PM +, Duncan Booth wrote regarding Re: 
Built-in functions and keyword arguments:
> 
> "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> 
> >> I think you are being a little bit unfair here: help(len) says:
> >> 
> >> len(...)
> >> len(object) -> integer
> >> 
> >> Return the number of items of a sequence or mapping.
> >> 
> >> which implies that the argument to len has the name 'object'
> >> (although in fact it doesn't have a name). The OP was simply asking
> >> about the difference in calling conventions, not proposing to write
> >> code using 'object' as the argument name.
> > 
> > Hmm  To my mind, that just implies that the *type* of the expected
> > input is an object.  Just like the "-> integer" tells you that the
> > type of the output is an integer.  If the documentation read
> > "len(s=object) -> integer", then I would expect a keyword argument s
> > typed as an object. 
> > 
> 
> How do you interpret:
> 
> >>> help(__import__)
> Help on built-in function __import__ in module __builtin__:
> 
> __import__(...)
> __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> 
> module
> ...
> >>> help(int)
> Help on class int in module __builtin__:
> 
> class int(object)
>  |  int(x[, base]) -> integer
> ...
> 
> Can you find any case (other than a single parameter identified as 
> 'object') where you can interpret the help string as telling you the types 
> of the parameters?

OK, good point.  Perhaps it's not so specific as the type, but certainly the 
use of name and x in the docstrings listed above only imply something about the 
character of the argument, not the name of the argument itself, which is what I 
was trying to get at.  Help documentation for keyword arguments usually shows 
the argument being used as a keyword, like the example from __import__ above.

Thanks for the correction.

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


Re: Iteration for Factorials

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: 
Iteration for Factorials:
> 
> Py-Fun wrote:
> > I'm stuck trying to write a function that generates a factorial of a
> > number using iteration and not recursion.  Any simple ideas would be
> > appreciated.
> > 
> 
> fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
> 
> hth :)
> 

Nice one.  I was trying to grok it, and started out by breaking it down:

>>> [1].__imul__(2)
[1, 1]
>>> map([1].__imul__,range(1,3))
[[1, 1], [1, 1]]

So far so good, but I tried to break it down a little more:

>>> [1].__imul__(1), [1].__imul__(2), [1].__imul__(3)
([1], [1, 1], [1, 1, 1])

Hmm.  Wasn't what I was expecting.

Then it hit me:

>>> L = [1]
>>> L.__imul__(1), L.__imul__(2), L.__imul__(3)
([1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1])

Pretty sneaky, sis.

Cheers,
Cliff

P.S.  Regards to those who lack a grounding in American pop-culture, or who are 
to young to remember the origins of "Pretty sneaky, sis."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iteration for Factorials

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: 
Iteration for Factorials:
> 
> Py-Fun wrote:
> > I'm stuck trying to write a function that generates a factorial of a
> > number using iteration and not recursion.  Any simple ideas would be
> > appreciated.
> > 
> 
> fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
> 

OK.  Now I've been sucked in.  How about this:

def fact(x):
def f(x):
if int(x) != x:
raise ValueError
elif x > 1:
return f(x-1) ** x
elif x == 1:
return 10
else:
raise ValueError
return len(str(f(x))) -1

The great part about this recursive solution is that you don't have to worry 
about the stack limit because performance degrades so quickly on the conversion 
to string!  fact(8) takes a little less than a second, fact(9) takes about a 
minute, and fact(10) takes more time than I had patience to wait for!

Cheers,
Cliff

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


Re: Iteration for Factorials

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 11:37:57AM -0700, [EMAIL PROTECTED] wrote regarding Re: 
Iteration for Factorials:
> 
> On Oct 30, 10:25 am, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> > On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: 
> > Iteration for Factorials:
> >
> >
> >
> > > Py-Fun wrote:
> > > > I'm stuck trying to write a function that generates a factorial of a
> > > > number using iteration and not recursion.  Any simple ideas would be
> > > > appreciated.
> >
> > > fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
> >
> > OK.  Now I've been sucked in.  How about this:
> >
> > def fact(x):
> > def f(x):
> > if int(x) != x:
> > raise ValueError
> > elif x > 1:
> > return f(x-1) ** x
> > elif x == 1:
> > return 10
> > else:
> > raise ValueError
> > return len(str(f(x))) -1
> >
> > The great part about this recursive solution is that you don't have to 
> > worry about the stack limit because performance degrades so quickly on the 
> > conversion to string!  fact(8) takes a little less than a second, fact(9) 
> > takes about a minute, and fact(10) takes more time than I had patience to 
> > wait for!
> 
> And the not-so-great part is that it raises an exception
> on fact(0) which makes it utterly useless for calculating
> combinations of m things taken n at a time: m!/n!*(m-n)!
> 
> Why is it that no one seems able to get this right?
> 

I can't speak for everyone, but my excuses are as follows:

* I haven't studied math or done math-heavy work in 8 years.
* I'm not at my home computer, and most of the thread (wherein, I now recall, 
that particular rule was specified) is downloaded to my home computer, so I was 
working from my feeble memory.
* I didn't care enough to google for it.

That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing xml file in python

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 11:45:17AM -0700, [EMAIL PROTECTED] wrote regarding Re: 
Parsing xml file in python:

Top-posting corrected

> 
> 
> 
> On Oct 30, 12:32 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > [EMAIL PROTECTED] schrieb:
> >
> >
> >
> > > I am a newbie in python
> > > I am trying to parse a xml file and write its content in a txt file.
> > > The txt contains null elements. Any reason what  iam doing wrong here
> >
> > > Here is the code that i wrote
> >
> > > import sys,os
> > > import xml.sax
> > > import xml.sax.handler
> > > from xml.sax.handler import ContentHandler
> > > from xml.sax import make_parser
> >
> > > class gmondxmlparse (ContentHandler):
> >
> > > def __init__(self,searchTerm):
> > > self.searchTerm=searchTerm;
> >
> > > def startElement(self,name,attrs):
> >
> > > if name=="HOST":
> > > self.hostname=attrs.get('NAME',"")
> > > self.IP=attrs.get('IP',"")
> > > elif name=="METRIC":
> > > self.metricname=attrs.get('NAME', "")
> > > self.metricvalue=attrs.get('VAL',"")
> > > self.metrictype=attrs.get('TYPE',"")
> > > self.metricunit=attrs.get('UNITS',"")
> > > return
> >
> > > def endElement(self,name):
> > > if name=="HOST" and self.searchTerm==self.hostname:
> > > try:
> > > fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
> > > except:
> > > print "File /root/yhpc-2.0/ganglia.txt can not be
> > > open"
> > > sys.exit(1)
> > > fh.write("This is a test for xml parsing with python with
> > > chris and amjad \n")
> > > fh.write("the host name is", self.hostname, "\n")
> > > fh.write("the ip address is", self.IP, "\n")
> > > fh.close()
> >
> > > searchTerm="HOST"
> > > parser=make_parser()
> > > curHandler=gmondxmlparse(searchTerm)
> > > parser.setContentHandler(curHandler)
> > > parser.parse(open("/root/yhpc-2.0/gmond.xml"))
> >
> > > Here is the sample of xml file
> >
> > > Here is the  xmk file called gmond.xml
> > >  > > TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
> > > GMOND_STARTED="1193170061">
> > >  > > TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>
> >
> > Without an actual error given, it's hard to know what your problem is.
> >
> > One thing though is noticable: your XML below isn't valid - XML has only
> > one root-element.
> >
> > And just for the record: it appears that you work under linux using a
> > root-account. Bad idea. Really.
> >
> > http://linuxbraindump.org/2007/08/13/the-10-commandments-for-new-linu...
> >
> > Diez
> 
> 
> That XML is just a snapshot
> I am not getting into the xml parser. The error is not generated but
> also the /root/yhpc-2.0/ganglia.txt does not contain anything.
> 

Well, if ganglia.txt contains nothing, and you received no output from the 
program, then either endElement never got called, or `if name=="HOST" and 
self.searchTerm==self.hostname:` never evaluated to true.  Because if you 
couldn't open for writing, you would have gotten the message you set up on the 
except block, and if you could, then even if your variables didn't contain any 
data, you would have seen the boilerplate text that you wrote.

Cheers,
Cliff

P.S. Please bottom-post when replying to the python list.  It sucks to have to 
look up and down a thread to see what's been said.

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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread J. Clifford Dyer
On Wed, Oct 31, 2007 at 03:55:49PM +0100, jelle feringa wrote regarding Re: 
shouldn't 'string'.find('ugh') return 0, not -1 ?:
> 
>There is a subtle point though.
> 
>If the substring is not found '_'.find(' '), will return -1
> 
>Semanticly, I was expecting the that if the substring was not found,
>the conditional statement would not be found.
> 
>However, python evaluates -1 to True, so that is what I do find
>confusing.
> 
>So, I was arguing that '_'.find(' ') might return 0, however that is
>obviously ambigious, since 0 might be an index as well.
> 
> 
> 
>So, perhaps I should rephrase and ask, why if -1 evaluates to True?
> 
>I think that's pretty ugly...
> 
> 

It is ugly, but there's no alternative.  In essence, you can't do a truth-test 
on it, because you're not testing the truth of the find statement.  The 
statement that you want to test the truth of is s.find(q) >= 0.  In other 
words, you want to see that the substring was found at a valid (non-negative) 
location. As someone else pointed out, it would make more sense to use None 
instead of -1.  You still couldn't use `if s.find(q):` because you'd get a 
false result for a substring found at the beginning of the string, but the 
return value would make more intuitive sense.  

Witness also the problem of actually using the result of find:

s[s.find(q)]

will yield a valid part of the string (the last character) when q is not found. 
 If it evaluated to none, you'd get a respectable TypeError instead.

But you still wouldn't--and never will--be able to say `if s.find(q)`, because 
valid array indices can be either true or false.

Cheers,
Cliff



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


Re: python newbie

2007-11-02 Thread J. Clifford Dyer
On Fri, Nov 02, 2007 at 11:13:00AM -0400, Jim Hendricks wrote regarding Re: 
python newbie:
> 
> BartlebyScrivener wrote:
> > On Nov 2, 8:51 am, Jim Hendricks <[EMAIL PROTECTED]> wrote:
> >> New to python, programming in 15 or so langs for 24 years.
> >>
> >> Couple of questions the tuts I've looked at don't explain:
> > 
> > Did you look at THE tut?  You would seem to be the perfect reader for
> > it, because you are already a programmer.
> > 
> > http://docs.python.org/tut/node6.html#SECTION00660
> > 
> > rd
> > 
> 
> I initially looked at THE tut, and it came across so techy that it's 
> such a slow read.  Therefore, I looked to other tuts that were very easy 
> reads and could give me the basic lowdown of the language.  Problem of 
> course is the easy read tuts don't get into the details.
> 
> That said, I looked at the section of the tutorial you provided (thanks) 
> and I am still confused.  It specifies a global var cannot be assigned 
> unless it's specified in the global statement.
> 
> Here's an example of what I am asking:
> 
> def my_function():
>global x
> 
>x = open( 
> 
> before calling my_function, x does not exist in my program.  So, my 
> question is in my_function, the combination of using the global 
> statement, then implicitly creating x via assignment to the result of 
> the open function, is x created in the global namespace?

Yes.

>>> y

Traceback (most recent call last):
  File "", line 1, in 
y
NameError: name 'y' is not defined
>>> def f():
global y
y = 123
>>> f()
>>> y
123
>>> 

Remember, the interactive interpreter is your friend.  Just type 'python' at 
the command line and hammer away.  (It's even better through a decent IDE).

Oh yeah, you have to actually call f before y will get defined.  

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


Re: Does eval has the same features as Perl's?

2007-01-22 Thread J. Clifford Dyer
The python editor won't "get exit."  It will raise an exception.  With
or without an eval, you can catch the exception.

try:
x = 1/0
except ZeroDivisionError:
x = "infinity"


Jm lists wrote:
> Hello members,
> 
> I want to know does the "eval" in python have the same features as in
> Perl (capture errors)?
> 
> For example,in perl I can wrote:
> 
> $re = eval { 1 / 0 };
> 
> Though 1/0 is a fatal error but since it's in "eval" block so the perl
> interpreter doesn't get exit.
> 
> Thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading assignment operator

2007-01-29 Thread J. Clifford Dyer
Steven D'Aprano wrote:
> On Tue, 23 Jan 2007 18:07:55 -0800, Russ wrote:
> 
>> Achim Domma wrote:
>>> Hi,
>>>
>>> I want to use Python to script some formulas in my application. The user
>>> should be able to write something like
>>>
>>> A = B * C
>>>
>>> where A,B,C are instances of some wrapper classes. Overloading * is no
>>> problem but I cannot overload the assignment of A. I understand that
>>> this is due to the nature of Python, but is there a trick to work around
>>> this?
>>> All I'm interested in is a clean syntax to script my app. Any ideas are
>>> very welcome.
>>>
>>> regards,
>>> Achim
>> Why do you need to overload assignment anyway? If you overloaded "*"
>> properly, it should return
>> the result you want, which you then "assign" to A as usual. Maybe I'm
>> missing something.
> 
> One common reason for overriding assignment is so the left-hand-side of
> the assignment can choose the result type. E.g. if Cheddar, Swiss and
> Wensleydale are three custom classes, mutually compatible for
> multiplication:
> 
> B = Cheddar()  # B is type Cheddar
> C = Swiss()# C is type Swiss
> # without overloading assignment
> A = B * C  # A is (possibly) Cheddar since B.__mul__ is called first
> A = C * B  # A is (possibly) Swiss since C.__mul__ is called first
> # with (hypothetical) assignment overloading 
> A = B * C  # A is type Wensleydale since A.__assign__ is called
> 
> Except, of course, there is no assignment overloading in Python. There
> can't be, because A may not exist when the assignment is performed, and
> if it does exist it might be a complete different type.
> 
> Instead, you can do something like this:
>  
> A = Wensleydale(B) * Wensleydale(C)
> 
> or 
> 
> A = Wensleydale(B * C)
> 
> 
> 
> 

I think that's the first time I've actually seen someone use a Monty
Python theme for a python example, and I must say, I like it.  However,
"We are all out of Wensleydale."

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


Re: Partial 1.0 - Partial classes for Python

2007-02-08 Thread J. Clifford Dyer
Martin v. Löwis wrote:
> I'm happy to announce partial 1.0; a module to implement
> partial classes in Python. It is available from
> 
> http://cheeseshop.python.org/pypi/partial/1.0
> 
> A partial class is a fragment of a class definition;
> partial classes allow to spread the definition of
> a class over several modules. One location serves
> as the original definition of the class.
> 
> To extend a class original_module.FullClass with
> an additional function, one writes
> 
> from partial import *
> import original_module
> 

Erm,

Please don't use 'from x import *', especially in a demo example like
this.  It makes it less clear which variables below come from your  module.

Thanks,
Cliff

> class ExtendedClass(partial, original_module.FullClass):
> def additional_method(self, args):
> body
> more_methods
> 
> This module is licensed under the Academic Free License v3.0.
> 
> Please send comments and feedback to [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Vim scripting with python

2007-02-12 Thread J. Clifford Dyer
Stuart D. Gathman wrote:
> On Sat, 03 Feb 2007 05:02:54 -0800, Tool69 wrote:
> 
>> Does anyone have any advice, and more genraly how to script Vim with
>> Python ?
> 
> :py import sys
> :py print sys.version
> :help :py
> 
>> I know I can put some python functions inside my vimrc file like
>> this :
>>
>> function! My_function()
>> python << EOF
>> import vim, string
>> ...blablabla
>> EOF
>> endfunction
>>
>> but I would like to use external ".py" files.
> 
> :py import myfile
> 
> Use :py inside your vimrc - don't run python externally.

Which versions of vim is this valid for?  I tried ":py print 'Hello'",
and got "E319: Sorry, the command is not available in this version"

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


Re: regular expressions

2007-11-06 Thread J. Clifford Dyer
On Tue, Nov 06, 2007 at 08:49:33AM -0800, [EMAIL PROTECTED] wrote regarding 
regular expressions:
> 
> hi i am looking for pattern in regular expreesion that replaces
> anything starting with and betweeen http:// until /
> like http://www.start.com/startservice/yellow/ fdhttp://helo/abcd will
> be replaced as
> p/startservice/yellow/ fdp/abcd
> 

You don't need regular expressions to do that.  Look into the methods that 
strings have.  Look at slicing. Look at len.  Keep your code readable for 
future generations.

Py>>> help(str)
Py>>> dir(str)
Py>>> help(str.startswith)

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


Re: why no automatic conversion in string concatenation?

2007-11-13 Thread J. Clifford Dyer
On Tue, Nov 13, 2007 at 07:15:06AM -0800, Michael Pelz Sherman wrote regarding 
why no automatic conversion in string concatenation?:
> 
>As a Java & PHP developer, I find it kind of annoying that I have to
>explicitly convert non-string variables to strings when concatenating
>them, especially when python is quite capable of doing the conversion
>automatically.
>i.e.:
>>>> myBool = True
>>>> print myBool
>True
>>>> print "myBool is " + myBool
>Traceback (most recent call last):
>  File "", line 1, in 
>TypeError: cannot concatenate 'str' and 'bool' objects
>>>> print "myBool is " + str(myBool)
>myBool is True
>Can anyone explain why this is so? 

Because python doesn't know if '1' + 1 should equal 2 or '11' and would rather 
you mad that decision.  Should it be different than 1 + '1'?  

or to put it more succinctly, because "explicit is better than implicit."
In fact, I think it's more often the case that I have string data that I need 
to treat as integers than the other way around (input from stdin and textfiles 
for example).

> Are there any plans to change this
>in python 3000?

I hope not, and I don't think so.

>Thanks,
>- Michael

No problem. 

Cheers,
Cliff

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


Re: Creating Installer or Executable in Python

2007-11-14 Thread J. Clifford Dyer
On Wed, Nov 14, 2007 at 03:34:14PM +0100, Laszlo Nagy wrote regarding Re: 
Creating Installer or Executable in Python:
> 
> DanielJohnson wrote:
> > I have a small project which has around 10 .py files and I run this
> > project using command line arguments. I have to distribute this
> > project to somebody.
> >
> > I was wondering how can I make an executable or some kind of
> > installer, so that end user doesn't need to compile and worry if he/
> > she has Python installed or not ?
> >   
> http://www.fuckinggoogleit.com/?q=py2exe
> 

While I agree with the sentiment, I'm left wondering how you think he would 
have known to google for py2exe.  Maybe you meant:

http://www.fuckinggoogleit.com/?q=python+executable

(Which also yields py2exe as the first result.)

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


Re: Printing user input?

2007-11-15 Thread J. Clifford Dyer
On Thu, Nov 15, 2007 at 09:03:26AM -0800, Mohammed_M wrote regarding Printing 
user input?:
> 
> Hi,
> I'm v.new to Python, so please don't be too harsh :)
> I get a NameError with the code below - All I want to do is store some
> input taken from the user in a variable called name, & then print name
> 
> # START CODE ==
> # Print name demo
> 
> 
> def PersonsDetails():
> name = input("What's your name?")
> PersonsDetails()
> 
> print(name)
> 
> 
> # END CODE ==
> 
> Thanks for reading & any help on this
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Also,  you'll want to use raw_input() instead of input.

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


Re: sorting contacts alphabetically, sorted by surname

2007-11-16 Thread J. Clifford Dyer
On Fri, Nov 16, 2007 at 12:31:19PM +, Marie Hughes wrote regarding sorting 
contacts alphabetically, sorted by surname:
> 
>HI
> 
>I have to write a program that contains a text file in the following
>format:
> 
>AcademicPositionRoom Ext.   Email
>Prof Marie Maguire  Head of
>School  M9002    [EMAIL PROTECTED]
> 
>And produce a output file where conatcts are sorted alphabetically-
>sorted by surname.
> 
>Has anyone any ideas.

Well, the first thing you need to do is develop a workable understanding of how 
your data file is formatted.  What separates one field from another?  Is it 
tab-delimited?  Does the field always start at a given column number?  Then you 
need to read each line of the file, and split the lines up according to the 
format.  Save to a data structure, sort by last name (you'll have to further 
parse the name to isolate this information), and reprint the results.

Depending on the details you uncover about the precise format of your data 
file, you will find it helpful to read the documentation on string methods, 
particularly s.split(), and sequence slicing: s[4:14].

Best of luck with it.

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


Re: implement random selection in Python

2007-11-17 Thread J. Clifford Dyer
On Fri, 2007-11-16 at 16:47 -0800, Bruza wrote:
I think I need to explain on the probability part: the "prob" is a
> relative likelihood that the object will be included in the output
> list. So, in my example input of
> 
>   items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)]
> 
> So, for any size of N, 'Tom' (with prob of 45) will be more likely to
> be included in the output list of N distinct member than 'Mary' (prob
> of 30) and much more likely than that of 'John' (with prob of 10).
> 
> I know "prob" is not exactly the "probability" in the context of
> returning a multiple member list. But what I want is a way to "favor"
> some member in a selection process.
> 
My understanding of what you are looking for is that on each individual 
selection, the probability of picking a given name is that name's prob value, 
divided by the sum of all prob values.  That is, in the following case:

items = [('Mary',96),('Shimon',1),('Aisha',1),('Toshiro',2)]
N = 3

On the first pass Mary has a 96% chance of getting selected, Shimon a 1% 
Chance, Aisha a 1% chance and Toshiro a 2% chance.

If Mary gets selected, then on the second round Shimon and Aisha should each 
have a 25% chance of getting selected, and Toshiro a 50% chance.

If Shimon gets selected, then on round three, Aisha will have a ~33% chance, 
and Toshiro a little less than 67%.

If that is correct, then the following might meet your needs:

from random import choice

def select(weighted_list, n=1):
selected = set()
for iteration in xrange(n):
print iteration
selection_list = []
for item in weighted_list:
if item[0] not in selected:
selection_list.extend([item[0]] * item[1])
#print selection_list
this_choice = choice(selection_list)
#print this_choice
selected.add(this_choice)
return selected

if __name__ == '__main__':
items = [('Mary',96),('Shimon',1),('Aisha',1),('Toshiro',2)]
N = 3
print select(items, 3)


It creates a new selection list at every pass, but it should be a marked 
improvement over solutions that have to flail against already chosen values, 
especially in unbalanced cases like the one I've shown above.  I have not run 
tests to establish this for certain.  Exercise left to the reader.  

If you care who was chosen first or last (like, say, if this is for selecting 
members of a kick ball team), you may want to replace the selected set with a 
list.  Or you may want to keep both the set and a list.  Depends on your needs.

Cheers,
Cliff

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


Re: Fwd: Sorting Countries by Region

2007-11-17 Thread J. Clifford Dyer

On Sat, 2007-11-17 at 03:34 -0800, [EMAIL PROTECTED] wrote:
> #This seems to not work today and I don't know why
> #for country in countries_list:
> #if country not in REGIONS_COUNTRIES['European Union'] or not in
> REGIONS_COUNTRIES['North America']:
> #print "%s is not in the expected list", country
> 

This snippet fails because you want 'and' rather than 'or'.  In this
one, you test to see that country is not in EU, and if you have, say
'France' as your country, the first half evaluates false, so the or
tells it to try again with North America.  Lo and behold, france is not
in North America, so the second half returns true.  False or True
returns True, so your code prints "France is not in the expected list."

Cheers,
Cliff


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


Re: overriding methods - two questions

2007-11-19 Thread J. Clifford Dyer
On Mon, Nov 19, 2007 at 01:41:46PM +0100, Bruno Desthuilliers wrote regarding 
Re: overriding methods - two questions:
> 
> Steven D'Aprano a ?crit :
> > On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote:
> > 
> >>> Question 1:
> >>>
> >>> Given that the user of the API can choose to override foo() or not, how
> >>> can I control the signature that they use?
> >> While technically possible (using inspect.getargspec), trying to make
> >> your code idiot-proof is a lost fight and a pure waste of time.
> > 
> > 
> > Worse: it's actually counter-productive!
> > 
> > The whole idea of being able to subclass a class means that the user 
> > should be able to override foo() *including* the signature. 
> 
> If you see subclassing as subtyping, the signatures should always stay 
> fully compatibles.
> 

Isn't that more what Zope-type interfaces are for than inheritance?  I'm 
uncertain here, but I'm not persuaded that changing signature is bad.  
-- 
http://mail.python.org/mailman/listinfo/python-list


[EMAIL PROTECTED]: Re: overriding methods - two questions]

2007-11-19 Thread J. Clifford Dyer
On Mon, Nov 19, 2007 at 04:33:39PM +0100, Bruno Desthuilliers wrote regarding 
Re: overriding methods - two questions:
> 
> J. Clifford Dyer a ?crit :
> > On Mon, Nov 19, 2007 at 01:41:46PM +0100, Bruno Desthuilliers wrote 
> > regarding Re: overriding methods - two questions:
> >> Steven D'Aprano a ?crit :
> >>> On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote:
> >>>
> >>>>> Question 1:
> >>>>>
> >>>>> Given that the user of the API can choose to override foo() or not, how
> >>>>> can I control the signature that they use?
> >>>> While technically possible (using inspect.getargspec), trying to make
> >>>> your code idiot-proof is a lost fight and a pure waste of time.
> >>>
> >>> Worse: it's actually counter-productive!
> >>>
> >>> The whole idea of being able to subclass a class means that the user 
> >>> should be able to override foo() *including* the signature. 
> >> If you see subclassing as subtyping, the signatures should always stay 
> >> fully compatibles.
> >>
> > 
> > Isn't that more what Zope-type interfaces are for than inheritance?
> 
> With dynamically typed languages like Python, you don't need any formal 
> mechanism (zope-like interface or whatever) for subtyping to work - just 
> make sure your two classes have the same public interface and it's ok. 
> So indeed inheritance is first a code-reuse feature.
> 

Makes sense.  As nifty as interfaces seem, there's also something that struck 
me as too club-like about them.  Your suggestion seems much more pythonically 
dynamic and ducky.

> > I'm uncertain here, but I'm not persuaded that changing signature is
> > bad.
> 
> Depends if the subclass is supposed to be a proper subtype (according to 
> LSP) too.

Also makes sense, somewhat, but I'll need to reread the previously linked 
article, because I'm not clear in my mind on what makes a subclass a subtype 
*other than* having a matching signature.

Thanks,
Cliff

- End forwarded message -
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python strings question (vertical stack)

2007-11-20 Thread J. Clifford Dyer
On Tue, Nov 20, 2007 at 11:40:59AM -0800, Farshid Lashkari wrote regarding Re: 
Python strings question (vertical stack):
> 
> dmitrey wrote:
> > Hi all,
> > I have some strings, let it be string1, string2, string3.
> > 
> > So how could String=
> > """
> > string1
> > string2
> > string3
> > """
> > 
> > be obtained?
> > 
> > Thank you in advance, D.
> 
> If you just want the to add newlines between the strings then you can do 
> the following:
> 
> String = '\\n'.join([string1,string2,string3])
> 
> -Farshid
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I think you mean '\n'.join([string1,string2,string3])

You actually do want the \ to do its thing in this case.

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


Re: Writing Error in program

2007-11-20 Thread J. Clifford Dyer
On Tue, Nov 20, 2007 at 01:02:38PM -0800, [EMAIL PROTECTED] wrote regarding 
Writing Error in program:
> 
> I have a code that writes to 2 seperate files.  I keep getting a "list
> index out of range" error.  The strange part is that when checking the
> files that I'm writing too, the script has already iterated through
> and finished writing, yet the error stated implies that it hasn't?  So
> how can it be, that my script has written to the files, yet the error
> is stating that it hasn't made it through the script?  I'll have 15
> files that I have written to and the script will bog out at number
> 10?  Is python doing something I'm not seeing?  I printed everything
> that was written on the shell and it shows that it went through the
> script, so how can it still say there are a few files left to iterate
> through?

As others have mentioned, posting code would be very helpful.  Also, what you 
say doesn't sound right.  "List index out of range" does not mean there are a 
few files left to iterate through.  It means that you have a list somewhere and 
you are trying to access an index beyond the last list item.

So say you have the following list:

l=['a','b','c']

and you try to access each item in it with the following loop:

for x in range(4):
print l[x]

You will get the following output.

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

in other words it will print l[0], l[1], and l[2], but then when it tries to 
print l[3], it will raise an IndexError, because there is no l[3].  This does 
not mean it still has files to process.  More likely, it means it has overshot 
the files it does have to process, but more likely still it has nothing to do 
with file access.  We can't help you diagnose that without a code sample, 
though.

Cheers,
Cliff



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


Re: [regex] Basic rewriting

2007-11-20 Thread J. Clifford Dyer
On Wed, 2007-11-21 at 03:24 +0100, Gilles Ganault wrote:
> Hello
> 
>   I've been reading tutorials on regexes in Python, but I still
> don't get it:
> 
> 
> #!/usr/bin/python
> 
> #myscript.py 0123456789
> 
> import sys,re
> 
> #Turn 0123456789 into 01.23.45.67.89
> p = re.compile('(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
> phone = p.sub('\1.\2.\3.\4.\5',sys.argv[1])
> print phone
> 
> 
> => Python displays "" instead. Any idea what I'm doing wrong?
> 
> Thank you.

Use raw strings for re expressions.

r'this is a raw string'
'this is not'

p = re.compile(r'(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
phone = p.sub(r'\1.\2.\3.\4.\5',sys.argv[1])

Should clear up your problem.

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


Re: Python strings question (vertical stack)

2007-11-20 Thread J. Clifford Dyer
On Tue, 2007-11-20 at 13:59 -0800, John Machin wrote:
> On Nov 21, 7:15 am, Farshid Lashkari <[EMAIL PROTECTED]> wrote:
> > J. Clifford Dyer wrote:
> > > I think you mean '\n'.join([string1,string2,string3])
> >
> > > You actually do want the \ to do its thing in this case.
> >
> > Yeah, my brain must still be asleep. Thanks for waking it up :)
> 
> You're not alone :-)
> 
> >>> a = """
> ... x
> ... y
> ... z
> ... """
> >>> a
> '\nx\ny\nz\n'
> >>> '\n'.join(['x', 'y', 'z'])
> 'x\ny\nz'
> >>>

It's true: my solution did not match the exact specification given by
the OP's code, but 1) I was responding to Farshid Lashkari's slip and 2)
It does what the OP was ultimately asking for--it stacks the results
vertically.  My brain was not asleep, I was just not interested in the
other, largely irrelevant part of the OP's question.  If he wants a new
line at the beginning and end, I'm sure he can figure out how to do it.
I don't need to jump through those hoops for him.

Cheers,
Cliff



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


Re: the annoying, verbose self

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 10:13:46AM +0100, A.T.Hofkamp wrote regarding Re: the 
annoying, verbose self:
> 
> On 2007-11-22, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> > On Wed, 21 Nov 2007 15:51:56 -0800, braver wrote:
> >
> >> Is there any trick to get rid of having to type the annoying,
> >> character-eating "self." prefix everywhere in a class?
> 

You're tilting against windmills.  This has been gone over many times.  There 
are very valid reasons for the explicit self, which I understood well enough 
when I read about them to stop complaining about self, but not well enough to 
be able to justify to someone else.  Sorry for that.  But since Alexy likes 
finding old threads that address his concerns, maybe he'll hunt them down, 
himself.  

> You got this highly flexible language, very good for rapid programming, no 
> more
> clutter from block brackets and variable declarations, and now this 'self' 
> pops
> up.
> 
> So much overhead
> 
> Can the computer not decide by itself what I want stored in the object? It can
> read my code too!
> 

But not every variable declared inside a class needs to be assigned to self.  
Make judicious use of non-self variables, if you don't want to see self 
everywhere.

> 
> > Oh I know! It' uch a pain. Sinc writing a hug cla lat wk, I'v had a 
> > trribl hortag o lowrca S E L and F charactr. It mak writing vry annoying.
> 
> Yes annoying isn't it?
> 
> Last week I was programming in C++ again, and now I have this terrible 
> sur-plus
> of lowercase T H I and S letters. I don't understand how they do it (I used 
> to,
> but not any more).
> 
> Maybe we should setup an exchange program so everybody can trade letters with
> each other.
> 
> 
> >> Sometimes I avoid OO just not to deal with its verbosity.
> >
> > There are other values than brevity. In fact, brevity is one of the less 
> > important values.
> 
> NO! You got it all wrong here! It is not about brevity, it is about SPEED.
> 

if you're looking for speed of typing, just type a one character self 
equivalent, like:

class q(object):
def method(;, arg):
;.var = 3

Then when you're done coding: :%s/;/self/g

> With less letters, there is less to read, so it can be read faster, so it must
> be better!
> 

Ah.  Speed of reading.  In fact, speed of reading is connected to clarity, not 
brevity.  If you have to keep looking back to some declaration section to 
remember if a given variable is tied to self, it's going to slow down your 
comprehension speed.  the written chinese language is far more concise than 
japansese, but it's faster to skim japanese, because of the three alphabet 
system.  Most of the meaning is contained in kanji, while the hiragana supplies 
disambiguation and grammatical specifiers, so you know you can skip past the 
hiragana and still retain the basic meaning.  Having self used by convention 
means that once you get used to seeing it, you don't need to read it any more.  
It would really mess with python coders, though, if each person made up their 
own self-equivalent.  You write "s", I write "self", Larry Wall starts coding 
python and uses "my".  Then we'd all have to actually pay attention, and 
reading really would slow down.  That's probably why self seems to !
 be the most consistently held convention in python.  Occasionally, someone 
will use cls, but that's for a different context, where you really do want 
people to slow down and realise that something different is going on.

> Just like "if x:" is MUCH BETTER than "if x != 0:"
> 
Only when "if x:" is what you mean.  The semantics are different:

py>>> x = ''
py>>> if x: print "x"
py>>> if x != 0: print "x != 0"
x != 0

> 
> The thing that should be fixed imho, is that the brain of some of us tries to
> deduce higher levels of abstractions from what is essentially a very long line
> of simple instructions.
> 

Sorry, no entiendo.  What needs to be fixed here?

> 
> >> But things grow -- is there any metaprogramming tricks or whatnot we can
> >> throw on the self?
> >
> > Oh yeah, that's just what I like to see! Complicated, brittle, hard to 
> > debug, difficult to understand metaprogramming tricks in preference to a 
> > simple, easy-to-read naming convention.
> 
> Maybe we should state first which variables we want to store in self, and then
> have a meta-programming hook that automatically puts assignments to those
> variables into the object.
> And while we are at it, maybe we should also state the type of data we want to
> put in it. That should help too.
> 
> Now that would be progress.
> 

I hope you are taking the piss.

> 
> Ah well, I guess we will have to wait a while before that happens.
> Albert

Oh God.  You are taking the piss.  IHBT.


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


Re: why it is invalid syntax?

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 06:47:33AM +, Marc 'BlackJack' Rintsch wrote 
regarding Re: why it is invalid syntax?:
> 
> It's quite unreadable and if this would be allowed you would have to
> introduce a special rule to forbid ``else``, ``except`` and ``finally``
> because it can lead to ambiguities. To which ``if`` does the ``else``
> belong to here? ::
> 
>   if 1: print 1 if: 1 print 1 else: print 1
> 
> Ciao,
>   Marc 'BlackJack' Rintsch

I don't reckon in matters much.  Your output will be:

1
1

;)

No, actually on second inspection your output will be:

File "", line 1
if 1: print 1 if: 1 print 1 else: print 1
^
SyntaxError: invalid syntax

But it's a good point.

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


Re: eof

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 06:53:59AM -0800, braver wrote regarding Re: eof:
> 
> > Language comparisons are sometimes good. They are best when
> > they are free of FUD.
> 
> So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)

Because that's not how you compare languages.  You compare languages by stating 
what you are actually trying to do, and figuring out the most natural solution 
in each language.  Not "I can do this in x--how come I can't do it in y?" 

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


Re: eof

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 07:17:41AM -0800, braver wrote regarding Re: eof:
> 
> On Nov 22, 6:08 pm, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> 
> > > So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)
> 
> > Because that's not how you compare languages.  You compare languages by 
> > stating what you are actually trying to do, and figuring out the most 
> > natural solution in each language.  Not "I can do this in x--how come I 
> > can't do it in y?"
> 
> Python doesn't have f.eof() because it doesn't compare to Ruby?  Or
> because I'm trying to compare them?  :)  That's giving up to Ruby too
> early!
> 

No and no, to your two questions.  I'm not giving up on Ruby at all.  In fact, 
I've never tried Ruby.  My point isn't that the languages don't compare.  My 
point is that your question shouldn't be "why doesn't python have an eof method 
on its file objects?"  Your question should be "I want to do something 
different with the last line of a file that I iterate over.  How do I do that 
best in python?"  You've been given a couple solutions, and a very valid reason 
(performance) why buffered file objects are not the default.  You may also 
consider trying subclassing file with a buffered file object that provides 
self.eof.  (I recommend making it an attribute rather than a method.  Set it 
when you hit eof.)  That way you have the fast version, and the robust version.

You may find something of interest in the for/else construction as well

for line in file:
pass
else:
# This gets processed at the end unless you break out of the for loop.
pass


> Ruby has iterators and generators too, but it also has my good ol'
> f.eof().  I challenge the assumption here of some majectically Python-
> wayist spirit forbidding Python to have f.eof(), while Ruby, which has
> all the same features, has it.  Saying "it's not the Python way" is
> not a valid argument.
> 

No, but showing a different python way is more valid, and if you were more 
forthcoming about your use case from the get-go, you would have gotten fewer 
vague answers.  

> The suspicion lurking in the thread above was that that has to do with
> Python IO buffering, that it somehow can't tell the f.eof() with
> automatic look-ahead/push-back/simulate read, as transparently an
> effectively as (in practice) Ruby does without much fuss.  The reason
> why such a useful feature -- useful not in Ruby or Perl or Pascal, but
> algorithmically -- is not present in Python is a recurrent mystery,
> evidenced in this group recurrently.
> 

A mystery which has been answered a couple times in this thread--it causes a 
performance hit, and python is designed so that you don't suffer that 
performance hit, unless you want it, so you have to program for it yourself.

You yourself said that performance is a complaint of yours regarding Ruby, so 
why claim that Ruby's way is clearly better in a case where it causes a known 
performance hit?

> Cheers,
> Alexy

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


Re: How to import xplt, pylab?

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 02:00:00PM -0800, Caren Balea wrote regarding How to 
import xplt, pylab?:
> 
> Hello,
> 
> I'm newbie to python.
> 
> So far, I'm a bit disappointed. It's awful to set Python up to work.
> It's not working!!!
> 
> Ok, calm down. Here are my settings:
> I'm using Windows XP machine and have installed
> Python 2.5.1.
> Also, I have also installed something called "Cygwin" to type
> in my commands.
> Finally, I have installed scipy-0.6.0.
> 
> After starting Cygin I type
> 
> python
> import math
> import scipy
> *
> Then I try
> 
> import xplt
> 
> and get the message
> Traceback (most recent call last):
> File "", line 1, in 
> ImportError: No module named xplt
> *
> 

xplt is a module within scipy, so it will not be available at the top level.  
However, all you need to do is

py>>> from scipy.sandbox import xplt

or

py>>> import scipy.sandbox.xplt

The advantage of the former is that you can just use the names xplt.*, while 
with the latter you have to type scipy.sandbox.xplt.*.

> Also I try
> 
> import pylab
> 
> and get the message
> Traceback (most recent call last):
> File "", line 1, in 
> ImportError: No module named pylab
> 
> *
> 

I haven't worked with pylab, but it looks like you may need another install 
(matplotlib?)  I'm not sure.  I just did a quick google search.

> So, how can I use xplt and pylab???
> 
> Any help would be much appreciated!!!
> 
> Thank you,
> Caren

Happy Thankgiving hacking!

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


Re: basic if stuff- testing ranges

2007-11-25 Thread J. Clifford Dyer

On Sun, 2007-11-25 at 20:49 +0200, Donn Ingle wrote:
> Sheesh, I've been going spare trying to find how to do this short-hand:
> if 0 > x < 20: print "within"
> 


  if 0 > x: print "within"


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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread J. Clifford Dyer
On Mon, Nov 26, 2007 at 04:07:03PM +0530, Ravi Kumar wrote regarding Need to 
call functions/class_methods etc using string ref :How:
> 
>Hi,
>First of all, since this is my first mail to Python-List, I want to say
>"Hello world!"
>After that;
>I am stuck in a project. Actually I am writing a module (for testing
>now), which takes URL, parses it, finds which modules and then which
>method to call or which class to initiate and which string to load.
>So far, I have done some basic URL manipulation and validation and
>extracted the name of modules in  a dict
>{
>  'ModuleName-1': None,
>  'ModuleName-2': None
>  --ETC--
>}
>Now I want your help about how to call the  function i.e _render() in
>the module. I have to iterate it calling all modules/also Class.methods
>and assinging the values in dict for each key as modulename.
>Means,
>just take that moduleName is a string which contains the name of module
>to load.
>FuncName is the string which contains the name of def  to
>call
>clName is the string which contains the name of the Class, which is to
>init and get returned object.
>means everything in string.
>ALso, if there are multiple methods to do it, if you provide a little
>pros/cons and comments, it would really be very nice of you.
>Before I came here, I have searched Google, and found a way
>hasattr()/getattr(), but that confused me a little and didnt worked for
>me. I am missing something I know, so please ENLIGHTEN Me :)
>Thanks in advance EVen you read this mail :P
>--
>-=Ravi=-

I see someone already showed you eval.  Eval is evil.  Don't use it.  
Especially if the functions are coming to you from a public URL!  

You are on the right track putting the module names in a dictionary.  Now tie 
those dictionary keys to functions.

func = { 'function_a': function_a,
 'function_b': function_b }

now you can call them as follows, with the desired function name extracted from 
the URL into the variable f_request:

if f_request in func:
result = func[f_request]()

This way, users can't call functions you haven't explicitly added to the func 
dictionary.

Cheers,
Cliff


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


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread J. Clifford Dyer
On Mon, Nov 26, 2007 at 06:04:54PM +0100, Diez B. Roggisch wrote regarding Re: 
How to write Regular Expression for recursive matching?:
> 
> lisong wrote:
> 
> > Hi All,
> > 
> > I have problem to split a string like this:
> > 
> > 'abc.defg.hij.klmnop'
> > 
> > and I want to get all substrings with only one '.' in mid. so the
> > output I expect is :
> > 
> > 'abc.defg', 'defg.hij', 'hij.klmnop'
> > 
> > a simple regular expression '\w+.\w' will only return:
> > 'abc.defg', 'hij.klmnop'
> > 
> > is there a way to get 'defg.hij' using regular expression?
> 
> Nope. Regular expressions can't get back in their input-stream, at least not
> for such stuff.
> 
> The problem at hand is easily solved using
> 
> s = 'abc.defg.hij.klmnop'
> 
> pairs = [".".join(v) for v in zip(s.split(".")[:-1], s.split(".")[1:])]
> 

which is veritably perlesque in its elegance and simplicity!

A slightly more verbose version.

l = s.split('.')
pairs = []
for x in xrange(len(l)-1):
pairs.append('.'.join(l[x:x+2]))

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


Re: Best ways of managing text encodings in source/regexes?

2007-11-27 Thread J. Clifford Dyer
On Tue, Nov 27, 2007 at 01:30:15AM +0200, tinker barbet wrote regarding Re: 
Best ways of managing text encodings in source/regexes?:
> 
> Hi
> 
> Thanks for your responses, as I said on the reply I posted I thought
> later it was a bit long so I'm grateful you held out!
> 
> I should have said (but see comment about length) that I'd tried
> joining a unicode and a byte string in the interpreter and got that
> working, but wondered whether it was safe (I'd seen the odd warning
> about mixing byte strings and unicode).  Anyway what I was concerned
> about was what python does with source files rather than what happens
> from the interpreter, since I don't know if it's possible to change
> the encoding of the terminal without messing with site.py (and what
> else).
> 
> Aren't both ASCII and ISO-8859-1 subsets of UTF-8?  Can't you then use
> chars from either of those charsets in a file saved as UTF-8 by one's
> editor, with a # -*- coding: utf-8 -*- pseudo-declaration for python,
> without problems?  You seem to disagree.
> 
I do disagree.  Unicode is a superset of ISO-8859-1, but UTF-8 is a specific 
encoding, which changes many of the binary values.  UTF-8 was designed 
specifically not to change the values of ascii characters.  0x61 (lower case a) 
in ascii is encoded with the bits 0110 0001.  In UTF-8 it is also encoded 0110 
0001.  However, ?, "latin small letter n with tilde", is unicode/iso-8859-1 
character 0xf1.  In ISO-8859-1, this is represented by the bits  0001.  

UTF-8 gets a little tricky here.  In order to be extensible beyond 8 bits, it 
has to insert control bits at the beginning, so this character actually 
requires 2 bytes to represent instead of just one.  In order to show that UTF-8 
will be using two bytes to represent the character, the first byte begins with 
110 (1110 is used when three bytes are needed).  Each successive byte begins 
with 10 to show that it is not the beginning of a character.  Then the 
code-point value is packed into the remaining free bits, as far to the right as 
possible.  So in this case, the control bits are 

110x  10xx .  

The character value, 0xf1, or:
 0001

gets inserted as follows:

110x xx{11}  10{11 0001}

and the remaining free x-es get replaced by zeroes.

1100 0011  1011 0001.

Note that the python interpreter agrees:

py>>> x = u'\u00f1'
py>>> x.encode('utf-8')
'\xc3\xb1'

(Conversion from binary to hex is left as an exercise for the reader)

So while ASCII is a subset of UTF-8, ISO-8859-1 is definitely not.  As others 
have said many times when this issue periodically comes up: UTF-8 is not 
unicode.  Hopefully this will help explain exactly why.

Note that with other encodings, like UTF-16, even ascii is not a subset.

See the wikipedia article on UTF-8 for a more complete explanation and external 
references to official documentation (http://en.wikipedia.org/wiki/UTF-8).



> The reason all this arose was that I was using ISO-8859-1/Latin-1 with
> all the right declarations, but then I needed to match a few chars
> outside of that range.  So I didn't need to use u"" before, but now I
> do in some regexes, and I was wondering if this meant that /all/ my
> regexes had to be constructed from u"" strings or whether I could just
> do the selected ones, either using literals (and saving the file as
> UTF-8) or unicode escape sequences (and leaving the file as ASCII -- I
> already use hex escape sequences without problems but that doesn't
> work past the end of ISO-8859-1).
> 

Do you know about unicode escape sequences?

py>>> u'\xf1' == u'\u00f1'
True

> Thanks again for your feedback.
> 
> Best wishes
> Tim
> 

No problem.  It took me a while to wrap my head around it, too.

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

Re: How to Teach Python "Variables"

2007-11-28 Thread J. Clifford Dyer

On Wed, Nov 28, 2007 at 11:23:42AM -0600, Chris Mellon wrote regarding Re: How 
to Teach Python "Variables":
> 
> On Nov 28, 2007 10:57 AM, hdante <[EMAIL PROTECTED]> wrote:
> > On Nov 28, 2:12 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> > >
> > > Right. Python variables are pointers, except for all the ways that
> > > they are different. By the same criteria, they are also puppies. Give
> > > it a rest.
> >
> >  I'm sorry if your notion of pointer is incorrect. A pointer (or, more
> > formally, a reference) is an object that points to some value. A
> > python variable isn't different than that in any way.
> >
> 
> A python name isn't an object. The difference between names and
> objects is at the core of this entire conversation. In fact, you are
> exactly the sort of person this discussion was targeted at, because
> you don't understand the difference.
> 
> You can play semantic games if you want and just declare that
> everything is the same at some fundamental level. It's a little like
> taking your ball and going home, because insisting on names that don't
> indicate the differences between things is useless at best and harmful
> at worst.
> 
> Whether you like it or not, the term "pointer" has a specific common
> meanings. They do not mean "any means by which you may reference a
> value". "variable" is certainly less clear and is used much more
> loosely, but in the specific context of comparison to C, python
> name/object bindings are not the same as C variables.
> 
> Pointers are values. They also point at other values, and those values
> may be other pointers, ad infinitum. Understanding this is core to
> understanding and using pointers.
> 
> Python names are *not* values, and all they do is tag a specific
> object in a specific namespace. You can't have a name that refers to
> another name, names can only refer to objects. Understanding this is
> core to understanding and using the Python object model, *especially*
> if some nitwit has been telling you that they're the same as pointers.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

OK, now we're down to mock sympathy, insulting analogies and name-calling.  Can 
we just let this thread die.  It was an interesting discussion for a while, but 
it's moved into that ugly putrefaction stage now.  Nothing new is being said, 
and the old stuff is being said more rudely than before.

This thread is bleedin' demised.

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


Re: Bit Operations

2007-11-28 Thread J. Clifford Dyer
On Wed, Nov 28, 2007 at 09:07:56PM +0100, Gianmaria Iaculo - NVENTA wrote 
regarding Bit Operations:
> 
> Hi there,
> I'm so new to python (coming from .net so excuse me for the stupid question) 
> and i'm tring to do a very simple thing,with bytes.
> 
> My problem is this:
> 
> i've a byte that naturally is composed from 2 nibbles hi&low, and two 
> chars.. like A nd B. What i wonna do is to write A to the High nibble and B 
> to the the lower nibble.
> Or an other example can be i've 2 numbers.. like 7 and 8 and whant to do the 
> same as for chars.
> 
> I'm really confused on how t do it, maybe cause python is type-less (dynamic 
> typed)
> 
Do you possibly mean that your letters are hexadecimal digits?  If so, you can 
follow the advice given to you by others for numbers, treating your letters as 
numbers:

A=10
B=11
...
F=15

py>>> hex(15)
'0xf'
>>> int('f', 16)
15
>>> int('0xf', 16)
15

Cheers,
Cliff

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


Re: Bit Operations

2007-11-28 Thread J. Clifford Dyer
On Wed, Nov 28, 2007 at 10:05:40PM +0100, Gianmaria Iaculo - NVENTA wrote 
regarding Re: Bit Operations:
> 
> Txs all,
> i wont to respond to who asked why i needed it:
> 
> I'm using python on GSM modules and the informations i have to move goes 
> along GPRS/UMTS connections so it's beatiful for me to transfer more 
> informations with less space...
> imagine i have to send this simple data
> 
> 41.232323,12.345678
> 
> i can send it as it's or use the nibble trick and on the receiving station 
> 'unlift" the data and rebuild the original information...
> 
> isn'it???
> 

Um, no.  It isn't.  How exactly are you going to pack floating point numbers 
into a half a byte?

Or are you sending it as strings?  Also a waste of space, and unnecessarily 
complex.


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


Re: Oh no, my code is being published ... help!

2007-11-30 Thread J. Clifford Dyer
On Fri, Nov 30, 2007 at 12:25:25PM -0200, Eduardo O. Padoan wrote regarding Re: 
Oh no, my code is being published ... help!:
> 
> On Nov 30, 2007 11:36 AM, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> > "Eduardo O. Padoan" <[EMAIL PROTECTED]> writes:
> >
> > > No, writing this way will confound the 2to3 tool.
> >
> > Why?  print("foo") is a perfectly valid Python 2 statement.  Maybe
> > it's simply a matter of fixing the tool.
> >
> 
> print("foo") -> print(("foo"))
> 

And more to the point

(2.5) print(foo, bar) != (3.0) print(foo, bar)

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


Re: C/C++ on UNIX Developer required in Woodmead, Johannesburg

2007-12-01 Thread J. Clifford Dyer
Please don't.  This job is not even vaguely python related.


On Sat, 2007-12-01 at 18:42 +0100, James Matthews wrote:
> Please post in the Python Wiki under the jobs
> 
> On Dec 1, 2007 9:38 AM, arnold <[EMAIL PROTECTED]> wrote:
> We seek the following sort of experience / skill for developer
> resources (if u do not qualify - we offer a handsome referral
> fee if
> you refer someone that is succesfully placed:-) .
> 
> C Programming  5 years
> C++ Programming  2 years
> SQL Programming  2 years
> Software Design  2 years
> Software Engineering Process  3 years
> GUI Development 1 year
> Unix/Linux environment 2 years
> Scientific/Mathematical Programming  2 years 
> 
> 
> These skills all need to be current.
> 
> 
> The candidate should demonstrate an ability to work
> resourcefully and
> independently, whilst delivering in the framework of a team.
>  The
> candidate must also demonstrate a willingness and desire to
> program 
> hands-on in C and C++ code.  He/she must have personally
> developed
> significant amounts of program code, demonstrating and
> requiring
> modular design and the use of a source code repository for
> version
> control.
> 
> 
> The candidate must communicate well, and be comfortable
> discussing
> design issues with both the team and the customer.  His / her
> present
> role should require this of him/her.
> 
> 
> The candidate must be able to describe the software
> development 
> lifecycle and identify his/her personal points of interaction
> in that
> cycle. These points must be Functional Requirements
> Specification,
> Software Design, Programming and Unit Testing.
> 
> 
> The following skills would be an advantage: 
>   Object oriented design
>   UML and the use of design tools like Rational Rose
>   Development tools (GDB, DBX, WxWidets/Qt/GTK,
> Makefiles
> etc.)
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> -- 
> http://search.goldwatches.com/?Search=Movado+Watches 
> http://www.jewelerslounge.com
> http://www.goldwatches.com 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: "Python" is not a good name, should rename to "Athon"

2007-12-01 Thread J. Clifford Dyer

On Sat, 2007-12-01 at 12:10 -0800, Russ P. wrote:
> On Dec 1, 2:10 am, Bjoern Schliessmann  [EMAIL PROTECTED]> wrote:
> > Russ P. wrote:
> > > I agree that Python is not a good name for a programming language,
> >
> > Why not?
> 
> Think about proposing its use to someone who has never heard of it
> (which I did not too long ago). As the OP pointed out, a Python is a
> snake. Why should a programming language be named after a snake?

That's not a persuasive argument.

First of all, Python is named for a comedy troupe from England.  For
comparison, Perl is named for a knitting technique, Lisp is named for a
speech impediment, Ruby is named for a rock, Smalltalk is named for a
not-so-useful form of communication, and Java is named after a beverage
or an island.  

Which of those is a good name for a programming language by your
criterion?  I like the name Python.  It has a nice ring to it, and has
connotations that are simultaneously badass and humorous.  

For that matter, why name sneakers after a goddess of justice?  Why name
a car after a planet/resort town/rodent/mountain?

Because brand names are supposed to be memorable, not meaningful.

Cheers,
Cliff



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


Re: Why did no one tell me about import antigravity?

2007-12-05 Thread J. Clifford Dyer

On Wed, 2007-12-05 at 10:08 +, Adrian Cherry wrote:
> Ant <[EMAIL PROTECTED]> wrote in news:52f0eca3-e807-4890-b21d-
> [EMAIL PROTECTED]:
> 
> > Python on xkcd:
> > 
> > http://xkcd.com/353/
> > 
> 
> Another good comic from xkcd, I'm surprised by the muted response 
> on here. Don't forget to check out the alt. text on the comic
> 
> Alt text: "I wrote 20 short programs in Python yesterday. It was 
> wonderful. Perl, I'm leaving you."
> 
> 
> Regards
> 
> Adrian

I did check it out.  Loved it.  I'm about to forward it to my coworkers.
I had previously wondered at his Perl zealousy.  Now we see--he just
didn't know any better.

:)

Cheers,
Cliff

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


Re: File to dict

2007-12-07 Thread J. Clifford Dyer

On Fri, 2007-12-07 at 03:31 -0800, [EMAIL PROTECTED] wrote: 
> Hello everyone,
> 
> I have written this small utility function for transforming legacy
> file to Python dict:
> 
> 
> def lookupdmo(domain):
> lines = open('/etc/virtual/domainowners','r').readlines()
> lines = [ [y.lstrip().rstrip() for y in x.split(':')] for x in
> lines]
> lines = [ x for x in lines if len(x) == 2 ]
> d = dict()
> for line in lines:
> d[line[0]]=line[1]
> return d[domain]
> 
> The /etc/virtual/domainowners file contains double-colon separated
> entries:
> domain1.tld: owner1
> domain2.tld: own2
> domain3.another: somebody
> ...
> 
> Now, the above lookupdmo function works. However, it's rather tedious
> to transform files into dicts this way and I have quite a lot of such
> files to transform (like custom 'passwd' files for virtual email
> accounts etc).

Don't do more lookup than you have to to get the answer you need.

(untested code)

class DictFromFile(object):
def __init__(self, filename):
self.f = open(filename)
self.d = dict()

def __getitem__(self, key):
while key not in self.d:
try:
k, v = self._retrieve_next()
self.d[k] = v
if k == key:
break
except StopIteration:
break
return self.d[key]

def _retrieve_next(self):
line = self.f.next()
k, v = line.split(':',1)
return k.strip(), v.strip()


This will act like a dictionary, but only look as far into the file as
it needs to.  If you've got a 10,000 line file, and all your results
come out of the first 10 lines, this will save you some processing.
There's more operator overloading you could do, of course.

Cheers,
Cliff

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


  1   2   >