Is vs Equality Operator

2008-05-01 Thread Good Z
Hello, 
I am having problem in using is. Here is what i am doing.

x=''
if x is None or x is '':
return 1

The above statement does not return value 1.

If i changed the above check to 
if x == None or x == '':
return 1
Now it works fine.

Any idea. What is happening here. I am using python 2.4.4 on ubuntu.

Mike


  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ--
http://mail.python.org/mailman/listinfo/python-list

A bug in difflib module? (find_longest_match)

2008-05-01 Thread n00m
from random import randint

s1 = ''
s2 = ''

for i in xrange(1000):
s1 += chr(randint(97,122))
s2 += chr(randint(97,122))

print s1[:25]
print s2[:25]

import difflib

s = difflib.SequenceMatcher(None, s1, s2)

print s.find_longest_match(0, len(s1), 0, len(s2))



>>> == RESTART 
>>>
yymgzldocfaafcborxbpqyade
urvwtnkwfmcduybjqmrleflqx
(0, 0, 0)
>>>

I think it's line #314 in difflib "who's to blame" --
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing with characters

2008-05-01 Thread Duncan Booth
George Sakkis <[EMAIL PROTECTED]> wrote:

> On Apr 30, 5:06 am, Torsten Bronger <[EMAIL PROTECTED]>
> wrote:
>> Hallöchen!
>>
>> SL writes:
>> > "Gabriel Genellina" <[EMAIL PROTECTED]> schreef in bericht
>> >news:[EMAIL PROTECTED]
>>
>> >> En Wed, 30 Apr 2008 04:19:22 -0300, SL <[EMAIL PROTECTED]> escribió: 
And
>> >> that's a very reasonable place to search; I think chr and ord are
>> >> builtin functions (and not str methods) just by an historical
>> >> accident. (Or is there any other reason? what's wrong with
>> >> "a".ord() or str.from_ordinal(65))?
>>
>> > yes when you know other OO languages you expect this. Anyone know
>> > why builtins were chosen? Just curious
>>
>> *Maybe* for aesthetical reasons.  I find ord(c) more pleasent for
>> the eye.  YMMV.
>>
>> The biggest ugliness though is ",".join().  No idea why this should
>> be better than join(list, separator=" ").  
> 
> Seconded. While we're at it, a third optional 'encode=str' argument
> should be added, to the effect of:
> 
> def join(iterable, sep=' ', encode=str):
> return sep.join(encode(x) for x in iterable)
> 
> I can't count the times I've been bitten by TypeErrors raised on
> ','.join(s) if s contains non-string objects; having to do
> ','.join(map(str,s)) or ','.join(str(x) for x in s) gets old fast.
> "Explicit is better than implicit" unless there is an obvious default.
> 
I'm afraid I don't agree with you on this. Most places where I use join 
I already know the type of the values being joined. In those few cases 
where I want to join non strings, or want to do some other processing on 
the values the generator comprehension is easy and has the advantage 
that I can use a more complex expression than a simple function call 
without having to wrap it in a lambda or otherwise contort things:

e.g. comma.join(x[1] for x in s)
vs.  comma.join(s, encode=operator.itemgetter(1))
or   comma.join(s, encode=lambda x: x[1])

Plus of course, you aren't going to be writing ','.join(str(x) for x in 
s) more than once in any given program before you extract it out to a 
function, are you?

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


Re: calling variable function name ?

2008-05-01 Thread Duncan Booth
"thinkofwhy" <[EMAIL PROTECTED]> wrote:

> Try a dictionary:
> 
> def funcA(blah, blah)
> def funcB(blah, blah)
> def funcC(blah, blah)
> functions = {'A': funcA, 'B': funcB, 'C': 
> funcC}
> user_func = 'A'
> functions[user_func] #execute function

Python has a neat concept for making this easy :^) it is called a class.

class MyFunctions(object):
def funcA(self, param1, param2):
  print "FA " + param1 + " " + param2

def funcB(self, param1, param2):
  print "FB " + param1 + " " + param2

def funcC(self, param1, param2):
  print "FC " + param1 + " " + param2

def defaultFunc(self, *args):
print "Command not recognised"

def doCommand(self, cmd, *args):
return getattr(self, 'func'+cmd, self.defaultFunc)(*args)

functions = MyFunctions()
result = functions.doCommand('A', 'foo', 'bar')

You have to add an extra 'self' argument to each function (or make it a 
staticmethod), but you could always use it to store state without resorting 
to globals.
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to host a membership site

2008-05-01 Thread Jeroen Ruigrok van der Werven
-On [20080430 17:48], Aaron Watters ([EMAIL PROTECTED]) wrote:
>Wow.  An initial glance looks great!  I need help with pronunciation,
>though :(.

Werkzeug is supposed to be pronounced in German.
It translates to 'tool'.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
Heaven can wait 'till another day...
--
http://mail.python.org/mailman/listinfo/python-list

Re: Sending Cntrl-C ??

2008-05-01 Thread Gabriel Genellina
En Wed, 30 Apr 2008 15:06:13 -0300, gamename <[EMAIL PROTECTED]>  
escribió:



win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pgid)


How do you determine the value of 'pgid'?


Make the child start a new process group, then its pid is the process  
group ID. You have to use the "creationflags" parameter of subprocess.open
The documentation for GenerateConsoleCtrlEvent  
http://msdn.microsoft.com/en-us/library/ms683155.aspx states that you  
can't send CTRL_C_EVENT to another process group, only CTRL_BREAK_EVENT  
(and only to the same console as the sender process). A little example:



import subprocess
import ctypes
import time

CREATE_NEW_PROCESS_GROUP = 512
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT = 1
GenerateConsoleCtrlEvent = ctypes.windll.kernel32.GenerateConsoleCtrlEvent

print "start child process"
p = subprocess.Popen("cmd /c for /L %d in (10,-1,0) do @(echo %d && sleep  
1)",

creationflags = CREATE_NEW_PROCESS_GROUP)
print "pid=", p.pid
print "wait 3 secs"
time.sleep(3)
print "send Ctrl-Break"
GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p.pid)
print "wait for child to stop"
print "retcode=", p.wait()
print "done"


Output:

start child process
pid= 872
wait 3 secs
10
9
8
7
send Ctrl-Break
wait for child to stop
retcode= 255
done

(Instead of ctypes and those magical constants, you can install the  
pywin32 package and use win32api.GenerateConsoleCtrlEvent,  
win32con.CTRL_BREAK_EVENT and win32process.CREATE_NEW_PROCESS_GROUP)


The only way I know of to send a Ctrl-C event to a different console  
involves remote code injection.


--
Gabriel Genellina

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


Re: A bug in difflib module? (find_longest_match)

2008-05-01 Thread Gabriel Genellina

En Thu, 01 May 2008 04:35:17 -0300, n00m <[EMAIL PROTECTED]> escribió:


from random import randint

s1 = ''
s2 = ''

for i in xrange(1000):
s1 += chr(randint(97,122))
s2 += chr(randint(97,122))

print s1[:25]
print s2[:25]

import difflib

s = difflib.SequenceMatcher(None, s1, s2)

print s.find_longest_match(0, len(s1), 0, len(s2))




== RESTART 


yymgzldocfaafcborxbpqyade
urvwtnkwfmcduybjqmrleflqx
(0, 0, 0)




I think it's line #314 in difflib "who's to blame" --


Me too. Could you think of some alternative? Simply disabling that  
"popularity check" would slow down the algorithm, according to the  
comments.


--
Gabriel Genellina

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


Re: A bug in difflib module? (find_longest_match)

2008-05-01 Thread n00m


Gabriel Genellina:
> En Thu, 01 May 2008 04:35:17 -0300, n00m <[EMAIL PROTECTED]> escribi�:
>
> > from random import randint
> >
> > s1 = ''
> > s2 = ''
> >
> > for i in xrange(1000):
> > s1 += chr(randint(97,122))
> > s2 += chr(randint(97,122))
> >
> > print s1[:25]
> > print s2[:25]
> >
> > import difflib
> >
> > s = difflib.SequenceMatcher(None, s1, s2)
> >
> > print s.find_longest_match(0, len(s1), 0, len(s2))
> >
> >
> >
>  == RESTART 
> 
> > yymgzldocfaafcborxbpqyade
> > urvwtnkwfmcduybjqmrleflqx
> > (0, 0, 0)
> 
> >
> > I think it's line #314 in difflib "who's to blame" --
>
> Me too. Could you think of some alternative? Simply disabling that
> "popularity check" would slow down the algorithm, according to the
> comments.
>
> --
> Gabriel Genellina

No idea :)
--
http://mail.python.org/mailman/listinfo/python-list

Re: Is vs Equality Operator

2008-05-01 Thread Gary Herron

Good Z wrote:

Hello,
I am having problem in using is. Here is what i am doing.


Short answer:  Use == for equality.Don't use "is".  Ever!  
(Especially if you are a newbie.)


Longer answer:  In a dozen years of programming Python, the only time I 
use "is" is when testing for something like 
 if x is None

but, even then
 if x == None
works just as well, and in any case, there is usually a better way.  
(See below.)


Don't use "is" until you can explain the following
>>> 11 is 10+1
True
>>> 11 is 10+1
False




x=''
if x is None or x is '':
return 1


Both None and an empty string (and empty lists, empty dictionaries, 
empty sets, and numeric values of 0 and 0.0) all evaluate a False in an 
if statement, so the above if statement can be written as


 if not x:
 return 1

If you have to test for None, just do
 if not x:

If you have to differentiate between a value of None and something that 
evaluates to False (e.g., and empty list) then do

 if x is None:
   # handle None explicitly
 elif not x:
   # handle empty list



The above statement does not return value 1.

If i changed the above check to
if x == None or x == '':
return 1
Now it works fine.

Any idea. What is happening here. I am using python 2.4.4 on ubuntu.

Mike


Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try 
it now. 
 




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


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


Re: __getattr__ and recursion ?

2008-05-01 Thread Stef Mientki

thanks Peter,

for your perfect explanation, and

By the way, looping over a dictionary destroys its key advantage, O(1)
lookup. Use

# untested
if attr in self.extra_setters:
self.extra_setters[attr](value)
else:
self.__dict__[attr] = value

and something similar in __getattr__().

  

yes, that's probably much better, have to get used to this Python behavior,
thanks,

cheers,
Stef

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


Re: Python -v import behavior

2008-05-01 Thread M.-A. Lemburg

On 2008-04-30 18:42, Sean Ryan wrote:

Hi all,
(A similar question was posted by a colleague, but did not appear to  reach
comp.lang.python or this list).

I am wondering if the -v option causes the python application to be more
tolerant to module import warnings and / or errors.

The reason is that a module is failing to import correctly (generating an
ImportError exception).  Examining this closer we re-ran the script using
the -v option. to find that "Unsatisfied symbol" errors we being displayed
during import (cx_Oracle 4.3.1, python 2.5.1, HP-UX 11, oracle 9.2).
However, the module is usable from the python prompt (when using -v)
displayed, i.e. dir (cx_Oracle) works correctly, as does  database
interaction.  Without the -v option the script is halted due to the
ImportError exception.

My questions are:
1.  Is there a way to mimic the seemingly more tolerant import behavior  of
python -v without producing the verbose output ?
2.  Is the behavior described above expected and documented ?


The -v option only causes Python to print more information to
stderr explaining where it is looking for modules.

You should be seeing any dynamic loader messages in both cases,
ie. when running with or without -v.

While it is possible that cx_Oracle does some extra processing
when running Python in -v mode, this is rather unlikely.

Note that the best way to track down "unsatified symbol" errors
is to inspect the dependencies of the modules and other shared
libs involved.

Running an strace (or similar system trace utility) will also
help to identify the problem, since this lists the shared libs
the process tries to load when starting up and also during
import of Python modules.

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 01 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: A bug in difflib module? (find_longest_match)

2008-05-01 Thread Gabriel Genellina

En Thu, 01 May 2008 06:21:22 -0300, n00m <[EMAIL PROTECTED]> escribió:


> import difflib
> s = difflib.SequenceMatcher(None, s1, s2)
> print s.find_longest_match(0, len(s1), 0, len(s2))
> (0, 0, 0)
>
> I think it's line #314 in difflib "who's to blame" --

Me too. Could you think of some alternative? Simply disabling that
"popularity check" would slow down the algorithm, according to the
comments.


No idea :)


The "ignore popular elements" is only an optmization, and it should not be  
applied in your case because it forces the algorithm to yield an invalid  
result.

I can think of two alternatives:
- tune up the conditions when the optimization is used, or
- make it user configurable

