HTTPS request

2007-09-05 Thread ashish
Hi ,

I want to send HTTPs put request to the server .Can any one help me how 
to do that .

I am using this code

import httplib
from group import *

class HTTPS:


def __init__(self,ip,port=443):

self.ip=ip
self.port=port

self.conn = httplib.HTTPSConnection(str(self.ip))

def send_request(self,method,uri,data=None,headers=None):


self.conn.request(method,uri,data,headers)

 if __name__=="__main__"

http_obj=HTTPS('10.51.26.203')
headers={"Content-type": "application/auth-policy+xml","Accept": 
"text/plain"}
data="some xml doc"
http_obj.send_request('PUT',uri,data,headers=headers)


But it dumps core where ever i run this.Please tell me where i am going 
wrong.

Regards
Ashish

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


Re: Calling a dos batch file from python

2007-09-05 Thread n o s p a m p l e a s e
On Sep 4, 5:01 pm, [EMAIL PROTECTED] wrote:
> On Sep 4, 8:42 am, n o s p a m p l e a s e <[EMAIL PROTECTED]>
> wrote:
>
> > Suppose I have a batch file called mybatch.bat  and I want to run it
> > from a python script. How can I call this batch file in python script?
>
> > Thanx/NSP
>
> The subprocess module should work.
>
Thanx to all those who responded. It was quite simple.

import os
os.system("mybatch.bat")

NSP

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


Calling a matlab script from python

2007-09-05 Thread n o s p a m p l e a s e
Suppose I have a matlab script mymatlab.m. How can I call this script
from a python script?

Thanx/NSP

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


Re: Tkinter(2)

2007-09-05 Thread Eric Brunel
On Tue, 04 Sep 2007 15:42:09 +0200, vijayca <[EMAIL PROTECTED]> wrote:

> my python installation is:Active python 2.5.1
> i am using Red Hat Linux
> i have the Tkinter module installed but any simple script produces an
> error
>
> script:
> from Tkinter import Label
> widget = Label(None, text='Hello GUI world!')
> widget.pack()
> widget.mainloop()
>
>
> error:
> Traceback (most recent call last):
>   File "guy.py", line 2, in 
> widget = Label(None, text='Hello GUI world!')
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 2464, in __init__
> Widget.__init__(self, master, 'label', cnf, kw)
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1923, in __init__
> BaseWidget._setup(self, master, cnf)
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1898, in _setup
> _default_root = Tk()
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1636, in __init__
> self.tk = _tkinter.create(screenName, baseName, className,
> interactive, wantobjects, useTk, sync, use)
> _tkinter.TclError: no display name and no $DISPLAY environment
> variable

Basically, this error has nothing to do with Python or Tkinter. If you  
tried to launch any GUI application, you should get the same error.

How are you logged in to your computer? Did you do any remote connection  
via telnet, or rlogin/rsh, or ssh? This error usually happens when you're  
logged in on a remote machine, and you didn't tell the remote machine  
where you wanted to display the windows you open. It may also happen when  
you're logged in as a user, but did a 'su' to change your identity.

In any case, solving the problem is quite easy: define the DISPLAY  
environment variable with the value :0  
and it should work. If you're using a remote machine, you may also have to  
issue a 'xhost + ' on the local machine  
(the one where the display should occur).

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Catching gtk.STOCK_SIGNALS

2007-09-05 Thread Kveldulv
Hi all,

I made simple GUI with Glade, window and toolbar with one button that
calls
dialog with stock yes or no buttons. It's loaded with:
def callDialog(self, widget):
self.wTree = gtk.glade.XML(self.gladefile, "yesorno")
self.dlg = self.wTree.get_widget("yesorno")
and it works.
Now,  I want to call other dialog named dlg1 if gtk.RESPONSE_YES,
how do I do that? I went through pygtk tutoral and tried various ways
but can't figure it out... I'm probably missing something trivial
here.

tia

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


Re: Calling a matlab script from python

2007-09-05 Thread A.T.Hofkamp
On 2007-09-05, n o s p a m p l e a s e <[EMAIL PROTECTED]> wrote:
> Suppose I have a matlab script mymatlab.m. How can I call this script
> from a python script?

use the mlabwrap module

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


Re: Calling a dos batch file from python

2007-09-05 Thread Wesley Brooks
I looked into this a little while ago so I could get the MAC address
of a machine while on linux or windows. Here's a simplified version
that just does the windows side;

self.macMatch = re.compile(r"((\w\w[:-]){5}\w\w)")
data = os.popen("ipconfig /all", 'r')
text = data.read()
tup = self.macMatch.search(text).span()
mac = text[tup[0]:tup[1]].replace('-',':')
return mac

This method allows you to catch the text which would normally be
output to the dos window.

Cheers,

Wes.

On 05/09/07, n o s p a m p l e a s e <[EMAIL PROTECTED]> wrote:
> On Sep 4, 5:01 pm, [EMAIL PROTECTED] wrote:
> > On Sep 4, 8:42 am, n o s p a m p l e a s e <[EMAIL PROTECTED]>
> > wrote:
> >
> > > Suppose I have a batch file called mybatch.bat  and I want to run it
> > > from a python script. How can I call this batch file in python script?
> >
> > > Thanx/NSP
> >
> > The subprocess module should work.
> >
> Thanx to all those who responded. It was quite simple.
>
> import os
> os.system("mybatch.bat")
>
> NSP
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parse or Pass?

2007-09-05 Thread A.T.Hofkamp
On 2007-09-05, Martin P. Hellwig <[EMAIL PROTECTED]> wrote:
> Martin v. Löwis wrote:
> Eingeben =  Input: (A bit of) data from outside the function
> Ausgeben =  Output: (A bit of) data to display, network 
> connection or file
> Zurückgeben =  Return: (altered)(bits of) data (from Input) 
> to Output
>
> Can I assume that Return in general always means that the particular 
> function has exited with that? If not what is the difference then 
> between Output and Return?

It depends on your point of view imho.

You can describe a function call from 'outside', ie I give it values for its
parameters, and it returns me a computed return value.
You can describe the same thing from 'inside', ie I get values from my caller,
compute a result, and output the result.

> And then we have "Übergeben" which translates to throughput (giving 
> over), which in my view is just something that gets data in and puts it 
> out, contextually unaltered.  But would that do that with exiting the 

I would consider this yet another view, namely performance. Function calls are
stil happening, but you focus more on the #calls/second, ie throughput.


So depending on what one is interested in, I think, one structures and
describes what is happening in a different way.
Wouldn't that be a possible explanation for all the subtle different ways of
describing the same thing?

Albert

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


Re: Printing lists in columns

2007-09-05 Thread cjt22
Thanks guys, I really appreciate it. I have never used google groups
before
and am so impressed with how helpful you all are. It is also lovely
that
none of you mock my little knowledge of Python but just want to
improve it.

I have another question in relation to the izip_longest function (I
persume
this should be within the same topic).
Using this funciton, is there a way to manipulate it so that the
columns can be formated
tabular i.e. perhaps using something such as str(list).rjust(15)
because currently the columns
overlap depending on the strings lengths within each column/list of
lists. i.e. my output is
currently like:

bo, daf, da
pres, ppar, xppc
magnjklep, *, dsa
*, *, nbi

But I want it justified, i.e:

bo   ,  daf,  da
pres , ppar,  xppc
magnjklep,*,  dsa
*,*,  nbi

I am struggling to understand how the izip_longest function works
and thus don't really know how it could be manipulated to do the
above.
It would be much apprecited if somoene could also explain how
izip_function
works as I don't like adding code into my programs which I struggle to
understand.
Or perhaps I have to pad out the lists when storing the Strings?

Any help would be much appreciated.

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


Re: Undeterministic strxfrm?

2007-09-05 Thread Tuomas
Gabriel Genellina wrote:
> I think it's not in the issue tracker - see  
> http://xforce.iss.net/xforce/xfdb/34060
> The fix is already in 2.5.1  
> http://www.python.org/download/releases/2.5.1/NEWS.txt

Thanks Gabriel, I'll try Python 2.5.1.

>> Reading the rev 54669 it seems to me, that the bug is not fixed. Man  
>> says:
>>
>> STRXFRM(3): ... size_t strxfrm(char *dest, const char *src, size_t n);
>> ... The first n characters of  the  transformed  string
>> are  placed in dest.  The transformation is based on the program’s
>> current locale for category LC_COLLATE.
>> ... The strxfrm() function returns the number of bytes required to
>> store  the transformed  string  in dest excluding the terminating ‘\0’
>> character.  If the value returned is n or more, the contents of dest are
>> *indeterminate*.
>>
>> Accordin the man pages Python should know the size of the result it
>> expects and don't trust the size strxfrm returns. I don't completely
>> understand the collate algorithm, but it should offer different levels
>> of collate. So Python too, should offer those levels as a second
>> parameter. Hovever strxfrm don't offer more parameters either except
>> there is another function strcasecmp. So Python should be able to
>> calculate the expected size before calling strxfrm or strcasecmp. I
>> don't how it is possible. May be strcoll knows better and I should kick
>> strxfrm off and take strcoll instead. It costs converting the seach key
>> in every step of the search.
> 
> 
> No. That's why strxfrm is called twice: the first one returns the 
> required  buffer size, the buffer is resized, and strxfrm is called 
> again. That's a  rather common sequence when buffer sizes are not known 
> in advance.
> [Note that `dest` is indeterminate, NOT the function return value which  
> always returns the required buffer size]
> 

OK, I made too quick conclusions of the man text without knowing the 
details.

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

Re: Printing lists in columns

2007-09-05 Thread Amit Khemka
On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Thanks guys, I really appreciate it. I have never used google groups
> before and am so impressed with how helpful you all are. It is also lovely
> that none of you mock my little knowledge of Python but just want to
> improve it.

And we are proud of it !

> I have another question in relation to the izip_longest function (I
> persume
> this should be within the same topic).
> Using this funciton, is there a way to manipulate it so that the
> columns can be formated
> tabular i.e. perhaps using something such as str(list).rjust(15)
> because currently the columns
> overlap depending on the strings lengths within each column/list of
> lists. i.e. my output is
> currently like:
>
> bo, daf, da
> pres, ppar, xppc
> magnjklep, *, dsa
> *, *, nbi
>
> But I want it justified, i.e:
>
> bo   ,  daf,  da
> pres , ppar,  xppc
> magnjklep,*,  dsa
> *,*,  nbi

You can format the output while "print"ing the table. Have a look at:

http://www.python.org/doc/current/lib/typesseq-strings.html

example:
for tup in  izip_longest(*d, **dict(fillvalue='*')):
print "%15s, %15s, %15s" %tup   # for a tuple of length 3, you can
generalize it


> I am struggling to understand how the izip_longest function works
> and thus don't really know how it could be manipulated to do the
> above.
> It would be much apprecited if somoene could also explain how
> izip_function
> works as I don't like adding code into my programs which I struggle to
> understand.
> Or perhaps I have to pad out the lists when storing the Strings?
>
> Any help would be much appreciated.

This is an example of "generator" functions, to understand what they
are and how they work you can:
1. web-search for "python generators"
2. have  a look at "itertools" module, for more generators

-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
-- 
http://mail.python.org/mailman/listinfo/python-list


Accessing Module variables from another Module

2007-09-05 Thread cjt22
Hi

I am new to Python (I have come from a large background of Java) and
wondered if someone could explain to me how I can access variables
stored in my main module to other functions within other modules
called
from this module

for example
file: main.py

from Storage import store
from Initialise import init
from ProcessSteps import process

storeList = store()   #Creates a object to store Step objects
init()
process()

file: Initialise.py
def init()
..
storeList.addStep([a,b,c])


file: ProcessSteps.py
def process()
for step in storeList.stepList:
etc

I am currently just passing the variable in as a parameter
but I thought with Python there would be a way to gain direct access
to
storeList within the modules called from the top main module?

Cheers
Chris

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


RE: Printing lists in columns

