ANN: pyfcp

2006-06-18 Thread aum
Hi all,

pyfcp is a suite of tools, including a package, modules and applications,
for accessing the Freenet network.

What is freenet?

Freenet - www.freenetproject.org - is a 'darknet' which supports anonymous
publication and retrieval of websites and other media, in a way that makes
it extremely expensive, if not impossible, for Big Brother to find out
the source or requesters of any given files.

pyfcp empowers python programmers to write applications which access the
freenet network.

Note that pyfcp only works with the new-generation 0.7 alpha freenet - it
will not work with the current stable 0.5 version. But that is most
certainly a plus :)

pyfcp is available on the freenet website (downloads section), but also
has its own website on the mainstream web:

 http://www.python.org/pyfcp

as well as within freenet:

 freenet:[EMAIL 
PROTECTED],E9uFCy0NhiTbR0jVQkY77doaWtxTrkS9kuMrzOtNzSQ,AQABAAE/pyfcp/50/

Enjoy!

-- 

Cheers
aum


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


Re: aligning SGML to text

2006-06-18 Thread Steven Bethard
Steven Bethard wrote:
> I have some plain text data and some SGML markup for that text that I 
> need to align.  (The SGML doesn't maintain the original whitespace, so I 
> have to do some alignment; I can't just calculate the indices directly.) 
[snip]
> Note that the SGML inserts spaces not only within the SGML elements, but 
> also around punctuation.
[snip]
> I need to determine the indices in the original text that each SGML 
> element corresponds to.

Ok, below is a working version that doesn't use regular expressions. 
It's far from concise, but at least it doesn't fail like re does when I 
have more than 100 words. =)

 >>> import elementtree.ElementTree as etree
 >>> def align(text, sgml):
... # convert SGML tree to words, and assemble a list of the
... # start word index and end word index for each SGML element
... sgml = sgml.replace('&', '&')
... tree = etree.fromstring('%s' % sgml)
... words = []
... if tree.text is not None:
... words.extend(tree.text.split())
... word_spans = []
... for elem in tree:
... elem_words = elem.text.split()
... start = len(words)
... end = start + len(elem_words)
... word_spans.append((start, end, elem.tag))
... words.extend(elem_words)
... if elem.tail is not None:
... words.extend(elem.tail.split())
... # determine the start character index and end character index
... # for each word from the SGML
... char_spans = []
... start = 0
... for word in words:
... while text[start:start + 1].isspace():
... start += 1
... end = start + len(word)
... assert text[start:end] == word, (text[start:end], word)
... char_spans.append((start, end))
... start = end
... # convert the word indices for each SGML element to
... # character indices
... for word_start, word_end, label in word_spans:
... start, _ = char_spans[word_start]
... _, end = char_spans[word_end - 1]
... yield label, start, end
...
 >>> text = '''TNF binding induces release of AIP1 (DAB2IP) from TNFR1, 
resulting in cytoplasmic translocation and concomitant formation of an 
intracellular signaling complex comprised of TRADD, RIP1, TRAF2, and 
AIPl.'''
 >>> sgml = ''' TNF  binding induces release of 
 AIP1  (  DAB2IP  ) from  
TNFR1  , resulting in cytoplasmic translocation and 
concomitant formation of an  intracellular signaling complex 
 comprised of  TRADD  ,  RIP1 
 ,  TRAF2  , and AIPl .
... '''
 >>> list(align(text, sgml))
[('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43), 
('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178), 
('PROTEIN', 180, 184), ('PROTEIN', 186, 191)]

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


Re: Change value of element in list

2006-06-18 Thread O Plameras
O Plameras wrote:
> Hi,
> 
> I'm doing python tutorial,
>> http://docs.python.org/tut/node5.html
> 
> and I have these,
> 
> lists = ['spam', 'eggs', 100, 1234]
> lists[2] = lists[2] + 23
> 
> I expected this,
> lists = ['spam', 'eggs', 123, 1234]
> 
> but got this,
> lists = ['spam', 'eggs', 100, 1234]
> 
> What's my problem here ?
> 
> I have Fedora C5 with python2.4.
> 
> Thanks.
> 
> O Plameras
> 

I reply to my post to say it is my
mistake. Before printing 'lists' I did
not do this

lists[2] = lists[2] + 23

Sorry for the bother.

O Plameras

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


Change value of element in list

2006-06-18 Thread O Plameras
Hi,

I'm doing python tutorial,
> http://docs.python.org/tut/node5.html

and I have these,

lists = ['spam', 'eggs', 100, 1234]
lists[2] = lists[2] + 23

I expected this,
lists = ['spam', 'eggs', 123, 1234]

but got this,
lists = ['spam', 'eggs', 100, 1234]

What's my problem here ?

I have Fedora C5 with python2.4.

Thanks.

O Plameras

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


Re: mapping None values to ''

2006-06-18 Thread Steven Bethard
Scott David Daniels wrote:
> Roberto Bonvallet wrote:
>> imho <[EMAIL PROTECTED]>:
>>> map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ])
>> You don't need map when using list comprehensions:
>>["" for i in [a, b, c] if i in ("None", None)]
>>
> More like:
> 
> [(i, "")[i in ("None", None)] for i in [a,b,c]]

Or in Python 2.5:

Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> a = 0
 >>> b = None
 >>> c = None
 >>> a, b, c = ('' if x in (None, 'None') else x for x in (a, b, c))
 >>> a, b, c
(0, '', '')

But someone please shoot me if I ever use something like that in 
production code. ;)

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


Re: Getting output from external programs...

2006-06-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Ten  <[EMAIL PROTECTED]> wrote:
.
.
.
>You can do this in various ways, ranging from the very simple and not very good
>
>from commands import getoutput
>
>x=getoutput(command)
>
>
>- to your more common and better popens.
>
>ie:
>
>import popen2
>
>(stdOut, stdIn) = popen2.popen4(command)
>
>x=stdOut.readlines()
>
>- asynchronously if appropriate.
>
>How are you running the command at the moment?
.
.
.
Why deprecate commands.getoutput()?  Are you merely
observing that it's applicable in fewer circumstances?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: aligning SGML to text

2006-06-18 Thread Steven Bethard
Gerard Flanagan wrote:
> Steven Bethard wrote:
>> I have some plain text data and some SGML markup for that text that I
>> need to align.  (The SGML doesn't maintain the original whitespace, so I
>> have to do some alignment; I can't just calculate the indices directly.)
>>   For example, some of my text looks like:
>>
>> TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in
>> cytoplasmic translocation and concomitant formation of an intracellular
>> signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl.
>>
>> And the corresponding SGML looks like:
>>
>>  TNF  binding induces release of  AIP1
>>  (  DAB2IP  ) from  TNFR1
>>  , resulting in cytoplasmic translocation and concomitant
>> formation of an  intracellular signaling complex 
>> comprised of  TRADD  ,  RIP1  ,
>>  TRAF2  , and AIPl .
>>
>> Note that the SGML inserts spaces not only within the SGML elements, but
>> also around punctuation.
>>
>>
>> I need to determine the indices in the original text that each SGML
>> element corresponds to.  Here's some working code to do this, based on a
>> suggestion for a related problem by Fredrik Lundh[1]::
>>
>>  def align(text, sgml):
>>  sgml = sgml.replace('&', '&')
>>  tree = etree.fromstring('%s' % sgml)
>>  words = []
>>  if tree.text is not None:
>>  words.extend(tree.text.split())
>>  word_indices = []
>>  for elem in tree:
>>  elem_words = elem.text.split()
>>  start = len(words)
>>  end = start + len(elem_words)
>>  word_indices.append((start, end, elem.tag))
>>  words.extend(elem_words)
>>  if elem.tail is not None:
>>  words.extend(elem.tail.split())
>>  expr = '\s*'.join('(%s)' % re.escape(word) for word in words)
>>  match = re.match(expr, text)
>>  assert match is not None
>>  for word_start, word_end, label in word_indices:
>>  start = match.start(word_start + 1)
>>  end = match.end(word_end)
>>  yield label, start, end
>>
> [...]
>>  >>> list(align(text, sgml))
>>  [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43),
>>  ('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178),
>>  ('PROTEIN', 180, 184), ('PROTEIN', 186, 191)]
>>
>> The problem is, this doesn't work when my text is long (which it is)
>> because regular expressions are limited to 100 groups.  I get an error
>> like::
> [...]
> 
> Steve
> 
> This is probably an abuse of itertools...
> 
> ---8<---
> text = '''TNF binding induces release of AIP1 (DAB2IP) from
> TNFR1, resulting in cytoplasmic translocation and concomitant
> formation of an intracellular signaling complex comprised of TRADD,
> RIP1, TRAF2, and AIPl.'''
> 
> sgml = ''' TNF  binding induces release of
>  AIP1  (  DAB2IP  ) from
>  TNFR1  , resulting in cytoplasmic translocation
> and concomitant formation of an  intracellular signaling
> complex  comprised of  TRADD  ,
>  RIP1  ,  TRAF2  , and AIPl .
> '''
> 
> import itertools as it
> import string
> 
> def scan(line):
> if not line: return
> line = line.strip()
> parts = string.split(line, '>', maxsplit=1)
> return parts[0]
> 
> def align(txt,sml):
> i = 0
> for k,g in it.groupby(sml.split('<'),scan):
> g = list(g)
> if not g[0]: continue
> text = g[0].split('>')[1]#.replace('\n','')
> if k.startswith('/'):
> i += len(text)
> else:
> offset = len(text.strip())
> yield k, i, i+offset
> i += offset
> 
> print list(align(text,sgml))
> 
> 
> 
> [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 38, 44),
> ('PROTEIN', 52, 57), ('PROTEIN', 131, 162), ('PROTEIN', 176, 181),
> ('PROTEIN', 184, 188), ('PROTEIN', 191, 196)]
> 
> It's off because of the punctuation possibly, can't figure it out.