SequenceMatcher is a public class, and it is also internally used by  
Differ and others to compare both sequences of lines *and* pairs of  
similar lines (considered as sequences of characters). In this last usage  
the "ignore popular elements" has no much sense, as shown in your example  
feeding directly two dissimilar strings.
In principle one should disable the "populardict" stuff when dealing with  
strings. Below is a simple attempt to detect that case:


(around line 311 in difflib.py)

b_is_string = isinstance(b, basestring) # add this line
for i, elt in enumerate(b):
if elt in b2j:
indices = b2j[elt]
if not b_is_string and n >= 200 and len(indices) * 100 >  
n: # change this line

populardict[elt] = 1
del indices[:]
else:
indices.append(i)
else:
b2j[elt] = [i]


--
Gabriel Genellina

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


buy desktop computers

2008-05-01 Thread sharma . mohit80
HP Pavilion Desktop with 17 inch LCD Model No: 6310,
Compaq Presario Desktop Model No: 3153,
Zenith Desktop Model No: 203L-XIl
latest desktop computer available  please visit -
http://www.homeshop18.com/shop/u/y/c-Computers-Q-and-Q-Peripherals-S-Desktops/Home_Online-clI_2-cI_919-pCI_909-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Jeff
Look at the pickle and marshal modules.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is vs Equality Operator

2008-05-01 Thread Christian Heimes
Good Z schrieb:
> Hello, 
> I am having problem in using is. Here is what i am doing.
> 
> x=''
> if x is None or x is '':
> return 1
> 
> The above statement does not return value 1.
> 
> If i changed the above check to 
> if x == None or x == '':
> return 1
> Now it works fine.
> 
> Any idea. What is happening here. I am using python 2.4.4 on ubuntu.

Never use the identity operator "is" on strings and numbers! In most of
the cases it won't do what you are expecting.

The behavior can be explained with with a simple analogy. You have a
street with a STOP sign on both ends. The stop sign on the near end is
equal to the stop sign on the far end. Both have the same form, colors
and meaning. The stop signs are also equal to every other stop sign in
your town. However the stop signs are NOT identical. They occupy two
different places and they are made from two totally different sets of atoms.

When you want to know if the stop sign on the near end is a stop sign,
you have to use the equality == operator. But if you want to check if
you are referring to exactly the one and only stop sign at the near end
of your road and no other sign in the universe you have to use 'is'.

HTH

Christian

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


Re: Is vs Equality Operator

2008-05-01 Thread Michael Mabin
'is' tests for identity (variable references the same memory location) while
'==' tests for equality.  Though it's probably best to use 'is' with more
complex classes and not the simpler built-in types like integers.
See how 'is' works for lists below:

>>> l1 = [1,2,3,4]
>>> l3 = [1,2,3,4]
>>> l1 == l3
True
>>> l1 is l3
False
>>> l2 = l1
>>> l1 is l2
True

l1 and l3 are equal because they contain the same elements. But they are not
identical because they reference different list objects in memory.  On the
other hand, l1 and l2 are identical, so using 'is' in this case tests True.

'is' will be true of the objects tested have the same address in memory.

On Thu, May 1, 2008 at 4:10 AM, Gary Herron <[EMAIL PROTECTED]>
wrote:

> Good Z wrote:
>
> > Hello,
> > I am having problem in using is. Here is what i am doing.
> >
>
> Short answer:  Use == for equality.Don't use "is".  Ever!  (Especially
> if you are a newbie.)
>
> Longer answer:  In a dozen years of programming Python, the only time I
> use "is" is when testing for something like  if x is None
> but, even then
>  if x == None
> works just as well, and in any case, there is usually a better way.  (See
> below.)
>
> Don't use "is" until you can explain the following
> >>> 11 is 10+1
> True
> >>> 11 is 10+1
> False
>
>
>
> > x=''
> > if x is None or x is '':
> >return 1
> >
>
> Both None and an empty string (and empty lists, empty dictionaries, empty
> sets, and numeric values of 0 and 0.0) all evaluate a False in an if
> statement, so the above if statement can be written as
>
>  if not x:
> return 1
>
> If you have to test for None, just do
>  if not x:
>
> If you have to differentiate between a value of None and something that
> evaluates to False (e.g., and empty list) then do
>  if x is None:
>   # handle None explicitly
>  elif not x:
>   # handle empty list
>
>
> > The above statement does not return value 1.
> >
> > If i changed the above check to
> > if x == None or x == '':
> >return 1
> > Now it works fine.
> >
> > Any idea. What is happening here. I am using python 2.4.4 on ubuntu.
> >
> > Mike
> >
> > 
> > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try
> > it now. <
> > http://us.rd.yahoo.com/evt=51733/*http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ%20>
> >
> > 
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

Re: Python 2.6 and wrapping C libraries on Windows

2008-05-01 Thread Christian Heimes
illume schrieb:
> Hi,
> 
> after a little research it appears that win9x is not supported by the
> msvcr90.dll run time.
> 
> Can you confirm this Lenard?
> 
> Has anyone tested the new python binaries that link to msvcr90.dll on
> win9x machines?

It doesn't matter to use because Python 2.6 and 3.0 require at least
Windows 2000 SP4. The 9x, ME and NT series aren't supported any more.

Christian

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread M.-A. Lemburg

On 2008-05-01 13:37, Lance Gamet wrote:

Hi, python beginner starting a new project here.

This project will store most of its actual data in a shared-database, but 
I have a small amount of user specific data that I need to be stored like 
configuration or preferences for example, the list of databases that the 
program should connect to.


On Unix this might be a .file, on windows this could be in the registry, 
or an ini file or an xml file in ProgramData or AppData or something.


Is there a pythony way to store such config data, perhaps there is 
already a standard python package for such a purpose?


I don't think this is a Python question, but more a platform
question. Users on different platforms will expect configuration
data in different places. It's usually best to stick to the platform
conventions.

Python has modules available for accessing INI-files, XML-files
and also for the Windows registry, so that part is easy.

My app uses Qt, and Qt has its method of doing it (QSettings), but for 
architectural reasons I don't want to use it.


Could sqlite be an option perhaps? I am still undecided if the ability 
for the user to edit the file independently of the program is a good or 
bad thing.


If the user is meant to change the data, then you should make this
easy for the user. Putting such data into SQLite will not satisfy that
requirement :-)

If you don't have a GUI tool for the user to change config settings,
then it's probably best to put the configuration into a file that's
easy to edit, e.g. an INI file.

Here's a nice module that supports both reading and writing
INI files:

http://www.voidspace.org.uk/python/configobj.html

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 01 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Photo gallery software

2008-05-01 Thread Jumping Arne
I've searching for some software that would allow me to present my photos on 
the web (I'm not interested a software that generates static pages that I 
upload) and there are quite a few, see for example 
, but I 
haven't managed to find one that I like - Gallery 2 is close.

So I've started to see if there is one that is based python (PHP isn't really 
"my language") but when I search on Google almost the only thing I find are 
photo galleries of snakes (to be honest I didn't know that people were *that* 
interested in pythons).

Do any anyone know if there exists photo gallery software written in Python?

I've found



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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Brian Vanderburg II

Lance Gamet wrote:

Hi, python beginner starting a new project here.

This project will store most of its actual data in a shared-database, but 
I have a small amount of user specific data that I need to be stored like 
configuration or preferences for example, the list of databases that the 
program should connect to.


On Unix this might be a .file, on windows this could be in the registry, 
or an ini file or an xml file in ProgramData or AppData or something.


Is there a pythony way to store such config data, perhaps there is 
already a standard python package for such a purpose?


My app uses Qt, and Qt has its method of doing it (QSettings), but for 
architectural reasons I don't want to use it.


Could sqlite be an option perhaps? I am still undecided if the ability 
for the user to edit the file independently of the program is a good or 
bad thing.


Thanks a lot.
Lance
--
http://mail.python.org/mailman/listinfo/python-list
  

Lance Gamet wrote:

Hi, python beginner starting a new project here.

This project will store most of its actual data in a shared-database, but 
I have a small amount of user specific data that I need to be stored like 
configuration or preferences for example, the list of databases that the 
program should connect to.


On Unix this might be a .file, on windows this could be in the registry, 
or an ini file or an xml file in ProgramData or AppData or something.


Is there a pythony way to store such config data, perhaps there is 
already a standard python package for such a purpose?


My app uses Qt, and Qt has its method of doing it (QSettings), but for 
architectural reasons I don't want to use it.


Could sqlite be an option perhaps? I am still undecided if the ability 
for the user to edit the file independently of the program is a good or 
bad thing.


Thanks a lot.
Lance
--
http://mail.python.org/mailman/listinfo/python-list
  
One way I've just started to use it to create a utility function to 
return the location of the user data folder, depending on the operating 
system:


import os, sys

def GetUserDataDirectory():
   dir = None

   # WINDOWS
   if os.name == "nt":

  # Try env APPDATA or USERPROFILE or HOMEDRIVE/HOMEPATH
  if "APPDATA" in os.environ:
 dir = os.environ["APPDATA"]

  if ((dir is None) or (not os.path.isdir(dir))) and ("USERPROFILE" 
in os.environ):

 dir = os.environ["USERPROFILE"]
 if os.path.isdir(os.path.join(dir, "Application Data")):
dir = os.path.join(dir, "Application Data"))

  if ((dir is None) or (not os.path.isdir(dir))) and ("HOMEDRIVE" 
in os.environ) and ("HOMEPATH" in os.environ):

 dir = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]
 if os.path.isdir(os.path.join(dir, "Application Data")):
dir = os.path.join(dir, "Application Data"))

  if (dir is None) or (not os.path.isdir(dir))
 dir = os.path.expanduser("~")

  # One windows, add vendor and app name
  dir = os.path.join(dir, "vendor", "app")

   # Mac
   elif os.name == "mac": # ?? may not be entirely correct
  dir = os.path.expanduser("~")
  dir = os.path.join(dir, "Library", "Application Support")
  dir = os.path.join(dir, "vendor", "app")

   # Unix/Linux/all others
   else:
  dir = os.path.expanduser("~")
  dir = os.path.join(dir, ".app")
  # Some applications include vendor
  # dir = os.path.join(dir, ".vendor", "app")

   return dir

  
Brian Vanderburg II
  
--

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


Signals/Slots support in Python

2008-05-01 Thread Brian Vanderburg II
I don't know if any such support is already built in, so I ended up 
making my own simple signals/slots like mechanism.  If anyone is 
interested then here it is, along with a simple test.  It can connect to 
normal functions as well as instance methods.  It also supports weak 
connections where when an object is gone, the slot is gone as well, the 
slot just holds a weak reference to the object.


Brian Vanderburg II


# Begin Signal
import weakref
import random

class Signal:
class Slot:
def __init__(self, fn):
self.__fn = fn

def __call__(self, accum, *args, **kwargs):
result = self.__fn(*args, **kwargs)
return accum(result)

class WeakSlot:
def __init__(self, conn, parent, fn, obj):
self.__conn = conn
# Avoid circular references so deleting a signal will
# allow deletion of the signal since the slot doesn't ref
# back to it but only weakefs back to it
self.__parent = weakref.ref(parent)

self.__fn = fn
self.__obj = weakref.ref(obj, self.Cleanup)

def __call__(self, accum, *args, **kwargs):
obj = self.__obj()
if obj is None:
return True

result = self.__fn(obj, *args, **kwargs)
return accum(result)

def Cleanup(self, ref):
parent = self.__parent()
if parent is not None:
parent.Disconnect(self.__conn)

class Accumulator:
def __call__(self, *args, **kwargs):
return True

def Finalize(self):
return None

def __init__(self):
self.__slots = [ ]

# This connects a signal to a slot, but stores a strong reference so
# The object will not be deleted as long as the signal is connected
def Connect(self, fn):
conn = self.NewConn()
self.__slots.append([conn, Signal.Slot(fn)])
return conn

# This connects a signal to a slot, but store a weak reference so
# when the object is gone the slot will not be called.  Because of
# the implemenations, it is not possible to do WeakConnect(obj.Fn),
# since obj.Fn is a new object and would go to 0 refcount soon after
# the call to WeakConnect completes.  Instead we must do a call as
# WeakConnect(ObjClass.Fn, obj)
# Only the object is weak-referenced.  The function object is still
# a normal reference, this ensures that as long as the object exists
# the function will also exist.  When the object dies, the slot will
# be removed
def WeakConnect(self, fn, obj):
conn = self.NewConn()
self.__slots.append([conn, Signal.WeakSlot(conn, self, fn, obj)])
return conn

# Disconnect a slot
def Disconnect(self, conn):
result = self.Find(conn)
if result >= 0:
del self.__slots[result]

# Disconnect all slots
def DisconnectAll(self):
self.__slots = [ ]