2007-09-05 Thread Ryan Ginstrom
> On Behalf Of [EMAIL PROTECTED]
> bo, daf, da
> pres, ppar, xppc
> magnjklep, *, dsa
> *, *, nbi
> 
> But I want it justified, i.e:
> 
> bo   ,  daf,  da
> pres , ppar,  xppc
> magnjklep,*,  dsa
> *,*,  nbi

Once you have a nice rectangular list of lists, you might want to take a
look at my padnums module.

# Usage:
import padnums
import sys

table = [row for row in izip_longest(*d, fillvalue='*')]
padnums.pprint_table(sys.stdout, table)

Code described here, with link to module:
http://ginstrom.com/scribbles/2007/09/04/pretty-printing-a-table-in-python/

Regards,
Ryan Ginstrom

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


Multi Heritage with slots

2007-09-05 Thread Alexandre Badez
Hye,

I'm developing a little app, and I want to make multi heritage.
My problem is that my both parent do have __slots__ define.

So I've got something like:

class foo(object):
__slots__ = ['a', 'b']
pass

class foo2(object):
__slots__ = ['c', 'd']
pass

class crash(foo, foo2):
pass

If you write only that in a sample file or in python console (as I
did), python refuse to load the module and report something like:

Traceback (most recent call last):
  File "", line 1, in ?
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict

Do you know why it append? And how could I make this work?

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


2 python questions!

2007-09-05 Thread resist_think


Hi python community!
First question has to do with threading support. There is the 
following simple case:
I have a dictionnary that gets it's values -which are url's-from a 
function. Sort of

dictionnary['1'] = "http://www.google.com";
dictionnary['2'] = "http://www.python.com";


I need to fill in the dictionnary with some url's. If I do it on 
the simplest way, it would be like:

for i in range(20):
   dictionnary["%s" % i] = get_urls(args)

and wait a long long time till it finishes. Can I do it easily with 
threads, without having to add too much code? Ideal case would be 
if all threads start simultaneously :)


Now the second question has to do with images retrieval and 
manipulation. Which libraries do you propose to work with to 
retrieve and resize images from the web? 


Thanks in advance for any help!


--
Handyman Franchises. Click Here.
http://tagline.hushmail.com/fc/Ioyw6h4fMyhGJzTqAUMT4o9Inh2I0NfM85HrFhPDGb7fSaLiZQZqWk/

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


decorator and signal handler

2007-09-05 Thread stalex
Hi all,

I wrote the following code since I want to try using a decorator to
install signal handler:

## The test.py script
#
import os
import time
import signal

def sigHandler(sid):
def handler(f):
signal.signal(sid, f)
return f
return handler

class Test(object):
@sigHandler(signal.SIGTERM)
def _sigHandler(self, signalId, currentFrame):
print "Received:", signalId

if __name__ == "__main__":
print "pid:", os.getpid()

t = Test()
time.sleep(300)

# From terminal, say A

$ python test.py
pid: 1234

# From terminal, say B
###
$ kill -TERM 1234

After issuing the kill command from terminal B, the process of test.py
from terminal A is terminated.
Python print out some exception message as following:
Traceback (most recent call last):
File "a.py", line 22, in 
time.sleep(300)
TypeError: _sigHandler() takes exactly 3 arguments (2 given)

At a guess, I think the decorator I defined did not pass the 'self' as
the first argument to _sigHandler() method, did it? And I have no idea
of how to write a correct one. Any suggestion?

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


creating really big lists

2007-09-05 Thread Dr Mephesto
Hi!

I would like to create a pretty big list of lists; a list 3,000,000
long, each entry containing 5 empty lists. My application will append
data each of the 5 sublists, so they will be of varying lengths (so no
arrays!).

Does anyone know the most efficient way to do this? I have tried:

list = [[[],[],[],[],[]] for _ in xrange(300)]

but its not s fast. Is there a way to do this without looping?

David.

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


Re: Python is overtaking Perl

2007-09-05 Thread Bryan Olson

The expression "faint praise" comes to mind.


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


Re: REGULAR EXPRESSION

2007-09-05 Thread Ricardo Aráoz
AniNair wrote:
> On Sep 5, 4:35 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>> Steve Holden wrote:
>>> AniNair wrote:
 hi.. I am trying to match '+ %&/-' etc using regular expression  in
 expressions like 879+34343. I tried \W+   but it matches only in the
 beginning of the string Plz help Thanking you in advance...
>>> Perhaps you could give a few example of strings that should and
>>> shouldn't match? It isn't clear from your description what pattern you
>>> are trying to find.
>>> regards
>>>   Steve
>> If it's operations between two numbers try :
>> r'([\d.]+?)\s*([-+/*%&])([\d.]+)'
>> It will give you 3 groups, first number, operation and second number
>> (caveat emptor).
> 
> 
> Hi.. Thanks alot for finding time to help a beginner like me. What I
> am trying to do is validate the input i get. I just want to take
> numbers and numbers only. So if the input is 23+1 or 2/3 or 9-0 or
> 7/0 , I want to find it using reg exp. I know there are other ways to
> do this... but i thought i will try this as i need to learn reg exp. I
> tried \D+   ,   \W+,  and \D+|\W+ .. Thanks once again...
> 

Well \d will match a number and '.' inside [] will match a dot ;) so if
you want only integer numbers ([\d.]*) should be replaced with  (\d+)
Only problem with the expression I sent is that it will match a number
with more than one dot.

HTH


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


Re: creating really big lists

2007-09-05 Thread Paul Rudin
Dr Mephesto <[EMAIL PROTECTED]> writes:

> Hi!
>
> I would like to create a pretty big list of lists; a list 3,000,000
> long, each entry containing 5 empty lists. My application will append
> data each of the 5 sublists, so they will be of varying lengths (so no
> arrays!).
>
> Does anyone know the most efficient way to do this? I have tried:
>
> list = [[[],[],[],[],[]] for _ in xrange(300)]
>
> but its not s fast. Is there a way to do this without looping?

You can do:

   [[[],[],[],[],[]]] * 300

although I don't know if it performs any better than what you already
have.
-- 
http://mail.python.org/mailman/listinfo/python-list


concise code (beginner)

2007-09-05 Thread bambam
I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

---
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read2()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read3()
except
print exception
remove dev from devs

etc. 


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


Re: doctest and decorators

2007-09-05 Thread Daniel Larsson
The __module__ attribute is set, but the problem is the test in
doctest.py(DocTestFinder._from_module)

...
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)

On 9/5/07, Michele Simionato <[EMAIL PROTECTED]> wrote:
>
> > En Tue, 04 Sep 2007 19:29:11 -0300, Daniel Larsson
> > <[EMAIL PROTECTED]> escribi?:
> >
> >
> >
> > > On 9/5/07, Ferenczi Viktor <[EMAIL PROTECTED]> wrote:
> >
> > >> > > @functools.wraps(f)
> > >> > > Pass the function to be wrapped by the decorator to the wraps
> > >> function.
> > >> > Ooops, right. That doesn't change the fact that decorated functions
> > >> get
> > >> > hidden from doctest though.
> >
> > > I have no issue when the decorator is defined in the same module as
> the
> > > decorated function, my problem is running doctests on functions using
> an
> > > imported decorator. Having to implement the decorator in every source
> > > module
> > > isn't very practical.
>
> I cannot reproduce your problem. Using functools.wraps
> the __module__ attribute is set correctly and everything
> works, even for decorators defined in separated modules.
> Care to post a complete example of what you are doing?


inspect.isfunction(object) returns true, but the function's func_globals
isn't the same as the module's __dict__, since the function is actually my
decorator wrapper function.

Here's my two files again:

# decorator.py
import functools

def simplelog(f):
@functools.wraps(f)
def new_f(*args, **kwds):
print "Wrapper calling func"
return f(*args, **kwds)
return new_f

# test.py
from decorator import simplelog

@simplelog
def test():
"""
This test should fail, since the decorator prints output. Seems I don't
get called though
>>> test()
'works!'
"""
return "works!"

if __name__ == '__main__':
import doctest
doctest.testmod()



 Michele Simionato
>
> P.S. for some reason your messages are not appearing on
> Google groups, I see only the replies.
>
>
Weird... afraid I have no clue why not :)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: concise code (beginner)

2007-09-05 Thread Diez B. Roggisch
bambam wrote:

> I have about 30 pages (10 * 3 pages each) of code like this
> (following). Can anyone suggest a more compact way to
> code the exception handling? If there is an exception, I need
> to continue the loop, and continue the list.
> 
> Steve.
> 
> ---
> for dev in devs
> try:
> dev.read1()
> except
> print exception
> remove dev from devs
> 
> for dev in devs
> try:
> dev.read2()
> except
> print exception
> remove dev from devs
> 
> for dev in devs
> try:
> dev.read3()
> except
> print exception
> remove dev from devs

for method in (DevClass.read1, DevClass.read2, ...):
  for dev in devs:
  try:
method(dev)
  except:
print execption
remove dev from devs

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


Re: creating really big lists

2007-09-05 Thread Diez B. Roggisch
Paul Rudin wrote:

> Dr Mephesto <[EMAIL PROTECTED]> writes:
> 
>> Hi!
>>
>> I would like to create a pretty big list of lists; a list 3,000,000
>> long, each entry containing 5 empty lists. My application will append
>> data each of the 5 sublists, so they will be of varying lengths (so no
>> arrays!).
>>
>> Does anyone know the most efficient way to do this? I have tried:
>>
>> list = [[[],[],[],[],[]] for _ in xrange(300)]
>>
>> but its not s fast. Is there a way to do this without looping?
> 
> You can do:
> 
>[[[],[],[],[],[]]] * 300
> 
> although I don't know if it performs any better than what you already
> have.

You are aware that this is hugely different, because the nested lists are
references, not new instances? Thus the outcome is most probably (given the
gazillion of times people stumbled over this) not the desired one...

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


Re: concise code (beginner)

2007-09-05 Thread Wesley Brooks
Try adding all the functions into a list such as;

funcList = [dev.read1, dev.read2, dev.read3]

for func in funcList:
   for dev in devs:
   try:
   func()
   except:
   print exception
   remove dev from devs

Wes.

On 05/09/07, bambam <[EMAIL PROTECTED]> wrote:
> I have about 30 pages (10 * 3 pages each) of code like this
> (following). Can anyone suggest a more compact way to
> code the exception handling? If there is an exception, I need
> to continue the loop, and continue the list.
>
> Steve.
>
> ---
> for dev in devs
> try:
> dev.read1()
> except
> print exception
> remove dev from devs
>
> for dev in devs
> try:
> dev.read2()
> except
> print exception
> remove dev from devs
>
> for dev in devs
> try:
> dev.read3()
> except
> print exception
> remove dev from devs
>
> etc.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: concise code (beginner)

2007-09-05 Thread Daniel Larsson
def process_devs(devs, fun):
for dev in devs:
try:
fun(dev)
except:
 print exception
 remove dev from devs
 return devs

process_devs(devs, lambda d: d.read1())
process_devs(devs, lambda d: d.read2())
...

On 9/5/07, bambam <[EMAIL PROTECTED]> wrote:
>
> I have about 30 pages (10 * 3 pages each) of code like this
> (following). Can anyone suggest a more compact way to
> code the exception handling? If there is an exception, I need
> to continue the loop, and continue the list.
>
> Steve.
>
> ---
> for dev in devs
> try:
> dev.read1()
> except
> print exception
> remove dev from devs
>
> for dev in devs
> try:
> dev.read2()
> except
> print exception
> remove dev from devs
>
> for dev in devs
> try:
> dev.read3()
> except
> print exception
> remove dev from devs
>
> etc.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: concise code (beginner)

2007-09-05 Thread Francesco Guerrieri
On 9/5/07, bambam <[EMAIL PROTECTED]> wrote:
>
> I have about 30 pages (10 * 3 pages each) of code like this
> (following). Can anyone suggest a more compact way to
> code the exception handling? If there is an exception, I need
> to continue the loop, and continue the list.
>
> Steve.
>
> ---
> for dev in devs
> try:
> dev.read1()
> except
> print exception
> remove dev from devs
>
> for dev in devs
> try:
> dev.read2()
> except
> print exception
> remove dev from devs
>
> for dev in devs
> try:
> dev.read3()
> except
> print exception
> remove dev from devs
>
> etc.
>