Thanks for taking a look.  Yeah, the alignment's a big part of the 
problem.  It'd be really nice if the thing that gives me SGML didn't add 
whitespace haphazardly. ;-)

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


Re: Chess module blog

2006-06-18 Thread faulkner
make psyco entirely optional by putting it in a try/except block.
change INITIAL_BOARD to be a triple-quoted string.
you seem to mostly follow pep8, which is all most folks ask, but i
really like this style for docstrings:
def test():
''' hello,
this text and the quotes line up
very nicely
in a monospace font.
'''
return
pep8 says function names shouldn't be capitalized, and use underscores
to separate words, so they can be distinguished from classes [which are
CamelCase] quickly.

i would make a few small functions inside adjudicate for each cmd case,
then make a dict mapping 'fen' to the function fen, 'reset' to the
function reset, etc. faster and more modular.

Will McGugan wrote:
> Hi folks,
>
> I have just blogged about a Python chess module of mine that I wrote a
> while back. I plan on using it for a commerical project, but making the
> module open source. So I would be interested in comments / advice
> reagarding programming style and also optimization.
>
> http://www.willmcgugan.com/2006/06/18/chesspy/
>
> Regards,
>
> Will McGugan
>
> --
> work: http://www.kelpiesoft.com
> blog: http://www.willmcgugan.com

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


Python with Eclipse

2006-06-18 Thread Stan Cook
I've been trying to use Eclipse with Python on Linux for a 
while and have noticed something odd.  After running the 
code or debugging a few times, its responsiveness gets 
really bad.  Upon checking the equivalent of the task 
manager, I find several instances of Python running.  When I 
kill these instances, the responsiveness comes back.  I'm 
not sure if there is a better place to post this, but it is 
Python related.  Is this just an issue with Eclipse or is 
there something else I should inspect?

Any help would be appreciated.

Regards,

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


Re: Popen3 on Windows

2006-06-18 Thread reed

Jeffrey Barish wrote:
> I have an application that has been working fine on Linux, but now I need to
> port it to Windows XP.  The program uses Popen3 to run another program.  I
> use Popen3 so that I can access the pid attribute, which I use to kill the
> auxiliary program when necessary.  Popen3 does not exist on Windows.  I see
> os.popen2 and os.popen3, but they provide only file objects for stdin,
> stdout, and stderr so I don't see a way to kill the auxiliary program that
> I start.  Is there a way to do this on Windows?
> --
> Jeffrey Barish

>>>import subprocess
>>>x = subprocess.Popen('nc -l 2')
>>>x.pid
2783
>>>subprocess.Popen('taskkill %s' % x.pid)

>>> x.poll()
1

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


Re: Getting output from external programs...

2006-06-18 Thread Ten
On Sunday 18 June 2006 21:28, ph0b0s wrote:
>  Hi,
>
>  i'm making an mp3 conversion program in Python, but am kind of stuck now.
>  The conversion routines work, using LAME, but now a i'm building a GUI
>   with GLADE around it, and would like to be able to show LAME's output
>   to the user in a status window in my gui.. but don't know where to
> start...
>
>  The command i use to invoke LAME is this :
>command = ("lame -b " + str(bitrate) + " " + infile + " \"" +
> dir_outpath + separator + outfile + "\"")
>
>            


You can do this in various ways, ranging from the very simple and not very good

from commands import getoutput

x=getoutput(command)


- to your more common and better popens.

ie:

import popen2

(stdOut, stdIn) = popen2.popen4(command)

x=stdOut.readlines()

- asynchronously if appropriate.

How are you running the command at the moment?



-- 
There are 10 types of people in this world,
those who understand binary, and those who don't.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Simple script to make .png thumbnails from .zip archive...

2006-06-18 Thread Scott David Daniels
hdante wrote:
>   there are too many ways to create a thumbnail from an
> image. I'll cite one, using the "python image" external module, that
> I've found to be very easy:
> 
> import Image
> def process(file):
>   try:
> image = Image.open(file)
> image.thumbnail ((128,128), Image.ANTIALIAS)
> image.save (file + '.thumb.png')
>   except:
> print 'Skipping file', file
> 
>  Links:
>  http://docs.python.org/lib/lib.html - Python Library Reference
>  http://www.pythonware.com/library/pil/handbook/image.htm - The Image
> Module

That, by the way, is the "PIL" library that you'll see a lot about --
The Python Imaging Library that the effbot is justly proud of.  You
won't do better than that.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mapping None values to ''

2006-06-18 Thread Scott David Daniels
Roberto Bonvallet wrote:
> imho <[EMAIL PROTECTED]>:
>> map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ])
> You don't need map when using list comprehensions:
>["" for i in [a, b, c] if i in ("None", None)]
> 
More like:

 [(i, "")[i in ("None", None)] for i in [a,b,c]]

-- 
--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mapping None values to ''

2006-06-18 Thread Max Erickson
"Roberto Bonvallet" <[EMAIL PROTECTED]> wrote:
> You don't need map when using list comprehensions:
> 
> ["" for i in [a, b, c] if i in ("None", None)]
> 

That loses list elements that aren't in the tests:

>>> a=7
>>> b="None"
>>> c=None
>>> ["" for i in [a,b,c] if i in ("None",None)]
['', '']
>>> 

max

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


Re: Seeking regex optimizer

2006-06-18 Thread Paddy
Kay Schluehr wrote:

> with reverse sorting as in your proposal.The naive solution is easy to
> generate but I'm sceptical about its cost effectiveness. On the other
> hand I do not want to investigate this matter if somebody else already
> did it thoroughly.
>
> Regards,
> Kay

Hi Kay,
The only way to know if something is optimised enough, is for you to
test it in your application.  If you haven't finished your application,
then don't sweat it. take a note of your options, stick one in, then
get the application finished.
Its only when its finished that you can really say if further
optimisations are necessary, and you would have to profile the complete
prog to see where it's spending its time.

I usually find myself using string methods where possible, then regular
expressions only for things that string methods cannot do. When I
finish my script I usually find that Pythons speed is adequate for most
of my text processing tasks, or if speed IS an issue, then i needed to
profile the completed application anyway.

- Pad.

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


Re: any subway web dev experiences

2006-06-18 Thread George Sakkis
a wrote:

> subway is pythons ruby on rails competitor
> pls tell me if u hav any expereinces
> thanks

u wanna know reils n subway ur so kewl omg! no expereinces watsoevah,
sori dud


PS: If you want to be taken seriously, put at least some effort to make
a readable english sentence. This is comp.lang.python, not Myspace.

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


Re: Extracting values from text file

2006-06-18 Thread Mirco Wahab
Thus spoke Dennis Lee Bieber (on 2006-06-18 22:37):

>   The only cure for that is complete and painful bone marrow
> transplant  As a start, after six months of no PERL go back and try
> reading some of your code.

Uhhh, this is like giving the
mounted knight a longbow and
push him onto the battlefield
of Agincourt ;-)

Regards

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


Re: Seeking regex optimizer

2006-06-18 Thread Mirco Wahab
Thus spoke Kay Schluehr (on 2006-06-18 19:07):

> I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a
> regular expression sx from it, such that sx.match(s) yields a SRE_Match
> object when s starts with an s_i for one i in [0,...,n].  There might
> be relations between those strings: s_k.startswith(s_1) -> True or
> s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa',
> ...,'...ab']. For this reason SRE_Match should provide the longest
> possible match.

With some ideas from Kay and Paddy, it tried to get
along with Python in doing this.

If its allowed to spread the individual strings
into alterations, the following would imho do:


#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
text = r'this is a text containing aaaöüöaaaµaaa and more';
lstr = [
  'a',
  'aa',
  'a',
  'aaaöüöaaaµaaa',
  'aaab'
]

import re
pat  = re.compile(\
   '(' +  \
   '|'.join(sorted(lstr,lambda a,b: len(b)-len(a)))  + \
')',  re.VERBOSE);

hits = sorted( pat.findall(text), lambda a,b: len(b)-len(a) )
print 'Longest: ', hits[0]



This will print 'aaaöüöaaaµaaa' from the text
and won't complain about specuial characters used.

in Perl, you could build up the regex
by dynamic evaluation (??{..}), but I
didn't manage to get this working in Python,
so here is (in Perl) how I thougt it would work:

my $text = "this is a text containing aaaöüöaaaµaaa and more";
my @lstr = (
  'a',
  'aa',
  'a',
  'aaaöüöaaaµaaa',
  'aaab',
   );

my $re = qr{
(??{
join '|',
   map { quotemeta }
  sort{ length $b <=> length $a }
 @lstr
 })
}x;

$_ = $text;
print "Longest: ", (my $hit) = reverse sort /$re/g;


Maybe the experts can bring some light to it.

Regards

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


Re: Passing data to system command

2006-06-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Chris Hieronymus  <[EMAIL PROTECTED]> wrote:
.
.
.
>input.  How do I get the data into the system call?  I used to do  
>things in csh and awk,
>i.e., something like
>
>awk '{; print $1, $2}' filename | psxy options> >! output.ps
.
.
.
There are several aspects to what you're after.  First, I think, is
to experiment with

  import os
  os.system("awk '{print $%column}'" % desired_column)

Does that move you forward?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seeking regex optimizer

2006-06-18 Thread John Machin
On 19/06/2006 6:30 AM, Paddy wrote:
> Kay Schluehr wrote:
>> I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a
>> regular expression sx from it, such that sx.match(s) yields a SRE_Match
>> object when s starts with an s_i for one i in [0,...,n].  There might
>> be relations between those strings: s_k.startswith(s_1) -> True or
>> s_k.endswith(s_1) -> True.