# Create an accumulator.  Accumulator will be called as a callable
# for each return value of the executed slots.  Execution of slots
# continues as long as the reutrn value of the accumulator call is
# True.  The 'Finalize'function will be called to get the result
# A custom accumulator can be created by deriving from Signal and
# Creating a custom 'Accumulator' class, or by deriving from Singal
# and creating CreateAccumulator
def CreateAccumulator(self):
return self.Accumulator()

# Execute the slots
def __call__(self, *args, **kwargs):
accum = self.CreateAccumulator()
for conn in xrange(len(self.__slots)):
if not self.__slots[conn][1](accum, *args, **kwargs):
break
return accum.Finalize()

# Create a connection name
def NewConn(self):
value = 0
while self.Find(value) >= 0:
value = random.randint(1, 1)
return value

def Find(self, conn):
for i in xrange(len(self.__slots)):
if self.__slots[i][0] == conn:
return i

return -1

# End Signal

def fn1():
print "Hello World"

def fn2():
print "Goodbye Space"

class O:
def __init__(self, value):
self.value = value

def Action(self):
print "O %d" % self.value

a = Signal()

a.Connect(fn1)
a.Connect(fn2)

print "Part 1"
a()

a.DisconnectAll()

o1 = O(4)
o2 = O(12)

a.WeakConnect(O.Action, o1)
a.Connect(o2.Action)

print "Part 2"
a()

print "Part 3"
o1 = None
a()

print "Part 4"
o2 = None
a()

a.DisconnectAll()

def f1():
print "Hello Neighbor"

def f2():
print "Back to Work"

c1 = a.Connect(f1)
c2 = a.Connect(f2)

print "Part 5"
a()

print "Part 6"
a.Disconnect(c2)
a()

a.DisconnectAll()

def f1(name):
print "Hello %s" % na

Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Diez B. Roggisch

Lance Gamet schrieb:

Hi, python beginner starting a new project here.

This project will store most of its actual data in a shared-database, but 
I have a small amount of user specific data that I need to be stored like 
configuration or preferences for example, the list of databases that the 
program should connect to.


On Unix this might be a .file, on windows this could be in the registry, 
or an ini file or an xml file in ProgramData or AppData or something.


Is there a pythony way to store such config data, perhaps there is 
already a standard python package for such a purpose?


My app uses Qt, and Qt has its method of doing it (QSettings), but for 
architectural reasons I don't want to use it.


Could sqlite be an option perhaps? I am still undecided if the ability 
for the user to edit the file independently of the program is a good or 
bad thing.


I'd go for .file in ConfigParser-format that resides in the users 
home-directory. ConfigParser is a standard lib module for .ini-like files.



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


Re: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching

2008-05-01 Thread Istvan Albert
On Apr 29, 3:51 am, "Zed A. Shaw" <[EMAIL PROTECTED]> wrote:

> You can grab the most recent draft of the book at:
>
>  http://zedshaw.com/projects/vellum/manual-final.pdf

> However, I'm curious to get other people's thoughts.

IMO if you would refrain from using swear words in the manual it would
help broadening its reach and acceptance.

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


Re: Cookie Confusion - How to Set a Cookie

2008-05-01 Thread cbhoem
On Apr 29, 3:35 pm, Aaron Watters <[EMAIL PROTECTED]> wrote:
> > Thanks for the code, Aaron.  I will give it a try.
>
> > I've been reading some more about cookielib and am not sure whether I
> > should use Cookie or cookielib.  This is what I want to do:  a user is
> > going to login.  Upon a successful login, I want to write their name
> > and date/time of visit to a cookie file. Which is the correct python
> > module to use?
>
> Cookie does parsing and generation of cookie strings
> for server-side applications like your CGI script.
>
> The cookielib module
> is designed for either implementing a client like a web browser
> or emulating a client/browser (for web scraping, for example).
>
> I think you want to use Cookie.
> The distinction could be made clearer in
> the docs, imho.
>
> Also, when you say "write the cookie file" I think you mean
> "store the cookie to the client browser".  This should happen
> automatically when you send the cookie header to the client
> correctly (if the client is configured to cooperate).
>
>   -- Aaron Watters
>
> ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=default+does+n...


Sorry for the slow replies.  I've been in & out with a sick child.

I'm used to my javascript cookies.  They are automatically written to
a cookie.txt file in a .mozilla dir under my user.  When I say to
'write the cookie file' this is what I was referring to.  I was
expecting my python cookie to automatically get written to the same
file.  I have't seen this happen yet.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Vellum 0.16: Lots Of Documentation and Watching

2008-05-01 Thread python
Zed,

Read the first 2 chapters of your book and love it! Fun to read - I like
your writing style. I agreed with most of your premises/philosophies -
very refreshing.

I didn't find your language offensive but you might consider toning down
your review of the Awesome Window Manager :)

When do you plan on posting your next update?

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Nick Craig-Wood
Lance Gamet <[EMAIL PROTECTED]> wrote:
>  This project will store most of its actual data in a shared-database, but 
>  I have a small amount of user specific data that I need to be stored like 
>  configuration or preferences for example, the list of databases that the 
>  program should connect to.
> 
>  On Unix this might be a .file, on windows this could be in the registry, 
>  or an ini file or an xml file in ProgramData or AppData or something.
> 
>  Is there a pythony way to store such config data, perhaps there is 
>  already a standard python package for such a purpose?

I've found

  http://docs.python.org/lib/module-ConfigParser.html

To be easy to use and built in.  It makes human readable / editable
.ini - like files.

As for where to store it, I use os.path.expanduser("~") to find the
base directory and a bit of platform specific code.

Something like this snippet

self.is_windows = sys.platform == 'win32'
self.home = os.path.expanduser("~")
if self.is_windows:
self.config_dir = os.path.join(self.home, "Application Data", self.NAME)
else:
self.config_dir = os.path.join(self.home, "."+self.NAME)
if not os.path.isdir(self.config_dir):
os.makedirs(self.config_dir, mode=0700)
self.config_file = os.path.join(self.config_dir, "config")

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


Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread idev
Hi all,
Please help me with my stuff.

I downloaded python 2.5.1 package from http://blastwave.org it was
compiled using Sun Studio 11 for Solaris 8 sparc.

My system is Solaris 10 sparc and I compiled using SunStudio 11
psycopg2 python binding for PostgreSQL 8.3.1.

Compilation was OK, but when I am trying to import psycopg2 I am
getting this error:

$ python
Python 2.5.1 (r251:54863, Nov  3 2007, 02:54:52) [C] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
Traceback (most recent call last):
  File "", line 1, in 
  File "/opt/csw/lib/python/site-packages/psycopg2/__init__.py", line
60, in 
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: ld.so.1: python: fatal: relocation error: file /opt/csw/
lib/python/site-packages/psycopg2/_psycopg.so: symbol round:
referenced symbol not found

Any suggestions or help will be appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread Ralf Schönian

idev schrieb:

Hi all,
Please help me with my stuff.

I downloaded python 2.5.1 package from http://blastwave.org it was
compiled using Sun Studio 11 for Solaris 8 sparc.

My system is Solaris 10 sparc and I compiled using SunStudio 11
psycopg2 python binding for PostgreSQL 8.3.1.

Compilation was OK, but when I am trying to import psycopg2 I am
getting this error:

$ python
Python 2.5.1 (r251:54863, Nov  3 2007, 02:54:52) [C] on sunos5
Type "help", "copyright", "credits" or "license" for more information.

import psycopg2

Traceback (most recent call last):
  File "", line 1, in 
  File "/opt/csw/lib/python/site-packages/psycopg2/__init__.py", line
60, in 
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: ld.so.1: python: fatal: relocation error: file /opt/csw/
lib/python/site-packages/psycopg2/_psycopg.so: symbol round:
referenced symbol not found

Any suggestions or help will be appreciated.


Hi,

maybe a stupid question - but why don't you want to use the "official" 
package? You can download it here: 
http://sunfreeware.mirrors.tds.net/indexsparc10.html


Regards,
Ralf
--
http://mail.python.org/mailman/listinfo/python-list


free fiction-- look

2008-05-01 Thread mickey333
http://www.authspot.com/Short-Stories/Disability.107809
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread Martin v. Löwis

> lib/python/site-packages/psycopg2/_psycopg.so: symbol round:
> referenced symbol not found

You need to link _psycopg.so with the math library, -lm.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread idev
On May 1, 10:17 am, Ralf Schönian <[EMAIL PROTECTED]> wrote:
> idev schrieb:
>
>
>
> > Hi all,
> > Please help me with my stuff.
>
> > I downloaded python 2.5.1 package fromhttp://blastwave.orgit was
> > compiled using Sun Studio 11 for Solaris 8 sparc.
>
> > My system is Solaris 10 sparc and I compiled using SunStudio 11
> > psycopg2 python binding for PostgreSQL 8.3.1.
>
> > Compilation was OK, but when I am trying to import psycopg2 I am
> > getting this error:
>
> > $ python
> > Python 2.5.1 (r251:54863, Nov  3 2007, 02:54:52) [C] on sunos5
> > Type "help", "copyright", "credits" or "license" for more information.
>  import psycopg2
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "/opt/csw/lib/python/site-packages/psycopg2/__init__.py", line
> > 60, in 
> > from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
> > ImportError: ld.so.1: python: fatal: relocation error: file /opt/csw/
> > lib/python/site-packages/psycopg2/_psycopg.so: symbol round:
> > referenced symbol not found
>
> > Any suggestions or help will be appreciated.
>
> Hi,
>
> maybe a stupid question - but why don't you want to use the "official"
> package? You can download it 
> here:http://sunfreeware.mirrors.tds.net/indexsparc10.html
>
> Regards,
> Ralf

I am trying to deploy Django env (apache2.x prefork MPM; mod_python
3.3.1; python 2.5.1; postgresql 8.3.x; psycopg2-2.0.7; subversion
1.4.5.x; openssl 0.98;) on Solaris 10 sparc box.
You are right they have pretty much everything what I need except
mod_python and psycopg2. So the first problem was PostgreSQL. It was
compiled without (--with-thread-safety) just ./configure. I compiled
psycopg2 by myself using gcc but I couldn't compile mod_pyhon by some
reasons. That is why I switched to blastwave.org they have everything
what I need except psycopg2. I compiled it by my self. And now I am
having the ld problems and I don't know how to resolve it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread idev
On May 1, 10:30 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > lib/python/site-packages/psycopg2/_psycopg.so: symbol round:
> > referenced symbol not found
>
> You need to link _psycopg.so with the math library, -lm.
>
> Regards,
> Martin

Martin, could you please tell me how to do this, I am pretty new in
Solaris.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Signals/Slots support in Python

2008-05-01 Thread Scott SA
On 5/1/08, Brian Vanderburg II ([EMAIL PROTECTED]) wrote:

>I don't know if any such support is already built in, so I ended up 
>making my own simple signals/slots like mechanism.  If anyone is 
>interested then here it is, along with a simple test.  It can connect to 
>normal functions as well as instance methods.  It also supports weak 
>connections where when an object is gone, the slot is gone as well, the 
>slot just holds a weak reference to the object.

Did you review this?


from what I understand is originally based upon this:


and subsequently integrated into this:


>-
># Begin Signal
>import weakref
>import random
>
>class Signal:
>class Slot:
>def __init__(self, fn):
>self.__fn = fn
>
>def __call__(self, accum, *args, **kwargs):
>result = self.__fn(*args, **kwargs)
>return accum(result)
>
>class WeakSlot:
>def __init__(self, conn, parent, fn, obj):
>self.__conn = conn
># Avoid circular references so deleting a signal will
># allow deletion of the signal since the slot doesn't ref
># back to it but only weakefs back to it
>self.__parent = weakref.ref(parent)
>
>self.__fn = fn
>self.__obj = weakref.ref(obj, self.Cleanup)
>
>def __call__(self, accum, *args, **kwargs):
>obj = self.__obj()
>if obj is None:
>return True
>
>result = self.__fn(obj, *args, **kwargs)
>return accum(result)
>
>def Cleanup(self, ref):
>parent = self.__parent()
>if parent is not None:
>parent.Disconnect(self.__conn)
>
>class Accumulator:
>def __call__(self, *args, **kwargs):
>return True
>
>def Finalize(self):
>return None
>
>def __init__(self):
>self.__slots = [ ]
>
># This connects a signal to a slot, but stores a strong reference so
># The object will not be deleted as long as the signal is connected
>def Connect(self, fn):
>conn = self.NewConn()
>self.__slots.append([conn, Signal.Slot(fn)])
>return conn
>
># This connects a signal to a slot, but store a weak reference so
># when the object is gone the slot will not be called.  Because of
># the implemenations, it is not possible to do WeakConnect(obj.Fn),
># since obj.Fn is a new object and would go to 0 refcount soon after
># the call to WeakConnect completes.  Instead we must do a call as
># WeakConnect(ObjClass.Fn, obj)
># Only the object is weak-referenced.  The function object is still
># a normal reference, this ensures that as long as the object exists
># the function will also exist.  When the object dies, the slot will
># be removed
>def WeakConnect(self, fn, obj):
>conn = self.NewConn()
>self.__slots.append([conn, Signal.WeakSlot(conn, self, fn, obj)])
>return conn
>
># Disconnect a slot
>def Disconnect(self, conn):
>result = self.Find(conn)
>if result >= 0:
>del self.__slots[result]
>
># Disconnect all slots
>def DisconnectAll(self):
>self.__slots = [ ]
>
># Create an accumulator.  Accumulator will be called as a callable
># for each return value of the executed slots.  Execution of slots
># continues as long as the reutrn value of the accumulator call is
># True.  The 'Finalize'function will be called to get the result
># A custom accumulator can be created by deriving from Signal and
># Creating a custom 'Accumulator' class, or by deriving from Singal
># and creating CreateAccumulator
>def CreateAccumulator(self):
>return self.Accumulator()
>
># Execute the slots
>def __call__(self, *args, **kwargs):
>accum = self.CreateAccumulator()
>for conn in xrange(len(self.__slots)):
>if not self.__slots[conn][1](accum, *args, **kwargs):
>break
>return accum.Finalize()
>
># Create a connection name
>def NewConn(self):
>value = 0
>while self.Find(value) >= 0:
>value = random.randint(1, 1)
>return value
>
>def Find(self, conn):
>for i in xrange(len(self.__slots)):
>if self.__slots[i][0] == conn:
>return i
>
>return -1
>
># End Signal
>
>def fn1():
>print "Hello World"
>
>def fn2():
>print "Goodbye Space"
>
>class O:
>def __init__(self, value):
>self.value = value
>
>def Action(self):
>print "O %d" % self.value
>
>a = Signal()
>
>a.Connect(fn1)
>a.Connect(fn2)
>
>print 

Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 08:30:03 -0500, Nick Craig-Wood wrote:

> Lance Gamet <[EMAIL PROTECTED]> wrote:
>>  This project will store most of its actual data in a shared-database,
>>  but I have a small amount of user specific data that I need to be
>>  stored like configuration or preferences for example, the list of
>>  databases that the program should connect to.
>> 
>>  On Unix this might be a .file, on windows this could be in the
>>  registry, or an ini file or an xml file in ProgramData or AppData or
>>  something.
>> 
>>  Is there a pythony way to store such config data, perhaps there is
>>  already a standard python package for such a purpose?
> 
> I've found
> 
>   http://docs.python.org/lib/module-ConfigParser.html
> 
> To be easy to use and built in.  It makes human readable / editable .ini
> - like files.

IMO .ini-like config files are from the stone age. The modern approach is 
to use YAML (http://www.yaml.org). 

It has a lot of advantages over .ini and xml, YAML syntax was designed to 
be easily mapped to Python data types and is very similar to Python.

More at http://en.wikipedia.org/wiki/YAML

As for where to store it, I completely agree with Nick Craig-Wood.

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


is +=1 thread safe

2008-05-01 Thread AlFire

Hi,

I have a piece of software which uses threads in very massive way - like 
hundreds of  them generated every second.


there is also a piece of code which maintains the number of outstanding 
threads, simply


counter+=1 is executed when before starting the thread and counter-=1 
after it finishes.


all is very simple and by the end of the program life I expect the 
counter to zero out.


however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as expected.

I guarded those statement with Lock.{acquire,release} and now it always 
returns 0.



But I still can not believe that +=1 is not a thread safe operation.


Any clue?

--

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


simple beginner question about lists and negative index

2008-05-01 Thread jmDesktop
This program:

s = 'abcde'
i = -1
for i in range (-1, -len(s), -1):
print s[:i], i

gives

abcd -1
abc -2
ab -3
a -4

Why doesn't the first one have the e if -1 is the end of the list?  In
Dive Into Python it said that -1 was the end of the list.  Thanks.

it is from Chun's book, slightly modified by me to see the index.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Photo gallery software

2008-05-01 Thread Scott SA
On 5/1/08, Jumping Arne ([EMAIL PROTECTED]) wrote:

>I've searching for some software that would allow me to present my photos on 
>the web (I'm not interested a software that generates static pages that I 
>upload) and there are quite a few, see for example 
>, but I 
>haven't managed to find one that I like - Gallery 2 is close.
>
>So I've started to see if there is one that is based python (PHP isn't really 
>"my language") but when I search on Google almost the only thing I find are 
>photo galleries of snakes (to be honest I didn't know that people were *that* 
>interested in pythons).
>
>Do any anyone know if there exists photo gallery software written in Python?
>
>I've found
>
>

I've been working with Photologue for a while with some nice results.


It is a Django project 
,

It includes support for tagging:
 

It easily allows configuration of different image sizes and integrates with 
generic templates providing gallery and detail view support. 

HTH

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


Re: Signals/Slots support in Python

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 08:44:27 -0600, Scott SA wrote:

> Did you review this?
> 
> 
> from what I understand is originally based upon this:
> 
> 
> and subsequently integrated into this:
> 

AFAIK PyDispatcher evolved into Louie project [1]. Louie has more 
features, but dispatch module inside Django is dramatically faster and is 
going to be even faster.

[1] http://pylouie.org/

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


Re: simple beginner question about lists and negative index

2008-05-01 Thread jmDesktop
On May 1, 10:59 am, jmDesktop <[EMAIL PROTECTED]> wrote:
> This program:
>
> s = 'abcde'
> i = -1
> for i in range (-1, -len(s), -1):
>     print s[:i], i
>
> gives
>
> abcd -1
> abc -2
> ab -3
> a -4
>
> Why doesn't the first one have the e if -1 is the end of the list?  In
> Dive Into Python it said that -1 was the end of the list.  Thanks.
>
> it is from Chun's book, slightly modified by me to see the index.

Sorry.  It's because of the : right?  up to but not including.  Dive
into was just list[-1] not list[:-1].  I looked at the for while
before posting and then as soon as I posted I saw it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is +=1 thread safe

2008-05-01 Thread Jeff
If no other threads will be accessing the counter, there will be no
problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Photo gallery software

2008-05-01 Thread Scott Sandeman-Allen
On 5/1/08, Jumping Arne ([EMAIL PROTECTED]) wrote:

>I've searching for some software that would allow me to present my photos on 
>the web (I'm not interested a software that generates static pages that I 
>upload) and there are quite a few, see for example 
>, but I 
>haven't managed to find one that I like - Gallery 2 is close.
>
>So I've started to see if there is one that is based python (PHP isn't really 
>"my language") but when I search on Google almost the only thing I find are 
>photo galleries of snakes (to be honest I didn't know that people were *that* 
>interested in pythons).
>
>Do any anyone know if there exists photo gallery software written in Python?
>
>I've found
>
>

I've been working with Photologue for a while with some nice results.


It is a Django project 
,

It includes support for tagging:
 

It easily allows configuration of different image sizes and integrates with 
generic templates providing gallery and detail view support. 

HTH

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


Re: computing with characters

2008-05-01 Thread George Sakkis
On May 1, 3:36 am, Duncan Booth <[EMAIL PROTECTED]> wrote:

> George Sakkis <[EMAIL PROTECTED]> wrote:
> > On Apr 30, 5:06 am, Torsten Bronger <[EMAIL PROTECTED]>
> > wrote:
> >> Hallöchen!
>
> >> SL writes:
> >> > "Gabriel Genellina" <[EMAIL PROTECTED]> schreef in bericht
> >> >news:[EMAIL PROTECTED]
>
> >> >> En Wed, 30 Apr 2008 04:19:22 -0300, SL <[EMAIL PROTECTED]> escribió:
> And
> >> >> that's a very reasonable place to search; I think chr and ord are
> >> >> builtin functions (and not str methods) just by an historical
> >> >> accident. (Or is there any other reason? what's wrong with
> >> >> "a".ord() or str.from_ordinal(65))?
>
> >> > yes when you know other OO languages you expect this. Anyone know
> >> > why builtins were chosen? Just curious
>
> >> *Maybe* for aesthetical reasons.  I find ord(c) more pleasent for
> >> the eye.  YMMV.
>
> >> The biggest ugliness though is ",".join().  No idea why this should
> >> be better than join(list, separator=" ").
>
> > Seconded. While we're at it, a third optional 'encode=str' argument
> > should be added, to the effect of:
>
> > def join(iterable, sep=' ', encode=str):
> > return sep.join(encode(x) for x in iterable)
>
> > I can't count the times I've been bitten by TypeErrors raised on
> > ','.join(s) if s contains non-string objects; having to do
> > ','.join(map(str,s)) or ','.join(str(x) for x in s) gets old fast.
> > "Explicit is better than implicit" unless there is an obvious default.
>
> I'm afraid I don't agree with you on this. Most places where I use join
> I already know the type of the values being joined. In those few cases
> where I want to join non strings, or want to do some other processing on
> the values the generator comprehension is easy and has the advantage
> that I can use a more complex expression than a simple function call
> without having to wrap it in a lambda or otherwise contort things:
>
> e.g. comma.join(x[1] for x in s)
> vs.  comma.join(s, encode=operator.itemgetter(1))
> or   comma.join(s, encode=lambda x: x[1])

You don't have to use encode; you can write it as
join((x[1] for x in s), comma)

The main benefit of encode is its obvious default (=str), otherwise
it's not strictly necessary (although it is handy for named functions
e.g. encode=repr).

> Plus of course, you aren't going to be writing ','.join(str(x) for x in
> s) more than once in any given program before you extract it out to a
> function, are you?

In fact I am, not every one-liner needs to be a function. Just the
fact that such a function would live in a general utils module that I
have to import in most of my other modules (effectively making it a
two-liner) is not worth the few extra keystrokes.

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


Re: is +=1 thread safe

2008-05-01 Thread Duncan Booth
AlFire <[EMAIL PROTECTED]> wrote:

> But I still can not believe that +=1 is not a thread safe operation.
> 
> 
> Any clue?

The statement:

x+=1

is equivalent to:

  x = x.__iadd__(1)

i.e. a function call followed by an assignment.

If the object is mutable then this *may* be safe so long as you never do 
any other assignment to x (the __iadd__ method will return the object being 
mutated so the assignment would in this restricted case be a noop).

Integers are immutable, so the assignment must always rebind x to a new 
object. There is no way given Python's semantics that this could be thread 
safe.

Generating hundreds of threads is, BTW, a very good way to get poor 
performance on any system. Don't do that. Create a few threads and put the 
actions for those threads into a Queue. If you want the threads to execute 
in parallel investigate using sub-processes.

The threading module already has a function to return the number of Thread 
objects currently alive.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is +=1 thread safe

2008-05-01 Thread John Nagle

AlFire wrote:

Hi,
all is very simple and by the end of the program life I expect the 
counter to zero out.


however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as expected.

I guarded those statement with Lock.{acquire,release} and now it always 
returns 0.



But I still can not believe that +=1 is not a thread safe operation.


Any clue?


   "counter += 1" is not an atomic operation, apparently.  Sorry.

   However, appending and removing from a list or dict are atomic operations,
because if they were not, memory allocation would break.

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


Re: is +=1 thread safe

2008-05-01 Thread Diez B. Roggisch

AlFire schrieb:

Hi,

I have a piece of software which uses threads in very massive way - like 
hundreds of  them generated every second.


there is also a piece of code which maintains the number of outstanding 
threads, simply


counter+=1 is executed when before starting the thread and counter-=1 
after it finishes.


all is very simple and by the end of the program life I expect the 
counter to zero out.


however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as expected.

I guarded those statement with Lock.{acquire,release} and now it always 
returns 0.



But I still can not believe that +=1 is not a thread safe operation.


don't confuse augmented assignment with incrementation as it is offered 
by C (if your data-type actually fits into a single addressable memory 
spot, that is)


python's += works like this


a += b  <=> a = a.__iadd__(b)

Thus you actually get a situation where the expression on the right is 
evaluated but not yet assigned - and then another thread can take over 
control, computing  with the old value of a.


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


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread Martin v. Löwis
> Martin, could you please tell me how to do this, I am pretty new in
> Solaris.

It's fairly complicated, so I'm not sure I can give you the full
tutorial in a Usenet message.

In essence, you need to spot the linker line in the build process,
(e.g. by the -o option to the compiler), and add -lm to it.