well the first thought is:  why don't you put all the calls in a single for
loop?
for dev in devs:
try:
call the methods on dev (instead of explicitly elencating all of them
there could and should be other solutions more mantainable)
except:
flag dev as unusable

Modifying the sequence you are iterating over can be tricky.


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

Re: concise code (beginner)

2007-09-05 Thread Wesley Brooks
Sorry, just seen a mistake in my code, however Diez beat me to what I
was actually thinking!

Wes

On 05/09/07, Wesley Brooks <[EMAIL PROTECTED]> wrote:
> Try adding all the functions into a list such as;
>
> funcList = [dev.read1, dev.read2, dev.read3]
>
> for func in funcList:
>for dev in devs:
>try:
>func()
>except:
>print exception
>remove dev from devs
>
> Wes.
>
> On 05/09/07, bambam <[EMAIL PROTECTED]> wrote:
> > I have about 30 pages (10 * 3 pages each) of code like this
> > (following). Can anyone suggest a more compact way to
> > code the exception handling? If there is an exception, I need
> > to continue the loop, and continue the list.
> >
> > Steve.
> >
> > ---
> > for dev in devs
> > try:
> > dev.read1()
> > except
> > print exception
> > remove dev from devs
> >
> > for dev in devs
> > try:
> > dev.read2()
> > except
> > print exception
> > remove dev from devs
> >
> > for dev in devs
> > try:
> > dev.read3()
> > except
> > print exception
> > remove dev from devs
> >
> > etc.
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: concise code (beginner)

2007-09-05 Thread Bruno Desthuilliers
bambam a écrit :
> I have about 30 pages (10 * 3 pages each) of code like this
> (following). Can anyone suggest a more compact way to
> code the exception handling? If there is an exception, I need
> to continue the loop, and continue the list.
> 
> Steve.
> 
> ---
> for dev in devs
> try:
> dev.read1()
> except
> print exception
> remove dev from devs


for method_name in ['read1', 'read2', 'read3']:
   for dev in devs:
 try:
   meth = getattr(dev, method_name)
 except AttributeError, e:
   # should not happen, but we want to handle it anyway
   your_code_here()
 else:
   try:
 meth()
   except (SomePossibleException, SomeOtherPossibleException), e:
 print e
 # do what's needed to remove dev from devs
 # paying attention not to screw the looping machinery...

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


Re: decorator and signal handler

2007-09-05 Thread Michele Simionato
On Sep 5, 11:39 am, stalex <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I wrote the following code since I want to try using a decorator to
> install signal handler:

I do have a decorator for exactly that purpose in my code. Here it is:

def on(sig):
'''
A factory of decorators for signal handlers. An example of usage
is

@on(signal.SIGTERM)
def termination(frame):
print 'sent SIGTERM'
raise SystemExit

Code calling termination.signal() will send a SIGTERM signal to
the
main thread, which in turns will call the termination handler,
which
will print a message and raise SystemExit.
'''
def handler_decorator(handler):
'Install the handler and add a .signal function attribute to
it'
signal.signal(sig, lambda signum, frame : handler(frame))
handler.signal = lambda : os.kill(os.getpid(), sig)
return handler
return handler_decorator

 Michele Simionato

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


Re: creating really big lists

2007-09-05 Thread Bryan Olson
Paul Rudin wrote:
> Dr writes:
>> I would like to create a pretty big list of lists; a list 3,000,000
>> long, each entry containing 5 empty lists. My application will append
>> data each of the 5 sublists, so they will be of varying lengths (so no
>> arrays!).
>>
>> Does anyone know the most efficient way to do this? I have tried:
>>
>> list = [[[],[],[],[],[]] for _ in xrange(300)]
>>
>> but its not s fast. Is there a way to do this without looping?
> 
> You can do:
> 
>[[[],[],[],[],[]]] * 300
> 
> although I don't know if it performs any better than what you already
> have.

Actually, that produces list of 300 references to the same
5-element list. A reduced example:

 >>> lst = [[[],[],[],[],[]]] * 3
 >>> lst[1][1].append(42)
 >>> print lst
[[[], [42], [], [], []], [[], [42], [], [], []], [[], [42], [], [], []]]


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


Re: creating really big lists

2007-09-05 Thread Paul Rudin
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:

> Paul Rudin wrote:
>
>> Dr Mephesto <[EMAIL PROTECTED]> writes:
>> 
>>> Hi!
>>>
>>> I would like to create a pretty big list of lists; a list 3,000,000
>>> long, each entry containing 5 empty lists. My application will append
>>> data each of the 5 sublists, so they will be of varying lengths (so no
>>> arrays!).
>>>
>>> Does anyone know the most efficient way to do this? I have tried:
>>>
>>> list = [[[],[],[],[],[]] for _ in xrange(300)]
>>>
>>> but its not s fast. Is there a way to do this without looping?
>> 
>> You can do:
>> 
>>[[[],[],[],[],[]]] * 300
>> 
>> although I don't know if it performs any better than what you already
>> have.
>
> You are aware that this is hugely different, because the nested lists are
> references, not new instances? Thus the outcome is most probably (given the
> gazillion of times people stumbled over this) not the desired one...

Err, yes sorry. I should try to avoid posting before having coffee in
the mornings.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorator and signal handler

2007-09-05 Thread Daniel Larsson
On 9/5/07, stalex <[EMAIL PROTECTED]> wrote:
>
> Hi all,
>
> I wrote the following code since I want to try using a decorator to
> install signal handler:
>
> ## The test.py script
> #
> import os
> import time
> import signal
>
> def sigHandler(sid):
> def handler(f):
> signal.signal(sid, f)
> return f
> return handler
>
> class Test(object):
> @sigHandler(signal.SIGTERM)
> def _sigHandler(self, signalId, currentFrame):
> print "Received:", signalId
>
> if __name__ == "__main__":
> print "pid:", os.getpid()
>
> t = Test()
> time.sleep(300)
>
> # From terminal, say A
> 
> $ python test.py
> pid: 1234
>
> # From terminal, say B
> ###
> $ kill -TERM 1234
>
> After issuing the kill command from terminal B, the process of test.py
> from terminal A is terminated.
> Python print out some exception message as following:
> Traceback (most recent call last):
> File "a.py", line 22, in 
> time.sleep(300)
> TypeError: _sigHandler() takes exactly 3 arguments (2 given)
>
> At a guess, I think the decorator I defined did not pass the 'self' as
> the first argument to _sigHandler() method, did it? And I have no idea
> of how to write a correct one. Any suggestion?


You can't call an unbound method without supplying the instance explicitly.

Try decorate a global function instead, and it should work.

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

Re: doctest and decorators

2007-09-05 Thread Michele Simionato
On 9/5/07, Daniel Larsson <[EMAIL PROTECTED]> wrote:
>  Here's my two files again:
>
>  # decorator.py
>  import functools
>
>  def simplelog(f):
>  @functools.wraps(f)
>  def new_f(*args, **kwds):
>  print "Wrapper calling func"
>  return f(*args, **kwds)
>  return new_f
>
>  # test.py
>  from decorator import simplelog
>
>  @simplelog
>  def test():
>  """
> This test should fail, since the decorator prints output. Seems I don't
> get called though
>  >>> test()
>  'works!'
>  """
>  return "works!"
>
>  if __name__ == '__main__':
>  import doctest
>  doctest.testmod()
>

Ok, I could not see the code before (Google groups as getting worse as
the time goes by).  It looks like you are right, it is a bug in
doctest.

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


Re: creating really big lists

2007-09-05 Thread Dr Mephesto
yep, thats why I'm asking :)

On Sep 5, 12:22 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Paul Rudin wrote:
> > Dr Mephesto <[EMAIL PROTECTED]> writes:
>
> >> Hi!
>
> >> I would like to create a pretty big list of lists; a list 3,000,000
> >> long, each entry containing 5 empty lists. My application will append
> >> data each of the 5 sublists, so they will be of varying lengths (so no
> >> arrays!).
>
> >> Does anyone know the most efficient way to do this? I have tried:
>
> >> list = [[[],[],[],[],[]] for _ in xrange(300)]
>
> >> but its not s fast. Is there a way to do this without looping?
>
> > You can do:
>
> >[[[],[],[],[],[]]] * 300
>
> > although I don't know if it performs any better than what you already
> > have.
>
> You are aware that this is hugely different, because the nested lists are
> references, not new instances? Thus the outcome is most probably (given the
> gazillion of times people stumbled over this) not the desired one...
>
> Diez


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


Re: Multi Heritage with slots

2007-09-05 Thread Eric Brunel
On Wed, 05 Sep 2007 11:01:56 +0200, Alexandre Badez  
<[EMAIL PROTECTED]> wrote:

> Hye,
>
> I'm developing a little app, and I want to make multi heritage.
> My problem is that my both parent do have __slots__ define.
>
> So I've got something like:
>
> class foo(object):
> __slots__ = ['a', 'b']
> pass
>
> class foo2(object):
> __slots__ = ['c', 'd']
> pass
>
> class crash(foo, foo2):
> pass
>
> If you write only that in a sample file or in python console (as I
> did), python refuse to load the module and report something like:
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: Error when calling the metaclass bases
> multiple bases have instance lay-out conflict
>
> Do you know why it append? And how could I make this work?

See http://mail.python.org/pipermail/python-list/2006-December/418768.html

Basically, the general advice you're likely to get here is: don't use  
__slots__, or at least don't use __slots__ with inheritance.

BTW, what are you trying to do? Is it really a memory footprint  
optimization, which is the intended use case for __slots__, or are you  
just doing Java in Python?
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Wanted: safe codec for filenames

2007-09-05 Thread Torsten Bronger
Hallöchen!

I'd like to map general unicode strings to safe filename.  I tried
punycode but it is case-sensitive, which Windows is not.  Thus,
"Hallo" and "hallo" are mapped to "Hallo-" and "hallo-", however, I
need uppercase Latin letters being encoded, too, and the encoding
must contain only lowercase Latin letters, numbers, underscores, and
maybe a little bit more.  The result should be more legible than
base64, though.

Has anybody created such a codec already?

Tschö,
Torsten.

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


Re: Printing lists in columns

2007-09-05 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Thanks guys, I really appreciate it. I have never used google groups
> before

Actually, comp.lang.python is a usenet newsgroup, not a google group. 
Google only gives you a web fronted (and archives...) for that group. I 
personnaly access it with my MUA.

> and am so impressed with how helpful you all are. It is also lovely
> that
> none of you mock my little knowledge of Python but just want to
> improve it.

Well... Why should we mock ? We've all been beginners, and we're still 
all beginners in a domain or another.

But welcome to c.l.py and thanks for appreciating this group anyway !-)

> I have another question in relation to the izip_longest function (I
> persume
> this should be within the same topic).
> Using this funciton, is there a way to manipulate it so that the
> columns can be formated
> tabular i.e. perhaps using something such as str(list).rjust(15)
> because currently the columns
> overlap depending on the strings lengths within each column/list of
> lists. i.e. my output is
> currently like:
> 
> bo, daf, da
> pres, ppar, xppc
> magnjklep, *, dsa
> *, *, nbi
> 
> But I want it justified, i.e:
> 
> bo   ,  daf,  da
> pres , ppar,  xppc
> magnjklep,*,  dsa
> *,*,  nbi
> 
> I am struggling to understand how the izip_longest function works

What's bothering you ?-)

Sorry, just joking. This code uses some 'advanced' stuffs like closures, 
HOFs and generators/iterators, so it's obviously not that simple to grok 
- FWIW, I myself had to read it at least thrice to understand it.

> and thus don't really know how it could be manipulated to do the
> above.