Kay, what is the relevance of one string being a suffix of another? I 
don't see how that could affect the outcome.

  An extreme case would be ls = ['a', 'aa',
>> ...,'...ab']. For this reason SRE_Match should provide the longest
>> possible match.
>>
>> Is there a Python module able to create an optimized regex rx from ls
>> for the given constraints?

Optimised with respect to what? speed? ease of construction?

I presume that you will ensure that the members of the list are unique.

Note that the Python regex engine will consider each candidate in 
Paddy's solution left to right until it gets a match or reaches the end 
(that's why the reverse sort is needed to get longest possible match). 
This is worst-case O(N) where N is the total of the lengths of all the 
strings in your list.

As far as I can see, this is the only basic solution (modulo one or two 
twiddles -- see below) using Python's re.

You could possibly consider producing "zzz|foo(?:bar)?|aaa" instead of 
"zzz|foobar|foo|aaa" -- but whether that would run sufficiently faster 
to offset the cost of construction is anybody's guess.

How many strings in your list? Average/maximum length? Likelihood of 
ls[i].startswith(ls[j]) == True? unicode or str?

Your requirements are rather constrained: "sx.match(s) yields a 
SRE_Match object" ... why do you need this? Surely all you need is 
matched_len (which may be zero) such that s[:matched_len] is the matched 
prefix.

I would have thought the way to approach this would be a simple 
character-by-character tree/trie-driven lookup. This would be worst case 
O(n) where n is the length of the longest string in your list. There may 
well be a Python-callable gadget for this on the net somewhere. Google 
"Danny Yoo ahocorasick" for a Python-callable solution to a similar but 
more complex problem.

A cheap hack using Python's re: divide the problem according to first 
character:

prefix_dict_match = {
 'a': re.compile('alpaca|alligator').match,
 'f': re.compile('foobar|foo').match,
 'z': re.compile('zoo|zebra').match,
 }
if s and s[0] in prefix_dict_match:
 match_obj = prefix_dict_match[s[0]](s)
else:
 match_obj = None

>>
>> Regards,
>> Kay
> 
> A start would be:
>   regexp = "^(" + "|".join(sorted(ls, reverse=True)) + ")"
> But the above does not work if you have special characters in your
> strings.

Paddy, fixing that problem, and "optimising" by removing the redundant 
^() metacharacters:

regexp = "|".join(map(re.escape, sorted(ls, reverse=True)))


Hoping some of this helps,
Regards,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing data to system command

2006-06-18 Thread faulkner
import os, subprocess

xys = [[1,2],[3,4]]
msg = '\n'.join([str(x) + ',' + str(y) for x, y in xys])
os.popen('command', 'w').write(msg)
os.popen2('command')[0].write(msg)

p = subprocess.Popen('command', stdin=subprocess.PIPE)
p.stdin.write(msg)

help(subprocess)
help(os.popen)
help(os.popen3)


Chris Hieronymus wrote:
> Hi,
>
> I have a bunch of x-y data contained in an array.  I would like to
> plot the data using an
> external program (psxy in GMT).  The plotting program takes x-y
> couples as standard
> input.  How do I get the data into the system call?  I used to do
> things in csh and awk,
> i.e., something like
>
> awk '{; print $1, $2}' filename | psxy  options> >! output.ps
>
> The reason I'm trying to use python is because the manipulations are
> getting too cumbersome
> in awk.  Now I have all the manipulations done in python, but I'm
> missing that last step.
>
> I've tried various things with os.system, popen, and subprocess, but
> so far without success.
> Does anyone know how to do this?
>
> chris
>
>
> 
> ---
> Christoph
> Hieronymus
> [EMAIL PROTECTED]
> Associate
> Professor
> phone: (+46) 18-471 2383
> Uppsala
> University
>fax:   (+46) 18-501   110
> Dept. of Earth Sciences (Geophysics)
> Villavägen 16
> SE-752 36 Uppsala,  Sweden

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


Re: Passing data to system command

2006-06-18 Thread hdante
 Should be like this:

 from subprocess import Popen, PIPE

 my_output = file('output1.ps', 'w')
 p1 = Popen(["psxy"], stdin = PIPE, stdout=my_output)
 p1.stdin.write(my_format(array))
 p1.communicate()
 my_output.close()

 I've never used that, though, please tell us if it worked.

Chris Hieronymus wrote:
> Hi,
>
> I have a bunch of x-y data contained in an array.  I would like to
> plot the data using an
> external program (psxy in GMT).  The plotting program takes x-y
> couples as standard
> input.  How do I get the data into the system call?  I used to do
> things in csh and awk,
> i.e., something like
>
> awk '{; print $1, $2}' filename | psxy  options> >! output.ps
>
> The reason I'm trying to use python is because the manipulations are
> getting too cumbersome
> in awk.  Now I have all the manipulations done in python, but I'm
> missing that last step.
>
> I've tried various things with os.system, popen, and subprocess, but
> so far without success.
> Does anyone know how to do this?
>
> chris
>
>
> 
> ---
> Christoph
> Hieronymus
> [EMAIL PROTECTED]
> Associate
> Professor
> phone: (+46) 18-471 2383
> Uppsala
> University
>fax:   (+46) 18-501   110
> Dept. of Earth Sciences (Geophysics)
> Villavägen 16
> SE-752 36 Uppsala,  Sweden

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


Re: code is data

2006-06-18 Thread BJörn Lindqvist
> > > community has no interest in it. When I absolutely need macros, I will
> > > go elsewhere.
> I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would
> have done it myself for *my* code.

I think this example more is a symptom of a childish need to get
things your way than of a deficiency in Python. BTW, range(5) = 0..4
in Ada and Ruby.

You said "when I absolutely need macros" but none of your examples
demonstrate any "absolute need." I can't see your point.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seeking regex optimizer

2006-06-18 Thread Kay Schluehr
Paddy wrote:
> Kay Schluehr wrote:
> > I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a
> > regular expression sx from it, such that sx.match(s) yields a SRE_Match
> > object when s starts with an s_i for one i in [0,...,n].  There might
> > be relations between those strings: s_k.startswith(s_1) -> True or
> > s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa',
> > ...,'...ab']. For this reason SRE_Match should provide the longest
> > possible match.
> >
> > Is there a Python module able to create an optimized regex rx from ls
> > for the given constraints?
> >
> > Regards,
> > Kay
>
> A start would be:
>   regexp = "^(" + "|".join(sorted(ls, reverse=True)) + ")"
> But the above does not work if you have special characters in your
> strings.

For special characters there might be a workaround using escapes. This
is indeed important, but I do think one should split the problem into
separate parts.

> You say you want something that is optimised. What have have you tried?

Sorting the list and checking for successor inclusions. Say you have ls
= ['x','a', 'aa', 'aab' ,'ab']

This can be mapped to:

'x|a(?:(?:ab)?|b?|a?)'

or to:

'^(x|ab|aab|aa|a)'

with reverse sorting as in your proposal.The naive solution is easy to
generate but I'm sceptical about its cost effectiveness. On the other
hand I do not want to investigate this matter if somebody else already
did it thoroughly.

Regards,
Kay

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


Re: wxPython GUI designer

2006-06-18 Thread diffuser78
Are there any good commercial project built with wx ? I am a newbie and
a have to write a small application in Python. I was wondering which
optin would be best for me in terms of least learning curve and getting
the final product ASAP.

Thanks

DH wrote:

> In my opinion none of the wx* or gtk* related designer tools are
> any good.  QT Designer (which can be used with pyqt) is excellent,
> however, you probably would only want to use that if you are
> developing non-commercial software or else can afford a commercial
> license from Trolltech.  For wx and gtk projects, I usually just write
> the gui by hand like you have already been doing.

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


any subway web dev experiences

2006-06-18 Thread a
subway is pythons ruby on rails competitor
pls tell me if u hav any expereinces
thanks

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


Re: USB support

2006-06-18 Thread rodmc
Thanks for this, I have managed to build PyUSB and install it in the
relevant directory. However I get bus errors when I try the PlugUSB.py
example.  Does anyone know why this is likely to be the case?

I am using Macpython 2.4, Libusb 0.1.12 and PyUSB 0.3.3 on an Intel
based mac.

Thanks in advance.

Rod

Tim Roberts wrote:
> "rodmc" <[EMAIL PROTECTED]> wrote:
> >
> >I need to write a program which can access the USB ports on Mac and
> >Linux, is there a library available for Python?
>
> The "stable" version of Libusb includes a Python binding.  The version in
> development does not yet.
> -- 
> - Tim Roberts, [EMAIL PROTECTED]
>   Providenza & Boekelheide, Inc.

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


Re: mapping None values to ''

2006-06-18 Thread Roberto Bonvallet
imho <[EMAIL PROTECTED]>:
> map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ])

You don't need map when using list comprehensions:

["" for i in [a, b, c] if i in ("None", None)]

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


Re: Simple script to make .png thumbnails from .zip archive...

2006-06-18 Thread hdante
 Hi,

 I don't know zipfile by heart, but python official documentation is
always good ( docs.python.org ). You need a loop in the file list like
this:

  for file in zip:
process(file)

 Unfortunatelly, there are too many ways to create a thumbnail from an
image. I'll cite one, using the "python image" external module, that
I've found to be very easy:

import Image
def process(file):
  try:
image = Image.open(file)
image.thumbnail ((128,128), Image.ANTIALIAS)
image.save (file + '.thumb.png')
  except:
print 'Skipping file', file

 Links:
 http://docs.python.org/lib/lib.html - Python Library Reference
 http://www.pythonware.com/library/pil/handbook/image.htm - The Image
Module