If you cannot do this on your own, I recommend you hire somebody
who can.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread idev
On May 1, 11:41 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Martin, could you please tell me how to do this, I am pretty new in
> > Solaris.
>
> It's fairly complicated, so I'm not sure I can give you the full
> tutorial in a Usenet message.
>
> In essence, you need to spot the linker line in the build process,
> (e.g. by the -o option to the compiler), and add -lm to it.
>
> If you cannot do this on your own, I recommend you hire somebody
> who can.
>
> Regards,
> Martin

Thanks Martin,
For sure I am not maintainer :).

Thanks for the help and explanations.
--
http://mail.python.org/mailman/listinfo/python-list


Symposium “Image Processing and Analysis” within the ICCES'09 Thailand - Announce & Call for Papers

2008-05-01 Thread [EMAIL PROTECTED]
(Our apologies for cross-posting.
We appreciate if you kindly distribute this information by your co-
workers and colleagues.)

**

Symposium “Image Processing and Analysis”
International Conference on Computational & Experimental Engineering
and Sciences 2009 (ICCES'09)
Phuket, Thailand, 8-13 April 2009
http://icces.org/cgi-bin/ices09/pages/index

**

Dear Colleague,

Within the International Conference on Computational & Experimental
Engineering and Sciences 2009 (ICCES'09), to be held in Phuket,
Thailand, in 8-13 April 2009, we are organizing the Symposium “Image
Processing and Analysis”.
Examples of some topics that will be considered in that symposium are:
Image restoring, Description, Compression, Segmentation and
Description; Objects tracking, Matching, Reconstruction and
Registration; Visualization Enhance; Simulation and Animation;
Software Development for Image Processing and Analysis; Grid Computing
in Image Processing and Analysis; Applications of Image Processing and
Analysis.

Due to your research activities in those fields, we would like to
invite you to submit your work and participate in the Symposium “Image
Processing and Analysis”.

For instructions and submission, please access to the conference
website at: http://icces.org/cgi-bin/ices09/pages/index.
Please note, when submitting your work you should choose the Symposium
“Image Processing and Analysis”.

Important dates and Instructions:

- 15 Oct 2008: Start abstract submission;
- 1 Jan 2009: Deadline for abstract submission;
- 10 Jan 2009: End of abstract selection.
If you intend to submit your work please notify as soon as possible
the main organizer of your intention ([EMAIL PROTECTED]);
Instructions for authors are available at: 
http://icces.org/cgi-bin/ices09/pages/guide.


With kind regards,
Yours sincerely,

The Organizers,

João Manuel R. S. Tavares ([EMAIL PROTECTED]) (main organizer)
Faculty of Engineering of University of Porto, Porto, Portugal
Yongjie (Jessica) Zhan ([EMAIL PROTECTED])
Department of Mechanical Engineering, Carnegie Mellon University,
Pittsburgh, USA
Maria João M. Vasconcelos ([EMAIL PROTECTED])
Faculty of Engineering of University of Porto, Porto, Portugal
--
http://mail.python.org/mailman/listinfo/python-list


PyGame, window is not closing, tut not helping

2008-05-01 Thread globalrev
im doing this :
http://www.learningpython.com/2006/03/12/creating-a-game-in-python-using-pygame-part-one/

and when closing the program the window stays up and doesnt respond. i
tried adding this:
http://www.pygame.org/wiki/FrequentlyAskedQuestions

bu it doesnt work, or maybe im doing it wrong.

heres the code without the added tutorial exit:


import os, sys
import pygame
from pygame.locals import *

if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'

class PyManMain:
"""The Main PyMan Class - This class handles the main
initialization and creating of the Game."""

def __init__(self, width=640,height=480):
"""Initialize"""
"""Initialize PyGame"""
pygame.init()
"""Set the window Size"""
self.width = width
self.height = height
"""Create the Screen"""
self.screen = pygame.display.set_mode((self.width
   , self.height))


def MainLoop(self):
"""This is the Main Loop of the Game"""
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()


class Snake(pygame.sprite.Sprite):
"""This is our snake that will move around the screen"""

def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('snake.png',-1)
self.pellets = 0

if __name__ == "__main__":
MainWindow = PyManMain()
MainWindow.MainLoop()

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


Re: PyGame, window is not closing, tut not helping

2008-05-01 Thread globalrev
another program that has the same problem:
import sys, pygame
pygame.init()

size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("snake.png")
ballrect = ball.get_rect()

while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()

ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]

screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Jon Ribbens
On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> IMO .ini-like config files are from the stone age. The modern approach is 
> to use YAML (http://www.yaml.org). 

You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
and so comprehensively and completely fails to achieve its stated
main goal of being "readable by humans", that I had assumed it
was an April Fool along the lines of Intercal or brainf***.

I certainly wouldn't recommend it as being suitable for, well,
anything at all.

Or were you trolling and I missed the joke? ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGame, window is not closing, tut not helping

2008-05-01 Thread Mike Driscoll
On May 1, 10:55 am, globalrev <[EMAIL PROTECTED]> wrote:
> im doing this 
> :http://www.learningpython.com/2006/03/12/creating-a-game-in-python-us...
>
> and when closing the program the window stays up and doesnt respond. i
> tried adding this:http://www.pygame.org/wiki/FrequentlyAskedQuestions
>
> bu it doesnt work, or maybe im doing it wrong.
>
> heres the code without the added tutorial exit:
>
> import os, sys
> import pygame
> from pygame.locals import *
>
> if not pygame.font: print 'Warning, fonts disabled'
> if not pygame.mixer: print 'Warning, sound disabled'
>
> class PyManMain:
>     """The Main PyMan Class - This class handles the main
>     initialization and creating of the Game."""
>
>     def __init__(self, width=640,height=480):
>         """Initialize"""
>         """Initialize PyGame"""
>         pygame.init()
>         """Set the window Size"""
>         self.width = width
>         self.height = height
>         """Create the Screen"""
>         self.screen = pygame.display.set_mode((self.width
>                                                , self.height))
>
>     def MainLoop(self):
>         """This is the Main Loop of the Game"""
>         while 1:
>             for event in pygame.event.get():
>                 if event.type == pygame.QUIT:
>                     sys.exit()
>
> class Snake(pygame.sprite.Sprite):
>     """This is our snake that will move around the screen"""
>
>     def __init__(self):
>         pygame.sprite.Sprite.__init__(self)
>         self.image, self.rect = load_image('snake.png',-1)
>         self.pellets = 0
>
> if __name__ == "__main__":
>     MainWindow = PyManMain()
>     MainWindow.MainLoop()

I think the issue is that you're running it from within IDLE. It looks
like pyGame's event loop and Tkinter's event loop interfere with each
other. If you run the scripts from the command line, it works.

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


Re: Is vs Equality Operator

2008-05-01 Thread Terry Reedy

"Good Z" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hello,
| I am having problem in using is. Here is what i am doing.
|
| x=''
| if x is None or x is '':
|return 1

x is not the singleton value None, nor is it the newly created null string 
object.  It is up to the implementation whether each instance of '' reuses 
one cached (or interned) null string object or creates another.  Don't 
depend on such behavior unless you really mean it.  Same goes for comparing 
ints.

|
| The above statement does not return value 1.
|
| If i changed the above check to
| if x == None or x == '':
|return 1
| Now it works fine.

x still is not None but does equal in value ''

I recommend here

if x is None or x == '': ...

tjr



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


Re: Zope/DTML Infuriating...

2008-05-01 Thread Michael Torrie
Jens wrote:
> - Why is it, when primitive data types seem to be objects (similar to
> javascript), that type casting is done through build-in functions
> rather than methods, e.g. String.toInt('5') or '5'.toInt() or x =
> Integer.fromString('5').

Mainly because it's much cleaner to do it the python way (absolutely
explicit), and just as clear or clearer what you are intending to do.
Digging a little deeper, you'll find that the built-in function "str,"
for example, actually calls object.__str__().  This is nice because it
allows any object class to define that method and have it work with
str() in a manner consistent across python.  It preserves some amount of
uniformity.

The second example, x = Integer.fromString('5') demonstrates a huge
weakness in Java.  In python, rather than asking an integer object to
convert from a limited selection of other objects, python works the
other way, asking objects to convert themselves to integers (if they
can).  We don't worry about the size of integers, since python's
integers are auto-sizing.  So any object that implements the __int__()
method can be used with the classic "int()" built-in function.  The same
goes for __float__ and float().

Little things like this really make me happy about how python does
things generally.  I think much of how Java works with Integer and
String (as you describe above) is because Java has primitive types
(which aren't objects at all) and then boxed objects around the
primitive types.  Python eliminates this idea, and makes everything,
even "simple" types objects.

Now sure python could just say always call the "int()" or "float()" or
"str()" method on objects to produce those respective conversions.  But
using a combination of a built-in language function and a specialized,
reserved class method name, allows a lot of flexibility without
infringing on the programmer's need to use method names like "int,
float, or str" if he or she so desired.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Carl Banks
On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>
> > IMO .ini-like config files are from the stone age. The modern approach is
> > to use YAML (http://www.yaml.org).
>
> You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
> and so comprehensively and completely fails to achieve its stated
> main goal of being "readable by humans", that I had assumed it
> was an April Fool along the lines of Intercal or brainf***.


YAML, ISTM, took a simple concept that worked for small,
straightforward data, and tried to make into a format that could
anything anywhere, with disastrous results.  It's not unlike Perl in
this regard.  It's quite ridiculous.


My recommendation to the OP would be:

If you intend to write a GUI that completely sets all the options, use
XML.  You can bet there are some users who would prefer text editing
options files, and XML, while not the most readable format available,
at least gives users the option.

If you don't intend to write a GUI to do that, write a simple text
file parser (if the options are simple), use ConfigParser, or use a
Python file that you exec.

Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
ApplicationData/Appname/config.ext on Windows.  I don't recommend
using the Windows registry to store options; use it to modify Windows
behavior (like file associations) but keep your own program's options
in your own file.


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


my module and unittest contend over commandline options...

2008-05-01 Thread chrisber
using the unittest module in Python 2.3.5, I've written some test code
that ends up with

if __name__ == "__main__":
unittest.main()

Since I want to run this code in various environments, I'd initially
added some commandline options, e.g. to specify a configuration file
like so

 test.py -c devtest.conf
or
 test.py -c localtest.conf

etc.
However, unittest also looks for options on the commandline, and it
was complaining about unrecognized options and quitting.

I've poked around to see if I could delete the options my earlier code
consumed from the commandline buffer, before invoking unittest, but
that seems klugy. Instead, I hardwired  in a testing config file name,
that always has to be local. That works pretty well, but it leaves me
wonderfing whether there would have been another clean way to allow
both my test code and unittest to have options without interfering
with one another.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Zope/DTML Infuriating...

2008-05-01 Thread Michael Torrie
Michael Torrie wrote:
> The second example, x = Integer.fromString('5') demonstrates a huge
> weakness in Java.  

Ahem.  Javascript.  Sorry.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Photo gallery software

2008-05-01 Thread Jumping Arne
On Thu, 1 May 2008 16:59:33 +0200, Scott Sandeman-Allen wrote
(in article <[EMAIL PROTECTED]>):

> I've been working with Photologue for a while with some nice results.
> 

Looks like it's time to start reading that Django book.

Thanks, JA

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


Re: pop langs website ranking

2008-05-01 Thread Jon Harrop
[EMAIL PROTECTED] wrote:
> Alexa's data is more reliable than quantcast.

Alexa claim to have accurate data on lots of sites but I just tried to
correlate their data with the exact data on our web server and the
discrepancies are huge. For example, combining our number of absolute
visitors with their measure of "reach" for our site indicates that there
are 58 billion internet users.

So their data are not even order-of-magnitude accurate. The only web analyst
I ever met was an astrophysicist so this does not really surprise me. ;-)

-- 
Dr Jon D Harrop, Flying Frog Consultancy
http://www.ffconsultancy.com/products/?u
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple beginner question about lists and negative index

2008-05-01 Thread Terry Reedy

"jmDesktop" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| This program:
|
| s = 'abcde'
| i = -1
| for i in range (-1, -len(s), -1):
|print s[:i], i
|
| gives
|
| abcd -1
| abc -2
| ab -3
| a -4
|
| Why doesn't the first one have the e if -1 is the end of the list?  In
| Dive Into Python it said that -1 was the end of the list.  Thanks.

A sequence with n items has n+1 slice positions, numbered 0 to n: the 2 at 
beginning and end and n-1 between items.  Example
-a-b-c-
0 1 2 3
has 4 slice positions.
Hence the first item is seq[0:1] and last is seq[n-1:n]

In a sense, we 'ought' to index sequences with average of two successive 
slice positions, giving seq[1/2],,,seq[n-1/2].
But this is inconvenient, so we either round down (C, Python, etc) or up 
(Fortran), giving seq[0]seq[n-1] or seq[1],,,seq[n].
Python allows n-1 and n-k to be abbreviated as -1 and -k.

-1 as an abbreviation of n-1 is only the end of the list for indexing.
n is the end for slicing.  It is abbreviated by omission.  Perhaps

for i in range(n+1): print i, 'abcde'[:5-i]

will make this all even clearer.

Terry Jan Reedy




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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 11:11:29 -0500, Jon Ribbens wrote:

> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> IMO .ini-like config files are from the stone age. The modern approach
>> is to use YAML (http://www.yaml.org).
> 
> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and so
> comprehensively and completely fails to achieve its stated main goal of
> being "readable by humans", that I had assumed it was an April Fool
> along the lines of Intercal or brainf***.
> 
> I certainly wouldn't recommend it as being suitable for, well, anything
> at all.
> 
> Or were you trolling and I missed the joke? ;-)

No, it isn't. I acually find it usefull and readable. I don't think that 
programmers at Google would use something that is a joke. 

I used XML files before for this purpose and found YAML much easier and 
better suitable for the task.

Please explain why don't like YANL so much?

PS. Your reply remind me of early days of Python when Perl programmers 
said exacly the same thing about Python.

-- 
Ivan


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


Re: Stream I/O to a java applet (os.popen?)

2008-05-01 Thread Michael Torrie
Cody Woolaver wrote:
> This is all done at the terminal though and i need to have it done through a 
> python file. I'm aware that i will have to use os.popen but am unfamiliar 
> with how it works.

You'll probably want to look at the subprocess module, which replaces
the old os.popen stuff.  It's also a bit better at running on Windows.
There are lots of docs and examples relating to subprocess.  Probably
some good recipes too, especially for running on windows.  I'd begin by
looking on google for "python subprocess example windows."

Bear in mind interactive control of a subprocess is sometimes fraught
with difficulty, as it's easy to deadlock if you're waiting for the
subprocess to say something and it's waiting for you to say something.

On another track, you might want to consider using Jython, as it will
allow your python class file to interact directly with the Java stuff,
rather than having to do it via pipes and subprocesses.  The only
downside to Jython currently is it's stuck at Python 2.2 stuff.  But
it's a nice integration of Java and Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Zope/DTML Infuriating...

2008-05-01 Thread Michael L Torrie
Michael Torrie wrote:
> The second example, x = Integer.fromString('5') demonstrates a huge
> weakness in Java.  

Ahem.  Javascript.  Sorry.

-- 
Michael Torrie
Assistant CSR, System Administrator
Chemistry and Biochemistry Department
Brigham Young University
Provo, UT 84602
+1.801.422.5771

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:

> On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
>> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>>
>> > IMO .ini-like config files are from the stone age. The modern
>> > approach is to use YAML (http://www.yaml.org).
>>
>> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and
>> so comprehensively and completely fails to achieve its stated main goal
>> of being "readable by humans", that I had assumed it was an April Fool
>> along the lines of Intercal or brainf***.
> 
> 
> YAML, ISTM, took a simple concept that worked for small, straightforward
> data, and tried to make into a format that could anything anywhere, with
> disastrous results.  It's not unlike Perl in this regard.  It's quite
> ridiculous.
> 
> 
> My recommendation to the OP would be:
> 
> If you intend to write a GUI that completely sets all the options, use
> XML.  You can bet there are some users who would prefer text editing
> options files, and XML, while not the most readable format available, at
> least gives users the option.
> 
> If you don't intend to write a GUI to do that, write a simple text file
> parser (if the options are simple), use ConfigParser, or use a Python
> file that you exec.
> 
> Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
> ApplicationData/Appname/config.ext on Windows.  I don't recommend using
> the Windows registry to store options; use it to modify Windows behavior
> (like file associations) but keep your own program's options in your own
> file.
> 
> 
> Carl Banks

If you don't like YAML, use JSON or something similar -- XML is overkill 
and .INI is too limited.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Patrick Mullen
YAML is a joke if you expect a windows user to be able to hand edit the
data.  Windows users typically expect a .ini file in the application's
directory.  (Usually not the users home directory, even if that may be a
better location).  XML is ok, but .ini is much preferred.

If you have a configuration gui or whatever and the file doesn't need to be
hand edited, it doesn't really matter what format you store it in.  Sqlite
db would be fine in this case.  Still keep the file as a ".yourappname" file
in users home linux directory, and probably do as mentioned above and keep
it in their windows home directory.
--
http://mail.python.org/mailman/listinfo/python-list

Problems with Cheese Shop

2008-05-01 Thread Torsten Bronger
Hallöchen!

How can I authorise to the Python Cheese Shop in order to use
setup.py upload?  Currently, I get

Upload failed (401): You must be identified to edit package information

Thanks!

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with Cheese Shop

2008-05-01 Thread Christian Heimes
Torsten Bronger schrieb:
> Hallöchen!
> 
> How can I authorise to the Python Cheese Shop in order to use
> setup.py upload?  Currently, I get
> 
> Upload failed (401): You must be identified to edit package information

Try "python setup.py register sdist upload"

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


Python application distribution

2008-05-01 Thread ron.longo

I haven't figured out a way to do this but see no reason why it cannot be
done.  I have a decent size application written in 100% Python.  I would
like to distribute this application, but only the .pyc files.  Since the
.pyc's are just the compiled sources I figured it would work, but if I copy
just the pyc's and my main app's py into a directory by themselves, I'm
unable to execute.  Why is this?  At this point I'm not really keen on
handing out the source files to my application, it feels unprofessional.

Thanks,
Ron
-- 
View this message in context: 
http://www.nabble.com/Python-application-distribution-tp16993351p16993351.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Tremendous slowdown due to garbage collection

2008-05-01 Thread Dieter Maurer
John Nagle <[EMAIL PROTECTED]> writes on Mon, 28 Apr 2008 11:41:41 -0700:
> Dieter Maurer wrote:
> > Christian Heimes <[EMAIL PROTECTED]> writes on Sat, 12 Apr 2008 18:47:32 
> > +0200:
> >> [EMAIL PROTECTED] schrieb:
> >>> which made me suggest to use these as defaults, but then
> 
> > We observed similar very bad behaviour -- in a Web application server.
> > Apparently, the standard behaviour is far from optimal when the
> > system contains a large number of objects and occationally, large
> > numbers of objects are created in a short time.
> > We have seen such behaviour during parsing of larger XML documents, for
> > example (in our Web application).
> 
> Our solution to that was to modify BeautifulSoup to use weak pointers.
> All the pointers towards the root and towards previous parts of the
> document are "weak".  As a result, reference counting alone is sufficient
> to manage the tree.  We still keep GC enabled, but it doesn't find much
> to collect.

It will not help in our setup.

We, too, have almost no cycles -- but the GC does not know this:

  If a large number of objects are created temporarily and not released
  before the generation 1 threshoold is reached, then
  the garbage collector will start collections -- even, if there
  are no or very few cycles.
  A generation 2 garbage collection takes time proportional
  to the total number of (GC aware) objects -- independent of
  the number of cycles.

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


send gpg encrypted emails (properly mime formatted)

2008-05-01 Thread Neal Becker
Any ideas on python packages that could help with sending gpg encrypted
(properly mime formatted) emails?

My idea is to forward all my emails to a remote imap server, but gpg encrypt
them to myself in the process.

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


Re: Problems with Cheese Shop

2008-05-01 Thread Torsten Bronger
Hallöchen!

Christian Heimes writes:

> Torsten Bronger schrieb:
>
>> How can I authorise to the Python Cheese Shop in order to use
>> setup.py upload?  Currently, I get
>> 
>> Upload failed (401): You must be identified to edit package
>> information
>
> Try "python setup.py register sdist upload"

I forgot to say that the package itself is already there, just not
the current release.  Is "register" still the way to go?

Thank you!

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with Cheese Shop

2008-05-01 Thread Martin v. Löwis
> How can I authorise to the Python Cheese Shop in order to use
> setup.py upload?  Currently, I get
> 
> Upload failed (401): You must be identified to edit package information

You need to add your PyPI password to .pypirc.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python application distribution

2008-05-01 Thread Martin v. Löwis
> I haven't figured out a way to do this but see no reason why it cannot be
> done.  I have a decent size application written in 100% Python.  I would
> like to distribute this application, but only the .pyc files.  Since the
> .pyc's are just the compiled sources I figured it would work, but if I copy
> just the pyc's and my main app's py into a directory by themselves, I'm
> unable to execute.  Why is this?

This should work fine. What precisely are you doing to execute it, and
how precisely does it fail?

> At this point I'm not really keen on
> handing out the source files to my application, it feels unprofessional.

I don't consider it unprofessional. If the software is packaged that
the end user readily notices the difference - that's unprofessional.
IOW, unless the user browsers your app's directory, he shouldn't even
have to know that the application is written in Python.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: tool to calculate color combination

2008-05-01 Thread Max M

Astan Chee skrev:

Hi,
I was just wondering if there is a tool/script in python that allows me 
to do color calculations; specifically, when I add them.


There is the colorsys module which I have used in this class:




from colorsys import rgb_to_hls, hls_to_rgb
import binascii
from types import StringType, TupleType, ListType, IntType, FloatType
from math import modf

class RGB:
""" Makes it easier to work with rgb colors """

def __init__(self, color):
# set color value
self.color = self.any2color(color)

def any2color(self, color):
"""
Takes a number of color formats and returns a sequence of 3 
floats:

(r,g,b)
Some legal formats for pure blue are: 
'0xFF','#FF','FF',

[0.0, 0.0, 1.0], [0, 0, 255], (0, 0.0, 'FF') and ('0', '0', 'f').
Mixed types are allowed in sequences.
"""
# it must be a hex, so convert to sequence of hex values
if isinstance(color, StringType):
# handle hex value
if color[:2].lower() == '0x': color = color[2:]
elif color[0] == '#': color = color[1:]
color = (color[:2], color[2:4], color[4:])
# convert sequence to floats
color_result = []
a = color_result.append
for part in color:
# what type is the part?
if isinstance(part, StringType): # hex part
if len(part) == 1:
part = '0%s' % part
b = binascii.a2b_hex(part)
a(ord(b[0])/255.0)
elif isinstance(part, IntType): # int part
a(part/255.0)
elif isinstance(part, FloatType): # float part
a(part)
return color_result


def __str__(self):
"Returns string representation of color (same as html_hex)"
return self.html_hex()


def r(self):
return self.color[0]

def g(self):
return self.color[1]

def b(self):
return self.color[2]


def bytes(self):
"""
Takes a sequence of colors in floats, and returns a sequence of 
int in

the range 0-255
"""
return map(lambda x: int(x*255), self.color)


def html_hex(self):
"""
Returns the color in a hex string representation of the form 
'#FF'

"""
r,g,b = self.color
return '#%02X%02X%02X' % (int(r*255),int(g*255),int(b*255))


def _cAdd(self, x, y):
"Private method! Cirkular add x+y so value allways in 0.0-1.0 
range"

fractional, integer  = modf(x + y)
if not fractional and integer: # special case 1.0
return 1.0
return abs(fractional)
# wrong result for negative values!


def hls_delta(self, dh, dl, ds):
"""
Returns a Color object same as self, but adjusted by delta hls
values
"""
h,l,s = rgb_to_hls(*self.color)
nh = self._cAdd(h, dh)
nl = l + dl
if nl > 1.0: nl = 1.0
if nl < 0.0: nl = 0.0
ns = s + ds
if ns > 1.0: ns = 1.0
if ns < 0.0: ns = 0.0
return RGB(hls_to_rgb(nh, nl, ns))


def change_ls(self, new_l=None, new_s=None):
"""
Returns a Color object same as self, but with new lightness and
saturation levels
"""
h,l,s = rgb_to_hls(*self.color)
if new_l == None:
new_l = l
if new_s == None:
new_s = s
return RGB(hls_to_rgb(h, new_l, new_s))


def spacer(self, transparent=None):
"""
Creates a 1x1 GIF89a of color. If no color it returns a 
transparent gif

Should probably not be in this module?
"""
template = [71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 0, 0, 255, 
255,
255, 0, 0, 0, 33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 
1, 0,

0, 2, 2, 68, 1, 0, 59]
if not transparent:
template[13:16] = self.bytes() # set rgb values
template[22] = 0 # remove transparency
return ''.join(map(chr, template))



if __name__=='__main__':

red = (255, 0, 0)
green   = (0.0, 1.0, 0.0)
blue= (0.0, 0.0, 1.0)
yellow  = '#00'

col = RGB(blue)
print col.color
print col.bytes()
print col

brighter = col.change_ls(0.0, 0.0)
print 'brighter:',brighter

#complementary = col.hls_delta(0.50, 0.0, 0.0)
#print complementary


--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

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


Re: DO U WANT TO KNOW ABOUT SCIENTOLOGY?

2008-05-01 Thread Mensanator
On May 1, 8:11�am, [EMAIL PROTECTED] wrote:
> � � � � � � � � � � HELLO FRIEND IAM SHALINI,
>
> � � � � � � � � � � � � � � � � � � � � DO U WANT TO KNOW ABOUT
> SCIENTOLOGY?

Do I need to know about wiping my ass with a rock?

Oh, wait...that's Islam, isn't it?

Sorry, I often get those two confused.

Scientology and ass wiping.

>
> � � � � � � � � � � � � � � � � � � � � � � �PLS LOOK AT THE BELOW
> WEBSITE.
>
> � � � � � � � � � � � � � � � � � � � � � � � � �www.bigconcern3.blogspot.com

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

Re: DO U WANT TO KNOW ABOUT SCIENTOLOGY?

2008-05-01 Thread Danyelle Gragsone
<3 BAHAHAHAA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Matimus
On May 1, 4:37 am, Lance Gamet <[EMAIL PROTECTED]> wrote:
> Hi, python beginner starting a new project here.
>
> This project will store most of its actual data in a shared-database, but
> I have a small amount of user specific data that I need to be stored like
> configuration or preferences for example, the list of databases that the
> program should connect to.
>
> On Unix this might be a .file, on windows this could be in the registry,
> or an ini file or an xml file in ProgramData or AppData or something.
>
> Is there a pythony way to store such config data, perhaps there is
> already a standard python package for such a purpose?
>
> My app uses Qt, and Qt has its method of doing it (QSettings), but for
> architectural reasons I don't want to use it.
>
> Could sqlite be an option perhaps? I am still undecided if the ability
> for the user to edit the file independently of the program is a good or
> bad thing.
>
> Thanks a lot.
> Lance

sqlite is a wonderful option, if the user doesn't need to directly
edit it.

Alternatively, you might consider just using python code. Something
like this:

[config_file.py]
class Config:
   optiona = 1
   optionb = 2
[/end file]

Then, in your code you can just:

>>> import imp
>>> m = imp.load_source("config_file", "./config_file.py") # use appropriate 
>>> path (of course)
>>> m.Config.optiona
1
>>> m.Config.optionb
2

Like any other solution, this option has advantages and disadvantages,
but I think it is worth exploring. The class method in the above code
is just an example, choose whatever format is appropriate.

As for generating the contents of the file, tripple quoted strings and
`%r` are your friends.

Matt

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Carl Banks
On May 1, 1:30 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:
> > On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> >> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>
> >> > IMO .ini-like config files are from the stone age. The modern
> >> > approach is to use YAML (http://www.yaml.org).
>
> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and
> >> so comprehensively and completely fails to achieve its stated main goal
> >> of being "readable by humans", that I had assumed it was an April Fool
> >> along the lines of Intercal or brainf***.
>
> > YAML, ISTM, took a simple concept that worked for small, straightforward
> > data, and tried to make into a format that could anything anywhere, with
> > disastrous results.  It's not unlike Perl in this regard.  It's quite
> > ridiculous.
>
> > My recommendation to the OP would be:
>
> > If you intend to write a GUI that completely sets all the options, use
> > XML.  You can bet there are some users who would prefer text editing
> > options files, and XML, while not the most readable format available, at
> > least gives users the option.
>
> > If you don't intend to write a GUI to do that, write a simple text file
> > parser (if the options are simple), use ConfigParser, or use a Python
> > file that you exec.
>
> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
> > ApplicationData/Appname/config.ext on Windows.  I don't recommend using
> > the Windows registry to store options; use it to modify Windows behavior
> > (like file associations) but keep your own program's options in your own
> > file.
>
> If you don't like YAML, use JSON or something similar -- XML is overkill
> and .INI is too limited.


I don't think you know the OP's requirements enough to know whether
INI or XML is suitable. You're welcome to suggest alternatives but
what I suggested is fine.

As for XML being overkill for anything, I highly disagree. XML is
suitable for the smallest tasks.  These days I use XML for almost all
my data exchange needs: including conf files.  Elementtree makes it
possible to process XML and pull out some typical data in ten or so
lines of code.  What could possibly be overkill about that?


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


data manipulation

2008-05-01 Thread Krishna
I have a script that reads an excel file and and do manipulations on
it. But, now, I have a text file that needs the same manipulation. I
tried the same script, but it will not work, when I use command such
as: workbook = xlrd.open_workbook('C:/trial.txt'), its giving me
errors saying "expected BOF record". I was wondering how to work
around this. Do I have to do some format conversion to accomplish this
or am I missing something

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Jon Ribbens
On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> I used XML files before for this purpose and found YAML much easier and 
> better suitable for the task.
>
> Please explain why don't like YANL so much?

Because even the examples in the spec itself are unreadable gibberish.
The PyYAML library is over 300kB! These are rather big clues that it's
unsuitable for the purpose for which it was designed. It's certainly
unsuitable for use as a configuration file format, where it is
overkill by several orders of magnitude.

  !!str &a1 "foo":
  !!str bar
  &a2 baz : *a1
  ! foo :
  ! baz

This is supposed to be human readable?

> PS. Your reply remind me of early days of Python when Perl programmers 
> said exacly the same thing about Python.

I think I would suffer irony overload if I saw a Perl programmer
criticising Python for being hard to read ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Micah Elliott
On 2008-05-01 Carl Banks wrote:

> If you don't intend to write a GUI to do that, write a simple
> text file parser (if the options are simple), use ConfigParser,
> or use a Python file that you exec.

INI is great for so many things.  It is also extremely
commonplace, regardless of platform.  The biggest challenge might
be choosing which one to adopt:

http://wiki.python.org/moin/ConfigParserShootout

-- 
Micah Elliott | [EMAIL PROTECTED] | http://MicahElliott.blogspot.com


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: data manipulation

2008-05-01 Thread Jeff
The function expects an excel file.  It cannot read a plain text
file.  You would need to figure out a way to convert the text file
data into an excel format and save it to a new file first.

The proper way to handle this is to make your data processing
functions expect a defined format.  Then, you write importer functions
for various types of files that convert the data in each file to the
defined format.  That way, you can support various file formats and
reuse your processing functions on all of them.
--
http://mail.python.org/mailman/listinfo/python-list


Python Wins "Favorite Scripting Language" Award

2008-05-01 Thread Steve Holden
The Linux Journal readers apparently suffer the same ambiguity as the 
rest of us when it comes to defining what the difference between a 
scripting language and a programming language.


They do, however, clearly like Python, which they voted their scripting 
language of 2008. PHP, Bash and Perl came in reasonably close on 
Python's heels, but 28.9% of those voting voted for Python.


See all the awards at

  http://www.linuxjournal.com/article/10065

regards
 Steve
--
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: i want to add a timeout to my code

2008-05-01 Thread maehhheeyy
On Apr 29, 3:29 pm, John Krukoff <[EMAIL PROTECTED]> wrote:
> On Tue, 2008-04-29 at 14:47 -0700, maehhheeyy wrote:
> > On Apr 17, 4:24 pm, Miki <[EMAIL PROTECTED]> wrote:
> > > On Apr 17, 1:10 pm,maehhheeyy<[EMAIL PROTECTED]> wrote:
>
> > > > I want to add a timeout so that when I pull out my gps from my serial
> > > > port, it would wait for a bit then loop and then see if it's there. I
> > > > also want to add a print statement saying that there is no GPS device
> > > > found. However when I run my code and unplug my serial port, my code
> > > > will just hang until I plug it back in.
> > > > This is my code right now:
>
> > > > def GetGPS():
> > > >       data = []
> > > >       #Open com1: 9600,8,N,1
> > > >       fi = serial.Serial(0, timeout = 1)
> > > >       print '[gps module] SERIAL PORT OPEN ON COM1:'
>
> > > > can anyone help me please? Thanks.
>
> > >http://docs.python.org/lib/node545.html
>
> > > HTH,
> > > --
> > > Miki <[EMAIL PROTECTED]>http://pythonwise.blogspot.com
>
> > I tried the code onto my codes but what came out was that in the line
> > signal.signal(signal.SIGSLRM, handler), an attributeError appeared
> > reading that 'module' object has no attribute 'SIGALRM'
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Are you writing your program on windows, or some other platform which is
> not unix?
>
> --
> John Krukoff <[EMAIL PROTECTED]>
> Land Title Guarantee Company- Hide quoted text -
>
> - Show quoted text -

Yeah I'm using Windows 2000.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread tinnews
Carl Banks <[EMAIL PROTECTED]> wrote:
> On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> > On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> >
> > > IMO .ini-like config files are from the stone age. The modern approach is
> > > to use YAML (http://www.yaml.org).
> >
> > You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
> > and so comprehensively and completely fails to achieve its stated
> > main goal of being "readable by humans", that I had assumed it
> > was an April Fool along the lines of Intercal or brainf***.
> 
> 
> YAML, ISTM, took a simple concept that worked for small,
> straightforward data, and tried to make into a format that could
> anything anywhere, with disastrous results.  It's not unlike Perl in
> this regard.  It's quite ridiculous.
> 
> 
> My recommendation to the OP would be:
> 
> If you intend to write a GUI that completely sets all the options, use
> XML.  You can bet there are some users who would prefer text editing
> options files, and XML, while not the most readable format available,
> at least gives users the option.
> 
But XML has human unfriendly syntax, is awkward to type, is difficult
to read, what's good about it?  If there's a GUI between you and the
XML then OK, but that wasn't where we were was it?

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 14:13:08 -0500, Jon Ribbens wrote:

> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> I used XML files before for this purpose and found YAML much easier and
>> better suitable for the task.
>>
>> Please explain why don't like YANL so much?
> 
> Because even the examples in the spec itself are unreadable gibberish.
> The PyYAML library is over 300kB! These are rather big clues that it's
> unsuitable for the purpose for which it was designed. It's certainly
> unsuitable for use as a configuration file format, where it is overkill
> by several orders of magnitude.
> 
>   !!str &a1 "foo":
>   !!str bar
>   &a2 baz : *a1
>   ! foo :
>   ! baz
> 
> This is supposed to be human readable?

Thanx, now I see your point. I didn't mean all the fancy features of 
YAML, but the most basic sintax.

Compare this:

Bob
Abooey
adv
555-1212
[EMAIL PROTECTED]
[EMAIL PROTECTED]


and this:
babooey:
computer : cpu1
firstname: Bob
lastname: Abooey
cell: 555-1212
addresses:
- address: [EMAIL PROTECTED]
  password: 
- address: [EMAIL PROTECTED]
  password: 

I find the latter *much* more readable.

And the most important thing is that it *maps directly to Python data 
types*, in this case dictionaries and lists:
{babooey: {computer: cpu1, firstname: Bob, lastname: Abooey, cell: 555, 
1212, addresses: [{address: [EMAIL PROTECTED], password: },
{address: [EMAIL PROTECTED], password: }]}

I took the example from 
http://www.kuro5hin.org/story/2004/10/29/14225/062
I haven't use my own example only because I don't have one at hand right 
now. YAML, in its simple form, definetely makes me more productive. I 
wasted too much time with XML in the past and I won't ever use it as a 
serialization or config/settings format again. .INI/ConfigParser is too 
limited and has no standards. I just don't see anything better than YAML 
to do human and Python editable config files and to serialize information 
for later use.

>> PS. Your reply remind me of early days of Python when Perl programmers
>> said exacly the same thing about Python.
> 
> I think I would suffer irony overload if I saw a Perl programmer
> criticising Python for being hard to read ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: send gpg encrypted emails (properly mime formatted)

2008-05-01 Thread Mike Driscoll
On May 1, 12:57 pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> Any ideas on python packages that could help with sending gpg encrypted
> (properly mime formatted) emails?
>
> My idea is to forward all my emails to a remote imap server, but gpg encrypt
> them to myself in the process.

Take a look at this for the gpg part:

http://wiki.python.org/moin/GnuPrivacyGuard

And the standard library has the email module which does mime
formatting.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 11:56:20 -0700, Carl Banks wrote:

> On May 1, 1:30 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:
>> > On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
>> >> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>>
>> >> > IMO .ini-like config files are from the stone age. The modern
>> >> > approach is to use YAML (http://www.yaml.org).
>>
>> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
>> >> and so comprehensively and completely fails to achieve its stated
>> >> main goal of being "readable by humans", that I had assumed it was
>> >> an April Fool along the lines of Intercal or brainf***.
>>
>> > YAML, ISTM, took a simple concept that worked for small,
>> > straightforward data, and tried to make into a format that could
>> > anything anywhere, with disastrous results.  It's not unlike Perl in
>> > this regard.  It's quite ridiculous.
>>
>> > My recommendation to the OP would be:
>>
>> > If you intend to write a GUI that completely sets all the options,
>> > use XML.  You can bet there are some users who would prefer text
>> > editing options files, and XML, while not the most readable format
>> > available, at least gives users the option.
>>
>> > If you don't intend to write a GUI to do that, write a simple text
>> > file parser (if the options are simple), use ConfigParser, or use a
>> > Python file that you exec.
>>
>> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
>> > ApplicationData/Appname/config.ext on Windows.  I don't recommend
>> > using the Windows registry to store options; use it to modify Windows
>> > behavior (like file associations) but keep your own program's options
>> > in your own file.
>>
>> If you don't like YAML, use JSON or something similar -- XML is
>> overkill and .INI is too limited.
> 
> 
> I don't think you know the OP's requirements enough to know whether INI
> or XML is suitable. You're welcome to suggest alternatives but what I
> suggested is fine.
>
> As for XML being overkill for anything, I highly disagree. XML is
> suitable for the smallest tasks.  These days I use XML for almost all my
> data exchange needs: including conf files.  Elementtree makes it
> possible to process XML and pull out some typical data in ten or so
> lines of code.  What could possibly be overkill about that?
> 
> 
> Carl Banks

I used XML for almost everything in the past until I found YAML. 
Elementtree makes it easy but not easy enough. The most powerful thing 
about YAML is that it was designed to map directly to native data types 
in languages like Python (see another my post in this thread for 
example). And this means that simple YAML files will always be easier to 
process in Python than XML or INI. And this in turn means that OP with 
any requirements will have to write less code to read and write his 
config files.

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


Getting started with pyvtk

2008-05-01 Thread Peter Pearson
I'm trying to get started with pyvtk, the Python interface
to the Visualization Toolkit, but there's obviously
something important that I haven't figured out after an
embarrassingly long morning of googling around.  When I run
sample pyvtk code (example1.py, from
http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/pyvtk/examples/example1.py),
nothing graphical happens, but some text files appear named
example1.vtk and example1b.vtk.  Guessing that I need to
feed one of these to vtk, I tried "vtk spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting started with pyvtk

2008-05-01 Thread Paul Melis
On 1 mei, 22:54, Peter Pearson <[EMAIL PROTECTED]> wrote:
> I'm trying to get started with pyvtk, the Python interface
> to the Visualization Toolkit,

It looks like you're using this package:
http://cens.ioc.ee/projects/pyvtk/

These are not the official Python bindings to VTK, but seem to be an
add-on that allow you to manipulate VTK _files_ from Python.

The official bindings are included in the VTK distribution and can be
enabled at build-time (assuming you build VTK yourself).

For a simple example that will open a window and show some 3D object,
see for example the example code the vtkConeSource class:
http://public.kitware.com/cgi-bin/viewcvs.cgi/*checkout*/Examples/Tutorial/Step1/Python/Cone.py?root=VTK&content-type=text/plain

> Simply running "vtk" (apparently 4.0)

VTK 4.0 is really really old. Consider switching to 5.0 at least or
use the CVS version if you feel adventurous.

Hope this helps,
Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Torsten Bronger
Hallöchen!

Ivan Illarionov writes:

> [...]
>
> I took the example from
> http://www.kuro5hin.org/story/2004/10/29/14225/062 I haven't use
> my own example only because I don't have one at hand right
> now. YAML, in its simple form, definetely makes me more
> productive. I wasted too much time with XML in the past and I
> won't ever use it as a serialization or config/settings format
> again. .INI/ConfigParser is too limited and has no standards. I
> just don't see anything better than YAML to do human and Python
> editable config files and to serialize information for later use.

Okay, but serialisation is something completely different.  Nobody
would use INI files for it.

For other things, it simply depends on the use case.  For example, I
*know* that the configuration files of my pet project will not
exceed the dumb section.key=value scheme so anything else would be
overkill.

Besides, YAML adds another dependency.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
--
http://mail.python.org/mailman/listinfo/python-list


where do I begin with web programming in python?

2008-05-01 Thread jmDesktop
I have been to the main python site, but am still confused.  I have
been using .net, so it may be obvious how to do this to everyone
else.  I am aware there are various frameworks (Django, Pylons, etc.),
but I would like to know how to create web pages without these.  If I
have mod_python or fastcgi on apache, where do I start?  I don't have
clue where to begin to create a web page from scratch in python.  I am
sure I will want to access database, etc., all the "normal" stuff, I
just want to do it myself as opposed to the frameworks, for learning.

Thank you for any help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: where do I begin with web programming in python?

2008-05-01 Thread Mike Driscoll
On May 1, 4:25 pm, jmDesktop <[EMAIL PROTECTED]> wrote:
> I have been to the main python site, but am still confused.  I have
> been using .net, so it may be obvious how to do this to everyone
> else.  I am aware there are various frameworks (Django, Pylons, etc.),
> but I would like to know how to create web pages without these.  If I
> have mod_python or fastcgi on apache, where do I start?  I don't have
> clue where to begin to create a web page from scratch in python.  I am
> sure I will want to access database, etc., all the "normal" stuff, I
> just want to do it myself as opposed to the frameworks, for learning.
>
> Thank you for any help.

The web frameworks make it a lot easier. But you can use the httplib
modules. You should check out the wiki: 
http://wiki.python.org/moin/WebProgramming

There's also a couple of books on the topic: "Python Web Programming"
by Steve Holden, and "Web Programming in Python" by Thiruvathukal.

Check out the cgi-type stuff especially.

Hope that helps some.

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


dropping win98 support? was Re: Python 2.6 and wrapping C libraries on Windows

2008-05-01 Thread illume
Ah, why is that?

There's still at least 1.1% of people using win98, if you believe this
source of stats:
http://www.w3schools.com/browsers/browsers_os.asp

I just noticed that win9x winme and win nt are all being dropped from
python.

I know they are old and crufty, but there's still heaps of people
using them.

Someone pointed me to the pep, where the un-support seems planned:
http://www.python.org/dev/peps/pep-0011/


Seems like a lot of people using it, so it's still worthwhile making
2.6 work with win98.





On May 1, 10:09 pm, Christian Heimes <[EMAIL PROTECTED]> wrote:
> illume schrieb:
>
> > Hi,
>
> > after a little research it appears that win9x is not supported by the
> > msvcr90.dll run time.
>
> > Can you confirm thisLenard?
>
> > Has anyone tested the new python binaries that link to msvcr90.dll on
> > win9x machines?
>
> It doesn't matter to use because Python 2.6 and 3.0 require at least
> Windows 2000 SP4. The 9x, ME and NT series aren't supported any more.
>
> Christian

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


Is anyone using Python for embedded applications?

2008-05-01 Thread Lori Welte
Hi Dean

 

I need a minimalist version of Python to run on a ColdFire-based
embedded system (written in C with no RTOS). It will be used by
mechanical engineers to test their servo and stepper motors. I need all
the basic features you are providing in PyMite.

 

I've managed to port PyMite and run a test "trivial" on my embedded
platform, but I am a bit confused about whether this is really what I
need.

 

I need an interactive Python interpreter running on my embedded...I will
be feeding it lines through my USB connection. It seems that PyMite is
not exactly what I'm looking for (?). I expected to be able to do
something like pm_run("abs(-1)") for example, but that doesn't work.
After reading carefully your docs, it seems like in fact that PyMite
should be used by writing Python programs on a PC, running your
PyImageCreator, then rebuilding the embedded with the native C code, and
downloading the image file to the embedded? Although this is pretty
nifty, this won't work for my needs.

 

Could you confirm that PyMite does not run like pm_run() =
PyRun_SimpleString() or if it does, what am I missing?

 

Thanks so much for all your excellent software

Lori Welte

"firmwaregirl"

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

Re: where do I begin with web programming in python?

2008-05-01 Thread Christian Heimes
jmDesktop schrieb:
> I have been to the main python site, but am still confused.  I have
> been using .net, so it may be obvious how to do this to everyone
> else.  I am aware there are various frameworks (Django, Pylons, etc.),
> but I would like to know how to create web pages without these.  If I
> have mod_python or fastcgi on apache, where do I start?  I don't have
> clue where to begin to create a web page from scratch in python.  I am
> sure I will want to access database, etc., all the "normal" stuff, I
> just want to do it myself as opposed to the frameworks, for learning.

I highly recommend WSGI instead of mod_python or (fast)cgi. I've heard
only bad things about mod_python over the past years and CGI is totally
old school.

Check out Python Paste, CherryPy and Django. You can also try the Zope,
Zope3 and Plone world but Zope is usually for larger and complex
applications.

Most frameworks come with their own little web server for development, too.

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


Re: Getting started with pyvtk

2008-05-01 Thread Robert Kern

Peter Pearson wrote:

I'm trying to get started with pyvtk, the Python interface
to the Visualization Toolkit, but there's obviously
something important that I haven't figured out after an
embarrassingly long morning of googling around.  When I run
sample pyvtk code (example1.py, from
http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/pyvtk/examples/example1.py),
nothing graphical happens, but some text files appear named
example1.vtk and example1b.vtk.  Guessing that I need to
feed one of these to vtk, I tried "vtk 

pyvtk is not the Python interface to VTK. It is for the creation of VTK files. 
The vtk(1) command is a Tcl shell with the VTK libraries loaded (I believe). 
Read the VTK documentation for information on the Tcl interface if you really 
want to use it. The Python interface is also included in the VTK sources, 
although it might not have been built on your machine. You have to enable it 
when you build VTK itself. The Python interface is essentially the same as the 
C++ interface. There are Python examples in the VTK source tree.


--
Robert Kern

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

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


Re: dropping win98 support?

2008-05-01 Thread Christian Heimes
illume schrieb:
> Ah, why is that?
> 
> There's still at least 1.1% of people using win98, if you believe this
> source of stats:
> http://www.w3schools.com/browsers/browsers_os.asp
> 
> I just noticed that win9x winme and win nt are all being dropped from
> python.
> 
> I know they are old and crufty, but there's still heaps of people
> using them.

The Python core developer team has limited resources. We don't want to
waste our energy with supporting ancient operation systems. Microsoft
has dropped the support for the 9x and NT series several years ago.
Dropping the support as well makes future development and new features
much easier for us.

Python can finally depend on the wide api functions and sane unicode
support.

> Someone pointed me to the pep, where the un-support seems planned:
> http://www.python.org/dev/peps/pep-0011/
> 
> 
> Seems like a lot of people using it, so it's still worthwhile making
> 2.6 work with win98.

People can still use Python 2.5. Users of deprecated and unsupported
OSes can't except new versions of software to run on their boxes.

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


pil:effbot and pythonware offline

2008-05-01 Thread spdegabrielle
Sorry, I'm new to python and was trying to get imageTK;
this led me to try find PIL, but pythonware and effbot both seem to be
offline.

I can't find any mention of an outage on python.org, this newsgroup,
or the planet-blogs.

Is it just me? and does anyone know where I can find ImageTK?

Cheers,

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 23:03:38 +0200, Torsten Bronger wrote:

> Hallöchen!
> 
> Ivan Illarionov writes:
> 
>> [...]
>>
>> I took the example from
>> http://www.kuro5hin.org/story/2004/10/29/14225/062 I haven't use my own
>> example only because I don't have one at hand right now. YAML, in its
>> simple form, definetely makes me more productive. I wasted too much
>> time with XML in the past and I won't ever use it as a serialization or
>> config/settings format again. .INI/ConfigParser is too limited and has
>> no standards. I just don't see anything better than YAML to do human
>> and Python editable config files and to serialize information for later
>> use.
> 
> Okay, but serialisation is something completely different.  Nobody would
> use INI files for it.
> 
> For other things, it simply depends on the use case.  For example, I
> *know* that the configuration files of my pet project will not exceed
> the dumb section.key=value scheme so anything else would be overkill.
> 
> Besides, YAML adds another dependency.
> 
> Tschö,
> Torsten.

For me it looks more like an old-school/new-school thing than use-case 
thing. I may be wrong, but I see more and more new projects use things 
like reST and YAML/JSON and it feels like they are gradually replacing 
traditional old-school solutions.

And I've got very strong impression that YAML is a the future of 
configuration files when Google released their App Engine.

Of course I may be wrong and it's just my opinion.

-- 
Ivan

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

  1   2   >