FWIW, you don't have - and IMHO should not try - to do this within 
izip_longest, which is a generic function.

> It would be much apprecited if somoene could also explain how
> izip_function
> works as I don't like adding code into my programs which I struggle to
> understand.
> Or perhaps I have to pad out the lists when storing the Strings?

I'd personnaly do the formatting just before printing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Looping through File Question

2007-09-05 Thread planetmatt
I am a Python beginner.  I am trying to loop through a CSV file which
I can do.  What I want to change though is for the loop to start at
row 2 in the file thus excluding column headers.

At present I am using this statement to initiate a loop though the
records:

for line in f.readlines():

How do I start this at row 2?

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


Re: Looping through File Question

2007-09-05 Thread Francesco Guerrieri
On 9/5/07, planetmatt <[EMAIL PROTECTED]> wrote:
>
> I am a Python beginner.  I am trying to loop through a CSV file which
> I can do.  What I want to change though is for the loop to start at
> row 2 in the file thus excluding column headers.
>
> At present I am using this statement to initiate a loop though the
> records:
>
> for line in f.readlines():
>
> How do I start this at row 2?
>

you can simply call (and maybe throw away) f.readline() a single time before
looping.
If the lenght of the first line is fixed, you can also use f.seek to start
reading from the second row.

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

Re: Looping through File Question

2007-09-05 Thread vijayca
On Sep 5, 3:58 pm, planetmatt <[EMAIL PROTECTED]> wrote:
> I am a Python beginner.  I am trying to loop through a CSV file which
> I can do.  What I want to change though is for the loop to start at
> row 2 in the file thus excluding column headers.
>
> At present I am using this statement to initiate a loop though the
> records:
>
> for line in f.readlines():
>
> How do I start this at row 2?

just use readline() method...this will move the file pointer to the
next line
example:
fd=open("/tmp.txt","r")
fd.readline()##THIS MOVES THE FILE POINTER TO THE
SECOND LINE

now carry on with...
for line in f.readlines():   #THIS WILL BEGIN WITH THE SECOND ROW AS
THE FILE POINTER IS IN 2NDLINE
  

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


Re: Looping through File Question

2007-09-05 Thread Amit Khemka
On 9/5/07, Francesco Guerrieri <[EMAIL PROTECTED]> wrote:
> On 9/5/07, planetmatt <[EMAIL PROTECTED]> wrote:
> > I am a Python beginner.  I am trying to loop through a CSV file which
> > I can do.  What I want to change though is for the loop to start at
> > row 2 in the file thus excluding column headers.
> >
> > At present I am using this statement to initiate a loop though the
> > records:
> >
> > for line in f.readlines():
> >
> > How do I start this at row 2?
> >
>
> you can simply call (and maybe throw away) f.readline() a single time before
> looping.
> If the lenght of the first line is fixed, you can also use f.seek to start
> reading from the second row.
>
> francesco

Btw, if you are trying to read a csv file and parse it, you can save
some work  .. have a look at "csv" module !

-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: So what exactly is a complex number?

2007-09-05 Thread Grzegorz Słodkowicz

>> In fact, a proper vector in physics has 4 features: point of
>> application, magnitude, direction and sense.
>> 
>
> so whats the "point of application" of the sum of two vectors?  Do
> tell.
I believe vectors can only be added if they have the same point of 
application. The result is then applied to the same point.

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


Re: Looping through File Question

2007-09-05 Thread John Machin
On Sep 5, 8:58 pm, planetmatt <[EMAIL PROTECTED]> wrote:
> I am a Python beginner.  I am trying to loop through a CSV file which
> I can do.  What I want to change though is for the loop to start at
> row 2 in the file thus excluding column headers.
>
> At present I am using this statement to initiate a loop though the
> records:
>
> for line in f.readlines():
>
> How do I start this at row 2?

The quick answer to your literal question is:
  for line in f.readlines()[1:]:
or, with extreme loss of elegance, this:
  for lino, line in enumerate(f.readlines()):
  if not lino:
  continue

But readline and readlines are old hat, and you wouldn't want to read
a file of a few million lines into a big list, so a better answer is:

_unused = f.next()
for line in f:

But you did say you were reading a CSV file, and you don't really want
to do your own CSV parsing, even if you think you know how to get it
right, so best is:

import csv
rdr = csv.reader(f)
heading_row = rdr.next()
for data_row in rdr:

HTH,
John

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


Re: Accessing Module variables from another Module

2007-09-05 Thread Daniel Larsson
On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> Hi
>
> I am new to Python (I have come from a large background of Java) and
> wondered if someone could explain to me how I can access variables
> stored in my main module to other functions within other modules
> called
> from this module


No, don't introduce circular dependencies, and make it explicit what your
functions operate on by passing things as parameters, instead of using
global references.

for example
> file: main.py
>
> from Storage import store
> from Initialise import init
> from ProcessSteps import process
>
> storeList = store()   #Creates a object to store Step objects
> init()
> process()


It is *much* more preferable to pass 'storeList' as a parameter to your
functions. Don't change things behind the scenes.

file: Initialise.py
> def init()
> ..
> storeList.addStep([a,b,c])
>
>
> file: ProcessSteps.py
> def process()
> for step in storeList.stepList:
> etc
>
> I am currently just passing the variable in as a parameter
> but I thought with Python there would be a way to gain direct access
> to
> storeList within the modules called from the top main module?


Keep it the way it is. It's wrong on too many levels to do it the other way.

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

Re: 2 python questions!

2007-09-05 Thread Christof Winter
[EMAIL PROTECTED] wrote:
[...]

> Now the second question has to do with images retrieval and 
> manipulation. Which libraries do you propose to work with to 
> retrieve and resize images from the web? 

urllib.urlretrieve() and
Python Imaging Library (PIL)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FCGI app reloading on every request

2007-09-05 Thread Sion Arrowsmith
John Nagle  <[EMAIL PROTECTED]> wrote:
>Tried putting this in the .htaccess file:
>
>
>SetHandler fcgid-script
>Options ExecCGI
>allow from all
>
>
>
>ErrorDocument 403 "File type not supported."
>
>
> Even with that, a ".foo" file gets executed as a CGI script,
>and so does a ".fcgi" file.  It's an Apache configuration problem.

I'd look to see if you've got a AllowOverride None set somewhere
unhelpful (probably on the cgi-bin directory, although I note the
default Apache2 config on my machine here does it for the document
root too). Mind you, if you're managing this with a web tool rather
than having access to the Apache config files, it might not be so
straightforward to do.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: So what exactly is a complex number?

2007-09-05 Thread Boris Borcic
Roy Smith wrote:
> Boris Borcic <[EMAIL PROTECTED]> wrote:
>> Complex numbers are like a subclass of real numbers 
> 
> I wouldn't use the term "subclass". 

Really you should name yourself as the author when you butcher someone else's 
prose to such a degree. Suppose I had written "Complex numbers are like an 
afghan beauty that has little chance to seduce you unless you first get to see 
her eyes despite the burkha she is usually wearing". Would you find it 
reasonable to cut this down to "Complex numbers are like an afghan beauty" and 
then criticize the result as if the word "like" hadn't survived this treatment ?

 > It certainly doesn't apply in the same
 > sense it applies in OOPLs.  For example, you can't say, "All complex
 > numbers are real numbers".  In fact, just the opposite.
 > But, it's equally wrong to say, "real numbers are a subclass of complex
 > numbers", at least not if you believe in LSP
 > (http://en.wikipedia.org/wiki/Liskov_substitution_principle).

Well, some edulcorated-analogical version of that principle was precisely what 
I 
had in mind when I wrote what I wrote - not what you cite and much less "just 
the opposite" of the latter, that you here adress.

What makes complex numbers magical to use is precisely that you can port to 
them 
without change (most of) the algebraic procedures that you first learn on the 
real number field. And manipulate them technically while neglecting that they 
are not really real numbers, except when convenient because (a) things will 
work 
uniformly using complex numbers where real numbers would present exceptions and 
(b) they allow more powerful results. And that's what LSP is about, is it not ?

> For example,
> it is true that you can take the square root of all complex numbers.  It is 
> not, however, true that you can take square root of all real numbers.

(a) note that with the subclass relation put in the order I had chosen, this 
would not contradict LSP

(b) and nevertheless :

 >>> x = -1.0
 >>> type(x)

 >>> import cmath
 >>> cmath.sqrt(x)
1j
 >>>

> 
> Don't confuse "subset" with "subclass".

Don't confuse myself with yourself, thanks :) Or are you going to say that you 
would have launched into the same diatribe if I had proposed a subclassing 
relation that wasn't counter the grain viz the purported subset relation ?

> The set of real numbers *is* a 
> subset of the set of complex numbers.

It *is* unfortunate that learning mathematics using sets allows to neglect the 
fundamental difference between the identity of physical objects and the 
identity 
of mathematical objects. The latter we only ever reach "up to isomorphism". 
There is a natural embedding of real numbers into complex numbers, but there is 
also a natural embedding of real numbers into surreal numbers. The two 
embeddings aren't compatible. So which should be promoted to "*being*", and why 
?

> It is *not* true that either reals 
> or complex numbers are a subclass of the other.

What I had written : "Complex numbers are like a subclass of real numbers that 
elegantly extends the usual arithmetic operations to provide access to 
trigonometric functions and related goodies. This then allows you to think of 
trigonometric problems as simple arithmetic problems."

Boris Borcic


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


Help me understand this script

2007-09-05 Thread Ryan J Nauman
Can someone help me understand this script please?
I understand everything except for the anagram function.  Could you break 
it down into more than 1 line of code for me or explain it? (I understand 
WHAT it does but HOW?) Thanks.

Script >>

###
# SCRABBLE.PY
#
# purpose: 
#   find usable "bingos" based on your rack
#
# usage:
#   python scrabble.py eilsnsy
#
# output:
# Straight anagrams: 
#  linseys
#  lysines
# Possible other words: 
# + B
#   sensibly
#+ K
#   skylines
#+ V
#   sylvines
###
# Scrabble is a registered trademark of J. W. Spear & Son PLC and 
# Hasbro Inc. Any and all uses of the word "Scrabble" in this code
# refers to this trademark.
#
# This code is not affiliated with any company.
###

import sys

WORDS = [ i.rstrip ().lower() for i in file ('c:\python25\TWL06.txt') ]
# you can download the current TWL and/or SOWPODS dictionaries from 
# http://67.19.18.90/twl.zip and http://67.19.18.90/sowpods.zip . 
# Update the file name above as appropriate if you want to use a "proper"
# Scrabble dictionary.



def alphabetise(word):
x = [i for i in word]
x.sort()
 
return "".join(x)

def anagram(word):
wordLength = len(word)
sortedWord = alphabetise(word.lower())
return [i for i in WORDS if len(i) == wordLength and alphabetise(i) == 
sortedWord]

for word in sys.argv[1:]:
print "Straight anagrams: "
for i in anagram(word):
print "  " + i
print "Possible other words: "
for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
a = anagram(i + word)
if a:
print "+", i
for h in a:
print "  ", h

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

关于用urllib post消息的问题。

2007-09-05 Thread liangxuliang79
想从www.mmmppp333.com下载本书,http://ishare.iask.sina.com.cn/cgi-bin/
fileid.cgi?fileid=844050
但是我post fileid=844050过去后,

当你post东西过去后,fileid=844050,然后server会回复回来header,header中的local还是location忘记
了,中的信息是一个指向另外的链接,这个链接就是mp3的实际地址,但是我试了几次,local中的信息不是mp3的地址,还是我刚刚发的地址,不知道
为什么。也不知道我哪里出错了。

而且我跟了一下python中urllib的信息,urllib已经又按照协议重新获取了local中的信息了,因为local中的不是mp3的实际地
址,我才不能下载mp3.。

我post的地址是/download.php, post的内容是fileid=844050,只要看一下网页的源文件就可以看到。不过不知道为什么
会失败。郁闷。谁是搞web开发的,指点我一下啊。
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: So what exactly is a complex number?

2007-09-05 Thread Boris Borcic
Paul Rubin wrote:
> Also, for
> example, the derivative of a complex valued function means something
> considerably stronger than the derivative of a real valued function.

I vaguely remember (it has been decades) an amazingly beautiful russian doll 
system of four of five theorems, the first hypothesizing a function of a 
complex 
variable with a property that IIRC appeared somewhat weaker than 
differentiability, and the latter theorems not hypothesizing anything more, but 
pushing the consequence further to ever stronger properties.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing Module variables from another Module

2007-09-05 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Hi
> 
> I am new to Python (I have come from a large background of Java) and
> wondered if someone could explain to me how I can access variables
> stored in my main module to other functions within other modules
> called
> from this module
> 
(snip code)
> I am currently just passing the variable in as a parameter

And this is the RightThing(tm) to do.

> but I thought with Python there would be a way to gain direct access
> to
> storeList within the modules called from the top main module?

Yes : passing it as a param !-)