K P S wrote:
> Hi.
>   I'm looking for a small script that will take a .zip archive and pull
> the first .jpg from the archive and convert it to a .png.
>
> The reason for this is I want to have tuhmbnails for these archives in
> nautilus under gnome.  I would like something similar to the following
> code, which will pull a thumbnail from an openoffice.org (oasis)
> document.  What I want is a little more involved, I guess, since I
> don't know the name of the file (for the zip.read command), and I need
> to convert the file from .jpg to .png once I get it.  Any help would be
> appreciated.  Including a pointer to a web page of a manual with
> examples. :-)
>
> #!/usr/bin/python
>
> import zipfile
> import sys
> import gnomevfs
>
> inURL=gnomevfs.get_local_path_from_uri(sys.argv[1])
> outURL=sys.argv[2]
>
> zip=zipfile.ZipFile(inURL,mode="r")
> picture=zip.read("Thumbnails/thumbnail.png")
> thumbnail=open(outURL,"w")
> thumbnail.write(picture)
> thumbnail.write("/n")
> zip.close()
> thumbnail.close()

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


Re: aligning SGML to text

2006-06-18 Thread Gerard Flanagan
Steven Bethard wrote:
> I have some plain text data and some SGML markup for that text that I
> need to align.  (The SGML doesn't maintain the original whitespace, so I
> have to do some alignment; I can't just calculate the indices directly.)
>   For example, some of my text looks like:
>
> TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in
> cytoplasmic translocation and concomitant formation of an intracellular
> signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl.
>
> And the corresponding SGML looks like:
>
>  TNF  binding induces release of  AIP1
>  (  DAB2IP  ) from  TNFR1
>  , resulting in cytoplasmic translocation and concomitant
> formation of an  intracellular signaling complex 
> comprised of  TRADD  ,  RIP1  ,
>  TRAF2  , and AIPl .
>
> Note that the SGML inserts spaces not only within the SGML elements, but
> also around punctuation.
>
>
> I need to determine the indices in the original text that each SGML
> element corresponds to.  Here's some working code to do this, based on a
> suggestion for a related problem by Fredrik Lundh[1]::
>
>  def align(text, sgml):
>  sgml = sgml.replace('&', '&')
>  tree = etree.fromstring('%s' % sgml)
>  words = []
>  if tree.text is not None:
>  words.extend(tree.text.split())
>  word_indices = []
>  for elem in tree:
>  elem_words = elem.text.split()
>  start = len(words)
>  end = start + len(elem_words)
>  word_indices.append((start, end, elem.tag))
>  words.extend(elem_words)
>  if elem.tail is not None:
>  words.extend(elem.tail.split())
>  expr = '\s*'.join('(%s)' % re.escape(word) for word in words)
>  match = re.match(expr, text)
>  assert match is not None
>  for word_start, word_end, label in word_indices:
>  start = match.start(word_start + 1)
>  end = match.end(word_end)
>  yield label, start, end
>
[...]
>  >>> list(align(text, sgml))
>  [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43),
>  ('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178),
>  ('PROTEIN', 180, 184), ('PROTEIN', 186, 191)]
>
> The problem is, this doesn't work when my text is long (which it is)
> because regular expressions are limited to 100 groups.  I get an error
> like::
[...]

Steve

This is probably an abuse of itertools...

---8<---
text = '''TNF binding induces release of AIP1 (DAB2IP) from
TNFR1, resulting in cytoplasmic translocation and concomitant
formation of an intracellular signaling complex comprised of TRADD,
RIP1, TRAF2, and AIPl.'''

sgml = ''' TNF  binding induces release of
 AIP1  (  DAB2IP  ) from
 TNFR1  , resulting in cytoplasmic translocation
and concomitant formation of an  intracellular signaling
complex  comprised of  TRADD  ,
 RIP1  ,  TRAF2  , and AIPl .
'''

import itertools as it
import string

def scan(line):
if not line: return
line = line.strip()
parts = string.split(line, '>', maxsplit=1)
return parts[0]

def align(txt,sml):
i = 0
for k,g in it.groupby(sml.split('<'),scan):
g = list(g)
if not g[0]: continue
text = g[0].split('>')[1]#.replace('\n','')
if k.startswith('/'):
i += len(text)
else:
offset = len(text.strip())
yield k, i, i+offset
i += offset

print list(align(text,sgml))



[('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 38, 44),
('PROTEIN', 52, 57), ('PROTEIN', 131, 162), ('PROTEIN', 176, 181),
('PROTEIN', 184, 188), ('PROTEIN', 191, 196)]

It's off because of the punctuation possibly, can't figure it out.
maybe you can tweak it?

hth

Gerard

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


Re: Seeking regex optimizer

2006-06-18 Thread Paddy

Kay Schluehr wrote:
> I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a
> regular expression sx from it, such that sx.match(s) yields a SRE_Match
> object when s starts with an s_i for one i in [0,...,n].  There might
> be relations between those strings: s_k.startswith(s_1) -> True or
> s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa',
> ...,'...ab']. For this reason SRE_Match should provide the longest
> possible match.
>
> Is there a Python module able to create an optimized regex rx from ls
> for the given constraints?
>
> Regards,
> Kay

A start would be:
  regexp = "^(" + "|".join(sorted(ls, reverse=True)) + ")"
But the above does not work if you have special characters in your
strings.

You say you want something that is optimised. What have have you tried?
 

- Pad.

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


Do you know good source codes to study?

2006-06-18 Thread Rintaro Masuda



Hi guys,
 
I am about to finish reading the book 
"Learning Python" which is published by O'reilly. This is
a good book and I get basic knowledge of 
Python from it.
 
I think it's time to read good source 
codes for the next step.  It might be great to join some open source 
projects.
 
So, do you guys know any good code I can 
get free? I am thinking of Zope, but It seems to be big for me. 
 
Thanks,
Rintaro Masuda
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Getting output from external programs...

2006-06-18 Thread ph0b0s




Hi,

i'm making an mp3 conversion program in Python, but am kind of stuck
now.
The conversion routines work, using LAME, but now a i'm building a GUI
 with GLADE around it, and would like to be able to show LAME's output
 to the user in a status window in my gui.. but don't know where to
start...

The command i use to invoke LAME is this :


command = ("lame -b " +
str(bitrate) + " " + infile + " \"" + dir_outpath + separator + outfile
+ "\"")


         






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

Re: wxPython GUI designer

2006-06-18 Thread DH
[EMAIL PROTECTED] wrote:
> I am newbie learning wxPython. I tried using GUI designer called
> wxGlade. When it generated code I couldnt get the same level of
> flexibility as writing the code by oneself.
> 
> Any view on what you think about using GUI designer tools.
> 
> Every help is appreciated.
> 

In my opinion none of the wx* or gtk* related designer tools are
any good.  QT Designer (which can be used with pyqt) is excellent,
however, you probably would only want to use that if you are
developing non-commercial software or else can afford a commercial
license from Trolltech.  For wx and gtk projects, I usually just write 
the gui by hand like you have already been doing.
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython GUI designer

2006-06-18 Thread diffuser78
I am newbie learning wxPython. I tried using GUI designer called
wxGlade. When it generated code I couldnt get the same level of
flexibility as writing the code by oneself.

Any view on what you think about using GUI designer tools.

Every help is appreciated.

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


Re: debugging in eclipse+pydev

2006-06-18 Thread Fabio Zadrozny
Hi,On 18 Jun 2006 07:46:48 -0700, yaru22 <[EMAIL PROTECTED]> wrote:
Hi.I'd like to know how to debug in eclipse+pydev.In the menu, "Pydev Debug", there's Start Debug Server option, but Idon't know how to use it.Few questions I have about debugging are:
1) how do i set a breakpoints in pydev?2) how do i execute the code line by line? I mean... step into, stepover, and so on...Can anyone give me a small tutorial as to how to debug in Eclipse +Pydev please?
That 'start debug server' is for remote debugging. Check: http://fabioz.com/pydev/manual_adv_remote_debugger.htmlFor the 'regular' debugger. Check 
http://fabioz.com/pydev/manual_adv_debugger.html. There is also a 'quick' screencast featuring it at 
http://showmedo.com/videos/video?name=PydevEclipseFabio&fromSeriesID=8&index=0 (takes you from configuring pydev until the point where you can debug it).Cheers,Fabio
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: import hook

2006-06-18 Thread Jeremy Sanders
Thomas Heller wrote:

> There are also other ways.  You could extend __path__ of foo, and the
> pkgutil module might also be useful.

The __path__ trick worked nicely, thanks. Here is the code in case anyone is
interested

# Allow veusz to be run even if not installed into PYTHONPATH
try:
import veusz
except ImportError:
# load in the veusz module, but change its path to
# the veusz directory, and insert it into sys.modules
import __init__ as veusz
thisdir = os.path.dirname( os.path.abspath(__file__) )
veusz.__path__ = [thisdir]
veusz.__name__ = 'veusz'
sys.modules['veusz'] = veusz

This is part of the main program. If it can't import it (i.e. it is not
installed), it imports the __init__ module, renames it, and corrects its
path, then sticks it into the list of imported modules.

Jeremy

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Simple script to make .png thumbnails from .zip archive...

2006-06-18 Thread K P S
Hi.
  I'm looking for a small script that will take a .zip archive and pull
the first .jpg from the archive and convert it to a .png.

The reason for this is I want to have tuhmbnails for these archives in
nautilus under gnome.  I would like something similar to the following
code, which will pull a thumbnail from an openoffice.org (oasis)
document.  What I want is a little more involved, I guess, since I
don't know the name of the file (for the zip.read command), and I need
to convert the file from .jpg to .png once I get it.  Any help would be
appreciated.  Including a pointer to a web page of a manual with
examples. :-)

#!/usr/bin/python

import zipfile
import sys
import gnomevfs

inURL=gnomevfs.get_local_path_from_uri(sys.argv[1])
outURL=sys.argv[2]

zip=zipfile.ZipFile(inURL,mode="r")
picture=zip.read("Thumbnails/thumbnail.png")
thumbnail=open(outURL,"w")
thumbnail.write(picture)
thumbnail.write("/n")
zip.close()
thumbnail.close()

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