For other modules to get direct access to main.storeList, you'd need 
these modules to import main in these other modules, which would 
introduce circular dependencies, which are something you usuallay don't 
want. Also, and while it's ok to read imported modules attributes, it's 
certainly not a good idea to mutate or rebind them IMHO, unless you're 
ok with spaghetti code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi Heritage with slots

2007-09-05 Thread Alexandre Badez
On Sep 5, 12:42 pm, "Eric Brunel" <[EMAIL PROTECTED]> wrote:
> Seehttp://mail.python.org/pipermail/python-list/2006-December/418768.html
>
> Basically, the general advice you're likely to get here is: don't use
> __slots__, or at least don't use __slots__ with inheritance.
>
> BTW, what are you trying to do? Is it really a memory footprint
> optimization, which is the intended use case for __slots__, or are you
> just doing Java in Python?
> --
> python -c "print ''.join([chr(154 - ord(c)) for c in
> 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

Thanks for your answer.
I use __slots__ not for memory optimization nor doing java.
I use __slots__ because my class are used by other lib, and in the
past, some of them misspell some attributes and involved a very
annoying comportment of the global application.
So the objective is only to prevent unwanted dynamism (but not in all
the application, just some class).

PS: I very like your signature ;)

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


Re: Looping through File Question

2007-09-05 Thread planetmatt
On 5 Sep, 12:34, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 5, 8:58 pm, planetmatt <[EMAIL PROTECTED]> wrote:
>
> > I am a Python beginner.  I am trying to loop through a CSV file which
> > I can do.  What I want to change though is for the loop to start at
> > row 2 in the file thus excluding column headers.
>
> > At present I am using this statement to initiate a loop though the
> > records:
>
> > for line in f.readlines():
>
> > How do I start this at row 2?
>
> The quick answer to your literal question is:
>   for line in f.readlines()[1:]:
> or, with extreme loss of elegance, this:
>   for lino, line in enumerate(f.readlines()):
>   if not lino:
>   continue
>
> But readline and readlines are old hat, and you wouldn't want to read
> a file of a few million lines into a big list, so a better answer is:
>
> _unused = f.next()
> for line in f:
>
> But you did say you were reading a CSV file, and you don't really want
> to do your own CSV parsing, even if you think you know how to get it
> right, so best is:
>
> import csv
> rdr = csv.reader(f)
> heading_row = rdr.next()
> for data_row in rdr:
>
> HTH,
> John

Thanks so much for the quick response.  All working now.

I had looked at the CSV module but when I ran into another problem of
trying to loop through all columns, I was given a solution in another
forum which used the readlines() method.

I have looked at the CSV documentation but didn't see any mention of
heading_row or data_row.  Is there a definitive Python documentation
site with code examples like MS's MSDN?


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


threads

2007-09-05 Thread vijayca
i have written a script that spawns some threads
all run in parallel
now i need to stop all the threads once i press a key(example: "\n")
how to do it...

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


Re: creating really big lists

2007-09-05 Thread Aahz
In article <[EMAIL PROTECTED]>,
Dr Mephesto  <[EMAIL PROTECTED]> wrote:
>
>I would like to create a pretty big list of lists; a list 3,000,000
>long, each entry containing 5 empty lists. My application will append
>data each of the 5 sublists, so they will be of varying lengths (so no
>arrays!).

Why do you want to pre-create this?  Why not just create the big list and
sublists as you append data to the sublists?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Many customs in this life persist because they ease friction and promote
productivity as a result of universal agreement, and whether they are
precisely the optimal choices is much less important." --Henry Spencer
http://www.lysator.liu.se/c/ten-commandments.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling a matlab script from python

2007-09-05 Thread Alexander Schmolck
n o s p a m p l e a s e <[EMAIL PROTECTED]> writes:

> Suppose I have a matlab script mymatlab.m. How can I call this script
> from a python script?

You could use .

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


Re: Multi Heritage with slots

2007-09-05 Thread Simon Brunning
On 9/5/07, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I use __slots__ not for memory optimization nor doing java.
> I use __slots__ because my class are used by other lib, and in the
> past, some of them misspell some attributes and involved a very
> annoying comportment of the global application.
> So the objective is only to prevent unwanted dynamism (but not in all
> the application, just some class).

Using slots to prevent the creation of new properties is what Eric
*means* by "doing java". You're trying to write Java style code in
Python, and it's not going to be pretty. Slots are not intended for
this purpose, and they aren't very good for it.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


StringIO MySQL data blob Image problem

2007-09-05 Thread dimitri pater
Hi,

I am trying to insert an image, which is stored as a blob in MySQL,
into a table using Reportlab.

I have tried this:
from StringIO import StringIO
cfoto = StringIO(result[0][1]) # where result[0][1] is the 'blob'
cfoto.seek(0)
foto=cfoto.getvalue

But when I do:
print foto, I see something similar to this:
array('c','\xff\xd8\etc...etc..')
This is also the string I see in the table, in stead of the actual image.

I have tried:
cfoto StringIO()
cfoto.write(result[0][1].tostring())
foto=cfoto.getvalue()
that returns:
ÿØÿàúlbo¤qÁ5¼–Ò\¸•£ˆˆ‡Y|Aø—­,ñé–ú…"ìâm3Z¸ŒÁfêñ""NÔ,­¡¾ÚÀIæÃt"[EMAIL 
PROTECTED]'ÍkÕÁå¼sàßd˜ª²«ÍÉ1؜Ï
‡^ÖJ*™C(r)ë{:tâ¥_‡Çâ–´°joÙÃ
¿C(c)¯äÜ[)¯gN«ÃæXßi etc... etc...
and return an UnicodeDecodeError when I try to insert this into the table

Any ideas or clues someone? Your help is appreciated.
Dimitri
(BTW, the MySQL image blob is valid, it shows up in MySQL Query Browser)

-- 
---
You can't have everything. Where would you put it? -- Steven Wright
---
please visit www.serpia.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing Module variables from another Module

2007-09-05 Thread cjt22
On Sep 5, 1:22 pm, Bruno Desthuilliers  wrote:
> [EMAIL PROTECTED] a écrit :
>
> > Hi
>
> > I am new to Python (I have come from a large background of Java) and
> > wondered if someone could explain to me how I can access variables
> > stored in my main module to other functions within other modules
> > called
> > from this module
>
> (snip code)
> > I am currently just passing the variable in as a parameter
>
> And this is the RightThing(tm) to do.
>
> > but I thought with Python there would be a way to gain direct access
> > to
> > storeList within the modules called from the top main module?
>
> Yes : passing it as a param !-)
>
> For other modules to get direct access to main.storeList, you'd need
> these modules to import main in these other modules, which would
> introduce circular dependencies, which are something you usuallay don't
> want. Also, and while it's ok to read imported modules attributes, it's
> certainly not a good idea to mutate or rebind them IMHO, unless you're
> ok with spaghetti code.

Cheers Bruno, I just wanted to make sure I was being consistent with
the "Python way of things" :)

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

Re: Multi Heritage with slots

2007-09-05 Thread Michele Simionato
On Sep 5, 2:52 pm, "Simon Brunning" <[EMAIL PROTECTED]> wrote:
> On 9/5/07, Alexandre Badez <[EMAIL PROTECTED]> wrote:
>
> > I use __slots__ not for memory optimization nor doing java.
> > I use __slots__ because my class are used by other lib, and in the
> > past, some of them misspell some attributes and involved a very
> > annoying comportment of the global application.
> > So the objective is only to prevent unwanted dynamism (but not in all
> > the application, just some class).
>
> Using slots to prevent the creation of new properties is what Eric
> *means* by "doing java". You're trying to write Java style code in
> Python, and it's not going to be pretty. Slots are not intended for
> this purpose, and they aren't very good for it.
>

Right, and this the way to do what the original poster wants:

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

  Michele Simionato

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


Re: threads

2007-09-05 Thread Diez B. Roggisch
vijayca wrote:

> i have written a script that spawns some threads
> all run in parallel
> now i need to stop all the threads once i press a key(example: "\n")
> how to do it...

That's a FAQ. Search this NG/ML for exhaustive discussions. The quick answer
is:

 - you can't stop externally

 - so you must rely on frequently checking some flag inside your worker
threads.

Like this (untested):

class MyThread(Thread):
  
  def __init__(self):
 Thread.__init__(self)
 self.running = True

  def run(self):
 while self.running:
 work()

Set MyThread.running to False when the key is pressed.


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


handling modules in packages

2007-09-05 Thread Tommy Grav
Hi,

   I am working on a package that contains a number of
different modules:

 > ls pyAstro
__init__.py
constants.py
conversion.py
observation.py
orbit.py
transformation.py

however, I find that several of the modules have the
same import statements:

orbit.py:

import numpy
import constants
import conversion
import observations

observations.py:

import numpy
import constants
import conversions
import transformations

The modules themselves are not overly large, but it bugs
me to have to import numpy twice (or even more as the
number of modules grow). Is there a way to import numpy
once in the package (like in the __init__.py file) such that
it is accessible to all the modules? Or is the multiple imports
just something one has to live with?

Thanks for any help or direction to webpages discussing this
topic.

Cheers
   Tommy

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


Re: Looping through File Question

2007-09-05 Thread John Machin
On Sep 5, 10:26 pm, planetmatt <[EMAIL PROTECTED]> wrote:
> On 5 Sep, 12:34, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sep 5, 8:58 pm, planetmatt <[EMAIL PROTECTED]> wrote:
>
> > > I am a Python beginner.  I am trying to loop through a CSV file which
> > > I can do.  What I want to change though is for the loop to start at
> > > row 2 in the file thus excluding column headers.
>
> > > At present I am using this statement to initiate a loop though the
> > > records:
>
> > > for line in f.readlines():
>
> > > How do I start this at row 2?
>
> > The quick answer to your literal question is:
> >   for line in f.readlines()[1:]:
> > or, with extreme loss of elegance, this:
> >   for lino, line in enumerate(f.readlines()):
> >   if not lino:
> >   continue
>
> > But readline and readlines are old hat, and you wouldn't want to read
> > a file of a few million lines into a big list, so a better answer is:
>
> > _unused = f.next()
> > for line in f:
>
> > But you did say you were reading a CSV file, and you don't really want
> > to do your own CSV parsing, even if you think you know how to get it
> > right, so best is:
>
> > import csv
> > rdr = csv.reader(f)
> > heading_row = rdr.next()
> > for data_row in rdr:
>
> > HTH,
> > John
>
> Thanks so much for the quick response.  All working now.
>
> I had looked at the CSV module but when I ran into another problem of
> trying to loop through all columns, I was given a solution in another
> forum which used the readlines() method.

Antique advice which still left you doing the CSV parsing :-)

>
> I have looked at the CSV documentation but didn't see any mention of
> heading_row or data_row.

Ummm ... 'heading_row' and 'data_row' are identifiers of the kind that
you or I would need to make up in any language; why did you expect to
find them in the documentation?

> Is there a definitive Python documentation
> site with code examples like MS's MSDN?

The definitive Python documentation site is (I suppose) 
http://www.python.org/doc/

I don't know what "code examples like MS's MSDN" means. I avoid MSDN
like I'd avoid a nurse carrying a bottle of Dettol and a wire
brush :-)

Here's an example of sucking your data into a list of lists and
accessing it columnwise:

rdr = csv.reader(f)
whatever_you_want_to_call_the_heading_row = rdr.next()
data = list(rdr)
sum_col_5 = sum(float(row[5]) for row in data)
print "The value in row 3, column 4 is", data[3][4]

HTH,
John

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


Re: StringIO MySQL data blob Image problem

2007-09-05 Thread Tim Golden

dimitri pater wrote:

I am trying to insert an image, which is stored as a blob in MySQL,
into a table using Reportlab.


[... snip stuff involving StringIO and getvalue / tostring etc. ...]


This is also the string I see in the table, in stead of the actual image.


[.. snip more stuff ...]


that returns:
ÿØÿàúlbo¤qÁ5¼–Ò\¸•£ˆˆ‡�Y|Aø—­,ñé–ú…"ìâm3Z¸ŒÁfêñ""NÔ,­¡¾ÚÀIæÃt"[EMAIL 
PROTECTED]'ÍkÕÁå¼sàßd˜ª²«Í�É1ØœÏ
‡^ÖJ�*™C(r)ë{:tâ¥_‡Çâ–´°joÙÃ
¿C(c)¯äÜ[)¯gN«ÃæXßi etc... etc...
and return an UnicodeDecodeError when I try to insert this into the table


Well, I'm mystified. Not by your results: that exactly what I
expected to get, but because you're doing everything *except*
manipulating an image and putting it into a PDF via ReportLab.

Just in case you're under any other impression, there's no such
thing as "a graphical image" in a database or in computer memory.
There's just a bunch of bytes which -- given the right libraries
-- can be represented as an image. Given other libraries, such
as the ones which print them to a text console, they can be
represented as a stream of apparent gibberish. You need to
use the former; you're using the latter.

It's a while since I did anything with ReportLab but I seem to
remember that you can pass it an image filename and, (possibly
as long as you have the Python Imaging Library installed),
it will insert it into the PDF you're building as a flowable.

Assuming I'm right, get hold of the bytes in your MySQL query,
save them as "temp.jpg" or whatever, and then pass that filename
along to ReportLab. Feel free to come back and ask if those
instructions aren't clear enough.

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

Re: creating really big lists

2007-09-05 Thread John Machin
On Sep 5, 7:50 pm, Dr Mephesto <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I would like to create a pretty big list of lists; a list 3,000,000
> long, each entry containing 5 empty lists. My application will append
> data each of the 5 sublists, so they will be of varying lengths (so no
> arrays!).

Will each and every of the 3,000,000 slots be used? If not, you may be
much better off storagewise if you used a dictionary instead of a
list, at the cost of slower access.

Cheers,
John

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


Re: creating really big lists

2007-09-05 Thread Hrvoje Niksic
Dr Mephesto <[EMAIL PROTECTED]> writes:

> I would like to create a pretty big list of lists; a list 3,000,000
> long, each entry containing 5 empty lists. My application will
> append data each of the 5 sublists, so they will be of varying
> lengths (so no arrays!).
>
> Does anyone know the most efficient way to do this? I have tried:
>
> list = [[[],[],[],[],[]] for _ in xrange(300)]

You might want to use a tuple as the container for the lower-level
lists -- it's more compact and costs less allocation-wise.

But the real problem is not list allocation vs tuple allocation, nor
is it looping in Python; surprisingly, it's the GC.  Notice this:

$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> t0=time.time(); l=[([],[],[],[],[]) for _ in xrange(300)];
>>> t1=time.time()
>>> t1-t0
143.89971613883972

Now, with the GC disabled:
$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gc
>>> gc.disable()
>>> import time
>>> t0=time.time(); l=[([],[],[],[],[]) for _ in xrange(300)];
>>> t1=time.time()
>>> t1-t0
2.9048631191253662

The speed difference is staggering, almost 50-fold.  I suspect GC
degrades the (amortized) linear-time list building into quadratic
time.  Since you allocate all the small lists, the GC gets invoked
every 700 or so allocations, and has to visit more and more objects in
each pass.  I'm not sure if this can be fixed (shouldn't the
generational GC only have to visit the freshly created objects rather
than all of them?), but it has been noticed on this group before.

If you're building large data structures and don't need to reclaim
cyclical references, I suggest turning GC off, at least during
construction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me understand this script

2007-09-05 Thread Gerardo Herzig
Ryan J Nauman wrote:

>Can someone help me understand this script please?
>I understand everything except for the anagram function.  Could you break 
>it down into more than 1 line of code for me or explain it? (I understand 
>WHAT it does but HOW?) Thanks.
>
>Script >>
>
>###
># SCRABBLE.PY
>#
># purpose: 
>#   find usable "bingos" based on your rack
>#
># usage:
>#   python scrabble.py eilsnsy
>#
># output:
># Straight anagrams: 
>#  linseys
>#  lysines
># Possible other words: 
># + B
>#   sensibly
>#+ K
>#   skylines
>#+ V
>#   sylvines
>###
># Scrabble is a registered trademark of J. W. Spear & Son PLC and 
># Hasbro Inc. Any and all uses of the word "Scrabble" in this code
># refers to this trademark.
>#
># This code is not affiliated with any company.
>###
>
>import sys
>
>WORDS = [ i.rstrip ().lower() for i in file ('c:\python25\TWL06.txt') ]
># you can download the current TWL and/or SOWPODS dictionaries from 
># http://67.19.18.90/twl.zip and http://67.19.18.90/sowpods.zip . 
># Update the file name above as appropriate if you want to use a "proper"
># Scrabble dictionary.
>
>
>
>def alphabetise(word):
>x = [i for i in word]
>x.sort()
> 
>return "".join(x)
>
>def anagram(word):
>wordLength = len(word)
>sortedWord = alphabetise(word.lower())
>return [i for i in WORDS if len(i) == wordLength and alphabetise(i) == 
>sortedWord]
>
>for word in sys.argv[1:]:
>print "Straight anagrams: "
>for i in anagram(word):
>print "  " + i
>print "Possible other words: "
>for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
>a = anagram(i + word)
>if a:
>print "+", i
>for h in a:
>print "  ", h
>
><< End script
>  
>
I guess the difficult part remains in the last line. (Untested code bellow)
[code]

def anagram(word):
resultValue = []
wordLength = len(word)
sortedWord = alphabetise(word.lower()) #not much to change until here
for WORD in WORDS:
if wordLength == len(WORD) and alphabetise(WORD) == sortedWord:
resultValue.append(WORD)

return resultValue

[/code]

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


python exec behaves inconsistent with respect to module imports

2007-09-05 Thread [EMAIL PROTECTED]
Hello

I am completely puzzled why the following exec code does not work:

mycode = "import math\ndef f(y):\nprint math.floor(y)\nf(3.14)"
def execute():
exec mycode
execute()


I get the error:

[EMAIL PROTECTED]:/opt/qbase# python error1.py
Traceback (most recent call last):
  File "error1.py", line 5, in ?
execute()
  File "error1.py", line 4, in execute
exec mycode
  File "", line 4, in ?
  File "", line 3, in f
NameError: global name 'math' is not defined


Note that the following code _does_ work:

mycode = "import math\ndef f(y):\nprint math.floor(y)\nf(3.14)"
exec mycode


I have tested this in python 2.3 and 2.4.


Regards
Carl

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


Re: Accessing Module variables from another Module

2007-09-05 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> On Sep 5, 1:22 pm, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] a écrit :
>>
>>> Hi
>>> I am new to Python (I have come from a large background of Java) and
>>> wondered if someone could explain to me how I can access variables
>>> stored in my main module to other functions within other modules
>>> called
>>> from this module
>> (snip code)
>>> I am currently just passing the variable in as a parameter
>> And this is the RightThing(tm) to do.
>>
>>> but I thought with Python there would be a way to gain direct access
>>> to
>>> storeList within the modules called from the top main module?
>> Yes : passing it as a param !-)
>>
>> For other modules to get direct access to main.storeList, you'd need
>> these modules to import main in these other modules, which would
>> introduce circular dependencies, which are something you usuallay don't
>> want. 

(NB : the canonical solution to circular dependencies is to move the 
relevent definitions to a third module.)

> Also, and while it's ok to read imported modules attributes, it's
>> certainly not a good idea to mutate or rebind them IMHO, unless you're
>> ok with spaghetti code.
> 
> Cheers Bruno, I just wanted to make sure I was being consistent with
> the "Python way of things" :)

Then fire up your python shell and type 'import this' !-)

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


Re: Multi Heritage with slots

2007-09-05 Thread Alexandre Badez
On Sep 5, 2:56 pm, Michele Simionato <[EMAIL PROTECTED]>
wrote:
> On Sep 5, 2:52 pm, "Simon Brunning" <[EMAIL PROTECTED]> wrote:
>
> > On 9/5/07, Alexandre Badez <[EMAIL PROTECTED]> wrote:
>
> > > I use __slots__ not for memory optimization nor doing java.
> > > I use __slots__ because my class are used by other lib, and in the
> > > past, some of them misspell some attributes and involved a very
> > > annoying comportment of the global application.
> > > So the objective is only to prevent unwanted dynamism (but not in all
> > > the application, just some class).
>
> > Using slots to prevent the creation of new properties is what Eric
> > *means* by "doing java". You're trying to write Java style code in
> > Python, and it's not going to be pretty. Slots are not intended for
> > this purpose, and they aren't very good for it.
>
> Right, and this the way to do what the original poster wants:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
>
>   Michele Simionato

Thanks every body for your remarks.
I still have a lot to learn in python...

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


Checking if elements are empty

2007-09-05 Thread Doran, Harold
Dear list:

Suppose I have a string as follows

x = '  \t'ff'

I can split this up as

y = x.split('\t')

Which gives

[ '  ', 'ff']

len(y)
2

Is there a way to check if the first element of y is null?

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

Re: handling modules in packages

2007-09-05 Thread Steve Holden
Tommy Grav wrote:
> Hi,
> 
>I am working on a package that contains a number of
> different modules:
> 
>  > ls pyAstro
> __init__.py
> constants.py
> conversion.py
> observation.py
> orbit.py
> transformation.py
> 
> however, I find that several of the modules have the
> same import statements:
> 
> orbit.py:
> 
> import numpy
> import constants
> import conversion
> import observations
> 
> observations.py:
> 
> import numpy
> import constants
> import conversions
> import transformations
> 
> The modules themselves are not overly large, but it bugs
> me to have to import numpy twice (or even more as the
> number of modules grow). Is there a way to import numpy
> once in the package (like in the __init__.py file) such that
> it is accessible to all the modules? Or is the multiple imports
> just something one has to live with?
> 
> Thanks for any help or direction to webpages discussing this
> topic.
> 
> Cheers
>Tommy
> 
The simplest thing to do would be to have PyAstro.__init__.py import all 
the sub-modules, and define __all__ as the set of names that the package 
should inject into importing modules.

Then you could write (for example)

from PyAstro import numpy, constants, conversion, obsrvations

However if you are simply worried about run-time efficiency then don't 
be: once a module is imported further imports essentially reduce to 
checking that the module is already present in the sys.modules dict, and 
so take almost no time at all.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: handling modules in packages

2007-09-05 Thread Diez B. Roggisch
Tommy Grav wrote:

> Hi,
> 
>I am working on a package that contains a number of
> different modules:
> 
>  > ls pyAstro
> __init__.py
> constants.py
> conversion.py
> observation.py
> orbit.py
> transformation.py
> 
> however, I find that several of the modules have the
> same import statements:
> 
> orbit.py:
> 
> import numpy
> import constants
> import conversion
> import observations
> 
> observations.py:
> 
> import numpy
> import constants
> import conversions
> import transformations
> 
> The modules themselves are not overly large, but it bugs
> me to have to import numpy twice (or even more as the
> number of modules grow). Is there a way to import numpy
> once in the package (like in the __init__.py file) such that
> it is accessible to all the modules? Or is the multiple imports
> just something one has to live with?