Re: code is data

2006-06-18 Thread Roberto Bonvallet
Ravi Teja <[EMAIL PROTECTED]> said:
> I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would
> have done it myself for *my* code.

You can write your own preprocessor to handle things like that.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code is data

2006-06-18 Thread Ravi Teja

Fredrik Lundh wrote:
> Ravi Teja wrote:
>
> > Web frameworks, which seem to be the rage now in Python community could
> > have benefited tremendously from Macro capabilities since they have a
> > lot of boiler plate.
>
> they do?  methinks you haven't done much web programming lately...
>
> 

You blogged on Django. Let's use that. Don't you think model creation
in Django can be represented better, given that it is done often
enough?

Let's take an example from the official tutorial
from
http://www.djangoproject.com/documentation/tutorial1/#creating-models

class Poll(models.Model):
question = models.CharField(maxlength=200)
pub_date = models.DateTimeField('date published')

class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(maxlength=200)
votes = models.IntegerField()

I don't use Django and I made this up quickly, so please don't pick on
subtleties.

@Poll:
question: char length 200
pub_date('date published'): date

@Choice:
poll -> Poll
choice: char length 200
votes: int

The following is my rationale. Annoted variables, symbols and code
layout visually cue more efficiently to the object nature than do
explicit text definitions. Of course, this is only sensible when there
aren't too many of any of those. In that case, the cognitive cost of
notation outweighs the representational cost of text.

Representational minimalism is troublesome in general code (ala Perl),
but not so in a DSL where the context is constrained.

I would also like to symbolize field types since they occur so commonly
in a definition file and only a few of them are commonly used. I admit
though that I find the code below a bit visually jarring and I might
use something else. But it serves to illustrate the point. I chose the
respective symbols based on their colloquial use and association with
the field types.

@Poll:
$question: length 200
%pub_date('date published')

@Choice:
poll -> Poll
$choice: length 200
#votes

Since you are on thread and are a prominent and involved member of the
Python community, I would like it if you (or any such other) can
provide feedback on the rest of my previous post rather than be
dismissive by just a small portion of it. Perhaps, that will give me
some insight how these language design decisions are rationally made (I
am not strictly a programmer by profession, much less a language
designer).

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


Re: Extracting values from text file

2006-06-18 Thread Preben Randhol
On Sun, 18 Jun 2006 17:46:43 +0200
Mirco Wahab <[EMAIL PROTECTED]> wrote:

> Thus spoke Preben Randhol (on 2006-06-18 13:34):
> > On Sun, 18 Jun 2006 10:54:01 +0200
> > Mirco Wahab <[EMAIL PROTECTED]> wrote:
> >> - no DWIM-ism (do what I mean) on 'value' addition
> > 
> > But you don't add two values. you add two strings. If you 
> > want numbers you must convert the strings. 
> 
> Why? At least - if its obvious, what I want.

If I say: I want something to eat.

Can you know if I want a dessert or a dinner ? ;-)

My point is that you don't specify. In your case you show that pyhton
is polymorphic, and that can have side-effects... Since in Python
you cannot define what type a function should accept you can throw
anything to it and it will happily much at it as best it can.

Computers are dumb and it is better that one give them enough
instructions than to let them second guess you IMHO

My other language of choice is Ada. Ada is quite the opposite of
Python in being a very strictly typed language. It takes some getting
used to Python for me ;-) In my opinion Ada95 & Ada2005 got strict
typing correct, while Java only partially is strictly typed. C/C++ is
not. Anyway Ada and Python has different targets so I can happily play
with both static and dynamic typing. 

I can recommend Ada as it will teach you to a very good programming
style that can be used when using other language.

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


aligning SGML to text

2006-06-18 Thread Steven Bethard
I have some plain text data and some SGML markup for that text that I 
need to align.  (The SGML doesn't maintain the original whitespace, so I 
have to do some alignment; I can't just calculate the indices directly.) 
  For example, some of my text looks like:

TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in 
cytoplasmic translocation and concomitant formation of an intracellular 
signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl.

And the corresponding SGML looks like:

 TNF  binding induces release of  AIP1 
 (  DAB2IP  ) from  TNFR1 
 , resulting in cytoplasmic translocation and concomitant 
formation of an  intracellular signaling complex  
comprised of  TRADD  ,  RIP1  , 
 TRAF2  , and AIPl .

Note that the SGML inserts spaces not only within the SGML elements, but 
also around punctuation.


I need to determine the indices in the original text that each SGML 
element corresponds to.  Here's some working code to do this, based on a 
suggestion for a related problem by Fredrik Lundh[1]::

 def align(text, sgml):
 sgml = sgml.replace('&', '&')
 tree = etree.fromstring('%s' % sgml)
 words = []
 if tree.text is not None:
 words.extend(tree.text.split())
 word_indices = []
 for elem in tree:
 elem_words = elem.text.split()
 start = len(words)
 end = start + len(elem_words)
 word_indices.append((start, end, elem.tag))
 words.extend(elem_words)
 if elem.tail is not None:
 words.extend(elem.tail.split())
 expr = '\s*'.join('(%s)' % re.escape(word) for word in words)
 match = re.match(expr, text)
 assert match is not None
 for word_start, word_end, label in word_indices:
 start = match.start(word_start + 1)
 end = match.end(word_end)
 yield label, start, end


 >>> text = '''TNF binding induces release of AIP1 (DAB2IP) from
 TNFR1, resulting in cytoplasmic translocation and concomitant
 formation of an intracellular signaling complex comprised of TRADD,
 RIP1, TRAF2, and AIPl.'''
 >>> sgml = ''' TNF  binding induces release of
  AIP1  (  DAB2IP  ) from
  TNFR1  , resulting in cytoplasmic translocation
 and concomitant formation of an  intracellular signaling
 complex  comprised of  TRADD  ,
  RIP1  ,  TRAF2  , and AIPl .
 '''
 >>> list(align(text, sgml))
 [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43),
 ('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178),
 ('PROTEIN', 180, 184), ('PROTEIN', 186, 191)]

The problem is, this doesn't work when my text is long (which it is) 
because regular expressions are limited to 100 groups.  I get an error 
like::

 Traceback (most recent call last):
 ...
 AssertionError: sorry, but this version only supports 100 named
 groups

I also played around with difflib.SequenceMatcher for a while, but 
couldn't get a solution based on that working.  Any suggestions?


[1]http://mail.python.org/pipermail/python-list/2005-December/313388.html

Thanks,

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


Passing data to system command

2006-06-18 Thread Chris Hieronymus

Hi,

I have a bunch of x-y data contained in an array.  I would like to  
plot the data using an
external program (psxy in GMT).  The plotting program takes x-y  
couples as standard
input.  How do I get the data into the system call?  I used to do  
things in csh and awk,
i.e., something like

awk '{; print $1, $2}' filename | psxy  >! output.ps

The reason I'm trying to use python is because the manipulations are  
getting too cumbersome
in awk.  Now I have all the manipulations done in python, but I'm  
missing that last step.

I've tried various things with os.system, popen, and subprocess, but  
so far without success.
Does anyone know how to do this?

chris


 
---
Christoph  
Hieronymus 
[EMAIL PROTECTED]
Associate  
Professor
phone: (+46) 18-471 2383
Uppsala  
University   
   fax:   (+46) 18-501   110
Dept. of Earth Sciences (Geophysics)
Villavägen 16
SE-752 36 Uppsala,  Sweden




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


Re: maximum integer length?

2006-06-18 Thread Grant Edwards
On 2006-06-18, Grant Edwards <[EMAIL PROTECTED]> wrote:

>> Que? An integer is just a whole number without fraction. What are you
>> talking about?
>
> He's talking about decimal digits.  Each decimal digit takes up
> 3.322 bits.  A byte can hold about 2.4 digits.  400MB should be
> able to hold an integer with about 1,010,000,000 decimal
> digits.

Oops.  The real answer is 15/16 of that.  I didn't realize that
the integer representation only uses 15 of 16 bits.

-- 
Grant Edwards
[EMAIL PROTECTED]

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


Re: download file from intranet linux server to windows clients

2006-06-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Luis P. Mendes <[EMAIL PROTECTED]> wrote:
.
.
.
>I'm building an intranet web server in Linux for around 40 windows
>clients with Django.
>
>The problem is that I want to build an excel file based on criteria
>entered by the client, that the client must be able do download to his
>personal work space.  I use pyExcelerator to create the Excel files.
>
>How can I do it?  Do I need another excel generator?
>
>Client's information about its working directory should be read, but
>how?  I could only find the way to read the server environment
>variables, where data is processed.
.
.
.
We do a lot of this--dynamic construction on the server-side of
Excel documents, delivered as Web pages.  My impression is that
you're working too hard:  don't bother worrying about where "the
client's workspace" is; just let the browser manage all that.
Browsers are adequate or better at downloading.
-- 
http://mail.python.org/mailman/listinfo/python-list


Chess module blog

2006-06-18 Thread Will McGugan
Hi folks,

I have just blogged about a Python chess module of mine that I wrote a 
while back. I plan on using it for a commerical project, but making the 
module open source. So I would be interested in comments / advice 
reagarding programming style and also optimization.

http://www.willmcgugan.com/2006/06/18/chesspy/

Regards,

Will McGugan

--
work: http://www.kelpiesoft.com
blog: http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extracting values from text file

2006-06-18 Thread Mirco Wahab
Thus spoke Marc 'BlackJack' Rintsch (on 2006-06-18 18:54):

> In <[EMAIL PROTECTED]>, Mirco Wahab wrote:
>> they use the _same_ operator (+) for number _addition_
>> and string _concatenation_, which is, imho, cumbersome.
> 
> And ``+`` means also list/tuple concatenation and really anything for user
> defined types.
> 
>> If you have an operator with meaning "add numbers" (+)
>> and one for "add strings" (.), the language could then
>> do the obvious for you.
> 
> The dot also has already a meaning, it's the attribute lookup operator.

Yes, that may be the real reason?

>> Why would one go from C/C++ to "dynamical typed"
>> things, if he has to be so explicit on easy
>> things?
> 
> Strings that act sometimes as strings and sometimes as numbers when used
> with ``+`` are quite confusing.  

No, thats not what I tried to say, it's rather:

/things/ act _always_ as strings and _always_ as
numbers _when used_ as a 'string' or as a 'number'.

I don't consider that one 'confusing'.

> Two relevant lines from the Zen of Python:
> Explicit is better than implicit.
> In the face of ambiguity, refuse the temptation to guess.

This is, iirc, /exactly/ the reason why in (e.g.) Perl
they put sigils ($%@) in front of the variables. So all
gets explicit - there's no more ambiguity ...

> And don't mix up weakly and dynamically typed.  
> Python is dynamically and strictly typed.

OK, right. I didn't separate 'strict' from
'weak' regarding data types.

I think I got used too much to these
nice 'backhand conversions'. I'm sure
I wouldn't have blinked once if I had
gone directly from C++ (or Java) to Python,
but now I have still the Perl disease in
my bones ;-)

Regards

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


Re: code is data

2006-06-18 Thread Fredrik Lundh
Ravi Teja wrote:

> Web frameworks, which seem to be the rage now in Python community could
> have benefited tremendously from Macro capabilities since they have a
> lot of boiler plate.

they do?  methinks you haven't done much web programming lately...




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


Re: mapping None values to ''

2006-06-18 Thread Jean-Paul Calderone
On Sun, 18 Jun 2006 07:37:00 -0500, Tim Chase <[EMAIL PROTECTED]> wrote:
>> i wish to map None or "None" values to "".
>> eg
>> a = None
>> b = None
>> c = "None"
>>
>> map(   ,  [i for i in [a,b,c] if i in ("None",None) ])
>>
>> I can't seem to find a way to put all values to "". Can anyone help?
>> thanks
>
>I'd consider this a VeryBadIdea(tm).  However, given Python's
>introspective superpowers, it *can* be done (even if it most
>likely *shouldn't* be done).  That caveat out of the way, here goes:
>
> >>> for scope in [locals, globals]:
>... s = scope()
>... for vbl, value in s.items():
>... if value == None or (type(value) == type("") and
>value == 'None'):
>... s[vbl] = ''
>

Hey Tim,

Actually this doesn't work for locals at all:


  >>> def f():
  ... x = 'x'
  ... locals()['x'] = 'y'
  ... print x
  ... 
  >>> f()
  x
  >>> 

Locals cannot be modified through the dict returned by locals().

>
>There may be some better way to determing whether an item is a
>string than my off-the-cufff
>
>   type(value) == type("")
>

Yes.  isinstance(value, str) is the best way to do this.

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


Re: code is data

2006-06-18 Thread Ravi Teja
Paddy wrote:
> Ravi Teja wrote:
> > BJörn Lindqvist wrote:
> > > > Personally, I would like to see macros in Python (actually Logix
> > > > succeeding is good enough). But I am no language designer and the
> > > > community has no interest in it. When I absolutely need macros, I will
> > > > go elsewhere.
> > >
> > > One must wonder, when is that? When do you absolutely need macros?
> >
> > Whenever there is significant boiler plate code that functions and
> > classes cannot eliminate alone.
> > Whenever there is a more elegant way to express your code.
> >
>
> Me, I am torn. I should now better. I have listened to the arguments
> against Macros in Python and the ones that struck home were the
> argument for maintainability:
>  Without macros, Python is Python. Statements do what you expect.

Yes! I heard those arguments too. And I am not convinced.

Static language programmer: Lack of static typing removes the necessary
safeguards. The code is more error prone. Objects have behavior that is
not obvious.
Dynamic language programmer: Really? I don't seem to have any more bugs
than in my statically typed code. And my code is compact and reads
better. I don't want to go back.

No to macros proponent: Macros introduce a lot of potential for abuse.
Code will be worse to read than Perl.
Macros proponent: Really? We have been doing macros for decades. We all
think our code is better for macros, not worse. We are not going back.

I just don't get it. Don't we often invoke the "We are all adults here"
argument.

Writing a macro is not as simple as writing a function. Sort of like
metaclasses. Many will stay off them. Those that really need them will
walk that extra mile. Don't we all believe that "Simple should be
possible. Complex should be doable"

> And the argument against DSLs altogether:
>  Make Python your DSL! If you design your own DSL before long you start
> to embellish it with more statements or data types and before long it
> becomes complex. If you used Python from the beginning then you would
> have a community for support.

Python has a low cognitive overhead. But it not a DSL by definition. No
language can be. The idea is that when the domain changes, a DSL should
be driven by the new domain as warranted. In other words, driven "by
the problem, not the tool".

  I don't want "a DSL". I want a language that allows me to make "my
DSL" based on it. That means I don't loose the community connection. I
can still use all the rich libraries in my DSL.

I like Python for its indentation syntax, sensible semantics and
readability. I invested a lot of time in Python. After much language
hopping, I settled with Python. I like the community and the code base
available for it. The libraries just seem to be designed at the right
level of abstraction for me (as opposed to say, Java). When I need to
do something, I know where to go. But all this ties me to the language
tightly that I cannot change.

> I know the arguments, but every once in a while I think if only I could
> craft my own ??? statement or 

My thoughts exactly.

Web frameworks, which seem to be the rage now in Python community could
have benefited tremendously from Macro capabilities since they have a
lot of boiler plate.

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


Seeking regex optimizer

2006-06-18 Thread Kay Schluehr
I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a
regular expression sx from it, such that sx.match(s) yields a SRE_Match
object when s starts with an s_i for one i in [0,...,n].  There might
be relations between those strings: s_k.startswith(s_1) -> True or
s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa',
...,'...ab']. For this reason SRE_Match should provide the longest
possible match.

Is there a Python module able to create an optimized regex rx from ls
for the given constraints?

Regards,
Kay

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


Re: Extracting values from text file

2006-06-18 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Mirco Wahab wrote:

> You see the picture? Pythons designer made the
> same mistake as the Java/Javascript designer -
> they use the _same_ operator (+) for number _addition_
> and string _concatenation_, which is, imho, cumbersome.

And ``+`` means also list/tuple concatenation and really anything for user
defined types.

> If you have an operator with meaning "add numbers" (+)
> and one for "add strings" (.), the language could then
> do the obvious for you.

The dot also has already a meaning, it's the attribute lookup operator.

> Why would one go from C/C++ to "dynamical typed"
> things, if he has to be so explicit on easy
> things?

Strings that act sometimes as strings and sometimes as numbers when used
with ``+`` are quite confusing.  Two relevant lines from the Zen of Python:

Explicit is better than implicit.
In the face of ambiguity, refuse the temptation to guess.

And don't mix up weakly and dynamically typed.  Python is dynamically and
strictly typed.

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


Re: Tetris

2006-06-18 Thread Rune Strand

Devon G. Parks wrote:
> I've been searching google and this group for a while now for a good
> tutorial on making a Tetris-style game in Python. I hear Tetris is a
> good starting point, and although I am fairly new to programming I
> think I would learn best if I had some code to experiment with because
> without a tutorial I have no idea where to start. If you know of a
> tutorial that is specific to this game please let me know where to find
> it.

There's a 600-liners here: http://www.pygame.org/projects/21/133/

Not a tutorial, but maybe just as good?

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


Re: Date Subtraction

2006-06-18 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Cameron Laird wrote:

> In article <[EMAIL PROTECTED]>,
> Marc 'BlackJack' Rintsch  <[EMAIL PROTECTED]> wrote:
>>In <[EMAIL PROTECTED]>,
>>rsutradhar_python wrote:
>>> date1="2006-01-10"
>>> date2="2005-12-15"
>>> date = date1 - date2
>>> should give me 25 but problem is that date1 and date2 datatype is 
>>> string which need to be conerted into date fromat which i am not able 
>>> to do so please help me.
>>
>>from datetime import date
>>
>>date_str_1 = '2006-01-10'
>>date_str_2 = '2005-12-15'
>>date_1 = date(*map(int, date_str_1.split('-')))
>>date_2 = date(*map(int, date_str_2.split('-')))
>>print (date_1 - date_2).days - 1
>   .
>   .
>   .
> Apparently you understand the original poster better than I.
> What's with the "- 1"?  If I read you correctly, you'd calculate
> that there are zero days between, for example,
>   2006-01-13
> and
>   2006-01-12
> Do I have that right?

No that's not what I would calculate.  I would do without the ``- 1`` but
the OP wanted 25 as result.  Without the substraction it's 26.  ;-)

Ciao,
Marc 'BlackJack' Rintsch

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


Tetris

2006-06-18 Thread Devon G. Parks
I've been searching google and this group for a while now for a good
tutorial on making a Tetris-style game in Python. I hear Tetris is a
good starting point, and although I am fairly new to programming I
think I would learn best if I had some code to experiment with because
without a tutorial I have no idea where to start. If you know of a
tutorial that is specific to this game please let me know where to find
it.

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


Re: maximum integer length?

2006-06-18 Thread [EMAIL PROTECTED]
nate wrote:
> Hey everyone,
>
> I am trying to figure out what is the largest integer I can. Lets say
> for 400 megabytes of memory at my disposal.
>
> I have tried a few things
> c = 2**100
> d = 2**200
> print c**d
>
> Obviously I didn't have enough memory for that, but I was able to c**3.
> (I think anyways, it is still trying to display the result)

Don't print, takes too long. Do e=c**3.

>
> So I am just wondering how long an integer can be with 400 megabytes of
> memory.
>
> I guess this is a question of logic?
> each integer takes up a byte right? If I have 400 megabytes that would
> mean I could have a long integer with up to 419,430,400,000 integers?
>
> Really I am not sure on this one and that is why I am asking. Because it
> is just bugging me I am not sure how it works...
>
> I know this probably seems trivial and just a stupid question, but I
> find this type of stuff interesting...

Using gmpy (and I don't know if it stores large ints different
from Python ints) and only 192M on my laptop, I can get
to billion bit numbers, but not much larger. Switching to
Python ints ran out of memory trying gen 11. It also ran out
of memory trying to calculate gen 10, which gmpy was able
to do successfully, so maybe gmpy is better for such things:

Closed form: Type12MH(k,i)
Find ith, kth Generation Type [1,2] Mersenne Hailstone
using the closed form equation

2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1

2**5-1  generation: 1
   2**29-1  generation: 2
  2**245-1  generation: 3
 2**2189-1  generation: 4
2**19685-1  generation: 5
   2**177149-1  generation: 6
  2**1594325-1  generation: 7
 2**14348909-1  generation: 8
2**129140165-1  generation: 9
   2**1162261469-1  generation:10

Traceback (most recent call last):
  File "C:\python24\user\user_home\gmpy ver 1.01\MHtest.py", line 41,
in -toplevel-
a = Type12MH(k,1)
  File "C:\python24\lib\collatz_functions.py", line 595, in Type12MH
return TWO**(SIX*a - ONE) - ONE
ValueError: mpz.pow outrageous exponent


>>>
>>> i=1
>>> k=11
>>> a = 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1

Traceback (most recent call last):
  File "", line 1, in -toplevel-
a = 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1
MemoryError

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


Re: Date Subtraction

2006-06-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Marc 'BlackJack' Rintsch  <[EMAIL PROTECTED]> wrote:
>In <[EMAIL PROTECTED]>,
>rsutradhar_python wrote:
>
>> How to subtract date which is stored in string variable?
>> 
>> Example:
>> 
>> date1="2006-01-10"
>> date2="2005-12-15"
>> date = date1 - date2
>> should give me 25 but problem is that date1 and date2 datatype is 
>> string which need to be conerted into date fromat which i am not able 
>> to do so please help me.
>
>from datetime import date
>
>date_str_1 = '2006-01-10'
>date_str_2 = '2005-12-15'
>date_1 = date(*map(int, date_str_1.split('-')))
>date_2 = date(*map(int, date_str_2.split('-')))
>print (date_1 - date_2).days - 1
.
.
.
Apparently you understand the original poster better than I.
What's with the "- 1"?  If I read you correctly, you'd calculate
that there are zero days between, for example,
  2006-01-13
and
  2006-01-12
Do I have that right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extracting values from text file

2006-06-18 Thread Mirco Wahab
Thus spoke Preben Randhol (on 2006-06-18 13:34):
> On Sun, 18 Jun 2006 10:54:01 +0200
> Mirco Wahab <[EMAIL PROTECTED]> wrote:
>> - no DWIM-ism (do what I mean) on 'value' addition
> 
> But you don't add two values. you add two strings. If you 
> want numbers you must convert the strings. 

Why? At least - if its obvious, what I want.

> Yes, but how can Python know that you want to add to 
> numbers and not concate two strings? 

The programming language should make some
rules regarding its operators and their
meaning.

Compare:

#  want to add NUMBERS ('1' + '1.'/1. = 2.)
#
#  in python in perl
#
a1  = int( '1' )   $a1  = '1';
a1 += float( '1.' )$a1 += '1.';
print a1   print $a1;

a2  = int( '1' )   $a2  = '1';
a2 += 1.   $a2 += 1.;
print a2   print $a2;

#  want to add strings ('1' . '1.'/1. = 11.)
#
b1  = '1'  $b1  = '1';
b1 += '1.';$b1 .= '1.';
print b1   print $b1;

b2  = '1'  $b2  = '1';
b2 += str( 1. )$b2 .= 1.;
print b2   print $b2;


You see the picture? Pythons designer made the
same mistake as the Java/Javascript designer -
they use the _same_ operator (+) for number _addition_
and string _concatenation_, which is, imho, cumbersome.

If you have an operator with meaning "add numbers" (+)
and one for "add strings" (.), the language could then
do the obvious for you.

Why would one go from C/C++ to "dynamical typed"
things, if he has to be so explicit on easy
things?

Of course, you will get along with it, you
'learn' the corresponding 'python-phrases'
that do specific things, you get used to it.
But if you come, like me, from elsewhere,
there is sometimes something to rant on ;-)

I really try to get into it (Python), but
I'm, in such cases, more or less shocked -
and try express that , but I'm not interested
in 'language supremacy' discussions and the like.

BTW.: what exactly did you try to solve?
What would be a 'complete example' where
the parser has to chew on?

Regards

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


Re: maximum integer length?

2006-06-18 Thread Grant Edwards
On 2006-06-18, Sybren Stuvel <[EMAIL PROTECTED]> wrote:
> nate enlightened us with:
>> Obviously I didn't have enough memory for that, but I was able to c**3. 
>> (I think anyways, it is still trying to display the result)
>>
>> So I am just wondering how long an integer can be with 400 megabytes of 
>> memory.
>
> I guess the best way would be a binary search for the proper value of
> the integer. You already have an upper (c**d) and a lower (c**3) bound
> for your search.
>
>> each integer takes up a byte right?
>
> That depends on the size of the integer, doesn't it?
>
>> If I have 400 megabytes that would mean I could have a long integer
>> with up to 419,430,400,000 integers?
>
> Que? An integer is just a whole number without fraction. What are you
> talking about?

He's talking about decimal digits.  Each decimal digit takes up
3.322 bits.  A byte can hold about 2.4 digits.  400MB should be
able to hold an integer with about 1,010,000,000 decimal
digits.

-- 
Grant Edwards
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


debugging in eclipse+pydev

2006-06-18 Thread yaru22
Hi.

I'd like to know how to debug in eclipse+pydev.

In the menu, "Pydev Debug", there's Start Debug Server option, but I
don't know how to use it.

Few questions I have about debugging are:

1) how do i set a breakpoints in pydev?
2) how do i execute the code line by line? I mean... step into, step
over, and so on...

When I searched on http://www.fabioz.com/pydev/,

I found that

Run/Debug   Step Into   F5  Debugging
Run/Debug   Step Over   F6  Debugging
Run/Debug   Step Return F7  Debugging
Run/Debug   Resume  F8  Debugging

However, Starting Debug Server and pressing F5, F6, F7 didn't do those
functions.

Can anyone give me a small tutorial as to how to debug in Eclipse +
Pydev please?

Thanks in advance.

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


Re: Detecting key presses

2006-06-18 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Ok, I'm pretty new to python, so this might be a stupid question. I'm
> trying to write a simple text-based pong clone, and I can't figure out
> how to read key presses to move the paddles. I just need something that
> does the same thing as getch() and kbhit(). I can't use those because
> their windows only, and I'm running Linux.
> 
> Someone suggested using curses, but that does crazy things with my
> output, and leaves the terminal unusable after the program closes.

Maybe using pygame for a graphical version is appealing to you - 
additionally, the event-sytem of it will do what you ask for.

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


Re: mapping None values to ''

2006-06-18 Thread Gerard Flanagan

[EMAIL PROTECTED] wrote:
> hi
> i wish to map None or "None" values to "".
> eg
> a = None
> b = None
> c = "None"
>
> map(   ,  [i for i in [a,b,c] if i in ("None",None) ])
>
> I can't seem to find a way to put all values to "". Can anyone help?
> thanks

a = [None, 'None', None]

def filtre(x):
if x is None or x == 'None':
return ''
else:
return x

assert map(filtre, a) == ['', '', '']

a = [1, 2, None, 'None', 3, 4]

assert map(filtre, a) == [1, 2, '', '', 3, 4]

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


Re: maximum integer length?

2006-06-18 Thread casevh

nate wrote:
> So I am just wondering how long an integer can be with 400 megabytes of
> memory.
>
> I guess this is a question of logic?
> each integer takes up a byte right? If I have 400 megabytes that would
> mean I could have a long integer with up to 419,430,400,000 integers?
>
Python longs are stored using 15 bits out of every 16 bits (2 bytes).
So every 2 bytes will contain approximately 4.5154 decimal digits.
Ignoring memory usage and overhead, the number of digits in the largest
possible long integer that can fit in 400 megabytes is

>>> import math
>>> 200 * 1024 * 1024 * 15 * math.log10(2)
946958486.2000643

Since memory space is required for temporary storage of intermediate
results, you won't actually be able to create a number that large if
you only have 400 megabytes.

casevh

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


Re: mapping None values to ''

2006-06-18 Thread imho
[EMAIL PROTECTED] ha scritto:
> hi
> i wish to map None or "None" values to "".
> eg
> a = None
> b = None
> c = "None"
> 
> map(   ,  [i for i in [a,b,c] if i in ("None",None) ])
> 
> I can't seem to find a way to put all values to "". Can anyone help?
> thanks
> 

You already filtered [a,b,c] in the comprehension list, so you just have 
to map all its values to "":

map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mapping None values to ''

2006-06-18 Thread Tim Chase
> i wish to map None or "None" values to "".
> eg
> a = None
> b = None
> c = "None"
> 
> map(   ,  [i for i in [a,b,c] if i in ("None",None) ])
> 
> I can't seem to find a way to put all values to "". Can anyone help?
> thanks

I'd consider this a VeryBadIdea(tm).  However, given Python's 
introspective superpowers, it *can* be done (even if it most 
likely *shouldn't* be done).  That caveat out of the way, here goes:

 >>> for scope in [locals, globals]:
... s = scope()
... for vbl, value in s.items():
... if value == None or (type(value) == type("") and 
value == 'None'):
... s[vbl] = ''


seems to do the trick.  You may, likely, just want to operate on 
locals, not every last global variable in your project, in which 
case you can just use

s = locals()
for vbl, value in s.items():
...

There may be some better way to determing whether an item is a 
string than my off-the-cufff

type(value) == type("")

but it worked to prevent trying to compare non-strings to the 
string 'None' later in the sub-clause of the if statement.

Note that if you wrap this in a function, you'll may have to pass 
in locals() as a parameter because otherwise, inside your 
function, you'll have a different set of available locals that 
you did when you called the function. :)

Beware your foot when shooting this gun...it likes to aim at feet.

-tkc




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


Re: Cycles between package imports

2006-06-18 Thread John Roth
Martin Blais wrote:
> Hi
>
> I'm a tad confused over a problem involving cycles between
> packages.

[lengthy  example snipped]

>
>
> I don't see why the reference to module a.alice could not be
> available via the "from" syntax, even if it is still incompletely
> initialized at the time of import.
>
> Can anyone shed some light onto this?  Is there a rule for
> determining when a module becomes available to import from a
> package using the "from" syntax?

It's really easy to see if you trace out, in detail, the exact
order in which things happen and when each object is initialized and
shows up in the respective module's  namespace.

The general rule is: don't do that. It doesn't work, and the
hoops you have to go through to force it to work are so
complex and bizzare that they're not worth it.  Redesign
the modules so you don't have cyclic dependencies.

John Roth

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


Re: Which compiler will Python 2.5 / Windows (Intel) be built with?

2006-06-18 Thread Roel Schroeven
Scott David Daniels schreef:
> I musunderstood you.  I thought you were advocating that Python itself
> be built on gcc, obviating many compiler access issues.  That wouldn't
> work because gcc cannot, by itself (as I understand it) get to all the
> nooks and crannies a windows developer may need to traverse.  I know I
> just repeated my argument here against a strawman, but that was really
> for other readers, not for you.

I'm not actively advocating it since I realize I don't know enough about 
all the pros and cons, but yes, I would like for Python and other open 
source projects to use gcc even on Windows.

It gives me an uneasy feeling when you can't use the source (apart from 
just reading it) of open source projects without depending on the whims 
of a third party. As an example, look what happened to the Linux kernel 
and Bitkeeper. One might argue that Microsoft is not really a third 
party since the whole Windows platform is made by them, but the problems 
are the same: as far as I understand, Visual Studio Express 2003 is no 
longer available, and the 2005 version is not binary compatible.

In my case, I'm even unable to uninstall any modern Microsoft compiler 
since AFAICT they all require XP SP2 and I'm stuck with SP1 on my laptop 
since SP2 conflicts with the touchpad driver resulting in Windows 
blocking on booting, but that only effects me (I hope) and is something 
for a whole other rant.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


mapping None values to ''

2006-06-18 Thread micklee74
hi
i wish to map None or "None" values to "".
eg
a = None
b = None
c = "None"

map(   ,  [i for i in [a,b,c] if i in ("None",None) ])

I can't seem to find a way to put all values to "". Can anyone help?
thanks

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


Re: Extracting values from text file

2006-06-18 Thread Preben Randhol
On Sun, 18 Jun 2006 10:54:01 +0200
Mirco Wahab <[EMAIL PROTECTED]> wrote:


> 
> For the other issue I stumbled upon:
> 
> - no DWIM-ism (do what I mean) on 'value' addition
> 
> a  = '1'
> a += '1.'
> print a
> 
>  will print
> 11.
> 
> and not 2., as in 'dynamically typed', 'operator based' languages.
> (maybe the lack of a simple string-concatenation operator is the
> reason?)

But you don't add two values. you add two strings. If you want numbers
you must convert the strings. 

> How could one approach these things without needing to
> get too explicitly about 'type conversions'
> (Python is supposed to be 'dynamically typed'?).

Yes, but how can Python know that you want to add to numbers and not
concate two strings? 
-- 
http://mail.python.org/mailman/listinfo/python-list


maximum integer length?

2006-06-18 Thread nate
Hey everyone,

I am trying to figure out what is the largest integer I can. Lets say 
for 400 megabytes of memory at my disposal.

I have tried a few things
c = 2**100
d = 2**200
print c**d

Obviously I didn't have enough memory for that, but I was able to c**3. 
(I think anyways, it is still trying to display the result)

So I am just wondering how long an integer can be with 400 megabytes of 
memory.

I guess this is a question of logic?
each integer takes up a byte right? If I have 400 megabytes that would 
mean I could have a long integer with up to 419,430,400,000 integers?

Really I am not sure on this one and that is why I am asking. Because it 
is just bugging me I am not sure how it works...

I know this probably seems trivial and just a stupid question, but I 
find this type of stuff interesting...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code is data

2006-06-18 Thread Paddy

Ravi Teja wrote:
> BJörn Lindqvist wrote:
> > > Personally, I would like to see macros in Python (actually Logix
> > > succeeding is good enough). But I am no language designer and the
> > > community has no interest in it. When I absolutely need macros, I will
> > > go elsewhere.
> >
> > One must wonder, when is that? When do you absolutely need macros?
>
> Whenever there is significant boiler plate code that functions and
> classes cannot eliminate alone.
> Whenever there is a more elegant way to express your code.
>

Me, I am torn. I should now better. I have listened to the arguments
against Macros in Python and the ones that struck home were the
argument for maintainability:
 Without macros, Python is Python. Statements do what you expect.

And the argument against DSLs altogether:
 Make Python your DSL! If you design your own DSL before long you start
to embellish it with more statements or datatypes and before long it
becomes complex. If you used Python from the beginning then you would
have a community for support.

I know the arguments, but every once in a while I think if only I could
craft my own ??? statement or 

Don't go their Paddy.

;-)

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


python texts?

2006-06-18 Thread nate
Everyone that took their time to reply, thank you. I have a better idea 
of where to go after Learning Python. I still do not have a good idea of 
where this book will put me in the grand scheme of things, but oh well. 
I suppose that is something I will find out soon enough.
Once again, thank you for your responses
--Nate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Standard Yes / No Windows Dialog box creation

2006-06-18 Thread flaus . a
Ravi Teja a écrit :

>
> Assuming you are on MS Windows.
> import win32api, win32con
> win32api.MessageBox(0, "Question", "Title", win32con.MB_YESNO)

Yes, that's exactly what I was looking for! Thanks!!

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


Re: Standard Yes / No Windows Dialog box creation

2006-06-18 Thread flaus . a

SuperHik a écrit :

> I've never seen "easier" way to do it, but my solution for you if you
> want to create a GUI application without learning any GUI programming
> would be to consider Glade, wxGlade and such...

Yes I wanted something easy because it's the first time that I use a
Gui into Python and I don't wanted to learn the complete Windows GUI
programming just to display a Yes / No dialog box...

> >>
> > Do it just the same way as you did it with the "Open File" or "Open
> > Folder" windows dialog. What is your problem with it?
> >
> I think what he means by "create" is somethink like
> win32ui.CreateFileDialog() because of the "easier" part.

Yes I wanted something like win32ui.CreateFileDialog() to create my
dialog box. Unfortunately, win32ui.CreateDialog() is not so easy...

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


Re: Extracting values from text file

2006-06-18 Thread Mirco Wahab
Thus spoke Dennis Lee Bieber (on 2006-06-18 06:29):

> On Sun, 18 Jun 2006 03:12:23 +0200, Mirco Wahab
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>> - you have to explicitly instantiate a dictionary value
>>   (with 0) if/before you want in-place add to it (why is that?)
> Uhm... Not quite...
> ...
> dict.get(key, default)
>
> returns the value associated by key, IFF key exists in the
> dictionary, otherwise it returns the value defined for default.

Thanks, Dennis, for your help on this part I bragged about.

Now the extractor loop, according to your suggestion, can
be written shorter:

for rule in filter:
k = re.search(r'\((.+)\)', rule) # pull out variable names ->k
if k.group(1):   # pull their values from text
varname[k.group(1)] = varname.get(k.group(1), 0) + float( \
re.search( re.sub(r'\((.+)\)', varscanner, rule), \
   example ).group(1)  ) # use regex in modified 'rule'

For the other issue I stumbled upon:

- no DWIM-ism (do what I mean) on 'value' addition

a  = '1'
a += '1.'
print a

 will print
11.

and not 2., as in 'dynamically typed', 'operator based' languages.
(maybe the lack of a simple string-concatenation operator is the reason?)

  whereas:

a  = '1'
a += 1.
print a

will fail magnificently. These thing would come handy
when working with text/table driven computations (as above)

How could one approach these things without needing to
get too explicitly about 'type conversions'
(Python is supposed to be 'dynamically typed'?).


Regards & thanks

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


Active Python versions

2006-06-18 Thread Tom Del Rosso
Why is the Windows msi install file for ActivePython-2.4.3.12 only 15MB
whereas the older msi file for ActivePython-2.4.2.10 was 19MB?

BTW, is that the prefered Python environment?


-- 

Reply in group, but if emailing add another
zero, and remove the last word.


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


Re: Which compiler will Python 2.5 / Windows (Intel) be built with?

2006-06-18 Thread Martin v. Löwis
Scott David Daniels wrote:
> I musunderstood you.  I thought you were advocating that Python itself
> be built on gcc, obviating many compiler access issues.  That wouldn't
> work because gcc cannot, by itself (as I understand it) get to all the
> nooks and crannies a windows developer may need to traverse.  I know I
> just repeated my argument here against a strawman, but that was really
> for other readers, not for you.

Even that is incorrect. Python 2.x can be built fully with gcc. It's
PythonWin that includes a lot of C++ and MFC code that won't compile
with gcc. That doesn't preclude to use gcc for Python 2.x compilation,
as long as a msvcrt is selected that can work together with some
version of MFC and the MS C++ RTL.

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