Essentially, yes. That's the way it is, and it's better for understanding
how things work in the respective submodules.

However, you can stuff things into the __builtins__-module using setattr,
and thus make names known globally.

But it's a hack, and it means that you possibly create conflicts if
different modules have different ideas on what is supposed to live under
one key.

so - don't do it. And live with the imports. After all, that's only c'n'p,
and not of the bad kind.

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


Re: python exec behaves inconsistent with respect to module imports

2007-09-05 Thread Daniel Larsson
On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> Hello
>
> I am completely puzzled why the following exec code does not work:
>
> mycode = "import math\ndef f(y):\nprint math.floor(y)\nf(3.14)"
> def execute():
> exec mycode
> execute()
>
>
> I get the error:
>
> [EMAIL PROTECTED]:/opt/qbase# python error1.py
> Traceback (most recent call last):
>   File "error1.py", line 5, in ?
> execute()
>   File "error1.py", line 4, in execute
> exec mycode
>   File "", line 4, in ?
>   File "", line 3, in f
> NameError: global name 'math' is not defined


This is due to a namespace issue with exec, see
http://docs.python.org/ref/exec.html#l2h-569

The namespace used in an exec statement is the local scope. This scope is
different in your two cases. If you change the exec call to

def execute():
exec mycode in globals()

It will work as you expect.


Note that the following code _does_ work:
>
> mycode = "import math\ndef f(y):\nprint math.floor(y)\nf(3.14)"
> exec mycode
>
>
> I have tested this in python 2.3 and 2.4.
>
>
> Regards
> Carl
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: handling modules in packages

2007-09-05 Thread Tommy Grav
>>
> The simplest thing to do would be to have PyAstro.__init__.py  
> import all
> the sub-modules, and define __all__ as the set of names that the  
> package
> should inject into importing modules.
>
> Then you could write (for example)
>
> from PyAstro import numpy, constants, conversion, obsrvations
>
> However if you are simply worried about run-time efficiency then don't
> be: once a module is imported further imports essentially reduce to
> checking that the module is already present in the sys.modules  
> dict, and
> so take almost no time at all.

So am I understanding it right that a second import numpy statement
in a different module (and thus a different namespace) just results in
a binding to the already existing numpy "object"?

Cheers
   Tommy


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


Re: handling modules in packages

2007-09-05 Thread Daniel Larsson
On 9/5/07, Tommy Grav <[EMAIL PROTECTED]> wrote:
>
> >>
> > The simplest thing to do would be to have PyAstro.__init__.py
> > import all
> > the sub-modules, and define __all__ as the set of names that the
> > package
> > should inject into importing modules.
> >
> > Then you could write (for example)
> >
> > from PyAstro import numpy, constants, conversion, obsrvations
> >
> > However if you are simply worried about run-time efficiency then don't
> > be: once a module is imported further imports essentially reduce to
> > checking that the module is already present in the sys.modules
> > dict, and
> > so take almost no time at all.
>
> So am I understanding it right that a second import numpy statement
> in a different module (and thus a different namespace) just results in
> a binding to the already existing numpy "object"?


Yes, correct
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python exec behaves inconsistent with respect to module imports

2007-09-05 Thread Peter Otten
Am Wed, 05 Sep 2007 13:12:24 + schrieb [EMAIL PROTECTED]:

> I am completely puzzled why the following exec code does not work:
> 
> mycode = "import math\ndef f(y):\nprint math.floor(y)\nf(3.14)"
> def execute():
> exec mycode
> execute()
> 
> 
> I get the error:
> 
> [EMAIL PROTECTED]:/opt/qbase# python error1.py
> Traceback (most recent call last):
>   File "error1.py", line 5, in ?
> execute()
>   File "error1.py", line 4, in execute
> exec mycode
>   File "", line 4, in ?
>   File "", line 3, in f
> NameError: global name 'math' is not defined
 
> Note that the following code _does_ work:
> 
> mycode = "import math\ndef f(y):\nprint math.floor(y)\nf(3.14)"
> exec mycode
 
> I have tested this in python 2.3 and 2.4.

exec breaks nested namespaces here.

Essentially

exec "import math"

puts the "math" name into the local namespace, but

"def f(): math.floor"

looks up "math" in the global namespace. On the module level global and
local namespace are identical

>>> globals() is locals()
True

but inside a function they are distinct

>>> def f(): return globals() is locals()
... 
>>> f()
False

A workaround is to declare "math" as global:

>>> s = """
... global math
... import math
... def f(y): print math.floor(y)
... f(3.14)
... """
>>> def execute():
... exec s
... 
>>> execute()
3.0

or pass it explicitly:

[new interpreter session]
>>> s = """
... import math
... def f(y, math=math): print math.floor(y)
... f(3.14)
... """
>>> def execute():
... exec s
... 
>>> execute()
3.0

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


Re: Checking if elements are empty

2007-09-05 Thread Steve Holden
Doran, Harold wrote:
> Dear list:
> 
> Suppose I have a string as follows
> 
> x = '  \t'ff'
> >>> x = '  \t'ff'
   File "", line 1
 x = '  \t'ff'
^
SyntaxError: invalid syntax
>>>

I presume you meant

x = '  \t\'ff'


> I can split this up as
> 
> y = x.split('\t')
> 
> Which gives
> 
> [ '  ', 'ff']
> 
> len(y)
> 2
> 
> Is there a way to check if the first element of y is null?
> 

len(y[0]) == 0

would be the obvious way, assuming "null" means "the null string".

If whitespace is significant that'll do, if it isn't then you may need 
to use the strip() method to remove it before your scheck.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


PythonAlley.com

2007-09-05 Thread Shawn Milochik
I bought the domain PythonAlley.com (and PerlAlley.com and
RubyAlley.com) not too long ago. I had the inspiration to make some
kind of community site thing, but never did get around to it.

Does anyone have any ideas as to what a wonderful use for
PythonAlley.com would be? I'd really like to do something with at
least the Python site, since I love Python. Not too sure about the
others -- maybe I'm make them wikis and open them up to the community.
Maybe I should just sell them.

Ideas?

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


Re: So what exactly is a complex number?

2007-09-05 Thread El Pitonero
On Sep 1, 3:54 am, Grzegorz S odkowicz <[EMAIL PROTECTED]> wrote:
>
> You're mixing definition with application. You didn't say a word about
> what complex numbers are, not a word about the imaginary unit, where
> does it come from, why is it 'imaginary' etc.  
> ...
> I'd also like to see a three-dimensional vector
> represented by a complex number.

Well, maybe you'd like to learn something about Geometric Algebra. :)

I am a bit surprised that today, September 2007, in a thread about
complex numbers, no one has mentioned about geometric algebra. There
is an older way of looking at complex numbers: the imaginary unit as
square root of -1. And then there is a new way of looking at complex
numbers: as the multi-vector space associated to the two-dimensional
vector space. So, yes, complex numbers are a bit like vectors, but
more precisely, they are "multi-vectors", where the first component
(the real part) is a "scalar", and the second part (the imaginary
part) is an "area".

This may all be just paraphrasing. But it gets more interesting when
you go to higher dimensions. You'd like to know whether there are
extension of complex numbers when you go to three dimensional space,
and the answer is definitely YES! But the new multivectors live in 8
dimensional space. Geometric product not only make this possible, but
this product is invertible. Moreover, complicated equations in
electromagnatism in physics (Maxwell's equations) can be written in a
single line when you use geometric algebra. When you see some of the
features of geometric algebra, you will realize that complex number
are but a small part of it. (There is a paper with the title
"Imaginary numbers are not real...", I guess the title says it all.)

Anyway, there are always many ways of looking at the same thing.
Geometric algebra is one. Who knows what tomorrow brings? But as of
today, I'd say that it's better to teach school children about
geometric algebra, instead of the present way of introducing imaginary
unit. Just my opinion.

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


Re: Checking if elements are empty

2007-09-05 Thread Chris Mellon
On 9/5/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> Doran, Harold wrote:

> >
> > Is there a way to check if the first element of y is null?
> >
>
> len(y[0]) == 0
>
> would be the obvious way, assuming "null" means "the null string".
>

Better spelled as

if y[0]:
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking if elements are empty

2007-09-05 Thread Daniel Larsson
On 9/5/07, Chris Mellon <[EMAIL PROTECTED]> wrote:
>
> On 9/5/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> > Doran, Harold wrote:
>
> > >
> > > Is there a way to check if the first element of y is null?
> > >
> >
> > len(y[0]) == 0
> >
> > would be the obvious way, assuming "null" means "the null string".
> >
>
> Better spelled as
>
> if y[0]:


Even better spelled as

if not y[0]:

;-)

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

Re: handling modules in packages

2007-09-05 Thread Bruno Desthuilliers
Tommy Grav a écrit :
(snip)
 >
> So am I understanding it right that a second import numpy statement
> in a different module (and thus a different namespace) just results in
> a binding to the already existing numpy "object"?

Yes.

And FWIW, you can drop the quotes around the word 'object', because 
Python's modules *are* objects:

Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import sys
 >>> sys.__class__

 >>>


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


Re: python exec behaves inconsistent with respect to module imports

2007-09-05 Thread [EMAIL PROTECTED]
Hi

Thank you for the explanation

It seems that python behaves different for variables created in the
toplevel namespace, versus deeper namespaces.

CODE:

def g():
  a=2
  print "a in LOC:",locals().has_key('a')
  print "a in GLO:",globals().has_key('a')
  def f():
print "a in LOC:",locals().has_key('a')
print "a in GLO:",globals().has_key('a')
print a
  f()
g()

b=3
print "b in LOC:",locals().has_key('b')
print "b in GLO:",globals().has_key('b')
def h():
  print "b in LOC:",locals().has_key('b')
  print "b in GLO:",globals().has_key('b')
  print b
h()


RESULT:

a in LOC: True
a in GLO: False
a in LOC: True
a in GLO: False
2
b in LOC: True
b in GLO: True
b in LOC: False
b in GLO: True
3


DISCUSSION:

locals() are passed through from a function to a nested function
locals() are not passed if you go from top-level to a nested function.

globals() are visible from all levels
globals() are auto-populated at top level

So now get back to my exec code in the previous post.
The exec applies a mixture of both rules
1. The exec looks at its namespace to apply the rule for globals().
Since I'm not at top-level, variables are not auto-populated in the
globals(), unless I add the keyword 'global' like you suggested.
2. However, the exec applies the other rule for locals(). It does NOT
copy the locals() from one level to the nested one, although it
should.

To me this seems a bug in python exec:
- exec should look at its context to find out if the exec is called
top-level or deeper
- if top-level: auto-populate globals, and do not allow inheritance of
locals to nested levels
- if non top-level: dont populate globals, but allow inheritance of
locals to nested levels.

What do you think?






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


Re: FCGI app reloading on every request - solved

2007-09-05 Thread John Nagle
Sion Arrowsmith wrote:
> John Nagle  <[EMAIL PROTECTED]> wrote:
> 
>>   Tried putting this in the .htaccess file:
>>
>>
>>SetHandler fcgid-script
>>Options ExecCGI
>>allow from all
>>
>>
>>
>>ErrorDocument 403 "File type not supported."
>>
>>
>>Even with that, a ".foo" file gets executed as a CGI script,
>>and so does a ".fcgi" file.  It's an Apache configuration problem.
> 
> 
> I'd look to see if you've got a AllowOverride None set somewhere
> unhelpful (probably on the cgi-bin directory, although I note the
> default Apache2 config on my machine here does it for the document
> root too). Mind you, if you're managing this with a web tool rather
> than having access to the Apache config files, it might not be so
> straightforward to do.

 I now know what's wrong; it's a combination of several problems.

 First, configuring Apache via Plesk has very limited options,
and no documentation telling you what it's doing.  The actual
problem is that Plesk generates, in "/etc/conf/httpd.conf".

 ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

This makes anything in cgi-bin executable with mod-cgi,
regardless of anything set up for any other suffix. For
historical reasons, CGI gets better treatment in Apache than
other "mod-" components, and apparently ScriptAlias outranks
Files and AddHandler.  So that's why .fcgi programs were being
run as .cgi programs.

 With the Plesk-created configuration, an executable ".fcgi" file
in any web-server-visible directory OTHER than "cgi-bin" will execute
with mod_fcgi.  So that's how to get around this.  Note that this is
backwards from the usual CGI configuration, where scripts will execute
only from "cgi-bin".  This has security implications.

 If you're using Plesk, you can't change the defaults, because Plesk
regenerates the config files when you use the Plesk control panel app.
Nor will overrides in .htaccess work; those are disallowed by an
"AllowOverride None".  So you're stuck with what Plesk gives you.
Even on a dedicated server using Plesk.

 Then there's mod_fcgid, which Plesk configures but has almost no
documentation either.  If mod_fcgid can't spawn an application
process, for any reason, including a simple Python error,
the error message is "[warn] mod_fcgid: can't apply process slot for ...".
That's all you get in the Apache log.  The web user gets "Service
Temporarily Unavailable", because mod_fcgid doesn't distinguish
internally between "don't have enough resources to spawn a new process"
and "new process didn't launch correctly".   I had to look at the
source code for mod_fcgid to figure out what it meant.  (Ruby on Rails
people get this message now and then, and they're puzzled by it.)

 So that's what's going on.  This sort of thing is why mod_fcgid,
which is actually a good concept, isn't used much.

John Nagle

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


Re: Noob: What is a slot? Me trying to understand another's code

2007-09-05 Thread Marc 'BlackJack' Rintsch
On Tue, 04 Sep 2007 13:03:16 -0500, Carnell, James E wrote:

> I am thinking about purchasing a book, but wanted to make sure I could
> get through the code that implements what the book is about (Artificial
> Intelligence a Modern Approach). Anyway, I'm not a very good programmer
> and OOP is still sinking in, so please don't answer my questions like I
> really know anything.
> 
> MY QUESTION:
> What is a slot? In class Object below the __init__ has a slot.  Note:
> The slot makes use of a data object called 'percept' that is used in the
> TableDrivenAgent(Agent) at the bottom of this post. I am guessing this
> is a type of Finite State Machine (I haven't bought the book yet so I am
> guessing).
> 
> […]
> 
> Anyway, why a slot (whatever that is)?
> 
> [Example code snipped.]

If you want to learn Python don't do it with that book because the authors
seem to write another programming language using Python syntax. I guess
there's an older issue of that book that used the SmallTalk programming
language and they switched to Python syntactically but not mentally and not
the vocabulary. A "slot" in SmallTalk is called "attribute" in Python.

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

ZSI sample and issues with the WSDL

2007-09-05 Thread David Ross
First two appologies, this is probably not a Python question, more
SOAP. And second, there is every possibilty I am terminally confused
having looked at this for two days now.

What I want is to create a Python SOAP server.  I am using the sample
which comes with ZSI, namely the Echo.wsdl and associated files.  I
then follow the instructions in the readme, and I CAN get a python
client and server to communicate.

But when I take the WSDL file and try to create a VB.NET program:

>wsdl.exe /language:VB /out:myProxyClass.vb Echo.wsdl 

I get:

Error: Unable to import binding 'EchoServer' from namespace
'urn:ZSI:examples'.
  - Unable to import operation 'Echo'.
  - Specified cast is not valid.

So I tried to set up the wsdl to point to my domain:



http://schemas.xmlsoap.org/wsdl/";
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/";
  xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/";
  xmlns:http="http://schemas.xmlsoap.org/wsdl/http/";
  xmlns:xsd="http://www.w3.org/2001/XMLSchema";
  xmlns:tns="http://www.me.org/Namespaces";
  targetNamespace="http://www.me.org/Namespaces"; >

  

  
  

  

  

  
  

  

  
http://schemas.xmlsoap.org/soap/http"/>

  

   


   


  

  

  http://localhost:7000"/>

  




I get a the same error:

Error: Unable to import binding 'EchoServer' from namespace
'http://www.me.org/Namespaces'.
  - Unable to import operation 'Echo'.
  - Specified cast is not valid.

My problem is that I'm not sure how to edit the ZSI example.  Worse,
this is pretty much as simple as it seems to get ;-(

Any pointers would be greatfully received.

I know I should ask in the MS forumns, but I was hoping someone would
understand the ZSI example better than I seem to.

Cheers

David


Note anti-spam in email address...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PythonAlley.com

2007-09-05 Thread O.R.Senthil Kumaran
* Shawn Milochik <[EMAIL PROTECTED]> [2007-09-05 10:27:08]:
> I bought the domain PythonAlley.com (and PerlAlley.com and
> 
> Does anyone have any ideas as to what a wonderful use for
> PythonAlley.com would be? I'd really like to do something with at

If "you" don't have an idea, most likely others wont have as well. :)

-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking if elements are empty

2007-09-05 Thread O.R.Senthil Kumaran
> Doran, Harold wrote:
> 
> I presume you meant
> 
> x = '  \t\'ff'
> 
> 
> > Is there a way to check if the first element of y is null?
> > 

You can use startswith() method of string objects.

if x.startswith(' '):
print True


-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
-- 
http://mail.python.org/mailman/listinfo/python-list


sqlite3.OperationalError: Could not decode to UTF-8 column

2007-09-05 Thread Filipe Sousa
Hi

I'm trying to use sqlite with python 2.5 but I have this problem:

Traceback (most recent call last):
   File "converter.py", line 13, in 
 c_old.execute('select id_aluno, nome from aluno')
sqlite3.OperationalError: Could not decode to UTF-8 column 'nome' with 
text 'Ana Margarida Fernandes Gonçalves de Sá'

The database was created with another program and all data is in 
database is in latin1.

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


Text processing and file creation

2007-09-05 Thread [EMAIL PROTECTED]
I have a text source file of about 20.000 lines.
>From this file, I like to write the first 5 lines to a new file. Close
that file, grab the next 5 lines write these to a new file... grabbing
5 lines and creating new files until processing of all 20.000 lines is
done.
Is there an efficient way to do this in Python?
In advance, thanks for your help.

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


Re: PythonAlley.com

2007-09-05 Thread Shawn Milochik
On 9/5/07, O.R.Senthil Kumaran <[EMAIL PROTECTED]> wrote:
> * Shawn Milochik <[EMAIL PROTECTED]> [2007-09-05 10:27:08]:
> > I bought the domain PythonAlley.com (and PerlAlley.com and
> >
> > Does anyone have any ideas as to what a wonderful use for
> > PythonAlley.com would be? I'd really like to do something with at
>
> If "you" don't have an idea, most likely others wont have as well. :)
>
> --
> O.R.Senthil Kumaran
> http://uthcode.sarovar.org
>

Faulty logic. Otherwise, you would have to agree that you don't know
what you want for lunch if I don't know.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: REGULAR EXPRESSION

2007-09-05 Thread Shawn Milochik
> Hi.. Thanks alot for finding time to help a beginner like me. What I
> am trying to do is validate the input i get. I just want to take
> numbers and numbers only. So if the input is 23+1 or 2/3 or 9-0 or
> 7/0 , I want to find it using reg exp. I know there are other ways to
> do this... but i thought i will try this as i need to learn reg exp. I
> tried \D+   ,   \W+,  and \D+|\W+ .. Thanks once again...
>
>
> --


Send a couple of strings and the output you would like from each.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Text processing and file creation

2007-09-05 Thread kyosohma
On Sep 5, 11:13 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> I have a text source file of about 20.000 lines.>From this file, I like to 
> write the first 5 lines to a new file. Close
>
> that file, grab the next 5 lines write these to a new file... grabbing
> 5 lines and creating new files until processing of all 20.000 lines is
> done.
> Is there an efficient way to do this in Python?
> In advance, thanks for your help.

I would use a counter in a for loop using the readline method to
iterate over the 20,000 line file. Reset the counter every 5 lines/
iterations and close the file. To name files with unique names, use
the time module. Something like this:

x = 'filename-%s.txt' % time.time()

Have fun!

Mike

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


Re: Text processing and file creation

2007-09-05 Thread Arnau Sanchez
[EMAIL PROTECTED] escribió:

> I have a text source file of about 20.000 lines.
>>From this file, I like to write the first 5 lines to a new file. Close
> that file, grab the next 5 lines write these to a new file... grabbing
> 5 lines and creating new files until processing of all 20.000 lines is
> done.
> Is there an efficient way to do this in Python?

Perhaps you could provide some code to see how you approached it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3.OperationalError: Could not decode to UTF-8 column

2007-09-05 Thread Carsten Haese
On Wed, 2007-09-05 at 16:40 +0100, Filipe Sousa wrote:
> Hi
> 
> I'm trying to use sqlite with python 2.5 but I have this problem:
> 
> Traceback (most recent call last):
>File "converter.py", line 13, in 
>  c_old.execute('select id_aluno, nome from aluno')
> sqlite3.OperationalError: Could not decode to UTF-8 column 'nome' with 
> text 'Ana Margarida Fernandes Gonçalves de Sá'
> 
> The database was created with another program and all data is in 
> database is in latin1.

Try setting

conn.text_factory = str

where conn is the name of your sqlite3 connection object. See
http://docs.python.org/lib/sqlite3-Connection-Objects.html for more
information.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: python exec behaves inconsistent with respect to module imports

2007-09-05 Thread Peter Otten
Am Wed, 05 Sep 2007 14:45:11 + schrieb [EMAIL PROTECTED]:

> So now get back to my exec code in the previous post.
> The exec applies a mixture of both rules
> 1. The exec looks at its namespace to apply the rule for globals().
> Since I'm not at top-level, variables are not auto-populated in the
> globals(), unless I add the keyword 'global' like you suggested.
> 2. However, the exec applies the other rule for locals(). It does NOT
> copy the locals() from one level to the nested one, although it
> should.
> 
> To me this seems a bug in python exec:
> - exec should look at its context to find out if the exec is called
> top-level or deeper
> - if top-level: auto-populate globals, and do not allow inheritance of
> locals to nested levels
> - if non top-level: dont populate globals, but allow inheritance of
> locals to nested levels.

I like your systematic approach.
 
> What do you think?

Too much work :)

Seriously, the local namespace in a normal python function is not a
dictionary, and the decision on how to access a variable is made at
compile time. One way to achieve consistency would be to always use
dictionaries and have the lookup work its way up through the enclosing
namespaces. Of course that would kill performance...

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


Re: Text processing and file creation

2007-09-05 Thread Bjoern Schliessmann
 [EMAIL PROTECTED] wrote:

> I would use a counter in a for loop using the readline method to
> iterate over the 20,000 line file. 

file objects are iterables themselves, so there's no need to do that
by using a method.

> Reset the counter every 5 lines/ iterations and close the file. 

I'd use a generator that fetches five lines of the file per
iteration and iterate over it instead of the file directly.

> Have fun!

Definitely -- and also do your homework yourself :)

Regards,


Björn

-- 
BOFH excuse #339:

manager in the cable duct

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


Re: Text processing and file creation

2007-09-05 Thread Shawn Milochik
On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I have a text source file of about 20.000 lines.
> >From this file, I like to write the first 5 lines to a new file. Close
> that file, grab the next 5 lines write these to a new file... grabbing
> 5 lines and creating new files until processing of all 20.000 lines is
> done.
> Is there an efficient way to do this in Python?
> In advance, thanks for your help.
>


I have written a working test of this. Here's the basic setup:




open the input file

function newFileName:
generate a filename (starting with 1.tmp).
If filename exists, increment and test again (0002.tmp and so on).
return fileName

read a line until input file is empty:

test to see whether I have written five lines. If so, get a new
file name, close file, and open new file

write line to file

close output file final time


Once you get some code running, feel free to post it and we'll help.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >