Re: Sorting by item_in_another_list

2006-10-25 Thread Paul Rubin
ZeD <[EMAIL PROTECTED]> writes:
> >   desired_result = B + sorted(x for x in A if x not in B)
> this. is. cool.

Actually it's better to use a set if B is large:

  B2 = set(B)
  desired_result = B + sorted(x for x in A if x not in B2)

That avoids a linear search through B for each element of A.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ZODB for inverted index?

2006-10-25 Thread Gabriel Genellina

At Wednesday 25/10/2006 03:54, [EMAIL PROTECTED] wrote:


anyway can someone help me on how to "rewrite" and "reload" a class
instance when using ZODB ?


What do you mean?


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Sorting by item_in_another_list

2006-10-25 Thread Fredrik Lundh
Paul Rubin wrote:

>> for example:
>>
>> A = [0,1,2,3,4,5,6,7,8,9,10]
>> B = [2,3,7,8]
>>
>> desired_result = [2,3,7,8,0,1,4,5,6,9,10]
> 
> How about:
> 
>   desired_result = B + sorted(x for x in A if x not in B)

assuming that "keep the existing order" means what it says, you might as 
well replace "sorted" with a list comprehension.



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


Re: Sorting by item_in_another_list

2006-10-25 Thread Paul Rubin
Fredrik Lundh <[EMAIL PROTECTED]> writes:
> >   desired_result = B + sorted(x for x in A if x not in B)
> assuming that "keep the existing order" means what it says, you might
> as well replace "sorted" with a list comprehension.

Hmm.  I didn't read it that way, but yeah, if that's what the OP meant
then the sort could be skipped.  I thought he just wanted a stable
sort, which the sorting primitives now promise.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com problem

2006-10-25 Thread cfriedalek

Gabriel Genellina wrote:
> Run it on the debugger step by step, and inspect all the intermediate objects.
> Synergy.StudyDoc might be a function, by example, so you should add
> another pair of ().
> This is not obvious looking at the VB code.

(Sorry, tied up this arvo so I could respond to your suggestion
earlier.)

Here's part of a debug session.

(Pdb) type(Synergy.StudyDoc)


(Pdb) type(Synergy.StudyDoc.GetFirstTet)


(Pdb) Synergy.StudyDoc.GetFirstTet
>

(Pdb) dir (Synergy.StudyDoc)
['_ApplyTypes_', '_FlagAsMethod', '_LazyAddAttr_', '_NewEnum',
'_Release_', '__A
ttrToID__', '__LazyMap__', '__call__', '__cmp__', '__doc__',
'__getattr__', '__g
etitem__', '__init__', '__int__', '__len__', '__module__',
'__nonzero__', '__rep
r__', '__setattr__', '__setitem__', '__str__', '_builtMethods_',
'_enum_', '_fin
d_dispatch_type_', '_get_good_object_', '_get_good_single_object_',
'_lazydata_'
, '_make_method_', '_mapCachedItems_', '_oleobj_', '_olerepr_',
'_print_details_
', '_proc_', '_unicode_to_string_', '_username_', '_wrap_dispatch_']

(Pdb) dir (Synergy.StudyDoc.GetFirstTet)
['_ApplyTypes_', '_FlagAsMethod', '_LazyAddAttr_', '_NewEnum',
'_Release_', '__A
ttrToID__', '__LazyMap__', '__call__', '__cmp__', '__doc__',
'__getattr__', '__g
etitem__', '__init__', '__int__', '__len__', '__module__',
'__nonzero__', '__rep
r__', '__setattr__', '__setitem__', '__str__', '_builtMethods_',
'_enum_', '_fin
d_dispatch_type_', '_get_good_object_', '_get_good_single_object_',
'_lazydata_'
, '_make_method_', '_mapCachedItems_', '_oleobj_', '_olerepr_',
'_print_details_
', '_proc_', '_unicode_to_string_', '_username_', '_wrap_dispatch_']

I'm pretty green with this kind of introspection (but willing to dig in
and learn). With the VBS code seems like GetFirstTet is a method of
StudyDoc that returns a variable which converted to string yields "TE1"
 etc. But that doesn't seem to be true for python.

Is there any other way I can find out what attributes etc are available
to the GetFirstTet instance?

The type library is not supplied with the app. so if my basic
understanding is correct, I can't early bind.

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


Re: Tkinter question

2006-10-25 Thread Hendrik van Rooyen
 "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:


> Eric Brunel wrote:
>
> > But Hendrik's solution is better, since it avoids the use of lambda, which
> > is often difficult to understand.
>
> storing the button reference in a variable doesn't help if you want to use the
> same callback for multiple buttons, though...
>
> 

I can't see how to use it for that - on the other hand, it enables you to use
the same button for different things at different times by re configuring the
command binding...

This can be used as a sort of "state machine" to keep track of what the user is
doing - changing button text, colour and command binding from "On", "green" and
onOn to "Off", "red" and onOff...

In my current project this style has developed to a point where onOn would
change the colour,etc, as well as setting up a deferred callback to onOnTimeout,
and firing off a message to the hardware in the field. A response from the
successful completion is then used to call onOnEnd, which cancels the timed
callback.
onOnTimeout does emergency stuff because something did not work, as onOnEnd was
not called...

It is a bit more complex than the above - as there are intermediate "grey out"
states - but the above illustrates the principle simply.

It seems to work quite robustly, and I am also developing a Simple Distributed
Control Language - SDCL (tm) , to do the work on the small micros in the field,
tying everything together. - It was fun and almost indecently easy to write a
one pass "compiler" resolving forward references on the fly in Python - more of
an assembler, really -   and no trace of lexx or yacc or bison - just a few
lines of Python code - but I digress...

And yes I know what SDLC is... *WEG*

- Hendrik


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


Re: question: script to input data into a webpage and then retrievethe result?

2006-10-25 Thread mxywp
Thank you, Christoph! I used twill to get my data. And Titus is really 
helpful in helping me learn how to use it.

Thank Paul, Haiyun and Dennis for your comments! Actually it turned out that 
the authentication code on that web page is kind of a joke. I finally found 
out that you could still submit a successful query and get desired result by 
ignoring the code. In rare cases the code is required. For most of the time 
it's useless. Isn't it funny?

Best,
mxywp
- Original Message - 
From: "Christoph Haas" <[EMAIL PROTECTED]>
To: 
Sent: Sunday, October 22, 2006 12:35 AM
Subject: Re: question: script to input data into a webpage and then 
retrievethe result?


> On Sunday 22 October 2006 08:06, mxywp wrote:
>> Could someone help me with this or share an example script with me?
>>
>> Here is what I want to accomplish:
>> (1) input 3 values into 3 boxes on a web page
>> (2) there is an authentication code each time you access this page and I
>> have to write this code into the fourth box on the same page (3) click
>> "submit" button
>> (4) this web page will turn into a page with a table having a value
>> calculated from my inputs (5) extract this value into a local file
>> (6) repeat the above for 12000 times.
>>
>> I would really appreciate it if someone can tell me how to do it using
>> python script. I am new to python web programming.
>
> Dark side way:
> http://www.idyll.org/~t/www-tools/twill.html
>
> Christoph
>
> P.S.: One posting is usually sufficient to get a reply.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


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


Re: python GUIs comparison (want)

2006-10-25 Thread Christophe
Fredrik Lundh a écrit :
> David Boddie wrote:
> 
>>> commercial deployment is expensive; free deployment must be GPL;
>>
>> Opinions differ on the first one of these.
> 
> even if you define "expensive" as "costs more money than the others" ?
Even if you consider that the huge time saving you get out of using Qt 
is worth more than what you pay to acquire a licence?

That's the idea anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python GUIs comparison (want)

2006-10-25 Thread Christophe
Fredrik Lundh a écrit :
> Christophe wrote:
> 
>> Also, the Tkinter API is far less elegant than the others.
> 
> huh?  create object, display object, create object, display object. sure 
> looks like plain old Python to me...

Let's see :

.pack(side = "left")

fred = Button(self, fg = "red", bg = "blue")
fred["fg"] = "red"

fred.bind("", turnRed)

Yep, unelegant API I mantain it.

And no modern layout manager available. Only those old school 
left/right/up/down pack and anchors are available.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python GUIs comparison (want)

2006-10-25 Thread Fredrik Lundh
Christophe wrote:

 commercial deployment is expensive; free deployment must be GPL;
 >>>
>>> Opinions differ on the first one of these.
>> even if you define "expensive" as "costs more money than the others" ?
 >
> Even if you consider that the huge time saving you get out of using Qt 
> is worth more than what you pay to acquire a licence?

then it sounds like a combination between "it's a silver bullet!" and 
"commercial software is better than free software!".

no matter how good Qt is, the reality is that if you spend that much 
time on the UI implementation parts of your project, you're probably 
developing at the wrong abstraction level -- no matter what toolkit 
you're using.  and if you're doing UI development the wrong way, chances 
are that you're doing other things the wrong way too.



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


python html 2 image (png)

2006-10-25 Thread baur79
hi everyone

how can i render html page to png image
ex:

http://www.website.com/index.html -> index.png

thanks a lot

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


Re: python GUIs comparison (want)

2006-10-25 Thread Fredrik Lundh
Christophe wrote:

>>> Also, the Tkinter API is far less elegant than the others.
>> huh?  create object, display object, create object, display object. sure 
>> looks like plain old Python to me...
> 
> Let's see :
> 
> .pack(side = "left")
> 
> fred = Button(self, fg = "red", bg = "blue")
> fred["fg"] = "red"
> 
> fred.bind("", turnRed)
> 
> Yep, unelegant API I mantain 

yuck.  if that's the kind of UI programs you're writing, we sure have 
different design ideals.

and arguing that Tkinter is unelegant when you're doing silly things in 
a silly way is a bit like arguing that Python is unelegant because your 
first attempt to write a "hello world" program resulted in:

  import sys
  # .stdout.write("Hello World") # gives unusable error message
  from sys import stdout as glah
  glah.writelines(iter(" ".join(["h3110", "W0rlD"])))

> And no modern layout manager available. Only those old school 
> left/right/up/down pack and anchors are available.

huh?  when did you last look at Tk?  1994?



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


Re: python html 2 image (png)

2006-10-25 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> how can i render html page to png image
> ex:
> 
> http://www.website.com/index.html -> index.png

what tools are you using to do that today?



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


Re: Ctypes Error: Why can't it find the DLL.

2006-10-25 Thread Jon Clements

Mudcat wrote:


> So then I use the find_library function, and it finds it:
>
> >>> find_library('arapi51.dll')
> 'C:\\WINNT\\system32\\arapi51.dll'
>

Notice it's escaped the '\' character.

> At that point I try to use the LoadLibrary function, but it still can't
> find it:
>
> >>> windll.LoadLibrary('C:\WINNT\system32\arapi51.dll')
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 395, in
> LoadLibrary
> return self._dlltype(name)
>   File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 312, in
> __init__
> self._handle = _dlopen(self._name, mode)
> WindowsError: [Errno 126] The specified module could not be found
>
> What am I doing wrong? [snip]

You need to use either
windll.LoadLibrary(r'c:\winnt\system32\arapi51.dll') or escape the \'s
as the find_library function did. You're getting caught out by \a which
is the alert/bell character. \w and \s aren't valid escape sequences so
you get away with them. I'm guessing it's worked before because you've
been lucky.

Works fine!:
>>> 'C:\winnt\system32\smtpctrs.dll'
'C:\\winnt\\system32\\smtpctrs.dll'

Uh oh, escaped:
>>> 'C:\winnt\system32\arapi51.dll'
'C:\\winnt\\system32\x07rapi51.dll'

Jon.

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


dict problem

2006-10-25 Thread Alistair King
Hi,

ive been trying to update a dictionary containing a molecular formula, but seem 
to be getting this error:


Traceback (most recent call last):
  File "DS1excessH2O.py", line 242, in ?
updateDS1v(FCas, C, XDS)
NameError: name 'C' is not defined

dictionary is: 

DS1v = {'C': 6, 'H': 10, 'O': 5}



#'Fxas' in each case will be integers but 'atoms' should be a float

def updateDS1v(Fxas, x, XDS):
while Fxas != 0:
atoms = DS1v.get('x') + Fxas*XDS
DS1v[x] = atoms

updateDS1v(FCas, C, XDS)
updateDS1v(FHas, H, XDS)
updateDS1v(FOas, O, XDS)
updateDS1v(FNas, N, XDS)
updateDS1v(FSas, S, XDS)
updateDS1v(FClas, Cl, XDS)
updateDS1v(FBras, Br, XDS)
updateDS1v(FZnas, Zn, XDS)
print DS1v

I know there is probably a simple solution but im quite new to python and am 
lost?


Ali


-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366 

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


problem with fft periodogram

2006-10-25 Thread aitor69gonzalez
Hello,

I am ploting a fft periodogram of my data using a script (found in
internet: http://linuxgazette.net/115/andreasen.html ) that gave me
good results before. There should be a periodicity of >160 in the data
as can be seen by eye. However, this script now says that there is
periodicity of ~9. Can somebody explain me what's wrong? Thank you in
advance.
I present first the python script and second my data.
## usage 
python  
# PYTHON SCRIPT ###
from scipy import *
import scipy.io.array_import
from scipy import gplt
from scipy import fftpack
# Read file
f=open(sys.argv[1], 'r')
tempdata = scipy.io.array_import.read_array(f)
minutes=tempdata[:,0]
wolfer=tempdata[:,1]
# plot data
gplt.plot(minutes,wolfer,'title "Meas" with linespoints')
gplt.xtitle('Minutes')
gplt.ytitle('Wolfer number')
gplt.grid("off")
Y=fft(wolfer)
n=len(Y)
power = abs(Y[1:(n/2)])**2
nyquist=1./2
print nyquist
freq=array(range(n/2))/(n/2.0)*nyquist
period=1./freq
# plot period
gplt.plot(period[1:len(period)], power,'title "Simul" with
linespoints')
gplt.xaxis((50,400))
gplt.xtitle('Period [minutes]')
gplt.ytitle('|FFT|**2')
##
 DATA 
0 48
20 49
40 54
60 49
80 69
100 92
120 98
140 58
160 50
180 66
200 76
220 82
240 119
260 141
280 128
300 107
320 93
340 78
360 74
380 74
400 93
420 109
440 135
460 118
480 90
500 64
520 58
540 56
560 70
580 90
600 115
620 158
640 150
660 96
680 73
700 61
720 55
740 66
760 81
780 116
800 142
820 111
840 102
860 84
880 64
#

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


Re: Change on file

2006-10-25 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Tuesday 24 October 2006 20:22, Alan Franzoni wrote:
> it could put the system under severe workload.

Thank you for the enlightment :-)
In my case it's meant to check a couple of files, but no more than 10 Mbytes.
The most purpose is to find differences since last check. I suppose it's a 
good way, as other programs using CRC as comparison between file, better than 
byte-to-byte diff. Also CD images and big files download are giving a MD5 
check.
My point stand as platform indipendent solution and won't take extra fancy 
modules which aren't part of python package itself. I'll look at SVF and 
timestamp options. I'm less actracted by the idea of 'stat' on the file, Now 
I'm on linux and I've some doubt about win32 options.

PS. C'e' la MList per iclp?

F


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


Re: Handling emails

2006-10-25 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Tuesday 24 October 2006 03:07, Gerard Flanagan wrote:
> The 'PopClient' class here might help you:

I got a look rather later. Let me say that is impressively pythonic :-)
On the other hand I've to go deep on learning the use of Python classes, as 
much as the POPClient likes a different config file and will upset a big 
chunk of my code.
Functions are good, I'll study the emails handling, only I need some time to 
prepair a method to discern local and remote emails and a way to save/recover 
the most important ones.

F

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


Re: return same type of object

2006-10-25 Thread Bruno Desthuilliers
Steve Holden wrote:
> Bruno Desthuilliers wrote:
>> David Isaac a écrit :
> [...]
>>
>>> But Steve suggests going with the latter.
>>
>>
>> That's what I'd do too a priori.
>>
> Believe it or not, I wasn't at the priory when I wrote that.

Steve, if it's a pun, I'm afraid I just don't get it...

> Sorry.



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python GUIs comparison (want)

2006-10-25 Thread Christophe
Fredrik Lundh a écrit :
> Christophe wrote:
> 
 Also, the Tkinter API is far less elegant than the others.
>>> huh?  create object, display object, create object, display object. 
>>> sure looks like plain old Python to me...
>>
>> Let's see :
>>
>> .pack(side = "left")

>> fred = Button(self, fg = "red", bg = "blue")
>> fred["fg"] = "red"

>> fred.bind("", turnRed)

>> Yep, unelegant API I mantain 
> 
> yuck.  if that's the kind of UI programs you're writing, we sure have 
> different design ideals.
Those are all small code examples you find in the Python manual! They 
are not a working program in itself and should not be taken so. I just 
state my point about an ugly API with them.

> and arguing that Tkinter is unelegant when you're doing silly things in 
> a silly way is a bit like arguing that Python is unelegant because your 
> first attempt to write a "hello world" program resulted in:
> 
>  import sys
>  # .stdout.write("Hello World") # gives unusable error message
>  from sys import stdout as glah
>  glah.writelines(iter(" ".join(["h3110", "W0rlD"])))
> 
>> And no modern layout manager available. Only those old school 
>> left/right/up/down pack and anchors are available.
> 
> huh?  when did you last look at Tk?  1994?
Yesterday. In fact, I could find no mention at all of layout managers 
others than those working with anchors. Anchors are s old school 
nowadays :)

Honestly, I can't stand using anchors or the Packer anymore. The systems 
used in wx, Qt are much better. Use them once and you cannot live 
without them anymore.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict problem

2006-10-25 Thread Roberto Bonvallet
Alistair King wrote:
> Hi,
> 
> ive been trying to update a dictionary containing a molecular formula, but 
> seem to be getting this error:
> 
> 
> Traceback (most recent call last):
>  File "DS1excessH2O.py", line 242, in ?
>updateDS1v(FCas, C, XDS)
> NameError: name 'C' is not defined
> 
> dictionary is: 
> 
> DS1v = {'C': 6, 'H': 10, 'O': 5}

Try DS1v['C'] instead of DS1v[C].

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


Re: Unicode support in python

2006-10-25 Thread sonald
Fredrik Lundh wrote:
>
> what does the word "validate" mean here?
>
Let me explain our module.
We receive text files (with comma separated values, as per some
predefined format) from a third party.
for example account file comes as "abc.acc" {.acc is the extension for
account file as per our code}
it must contain account_code, account_description, account_balance in
the same order.

So, from the text file("abc.acc") we receive for 2 or more records,
will look like
A001, test account1, 10
A002, test account2, 50

We may have multiple .acc files

Our job is to validate the incoming data on the basis of its datatype,
field number, etc and copy all the error free records in acc.txt

for this, we use a schema as follows
--
if account_flg == 1:
start = time()

# the input fields
acct_schema = {
0: Text('AccountCode', 50),
1: Text('AccountDescription', 100),
2: Text('AccountBalance', 50)
}

validate( schema= acct_schema,
  primary_keys  = [acct_pk],
  infile= '../data/ACC/*.acc',
  outfile   = '../data/acc.txt',
  update_freq = 1)
--
In a core.py, we have defined a function validate, which checks for the
datatypes & other validations.
All the erroneous records are copied in a error log file, and the
correct records are copied to a clean acc.text file

The validate function is as given below...
---
def validate(infile, outfile, schema, primary_keys=[], foreign_keys=[],
record_checks=[], buffer_size=0, update_freq=0):

show("intitalizing ... ")

# find matching input files
all_files  = glob.glob(infile)
if not all_files:
raise ValueError('No input files were found.')

# initialize data structures
freq   = update_freq or DEFAULT_UPDATE
input  = fileinput.FileInput(all_files, bufsize = buffer_size
or DEFAULT_BUFFER)
output = open(outfile, 'wb+')
logs   = {}
for name in all_files:
logs[name]  = open(name + DEFAULT_SUFFIX, 'wb+')
#logs[name]  = open(name + DEFAULT_SUFFIX, 'a+')

errors = []
num_fields = len(schema)
pk_length  = range(len(primary_keys))
fk_length  = range(len(foreign_keys))
rc_length  = range(len(record_checks))

# initialize the PKs and FKs with the given schema
for idx in primary_keys:
idx.setup(schema)
for idx in foreign_keys:
idx.setup(schema)

# start processing: collect all lines which have errors
for line in input:
rec_num = input.lineno()
if rec_num % freq == 0:
show("processed %d records ... " % (rec_num))
for idx in primary_keys:
idx.flush()
for idx in foreign_keys:
idx.flush()

if BLANK_LINE.match(line):
continue

try:
data = csv.parse(line)

# check number of fields
if len(data) != num_fields:
errors.append( (rec_num, LINE_ERROR, 'incorrect number
of fields') )
continue

# check for well-formed fields
fields_ok = True
for i in range(num_fields):
if not schema[i].validate(data[i]):
errors.append( (rec_num, FIELD_ERROR, i) )
fields_ok = False
break

# check the PKs
for i in pk_length:
if fields_ok and not primary_keys[i].valid(rec_num,
data):
errors.append( (rec_num, PK_ERROR, i) )
break

# check the FKs
for i in fk_length:
if fields_ok and not foreign_keys[i].valid(rec_num,
data):
#print 'here ---> %s, rec_num : %d'%(data,rec_num)
errors.append( (rec_num, FK_ERROR, i) )
break

# perform record-level checks
for i in rc_length:
if fields_ok and not record_checks[i](schema, data):
errors.append( (rec_num, REC_ERROR, i) )
break

except fastcsv.Error, err:
errors.append( (rec_num, LINE_ERROR, err.__str__()) )

# finalize the indexes to check for any more errors
for i in pk_length:
error_list = primary_keys[i].finalize()
primary_keys[i].save()
if error_list:
errors.extend( [ (rec_num, PK_ERROR, i) for rec_num in
error_list ] )

for i in fk_length:
error_list = foreign_keys[i].finalize()
if error_list:
errors.extend( [ (rec_num,

Re: Visibility against an unknown background

2006-10-25 Thread Sergei Organov
"Filip Salomonsson" <[EMAIL PROTECTED]> writes:
> On 10/24/06, Sergei Organov <[EMAIL PROTECTED]> wrote:
>> I'd be very upset to see, say, 5-6 highly intersecting
>> scientific plots on the same picture drawn using the
>> "marching ants" approach.
>
> I'd be a bit upset to see scientific plots *on a picture* at all,
> regardless of approach.

Sorry, probably I just wrongly used the word "picture" here, I didn't
mean to mean something like "photo". Maybe "canvas" should have been a
better word.

-- Sergei.

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


Re: dict problem

2006-10-25 Thread Roberto Bonvallet
Roberto Bonvallet wrote:
> Alistair King wrote:
>> DS1v = {'C': 6, 'H': 10, 'O': 5}
> 
> Try DS1v['C'] instead of DS1v[C].

> updateDS1v(FCas, C, XDS)
> updateDS1v(FHas, H, XDS)
> updateDS1v(FOas, O, XDS)
> updateDS1v(FNas, N, XDS)
> updateDS1v(FSas, S, XDS)
> updateDS1v(FClas, Cl, XDS)
> updateDS1v(FBras, Br, XDS)
> updateDS1v(FZnas, Zn, XDS)
> print DS1v

Sorry, I hadn't seen this part.
Change C, H, O, ... with 'C', 'H', 'O', ...

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


Re: Looking for assignement operator

2006-10-25 Thread Bruno Desthuilliers
Tommi wrote:
> Bruno Desthuilliers wrote:
> 
(about Traits)
>
>> How could it help ?
> 
> To me they just looked a bit alike:
> 
> --- op's example ---
> a = MyInt(10)
> # Here i need to overwrite the assignement operator
> a = 12
> 
> --- traits' example ---
> moe = Child()
> # NOTIFICATION in action
> moe.age = 10
> 

You do understand the difference between rebinding a name and modifying
a mutable object, do you ?

FWIW, you definitively don't need Traits here - properties are enough.

class Something(object):
  @apply
  def age():
def fget(self):
  return self._age
def fset(self, val):
  self._age = MyInt(val)
return property(**locals())

s = Something()
s.age = 42
type(s.age)

But this is not what the OP was asking for...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode support in python

2006-10-25 Thread sonald
HI
Can u please tell me if there is any package or class that I can import
for internationalization, or unicode support?

This module is just a small part of our application, and we are not
really supposed to alter the code.
We do not have nobody here to help us with python here. and are
supposed to just try and understand the program. Today I am in a
position, that I can fix the bugs arising from the code, but cannot
really try something like internationalization on my own. Can u help?
Do you want me to post the complete code for your reference?
plz lemme know asap.


John Roth wrote:
> sonald wrote:
> > Hi,
> > I am using python2.4.1
> >
> > I need to pass russian text into python and validate the same.
> > Can u plz guide me on how to make my existing code support the
> > russian  text.
> >
> > Is there any module that can be used for unicode support in python?
> >
> > Incase of decimal numbers, how to handle "comma as a decimal point"
> > within a number
> >
> > Currently the existing code is woking fine for English text
> > Please help.
> >
> > Thanks in advance.
> >
> > regards
> > sonal
>
> As both of the other responders have said, the
> coding comment at the front only affects source
> text; it has absolutely no effect at run time. In
> particular, it's not even necessary to use it to
> handle non-English languages as long as you
> don't want to write literals in those languages.
>
> What seems to be missing is the notion that
> external files are _always_ byte files, and have to
> be _explicitly_ decoded into unicode strings,
> and then encoded back to whatever the external
> encoding needs to be, each and every time you
> read or write a file, or copy string data from
> byte strings to unicode strings and back.
> There is no good way of handling this implicitly:
> you can't simply say "utf-8" or "iso-8859-whatever"
> in one place and expect it to work.
>
> You've got to specify the encoding on each and
> every open, or else use the encode and decode
> string methods. This is a great motivation for
> eliminating duplication and centralizing your
> code!
>
> For your other question: the general words
> are localization and locale. Look up locale in
> the index. It's a strange subject which I don't
> know much about, but that should get you 
> started.
> 
> John Roth

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


Re: dict problem

2006-10-25 Thread Peter Otten
Alistair King wrote:

> Hi,
> 
> ive been trying to update a dictionary containing a molecular formula, but
> seem to be getting this error:
> 
> 
> Traceback (most recent call last):
>   File "DS1excessH2O.py", line 242, in ?
> updateDS1v(FCas, C, XDS)
> NameError: name 'C' is not defined
> 
> dictionary is:
> 
> DS1v = {'C': 6, 'H': 10, 'O': 5}
> 
> 
> 
> #'Fxas' in each case will be integers but 'atoms' should be a float
> 
> def updateDS1v(Fxas, x, XDS):
> while Fxas != 0:
> atoms = DS1v.get('x') + Fxas*XDS
> DS1v[x] = atoms
> 
> updateDS1v(FCas, C, XDS)
> updateDS1v(FHas, H, XDS)
> updateDS1v(FOas, O, XDS)
> updateDS1v(FNas, N, XDS)
> updateDS1v(FSas, S, XDS)
> updateDS1v(FClas, Cl, XDS)
> updateDS1v(FBras, Br, XDS)
> updateDS1v(FZnas, Zn, XDS)
> print DS1v
> 
> I know there is probably a simple solution but im quite new to python and
> am lost?

Ali, 

the NameError stems from the variable C not being defined.
This can be fixed either by defining it:

C = "C"
updateDS1v(FCas, C, XDS)

or by calling updateDS1v() with a string constant.

updateDS1v(FCas, "C", XDS)

However, there are so many errors in the updateDS1v() function that I
recommend reading an introductory text on Python before you proceed.

Python is so much /more/ fun if you have at least some clue :-)

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


Re: dict problem

2006-10-25 Thread Jon Clements

Alistair King wrote:

> Hi,
>
> ive been trying to update a dictionary containing a molecular formula, but 
> seem to be getting this error:
>
>
> Traceback (most recent call last):
>   File "DS1excessH2O.py", line 242, in ?
> updateDS1v(FCas, C, XDS)
> NameError: name 'C' is not defined
>
> dictionary is:
>
> DS1v = {'C': 6, 'H': 10, 'O': 5}
>
>
>
> #'Fxas' in each case will be integers but 'atoms' should be a float
>
> def updateDS1v(Fxas, x, XDS):
> while Fxas != 0:
> atoms = DS1v.get('x') + Fxas*XDS
> DS1v[x] = atoms
>
> updateDS1v(FCas, C, XDS)
> updateDS1v(FHas, H, XDS)
> updateDS1v(FOas, O, XDS)
> updateDS1v(FNas, N, XDS)
> updateDS1v(FSas, S, XDS)
> updateDS1v(FClas, Cl, XDS)
> updateDS1v(FBras, Br, XDS)
> updateDS1v(FZnas, Zn, XDS)
> print DS1v
>
> I know there is probably a simple solution but im quite new to python and am 
> lost?
>

I strongly suggest reading through the tutorial.

I don't think there's enough code here for anyone to check it properly.
For instance, it looks like FCas exists somewhere as it's barfing on
trying to find C. Where is XDS defined etc...?

I can't see updateDS1v() ever completing: any Fxas passed in not equal
to 0 will repeat indefinately.

I'm guessing unless C is meant to be a variable, you mean to pass in
the string 'C'.

A dictionary already has it's own update method

Perhaps if you explain what you're trying to do in plain English, we
could give you some pointers.

Jon.

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


Re: Visibility against an unknown background

2006-10-25 Thread Sergei Organov
Fredrik Lundh <[EMAIL PROTECTED]> writes:
> Sergei Organov wrote:
>
[...]
>> Where "most cases" depends on application. I'd be very upset to see,
>> say, 5-6 highly intersecting scientific plots on the same picture drawn
>> using the "marching ants" approach.
>
> but the mostly random colors you get from XOR wouldn't upset your color 
> vision subsystem?

Here I don't care much about particular colors, -- it's enough for them
to be different.

> to solve your specific case, I'd use bitmask algebra to generate alpha 
> layers (or masks/stencil buffers), and use standard compositing to 
> generate the final result.

Well, it's enough for me to know that you won't use marching ants for
that ;)

-- Sergei.

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


Re: Change on file

2006-10-25 Thread Ben Finney
Fulvio <[EMAIL PROTECTED]> writes:

> ***
> Your mail has been scanned by InterScan MSS.
> ***

Fulvio, something between your fingers and the Python mailing list is
causing this to appear at on *every* message you send to this list.

Please do whatever you need to do to make it stop. It's unwelcome and
obnoxious.

-- 
 \ "In prayer, it is better to have a heart without words than |
  `\  words without heart."  -- Mahatma Gandhi |
_o__)  |
Ben Finney

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


Re: Sending Dictionary via Network

2006-10-25 Thread Frithiof Andreas Jensen

> "mumebuhi" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> The simplejson module is really cool and simple to use. This is great!

JUST what I need for some configuration files!!
Thanks for the link (die, configparse, dieee).


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


unsigned 32 bit arithmetic type?

2006-10-25 Thread Robin Becker
Hi, just trying to avoid wheel reinvention. I have need of an unsigned 32 bit 
arithmetic type to carry out a checksum operation and wondered if anyone had 
already defined such a beast.

Our current code works with 32 bit cpu's, but is failing with 64 bit 
comparisons; it's clearly wrong as we are comparing a number with a negated 
number; the bits might drop off in 32 bits, but not in 64.
-- 
Robin Becker

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


dict problem

2006-10-25 Thread Alistair King
Jon Clements wrote:

> > Alistair King wrote:
> >
> >   
>   
>> >> Hi,
>> >>
>> >> ive been trying to update a dictionary containing a molecular formula, 
>> >> but seem to be getting this error:
>> >>
>> >>
>> >> Traceback (most recent call last):
>> >>   File "DS1excessH2O.py", line 242, in ?
>> >> updateDS1v(FCas, C, XDS)
>> >> NameError: name 'C' is not defined
>> >>
>> >> dictionary is:
>> >>
>> >> DS1v = {'C': 6, 'H': 10, 'O': 5}
>> >>
>> >>
>> >>
>> >> #'Fxas' in each case will be integers but 'atoms' should be a float
>> >>
>> >> def updateDS1v(Fxas, x, XDS):
>> >> while Fxas != 0:
>> >> atoms = DS1v.get('x') + Fxas*XDS
>> >> DS1v[x] = atoms
>> >>
>> >> updateDS1v(FCas, C, XDS)
>> >> updateDS1v(FHas, H, XDS)
>> >> updateDS1v(FOas, O, XDS)
>> >> updateDS1v(FNas, N, XDS)
>> >> updateDS1v(FSas, S, XDS)
>> >> updateDS1v(FClas, Cl, XDS)
>> >> updateDS1v(FBras, Br, XDS)
>> >> updateDS1v(FZnas, Zn, XDS)
>> >> print DS1v
>> >>
>> >> I know there is probably a simple solution but im quite new to python and 
>> >> am lost?
>> >>
>> >> 
>> 
> >
> > I strongly suggest reading through the tutorial.
> >
> > I don't think there's enough code here for anyone to check it properly.
> > For instance, it looks like FCas exists somewhere as it's barfing on
> > trying to find C. Where is XDS defined etc...?
> >
> > I can't see updateDS1v() ever completing: any Fxas passed in not equal
> > to 0 will repeat indefinately.
> >
> > I'm guessing unless C is meant to be a variable, you mean to pass in
> > the string 'C'.
> >
> > A dictionary already has it's own update method
> >
> > Perhaps if you explain what you're trying to do in plain English, we
> > could give you some pointers.
> >
> > Jon.
> >
> >   
>   
sorry,

this has been a little rushed

XDS is defined before the function and is a float.
the Fxas values are also and they are integers


now ive tried

def updateDS1v(Fxas, x, XDS):
while Fxas != 0:
atoms = DS1v.get(x) + Fxas*XDS
DS1v['x'] = atoms

updateDS1v(FCas, 'C', XDS)
updateDS1v(FHas, H, XDS)
updateDS1v(FOas, O, XDS)
updateDS1v(FNas, N, XDS)
updateDS1v(FSas, S, XDS)
updateDS1v(FClas, Cl, XDS)
updateDS1v(FBras, Br, XDS)
updateDS1v(FZnas, Zn, XDS)
print DS1v

from this i get the error:

Traceback (most recent call last):
File "DS1excessH2O.py", line 242, in ?
updateDS1v(FCas, 'C', XDS)
File "DS1excessH2O.py", line 239, in updateDS1v
atoms = DS1v.get(x) + Fxas*XDS
TypeError: unsupported operand type(s) for +: 'int' and 'str'


with single quotes (FCas, 'C', XDS) to retrieve the value for that key
from the dictionary and then create the new value and replace the old value.

a


-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366 

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Travis E. Oliphant
Robin Becker wrote:
> Hi, just trying to avoid wheel reinvention. I have need of an unsigned 32 bit 
> arithmetic type to carry out a checksum operation and wondered if anyone had 
> already defined such a beast.
> 
> Our current code works with 32 bit cpu's, but is failing with 64 bit 
> comparisons; it's clearly wrong as we are comparing a number with a negated 
> number; the bits might drop off in 32 bits, but not in 64.


NumPy defines an array and an array scalar for all signed and unsigned 
integers defined in C.

import numpy as nx
type(nx.array([1,2,3],dtype=nx.uint32)[0])





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


pygtk and threading

2006-10-25 Thread kingcrowbar . list
Hello Everyone

I have been playing a little with pyGTK and threading to come up with
simple alert dialog which plays a sound in the background. The need for

threading came when in the first version i made, the gui would freeze
after clicking the close button until pygame finished playing the
sound.
In Windows it was acceptable because it could be ignored easily, but in

testing on linux (red hat 9) Gnome was throwing up a dialog for killing

hanging applications.

So now i have a threaded version that seems to work as it should
(except not
on rh9 beause gtk is to old, but that is getting upgraded to fc5/6 so
no
matter). So i was hoping to get some general comments about the code as
i am
not sure if i am doing the gtk or threading correctly (i hope the
pygame part
is simple enough that i have it right).


##code start##
#!/usr/bin/env python
"""
Simple alert message dialog with sound.
Runs a dummy audio function if pygame is missing and not run on
Windows.
It does work on linux (fc5) but i don't know the name of any wav file
so
i just copy the Windows tada.wav into same directory as script.
"""

import sys
import threading
import time
import gobject
import gtk
import os.path
try:
import pygame.mixer as pgmixer
import pygame.time as pgtime
except ImportError:
print "pygame not found, using dummy audio"

gobject.threads_init()

alertmsg = "Ding Dong"

class ThreadOne(threading.Thread):
"""Dialog thread"""
stopthread = threading.Event()
def __init__(self):
super(ThreadOne, self).__init__()
self.dialog = gtk.MessageDialog(parent=None,
type=gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_NONE, flags=gtk.DIALOG_MODAL,
message_format=alertmsg)
self.quit = False

def run(self):
"""Run idle sleep loop while stopthread Event is not set"""
while not self.stopthread.isSet():
print self, " is running"
time.sleep(1)

def stop(self):
"""Set stopthread Event"""
self.stopthread.set()

class ThreadTwo(threading.Thread):
"""Audio thread"""
stopthread = threading.Event()
def __init__(self):
super(ThreadTwo, self).__init__()
self.quit = False
self.cnt = 0
self.killaudio = 0

def run(self):
"""While audioalert returns True, increment counter"""
if (sys.modules.has_key('pygame')) and (sys.platform ==
'win32'):
while audioalert():
self.cnt += 1
else:
while audiodummy():
self.cnt += 1

def stop(self):
"""Set killaudio flag to 1, set stopthread Event"""
self.killaudio = 1
self.stopthread.set()
print self, " stop was called"

def audiodummy():
"""dummy audio playback"""
while t2.cnt >= 0 :
if t2.killaudio == 0:
print 'Beep!'
time.sleep(1)
else:
print 'audiodummy done'
return False
return True

def audioalert():
"""
Slightly expanded pygame/examples/sound.py
Playback sound and then test for audio channel usage
While channel is busy and while killaudio flag is set to 0
Check every second and return True at end of sound playback
When killaudio is set to 1 stop the playback and kill the mixer
Return False for ThreadTwo.run
NOTE: Copy tada.wav from X:\WINDOWS\Media\
"""
pgmixer.init(11025)
soundfile = os.path.join('.', 'tada.wav')
sound = pgmixer.Sound(soundfile)
channel = sound.play()
while channel.get_busy():
if t2.killaudio == 0:
pgtime.wait(1000)
else:
sound.stop()
pgmixer.quit()
return False
print '[DEBUG] loop number: ', t2.cnt
return True

t1 = ThreadOne()
t2 = ThreadTwo()

mainwindow = t1.dialog
mainwindow.show_all()
mainwindow.connect("destroy", lambda _: gtk.main_quit())

t1.start()
t2.start()

gtk.main()

print 't2.stop'
t2.stop()
print 't1.stop'
t1.stop()

##code end##

Thanks for your time.

Brendan Mchugh

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


Re: dict problem

2006-10-25 Thread Jon Clements

Alistair King wrote:

> Jon Clements wrote:
>
> > > Alistair King wrote:
> > >
> > >
> >
> >> >> Hi,
> >> >>
> >> >> ive been trying to update a dictionary containing a molecular formula, 
> >> >> but seem to be getting this error:
> >> >>
> >> >>
> >> >> Traceback (most recent call last):
> >> >>   File "DS1excessH2O.py", line 242, in ?
> >> >> updateDS1v(FCas, C, XDS)
> >> >> NameError: name 'C' is not defined
> >> >>
> >> >> dictionary is:
> >> >>
> >> >> DS1v = {'C': 6, 'H': 10, 'O': 5}
> >> >>
> >> >>
> >> >>
> >> >> #'Fxas' in each case will be integers but 'atoms' should be a float
> >> >>
> >> >> def updateDS1v(Fxas, x, XDS):
> >> >> while Fxas != 0:
> >> >> atoms = DS1v.get('x') + Fxas*XDS
> >> >> DS1v[x] = atoms
> >> >>
> >> >> updateDS1v(FCas, C, XDS)
> >> >> updateDS1v(FHas, H, XDS)
> >> >> updateDS1v(FOas, O, XDS)
> >> >> updateDS1v(FNas, N, XDS)
> >> >> updateDS1v(FSas, S, XDS)
> >> >> updateDS1v(FClas, Cl, XDS)
> >> >> updateDS1v(FBras, Br, XDS)
> >> >> updateDS1v(FZnas, Zn, XDS)
> >> >> print DS1v
> >> >>
> >> >> I know there is probably a simple solution but im quite new to python 
> >> >> and am lost?
> >> >>
> >> >>
> >>
> > >
> > > I strongly suggest reading through the tutorial.
> > >
> > > I don't think there's enough code here for anyone to check it properly.
> > > For instance, it looks like FCas exists somewhere as it's barfing on
> > > trying to find C. Where is XDS defined etc...?
> > >
> > > I can't see updateDS1v() ever completing: any Fxas passed in not equal
> > > to 0 will repeat indefinately.
> > >
> > > I'm guessing unless C is meant to be a variable, you mean to pass in
> > > the string 'C'.
> > >
> > > A dictionary already has it's own update method
> > >
> > > Perhaps if you explain what you're trying to do in plain English, we
> > > could give you some pointers.
> > >
> > > Jon.
> > >
> > >
> >
> sorry,
>
> this has been a little rushed
>
> XDS is defined before the function and is a float.
> the Fxas values are also and they are integers
>
>
> now ive tried
>
> def updateDS1v(Fxas, x, XDS):
> while Fxas != 0:
> atoms = DS1v.get(x) + Fxas*XDS
> DS1v['x'] = atoms
>
> updateDS1v(FCas, 'C', XDS)
> updateDS1v(FHas, H, XDS)
> updateDS1v(FOas, O, XDS)
> updateDS1v(FNas, N, XDS)
> updateDS1v(FSas, S, XDS)
> updateDS1v(FClas, Cl, XDS)
> updateDS1v(FBras, Br, XDS)
> updateDS1v(FZnas, Zn, XDS)
> print DS1v
>
> from this i get the error:
>
> Traceback (most recent call last):
> File "DS1excessH2O.py", line 242, in ?
> updateDS1v(FCas, 'C', XDS)
> File "DS1excessH2O.py", line 239, in updateDS1v
> atoms = DS1v.get(x) + Fxas*XDS
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
>
> with single quotes (FCas, 'C', XDS) to retrieve the value for that key
> from the dictionary and then create the new value and replace the old value.

One of Fxas or XDS is a string then...

Again, no-one can help you if we can't see what's actually there.

What are FCas, FHas etc... do they relate to the element? If so, isn't
that a dictionary in itself? And your update function is still an
infinite loop!

We're still in the dark as to what you're trying to do, try describing
something like: "for each element there is an associated 'F' value. For
each element in an existing molecule I wish to change the number of
'whatever' to be 'whatever' + my 'F' value * value XDS..."



Jon.

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


Re: problem with fft periodogram

2006-10-25 Thread Travis E. Oliphant
[EMAIL PROTECTED] wrote:
> Hello,
> 
> I am ploting a fft periodogram of my data using a script (found in
> internet: http://linuxgazette.net/115/andreasen.html ) that gave me
> good results before. There should be a periodicity of >160 in the data
> as can be seen by eye. However, this script now says that there is
> periodicity of ~9. Can somebody explain me what's wrong? Thank you in
> advance.

The units are wrong on your period axis.  Right now you have them in 
units of "sample-spacing".  So, the plot is telling you that you have a 
periodicity of ~9 sample spacings.   To get it in unites of minutes you 
need to multiply period by the difference in minutes

period_in_minutes = period * (minutes[1] - minutes[0])

Then, plot period_in_minutes versus power.  I see a peak around 180 
minutes in your data.



-Travis

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


Re: Attempting to parse free-form ANSI text.

2006-10-25 Thread Frederic Rentsch
Dennis Lee Bieber wrote:
> On Mon, 23 Oct 2006 20:34:20 +0100, Steve Holden <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>
>   
>> Don't give up, attach it as a file!
>>
>> 
>   Which might be acceptable on a mailing list, but might be
> problematic on a "text" newsgroup... Though one attachment a year might
> not be noticed by those providers with strict "binaries in binary groups
> only" 
>   
The comment isn't lost on me. Much less as it runs in an open door. 
Funny thing is that I verified my settings by sending the message to 
myself and it looked fine. Then I sent it to the news group and it was 
messed up again. I will work some more on my setting.

Frederic


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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Robin Becker
Travis E. Oliphant wrote:
> Robin Becker wrote:

> NumPy defines an array and an array scalar for all signed and unsigned 
> integers defined in C.
> 
> import numpy as nx
> type(nx.array([1,2,3],dtype=nx.uint32)[0])
> 
> 

great, but do we have a pure python version?
-- 
Robin Becker

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


web-based SSH

2006-10-25 Thread Astan Chee
Hi,
I was looking for a web-based SSH client (something like
www.port42.com..but for some reason it doesnt work..can anyone verify
this)..does anyone know any other alternative to other websites that offer
this? If you're gonna scream 'security!security!' well, its for testing
purposes and the box im ssh-ing into is "expandable" and "disposeable"
Cheers


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


Re:

2006-10-25 Thread Michael S
Thanks Gabriel.
I think I'll try calling my module from a separate
thread as calling wxPython or even Python code from C
would be a bit complicated. My extension calls simple
 functions, but the issue was that the files
I operate on are huge in size and Python was taking a
long time and/or choking.

--- Gabriel Genellina <[EMAIL PROTECTED]> wrote:

> At Tuesday 24/10/2006 23:25, Michael S wrote:
> 
> >I extended part of my program in C, since that part
> >was too involved for Python. Now when I import the
> >module I created and call its functions, I am
> trying
> >to feedback some information bac to my wxPython
> >program. The function runs for a while and I wanted
> to
> >update a progress bar, but when I call the function
> of
> >my new module, wxPython doesn't respond when
> wx.Timer
> >is supposed to fire.
> 
> Does your extension run on a separate thread? I
> guess not. So the 
> wxPython code does not have a chance to run.
> Do it the other way: from your C code, call a Python
> function which 
> in turn updates the progress bar (and keep it
> simple!)
> 
> 
> -- 
> Gabriel Genellina
> Softlab SRL 
> 
> __
> Correo Yahoo!
> Espacio para todos tus mensajes, antivirus y
> antispam �gratis! 
> �Abr� tu cuenta ya! - http://correo.yahoo.com.ar
> 

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


Re: web-based SSH

2006-10-25 Thread Christoph Haas
On Wednesday 25 October 2006 11:59, Astan Chee wrote:
> I was looking for a web-based SSH client (something like
> www.port42.com..but for some reason it doesnt work..can anyone verify
> this)..does anyone know any other alternative to other websites that
> offer this? If you're gonna scream 'security!security!' well, its for
> testing purposes and the box im ssh-ing into is "expandable" and
> "disposeable" Cheers

Perhaps "Ajaxterm" helps. But how is that connected to Python?

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


Re: using mmap on large (> 2 Gig) files

2006-10-25 Thread Martin v. Löwis
sturlamolden schrieb:
> 2. The OS may be stupid. Mapping a large file may be a major slowdown
> simply because the memory mapping is implemented suboptimally inside
> the OS. For example it may try to load and synchronise huge portions of
> the file that you don't need.

Can you give an example of an operating system that behaves that way?
To my knowledge, all current systems integrating memory mapping somehow
with the page/buffer caches, using various strategies to write-back
(or just discard in case of no writes) pages that haven't been used
for a while.

> The missing offset argument is essential for getting adequate
> performance from a memory-mapped file object.

I very much question that statement. Do you have any numbers to
prove it?

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


Re: [wxPython-users] Re:

2006-10-25 Thread Michael S
If I create a threading.Thread derived class, and run
the wxPython code in the main thread; using a lock,
will I be able to suspend the Thread, even though it
will run the C code, which is essentially a while loop
looping through millions of lines of a text file?

Thanks in advance.
Michael

--- Josiah Carlson <[EMAIL PROTECTED]> wrote:

> 
> Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> > At Tuesday 24/10/2006 23:25, Michael S wrote:
> > 
> > >I extended part of my program in C, since that
> part
> > >was too involved for Python. Now when I import
> the
> > >module I created and call its functions, I am
> trying
> > >to feedback some information bac to my wxPython
> > >program. The function runs for a while and I
> wanted to
> > >update a progress bar, but when I call the
> function of
> > >my new module, wxPython doesn't respond when
> wx.Timer
> > >is supposed to fire.
> > 
> > Does your extension run on a separate thread? I
> guess not. So the 
> > wxPython code does not have a chance to run.
> > Do it the other way: from your C code, call a
> Python function which 
> > in turn updates the progress bar (and keep it
> simple!)
> 
> Unless the GUI thread has a chance to take passes
> through the wxPython
> mainloop, the progress bar, etc., may not actually
> be updated on some
> platforms.
> 
> Mr. Sherman would likely be better off creating a
> new thread which
> handles processing, which could update a C global
> variable, which the
> GUI thread can poll to update its progress bar, etc.
>  Alternatively, if
> the processing can be broken down into smaller
> pieces, the secondary
> thread can call the pieces and post events back to
> the GUI thread to
> update the progress bar (via explicit wx.PostEvent
> or implicit
> wx.CallAfter).
> 
> 
>  - Josiah
> 
> 
>
-
> To unsubscribe, e-mail:
> [EMAIL PROTECTED]
> For additional commands, e-mail:
> [EMAIL PROTECTED]
> 
> 

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Martin v. Löwis
Robin Becker schrieb:
> Hi, just trying to avoid wheel reinvention. I have need of an unsigned
> 32 bit arithmetic type to carry out a checksum operation and wondered if
> anyone had already defined such a beast.
> 
> Our current code works with 32 bit cpu's, but is failing with 64 bit
> comparisons; it's clearly wrong as we are comparing a number with a
> negated number; the bits might drop off in 32 bits, but not in 64.

Not sure what operations you are doing: In Python, bits never drop off
(at least not in recent versions).

If you need to drop bits, you need to do so explicitly, by using the
bit mask operations. I could tell you more if you'd tell us what
the specific operations are.

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


Re: mean ans std dev of an array?

2006-10-25 Thread Frederic Rentsch
SpreadTooThin wrote:
> import array
> a = array.array('f', [1,2,3])
>
> print a.mean()
> print a.std_dev()
>
> Is there a way to calculate the mean and standard deviation on array
> data?
>
> Do I need to import it into a Numeric Array to do this?
>
>   
I quickly fish this out of my functions toolbox. There's got to be 
faster functions in scipy, though.

Frederic

(Disclaimer: If you build an air liner or a ocean liner with this and 
the wings fall off at thirty thousand feet or it turns upside down in 
the middle of an ocean, respectively of course, I expect a bunch of 
contingency lawers lining up at my door wanting to sue you on my behalf.)


def standard_deviation (values):

   """
  Takes a sequence and returns mean, variance and standard deviation.
  Non-values (None) are skipped

   """

   import math
 
   mean = _sum_values_squared = _sum_values = 0.0

   l = len (values)
   i = 0
   item_count = 0
   while i < l:
  value = values [i]
  if value != None:
 _sum_values += value
 _sum_values_squared += value * value
 item_count += 1
  i += 1

   if item_count < 2:  # having skipped all Nones
  return None, None, None

   mean = _sum_values / item_count

   variance = (_sum_values_squared - item_count * mean * mean) / 
(item_count - 1)

   if variance < 0.0: variance = 0.0 
   # Rounding errors can cause minute negative values which would crash 
the sqrt

   standard_deviation = math.sqrt (variance)

   return mean, variance, standard_deviation


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


Re: [0T] Re: Simple python + html + from --> to python script

2006-10-25 Thread Bruno Desthuilliers
Bruno Desthuilliers wrote:
(snip)
> 
(snip)
> Also, the "button" tag doesn't require a end tag.

oops ! Sorry, your syntax was ok - button elements actually requires the
end tag.

my bad :(


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Handling emails

2006-10-25 Thread Gerard Flanagan

Fulvio wrote:
> On Tuesday 24 October 2006 03:07, Gerard Flanagan wrote:
> > The 'PopClient' class here might help you:
>
> I got a look rather later. Let me say that is impressively pythonic :-)

I don't know if everyone would agree with you, but thanks!

Have you looked at the email.utils module? Some useful functions there.

All the best

Gerard

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


Re: Ctypes Error: Why can't it find the DLL.

2006-10-25 Thread Chetan
"Jon Clements" <[EMAIL PROTECTED]> writes:

> Mudcat wrote:
> 
> 
> > So then I use the find_library function, and it finds it:
> >
> > >>> find_library('arapi51.dll')
> > 'C:\\WINNT\\system32\\arapi51.dll'
> >
> 
> Notice it's escaped the '\' character.
> 
> > At that point I try to use the LoadLibrary function, but it still can't
> > find it:
> >
> > >>> windll.LoadLibrary('C:\WINNT\system32\arapi51.dll')
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 395, in
> > LoadLibrary
> > return self._dlltype(name)
> >   File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 312, in
> > __init__
> > self._handle = _dlopen(self._name, mode)
> > WindowsError: [Errno 126] The specified module could not be found
> >
> > What am I doing wrong? [snip]
> 
> You need to use either
> windll.LoadLibrary(r'c:\winnt\system32\arapi51.dll') or escape the \'s
> as the find_library function did. You're getting caught out by \a which
> is the alert/bell character. \w and \s aren't valid escape sequences so
> you get away with them. I'm guessing it's worked before because you've
> been lucky.
> 
> Works fine!:
> >>> 'C:\winnt\system32\smtpctrs.dll'
> 'C:\\winnt\\system32\\smtpctrs.dll'
> 
> Uh oh, escaped:
> >>> 'C:\winnt\system32\arapi51.dll'
> 'C:\\winnt\\system32\x07rapi51.dll'
I wondered about it, but that would not explain why it fails in the first case
- perhaps the OP now knows what happened. Interestingly I get a different
error with the distribution binary for 2.5 - I get "Error 22" instead of "Errno
126", but the message text was same, so I assumed this was from a different 
version and something had changed about how the errno is reported. 

However, I checked the windows error codes and 126 seems to be the correct
error. The error code talks about bad command and the corresponding message
text reads "The device does not recognize the command."

-Chetan

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


Re: dict problem

2006-10-25 Thread Ben Finney
"Jon Clements" <[EMAIL PROTECTED]> writes:

> We're still in the dark as to what you're trying to do, try
> describing something like: "for each element there is an associated
> 'F' value. For each element in an existing molecule I wish to change
> the number of 'whatever' to be 'whatever' + my 'F' value * value
> XDS..."

Even better, work on a minimal program to do nothing but reproduce the
unexpected behaviour. If you get to such a program and still don't
understand, then post it here so others can run it themselves and
explain.

-- 
 \ "A cynic is a man who, when he smells flowers, looks around for |
  `\   a coffin."  -- Henry L. Mencken |
_o__)  |
Ben Finney

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Robin Becker
Martin v. Löwis wrote:
> Robin Becker schrieb:
>> Hi, just trying to avoid wheel reinvention. I have need of an unsigned
>> 32 bit arithmetic type to carry out a checksum operation and wondered if
>> anyone had already defined such a beast.
>>
>> Our current code works with 32 bit cpu's, but is failing with 64 bit
>> comparisons; it's clearly wrong as we are comparing a number with a
>> negated number; the bits might drop off in 32 bits, but not in 64.
> 
> Not sure what operations you are doing: In Python, bits never drop off
> (at least not in recent versions).
> 
> If you need to drop bits, you need to do so explicitly, by using the
> bit mask operations. I could tell you more if you'd tell us what
> the specific operations are.


This code is in a contribution to the reportlab toolkit that handles TTF fonts.
The fonts contain checksums computed using 32bit arithmetic. The original 
Cdefintion is as follows


> ULONG CalcTableChecksum(ULONG *Table, ULONG Length)
> {
> ULONG Sum = 0L;
> ULONG *Endptr = Table+((Length+3) & ~3) / sizeof(ULONG);
> 
> while (Table < EndPtr)
>   Sum += *Table++;
> return Sum;
> }

so effectively we're doing only additions and letting bits roll off the end.

Of course the actual semantics is dependent on what C unsigned arithmetic does 
so we're relying on that being the same everywhere.

This algorithm was pretty simple in Python until 2.3 when shifts over the end 
of 
ints started going wrong. For some reason we didn't do the obvious and just do 
everything in longs and just mask off the upper bits. For some reason (probably 
my fault) we seem to have accumulated code like

def _L2U32(L):
 '''convert a long to u32'''
 return unpack('l',pack('L',L))[0]


if sys.hexversion>=0x0203:
 def add32(x, y):
 "Calculate (x + y) modulo 2**32"
 return _L2U32((long(x)+y) & 0xL)
else:
 def add32(x, y):
 "Calculate (x + y) modulo 2**32"
 lo = (x & 0x) + (y & 0x)
 hi = (x >> 16) + (y >> 16) + (lo >> 16)
 return (hi << 16) | (lo & 0x)

def calcChecksum(data):
 """Calculates TTF-style checksums"""
 if len(data)&3: data = data + (4-(len(data)&3))*"\0"
 sum = 0
 for n in unpack(">%dl" % (len(data)>>2), data):
 sum = add32(sum,n)
 return sum

and also silly stuff like

def testAdd32(self):
 "Test add32"
 self.assertEquals(add32(10, -6), 4)
 self.assertEquals(add32(6, -10), -4)
 self.assertEquals(add32(_L2U32(0x8000L), -1), 0x7FFF)
 self.assertEquals(add32(0x7FFF, 1), _L2U32(0x8000L))

def testChecksum(self):
 "Test calcChecksum function"
 self.assertEquals(calcChecksum(""), 0)
 self.assertEquals(calcChecksum("\1"), 0x0100)
 self.assertEquals(calcChecksum("\x01\x02\x03\x04\x10\x20\x30\x40"), 
0x11223344)
 self.assertEquals(calcChecksum("\x81"), _L2U32(0x8100L))
   _L2U32(0x8000L))

where while it might be reasonable to do testing it seems the tests aren't very 
sensible eg what is -6 doing in a u32 test? This stuff just about works on a 32 
bit machine, but is failing miserably on a 64bit AMD. As far as I can see I 
just 
need to use masked longs throughout.

In a C extension I can still do the computation exfficiently on a 32bit 
machine, 
but I need to do masking for a 64 bit machine.
-- 
Robin Becker

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


Re: dict problem

2006-10-25 Thread Alistair King
Ben Finney wrote:
> "Jon Clements" <[EMAIL PROTECTED]> writes:
>
>   
>> We're still in the dark as to what you're trying to do, try
>> describing something like: "for each element there is an associated
>> 'F' value. For each element in an existing molecule I wish to change
>> the number of 'whatever' to be 'whatever' + my 'F' value * value
>> XDS..."
>> 
>
> Even better, work on a minimal program to do nothing but reproduce the
> unexpected behaviour. If you get to such a program and still don't
> understand, then post it here so others can run it themselves and
> explain.
>
>   
ive checked the values and XDS is actually returning a string where i
want a float ie '123.45' not 123.45.

-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366 

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


Re: python html 2 image (png)

2006-10-25 Thread baur79
> what tools are you using to do that today?

where are many of EXE programs
but i need python solution for adding it to my automate program under
lunix


Fredrik Lundh wrote:
> [EMAIL PROTECTED] wrote:
>
> > how can i render html page to png image
> > ex:
> >
> > http://www.website.com/index.html -> index.png
> 
> what tools are you using to do that today?
> 
> 

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


Re: python GUIs comparison (want)

2006-10-25 Thread David Boddie
Fredrik Lundh wrote:
> Christophe wrote:

> > Even if you consider that the huge time saving you get out of using Qt
> > is worth more than what you pay to acquire a licence?
>
> then it sounds like a combination between "it's a silver bullet!" and
> "commercial software is better than free software!".

Well, nobody's stopping you from paying the commercial license fee (to
get access to support services) and releasing software under the GPL.

> no matter how good Qt is, the reality is that if you spend that much
> time on the UI implementation parts of your project, you're probably
> developing at the wrong abstraction level -- no matter what toolkit
> you're using.  and if you're doing UI development the wrong way, chances
> are that you're doing other things the wrong way too.

You're forgetting that Qt isn't just a widget toolkit.

David

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


Re: Sending Dictionary via Network

2006-10-25 Thread Leif K-Brooks
Frithiof Andreas Jensen wrote:
>> "mumebuhi" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> The simplejson module is really cool and simple to use. This is great!
> 
> JUST what I need for some configuration files!!
> Thanks for the link (die, configparse, dieee).


I would personally use YAML for configuration files instead of JSON, 
because it's more human-readable. But it's a matter of personal preference.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't open word document after string replacements

2006-10-25 Thread Duncan Booth
Frederic Rentsch <[EMAIL PROTECTED]> wrote:

> DOC files contain housekeeping info which becomes inconsistent if you 
> change text. Possibly you can exchange stuff of equal length but that 
> wouldn't serve your purpose. RTF files let you do substitutions and they 
> save a lot of space too. But I kind of doubt whether RTF files can 
> contain pictures.

They wouldn't be a lot of use as a document file format if they couldn't 
contain pictures. RTF files can contain just about anything, they can even 
embed other non-rtf objects. Whether rtf applications apart from Word can 
actually handle all of the tags is, of course, another question.

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


Re: numbers to string

2006-10-25 Thread David Isaac
Robert Kern wrote:
 >>> from numpy import *
 >>> y = [116, 114, 121, 32, 116, 104, 105, 115]
 >>> a = array(y, dtype=uint8)
 >>> z = a.tostring()
 >>> z
'try this'



Very nice!  Thanks also to Paul and Travis!
Alan Isaac


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


To remove some lines from a file

2006-10-25 Thread umut . tabak
Dear all,

I am quite new to python. I would like to remove two lines from a file.
The file starts with some comments, the comment sign is $. The file
structure is

$
$
$
$
$
$
$
.
.
.
.
$
line1
line 2
$
$
.
.
.
$
actual commands

I would like to delete those two lines at the very beginning of the
file between two comment blocks. I have read things about python but my
library knowledge is still weak. So could you please help me with this
code.

I would like to call this as

myscript targetfile

I have read sth about command line arguments. Perhaps I can cope with
that myself but help is also appreciated on that.

Best regards,

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


Re: To remove some lines from a file

2006-10-25 Thread Jerry
Very inelegant, but you get the idea:

counter = 0

f = open("test.txt")
for line in f.readlines():
if line[0] != "$" and counter < 2:
counter += 1
continue
else:
print line,

--
Jerry

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


Re: python GUIs comparison (want)

2006-10-25 Thread rdsteph
Paul Boddie wrote:

"""The figures behind the scenes are quite enlightening for that
particular page. If you (or community experiences) don't agree with the

rankings (wxPython apparently even easier to learn than PythonCard and
Tinder, a bunch of Gtk-based toolkits having more or less "full" Linux
scores) then you'll have some surprises, I'm sure. Nevertheless, it's
an interesting concept. """

Well, I don't know what I was thinking, exactly, when I rated
PythonCard's ease of use...so I went back and changed it to rate it a
lot higher. The ratings in this script were done a long time ago now
and I need to re-do them, and add some new categories to rate also.
Maybe this weekend...

I have been thinking about doing a new version of this script that
allows visitors to the web site to enter their own ratings for each GUI
toolkit, for each criterion, store them by CGI and calculate a running
average of the ratings, maybe eliminating the very extreme high and low
scores to weed out spam, etc. Then, a visitor could use an online
script with each GUI toolkit rated by the "community" for each
criterion. I could do the same for Python IDE's, web frameworks, etc.

Still, these would still be toys and not to be taken too seriously, but
I might do it as a little project nonetheless.

Concerning GUI toolkits, I find myself coming back to Tkinter these
days. A lot of Python programs are written using Tkinter. I like to
fool around with a lot of the old stuff on the web for free,
miscellaneous apps and such, and there are still more Tkinter GUI's out
there than anything else.

Recently I have been having fun figuring out which new phone to buy. I
decided to get a smart phone that could run Python. If I lived in
Europe, or anywhere GSM rules, one of the Nokia series 60 would be a no
-brainer. But here in the USA, I will probably will wind up getting a
Windows based model.

Guess what: Folks have Tkinter up and running on Pocket PC's and
smartphones. I like that. Tkinter is everywhere. Don't forget, the
Komodo IDE has a Tk based GUI builder.

Just my 2 cents worth...

Ron Stephens

P.S. There is a 3 hour lecture by Dr. Sergio Rey of San Diego St. U. I
am putting up as a podcast. He teaches a course in Python in the
graduate department of Geographical Sciences. Python is heavily used in
that field of study (as is Tkinter).

The lecture is in 2 parts. Sound quality is excellent. http://www.awaretek.com/python/index.html";>Tkinter podcasts

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


Re: To remove some lines from a file

2006-10-25 Thread umut . tabak

Thanks, I have learnt sth from the library BTW.

Regards
On Oct 25, 3:32 pm, "Jerry" <[EMAIL PROTECTED]> wrote:
> Very inelegant, but you get the idea:
>
> counter = 0
>
> f = open("test.txt")
> for line in f.readlines():
> if line[0] != "$" and counter < 2:
> counter += 1
> continue
> else:
> print line,
> 
> --
> Jerry

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


Re: dict problem

2006-10-25 Thread Ben Finney
Alistair King <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > Even better, work on a minimal program to do nothing but reproduce
> > the unexpected behaviour. If you get to such a program and still
> > don't understand, then post it here so others can run it
> > themselves and explain.
> ive checked the values and XDS is actually returning a string where i
> want a float ie '123.45' not 123.45.

Can you please post a small, complete program that shows the behaviour
you want explained?

You get this program by writing it -- either by cutting away
irrelevant parts of the existing program, or (better) writing a new
program from scratch that does nothing except demonstrate the
behaviour.

Note that in the process of getting such a program behaving this way,
you may end up understanding the problem better.

-- 
 \ "Democracy is the art of running the circus from the monkey |
  `\   cage."  -- Henry L. Mencken |
_o__)  |
Ben Finney

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


Re: Want to reduce steps of an operation with dictionaries

2006-10-25 Thread pretoriano_2001
James:
Your solution works for me, many, many thanks for your help and many
thanks for the time, teaching and reflections I received from all the
guys that participated in this thread.


James Stroud wrote:
> [EMAIL PROTECTED] wrote:
> > Hello:
> > I have next dictionaries:
> > a={'a':0, 'b':1, 'c':2, 'd':3}
> > b={'a':0, 'c':1, 'd':2, 'e':3}
> > I want to put in a new dictionary named c all the keys that are in b
> > and re-sequence the values. The result I want is:
> > c={'a':0, 'c':1, 'd':2}
> > How can I do this with one line of instruction?
> >
> > I attempted the next but the output is not the expected:
> > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)])
> > erroneously (for me) gets:
> > {'a': 0, 'c': 2, 'd': 3}
> >
> > Thanks for your help.
> >
> I think you have the right idea if I understand what you want:
>
> c = dict(((k,v) for (v,k) in enumerate(x for x in a if b.has_key(x
>
> --
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA 90095
> 
> http://www.jamesstroud.com/

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


Re: Sending Dictionary via Network

2006-10-25 Thread Chris Mellon
On 24 Oct 2006 16:56:43 -0700, Simon Forman <[EMAIL PROTECTED]> wrote:
>
> mumebuhi wrote:
> > Thank you very much for the reply.
> >
> > Can pickle work directly with socket? The way I am doing right now is
> > to pickle the object to a file then send the file content through the
> > socket.
>
> Pickle aso has dumps() and loads() to work with strings rather than
> files.


I would recommend against using pickle if you're going to push it over
a network - there are signifigant dangers in unpickling anything
untrusted.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want to reduce steps of an operation with dictionaries

2006-10-25 Thread pretoriano_2001
Mike:
Many thanks for your solution. It looks really nice.



Mike Erickson wrote:
> * [EMAIL PROTECTED] ([EMAIL PROTECTED]) wrote:
> > Hello:
> > I have next dictionaries:
> > a={'a':0, 'b':1, 'c':2, 'd':3}
> > b={'a':0, 'c':1, 'd':2, 'e':3}
> > I want to put in a new dictionary named c all the keys that are in b
> > and re-sequence the values. The result I want is:
> > c={'a':0, 'c':1, 'd':2}
> > How can I do this with one line of instruction?
> >
> > I attempted the next but the output is not the expected:
> > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)])
> > erroneously (for me) gets:
> > {'a': 0, 'c': 2, 'd': 3}
>
> I am not 100% I understand your questions, but k,v are being pulled from
> a, try:
>
> c=dict([(k,b[k]) for v,k in enumerate(a) if b.has_key(k)])
> 
> mike

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


255 argument limit?

2006-10-25 Thread Michael Yanowitz
Hello:

   It appears that there is a 255 argument limit in Python 2.4.3?

>>> packed_data = struct.pack("260i",
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,
47,4
8,49,50,1,1,1,1,1,1,1,1,1,60,1,2,3,4,5,6,7,8,9,70,1,2,3,4,5,6,7,8,9,80,1,2,3
,4,5
,6,7,8,9,90,1,2,3,4,5,6,7,8,9,100,1,2,3,4,5,6,7,8,9,110,1,2,3,4,5,6,7,8,9,12
0,1,
2,3,4,5,6,7,8,9,130,1,2,3,4,5,6,7,8,9,140,1,2,3,4,5,6,7,8,9,150,1,2,3,4,5,6,
7,8,
9,160,1,2,3,4,5,6,7,8,9,170,1,2,3,4,5,6,7,8,9,180,1,2,3,4,5,6,7,8,9,190,1,2,
3,4,
5,6,7,8,9,200,1,2,3,4,5,6,7,8,9,210,1,2,3,4,5,6,7,8,9,220,1,2,3,4,5,6,7,8,9,
230,
1,2,3,4,5,6,7,8,9,240,1,2,3,4,5,6,7,8,9,250,1,2,3,4,5,6,7,8,9)
SyntaxError: more than 255 arguments

   Is there a way to increase this limit?
(This is just a made up example, I would not normally do this).

Thanks in advance:
Michael Yanowitz


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


starship.python.net status update

2006-10-25 Thread T. Bryan
We are now ready to start re-enabling user accounts on starship.python.net. 
If you had an account on the machine, then you should have received an
e-mail about it already.  If you didn't, you should send e-mail to 
webmaster.  If you did, expect it to take at least 24 hours for your
account to be re-enabled.  

Once "crew" members on starship.python.net have access to their accounts
again, they will be able to restore the content that is normally available
on starship.python.net.  At that point, starship.python.net should be back
to normal again.

Regards,
---Tom

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


Re: To remove some lines from a file

2006-10-25 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Dear all,
> 
> I am quite new to python. I would like to remove two lines from a file.

The canonical way to do so (at least for text files - which is the case
here) is :

open the source file in read mode
open a tmp file in write mode

for each line in source file:
  if this line should be kept:
 write it to the tmp file

close both files
replace source file with tmp file

(snip)

> I would like to call this as
> 
> myscript targetfile
> 
> I have read sth about command line arguments. Perhaps I can cope with
> that myself but help is also appreciated on that.

import sys
print sys.argv


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


py and Dabo class in chi

2006-10-25 Thread Carl K
I am organizing 3 python events in Chicago:  2 free, one cheap.

1st is really just an extended VFP users group meeting featuring Ed Leafe, one 
of the Dabo developers.  I am getting a larger room to accommodate the python 
group too.  The meeting is Nov 14 5:30pm in the loop:  (not sure yet where, 
watch this page http://chipy.org/EdOnDabo )

There is some interest in an afternoon talk at 1:00 to 4:30.  If I can get 5 or 
so people to commit to showing up, then Ed will talk then too.  Probably worth 
staying for the evening presentation too - the Q/A will be worth as much as his 
presentation.

I am hosting a 2 day mini event too: http://chipy.org/BootCampy - nothing like 
a 
fest.  For this I am planing on spending a few $ on an instructor, which I have 
not found yet - I have some nibbles - but hoping to get a few more instead of 
just going with the first to respond.  So if anyone is interested in either 
attending or instructing, please let me know.

And of course, please forward this to any other list/group that may have some 
interest.

If you are interested, or are near Chicago, please join the chipy list:
http://mail.python.org/mailman/listinfo/chicago
very low post rate - about 5 per day, mostly about the monthly meetings.

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


batteries included

2006-10-25 Thread marc . wyburn
Could someone confirm that modules like socket don't use libraries/
dlls on a particular OS, they are completly self contained.

Thanks, Marc.

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


Re: Sending Dictionary via Network

2006-10-25 Thread Lawrence Oluyede
Chris Mellon <[EMAIL PROTECTED]> wrote:
> I would recommend against using pickle if you're going to push it over
> a network - there are signifigant dangers in unpickling anything
> untrusted.

I confirm: http://jcalderone.livejournal.com/15864.html

-- 
Lawrence - http://www.oluyede.org/blog
http://www.neropercaso.it
"Nothing is more dangerous than an idea
if it's the only one you have" - E. A. Chartier
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Save/Store whole class (or another object) in a file

2006-10-25 Thread alexLIGO
Hi,

Fredrik Lundh wrote:

> [EMAIL PROTECTED] wrote:
>
> > thanks for the reply,but unfortunately this does not work with the type
> > of classes I am dealing with. When trying to pickle the class I get the
> > following error:
> >
> >  File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex
> > raise TypeError("a class that defines __slots__ without "
> > TypeError: a class that defines __slots__ without defining __getstate__
> > cannot be pickled
> >
> > So there is something missing in this class?
>
> did you remember to read the error message before posting ?
>

of course I read the error-message, I understand the error-message, BUT
this message is not telling me how anyway to save the data of such a
class in a file!  It does not tell me, that there is absolutely no way
to do that. Maybe there is, maybe there is not.
Thats why I am posting it here!

Alex

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


Re: To remove some lines from a file

2006-10-25 Thread Sebastian Busch
[EMAIL PROTECTED] wrote:
> ... I would like to remove two lines from a file.
> ...

I am quite new myself -- but wouldn't grep -v do that easier (and
perhaps faster)?

Greetings,
Sebastian.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: batteries included

2006-10-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Could someone confirm that modules like socket don't use libraries/
> dlls on a particular OS, they are completly self contained.

They might need DLLs, but if so they ship with the distribution.

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


class method question

2006-10-25 Thread Sylvain Ferriol
hello
can you explain why python does not see difference between instance 
method and class method, having the same name

example
 >>> class toto(object):
... def f(self):
... print('instance method')
... @classmethod
... def f(cls):
... print('class method')
...
 >>> t=toto()
 >>> t.f
>
 >>> t.f()
class method
 >>> toto.f()
class method


if i do the same in ruby:
"""
class Toto
   def meth
 print "instance method\n"
   end

   def Toto.meth
 print "class method\n"
   end
end

i = Toto.new
i.meth
Toto.meth
"""

$> ruby1.9 test_classmethod.rb
instance method
class method

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


Re: python GUIs comparison (want)

2006-10-25 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
>
> Well, I don't know what I was thinking, exactly, when I rated
> PythonCard's ease of use...so I went back and changed it to rate it a
> lot higher. The ratings in this script were done a long time ago now
> and I need to re-do them, and add some new categories to rate also.
> Maybe this weekend...

I know you're a big advocate of PythonCard, but if it weren't easier to
use than wxPython, then it would surely be hard to justify its
existence.

> I have been thinking about doing a new version of this script that
> allows visitors to the web site to enter their own ratings for each GUI
> toolkit, for each criterion, store them by CGI and calculate a running
> average of the ratings, maybe eliminating the very extreme high and low
> scores to weed out spam, etc. Then, a visitor could use an online
> script with each GUI toolkit rated by the "community" for each
> criterion. I could do the same for Python IDE's, web frameworks, etc.
>
> Still, these would still be toys and not to be taken too seriously, but
> I might do it as a little project nonetheless.

A collaborative scoring application would be interesting and either
amusing or rather useful. It might have uses in other domains, too.

> Concerning GUI toolkits, I find myself coming back to Tkinter these
> days. A lot of Python programs are written using Tkinter. I like to
> fool around with a lot of the old stuff on the web for free,
> miscellaneous apps and such, and there are still more Tkinter GUI's out
> there than anything else.

There's nothing particularly wrong about Tkinter as such, but if I were
doing serious user interface development these days, I'd have a hard
time justifying using Tkinter even though I was once a big fan of the
technology, Pmw and related stuff. Although people may assert that the
Tk scene is still vibrant, the intersection of Tk and Python doesn't
seem to have moved very far, despite Fredrik's efforts: what happened
to Tkinter 3000 or was that a codename for something else? And whilst
things like the Tk canvas were almost revolutionary back in the early
1990s, the momentum just doesn't seem to have been there to produce
similarly revolutionary things in the Tk universe today, at least as
far as I can tell.

> Recently I have been having fun figuring out which new phone to buy. I
> decided to get a smart phone that could run Python. If I lived in
> Europe, or anywhere GSM rules, one of the Nokia series 60 would be a no
> -brainer. But here in the USA, I will probably will wind up getting a
> Windows based model.

I wonder whether we'll see Python plus user interface integration on
this device:

http://www.trolltech.com/products/qtopia/greenphone/index

> Guess what: Folks have Tkinter up and running on Pocket PC's and
> smartphones. I like that. Tkinter is everywhere. Don't forget, the
> Komodo IDE has a Tk based GUI builder.

I guess a decent IDE comparison would make a good resource given the
repetitive "which IDE is best?" threads that appear on
comp.lang.python.

> P.S. There is a 3 hour lecture by Dr. Sergio Rey of San Diego St. U. I
> am putting up as a podcast. He teaches a course in Python in the
> graduate department of Geographical Sciences. Python is heavily used in
> that field of study (as is Tkinter).
>
> The lecture is in 2 parts. Sound quality is excellent.  href="http://www.awaretek.com/python/index.html";>Tkinter podcasts

I'm a regular listener of your podcasts, and look forward to many more!

Paul

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


Re: 255 argument limit?

2006-10-25 Thread Fredrik Lundh
Michael Yanowitz wrote:

>It appears that there is a 255 argument limit in Python 2.4.3?
> 
 packed_data = struct.pack("260i", /... snip .../)

ouch.  if you need to pass large amounts of data to struct.pack (or any 
other function), use a sequence:

import struct

data = range(100)

packed_data = struct.pack("100i", *data)

print len(packed_data) # prints 400



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


Python's CRT licensing on Windows

2006-10-25 Thread sturlamolden

On Windows, the standard Python 2.4 distro is compiled with Microsoft
Visual C++ 2003 and is shipped with msvcr71.dll as a part of the binary
installer. That is ok, as those who has a license for Microsoft Visual
C++ 2003 is allowed to redistribute msvcr71.dll. Without a license for
Microsoft Visual C++ 2003 one it not allowed to redistribute this DLL.

This has some interesting implications:

** If you don't have Microsoft Visual C++ 2003, is it illegal to
redistribute the binary Python installer from www.python.org? Does
redistribution of Python also violate Microsoft's copyright on the CRT?
And if so, is someone developing in Python required to ask the customer
to download a binary installer from www.python.org (instead of shipping
a copy)?

** Not everyone that develops in Python has a license for Microsoft
Visual C++ 2003. I have the Microsoft Visual C++ 2003 Toolkit, but it
only allows me to link and redistribute a static version of msvcr71.
So, does this prevent me from using Py2Exe?

** It is apparently not possible to buy a license for VS2003 anymore,
as the product has expired. One can only buy a new get a license for
VS2005, which allows redistribution of msvcr81.dll, but not
msvcr71.dll. Microsoft said something about a right to "downgrade the
compiler" once a license for VS2005 is bought, but I am not sure if
this applies to the crt redistribution rights as well.

I understand that Microsoft has donated Microsoft Visual C++ 2003
compilers to key Python developers. That is generous of them. But what
did they say about the crt licensing?

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


Re: class method question

2006-10-25 Thread Fredrik Lundh
Sylvain Ferriol wrote:

> can you explain why python does not see difference between instance 
> method and class method, having the same name

You're trying to put two objects with the same name in the same namespace.

> example
>  >>> class toto(object):
> ... def f(self):
> ... print('instance method')
> ... @classmethod
> ... def f(cls):
> ... print('class method')
> ...
>  >>> t=toto()
>  >>> t.f
> >
>  >>> t.f()
> class method
>  >>> toto.f()
> class method
> 
> if i do the same in ruby:

Python works better if you use it to write Python programs.



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


Re: python GUIs comparison (want)

2006-10-25 Thread Fredrik Lundh
Paul Boddie wrote:

> seem to have moved very far, despite Fredrik's efforts: what happened
> to Tkinter 3000 or was that a codename for something else?

the first Tk3K project solved 95% of the problems (*) I had
with Tkinter:

 http://effbot.org/zone/wck.htm

(especially when combined with OpenGL).

don't leave home without it.



*) the remaining five are better handled by application-specific 
abstractions.  like most other things in Python.

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


Re: [wxPython-users] Re:

2006-10-25 Thread Josiah Carlson

Michael S <[EMAIL PROTECTED]> wrote:
> If I create a threading.Thread derived class, and run
> the wxPython code in the main thread; using a lock,
> will I be able to suspend the Thread, even though it
> will run the C code, which is essentially a while loop
> looping through millions of lines of a text file?

If all your C code is doing is looping through lines in a text file, you
can rewrite it fairly reasonably in Python via 'for line in open(fn):'.

In terms of locks, you have to use a lock that can be acquired by either
thread (GUI or C), but that won't necessarily give you what you want;
the GUI thread in wxPython may still not like being called directly.

If you want the ability to easily restart your C code, you may want to
consider at least looking at the following page on coroutines in C:
http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html .  It would
allow you to do all of your GUI manipulation/updating in Python without
having to worry about locks or calling Python code from C.

 - Josiah


> --- Josiah Carlson <[EMAIL PROTECTED]> wrote:
> 
> > 
> > Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> > > At Tuesday 24/10/2006 23:25, Michael S wrote:
> > > 
> > > >I extended part of my program in C, since that
> > part
> > > >was too involved for Python. Now when I import
> > the
> > > >module I created and call its functions, I am
> > trying
> > > >to feedback some information bac to my wxPython
> > > >program. The function runs for a while and I
> > wanted to
> > > >update a progress bar, but when I call the
> > function of
> > > >my new module, wxPython doesn't respond when
> > wx.Timer
> > > >is supposed to fire.
> > > 
> > > Does your extension run on a separate thread? I
> > guess not. So the 
> > > wxPython code does not have a chance to run.
> > > Do it the other way: from your C code, call a
> > Python function which 
> > > in turn updates the progress bar (and keep it
> > simple!)
> > 
> > Unless the GUI thread has a chance to take passes
> > through the wxPython
> > mainloop, the progress bar, etc., may not actually
> > be updated on some
> > platforms.
> > 
> > Mr. Sherman would likely be better off creating a
> > new thread which
> > handles processing, which could update a C global
> > variable, which the
> > GUI thread can poll to update its progress bar, etc.
> >  Alternatively, if
> > the processing can be broken down into smaller
> > pieces, the secondary
> > thread can call the pieces and post events back to
> > the GUI thread to
> > update the progress bar (via explicit wx.PostEvent
> > or implicit
> > wx.CallAfter).
> > 
> > 
> >  - Josiah
> > 
> > 
> >
> -
> > To unsubscribe, e-mail:
> > [EMAIL PROTECTED]
> > For additional commands, e-mail:
> > [EMAIL PROTECTED]
> > 
> > 

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


Re: python GUIs comparison (want)

2006-10-25 Thread BartlebyScrivener

Well, I am woefully unqualified to speak to the general state of Python
gui frameworks, but I am in a similar situation as the OP, i.e., a
beginner looking to TRY some easy gui programming in Python. Not being
a computer science person, just an amateur scripter, I tend to learn
best from lots of examples.

With all of that as background, I downloaded the latest wxPython demos
and docs yesterday. I suggest that the OP do the same. The demo.py
program is an amazing piece of work. It's loaded with specific examples
which allow you to view the frame or dialog etc, and then look behind
it to see the code used to create it.

rd

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


Re: Python's CRT licensing on Windows <-- FUD

2006-10-25 Thread Fredrik Lundh
sturlamolden wrote:

 > On Windows, the standard Python 2.4 distro is compiled with Microsoft
 > Visual C++ 2003 and is shipped with msvcr71.dll as a part of the binary
 > installer. That is ok, as those who has a license for Microsoft Visual
 > C++ 2003 is allowed to redistribute msvcr71.dll. Without a license for
 > Microsoft Visual C++ 2003 one it not allowed to redistribute this DLL.

that's a myth, based on a flawed reading of the MS license.  to repeat
myself from various other fora:

   "As long as you're using a standard Python build, you don't need to
   buy VC7 to [legally redistribute the C runtime]. The python.org team
   use a properly licensed VC7 to build Python, which turns Python into
   "licensee software" and you into a "distributor" doing "further
   distribution" of Python to end users (with your own stuff added on
   top, of course).  And further distribution is perfectly okay, as long
   as you only ship the MS components together with proper "licensee
   software" (=Python), and that all parties respect the relevant
   portions of the original EULA (this basically means that you cannot
   use tricks to circumvent the MS EULA, e.g. by attempting to relicense
   the MS DLL's under less restrictive licenses or "viral" licenses.  The
   same applies to all other licensed components, of course. You cannot
   relicense the Python core either.)."

   "(If in doubt, consult a real lawyer. If you do, make sure that he/she
   understands the various levels here -- i.e. that "you" in the MS
   EULA applies to the Python developers, not yourself)."



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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Paul Rubin
Robin Becker <[EMAIL PROTECTED]> writes:
> > type(nx.array([1,2,3],dtype=nx.uint32)[0])
> > 
> 
> great, but do we have a pure python version?

array.array('L', [1,2,3])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web-based SSH

2006-10-25 Thread Paul Rubin
Astan Chee <[EMAIL PROTECTED]> writes:
> I was looking for a web-based SSH client (something like
> www.port42.com..but for some reason it doesnt work..can anyone verify

http://www.google.com/search?q=ssh+applet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class method question

2006-10-25 Thread Bruno Desthuilliers
Sylvain Ferriol wrote:
> hello
> can you explain why python does not see difference between instance
> method and class method, having the same name

Because class namespaces are dicts, and you can't have duplicate keys in
dicts. It's totally unrelated to class/instance method distinction (try
with any kind of attribute, you'll get the same result : only the last
attribute is kept).

> example
 class toto(object):
> ... def f(self):
> ... print('instance method')
>
> ... @classmethod
> ... def f(cls):
> ... print('class method')


 t=toto()
 t.f
> >
 t.f()
> class method
 toto.f()
> class method

Also note that Python classmethods can be called on instances. Here
you're calling the same function twice.

A python object is a data structure holding references to other objects.
One of these references points to a dict (named __dict__) storing the
object's own attributes ('instance' attributes), and another one (named
__class__) points to the class object - which is itself an object that
holds references to it's parent classes.

When a name is looked up on an object, the name is first looked up in
the object's __dict__, then in the class, then in the class's parent
classes...

If you want a Ruby-like behaviour, it's still possible, but you have to
do it by manually:

import types

class Rubysh(object):
@classmethod
def test(cls):
print "in classmethod test, cls : %s" % cls

def __init__(self):
def test(self):
print "in instance method test, self : %s" % self
self.test = types.MethodType(test, self, self.__class__)

Rubysh.test()
r = Rubysh()
r.test()

Also note that most python programmers may find this a bit confusing,
since they'd expect Rubish.test() and r.test() to resolve to the same
attribute...

> 
> if i do the same in ruby:

You're not "doing the same", you're doing something that *looks* the same.

While they look quite similar at first sight - and indeed share a lot of
characteristics (lightweight, highly dynamic, hi-level object languages)
-, Python and Ruby are very different beasts under the hood. So beware :
superficial similarities can hide very different meanings and behaviours.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting by item_in_another_list

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

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

Given these variables:

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

which of the following should the function yield?

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

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

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

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

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Robin Becker
Paul Rubin wrote:
> Robin Becker <[EMAIL PROTECTED]> writes:
>>> type(nx.array([1,2,3],dtype=nx.uint32)[0])
>>> 
>> great, but do we have a pure python version?
> 
> array.array('L', [1,2,3])
yes that works if @L is unsigned 32 bit. I guess >L is always 4 bytes. Part of 
my confusion comes from not realizing all the different 64 bit models. In 
python 
I can get away with the following

def add32(x, y):
"Calculate (x + y) modulo 2**32"
return ((x&0xL)+(y&0xL)) & 0xL

def calcChecksum(data):
"""Calculates TTF-style checksums"""
if len(data)&3: data = data + (4-(len(data)&3))*"\0"
sum = 0
for n in unpack(">%dl" % (len(data)>>2), data):
sum = add32(sum,n)
return sum

but my tests sometimes look a bit odd.

eg
self.assertEquals(add32(10, -6), 4)
self.assertEquals(add32(6, -10), -4&0xL)
self.assertEquals(add32(0x8000L, -1), 0x7FFF)
self.assertEquals(add32(0x7FFF, 1), 0x8000L)

-- 
Robin Becker

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


Re: To remove some lines from a file

2006-10-25 Thread Steve Holden
Sebastian Busch wrote:
> [EMAIL PROTECTED] wrote:
> 
>>... I would like to remove two lines from a file.
>>...
> 
> 
> I am quite new myself -- but wouldn't grep -v do that easier (and
> perhaps faster)?
> 
Kindly show how to use grep to solve this problem:

   Remove the first two lines that don't begin with "@" from a file.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Printing file with printer dialog

2006-10-25 Thread Marco Bonifazi
Hello!

I have a file (in my situation it is a Postscript file or a Pdf file,
but it isn't important).

I must send this file to a printer, using Python, and I need to select
the printer to which I want send this file.
Then I would use a Dialog Window.

I use PyGtk on Windows (but if I can open a dialog without PyGtk is
also good), I would know all methods to do it.

Thanks also if you don't answer!

Marco Bonifazi

http://www.bonifazi.eu

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


Re: web-based SSH

2006-10-25 Thread Dieter Deyke
Paul Rubin  writes:

> Astan Chee <[EMAIL PROTECTED]> writes:
>> I was looking for a web-based SSH client (something like
>> www.port42.com..but for some reason it doesnt work..can anyone verify
>
> http://www.google.com/search?q=ssh+applet

http://www.appgate.com/products/80_MindTerm/110_MindTerm_Download/

-- 
Dieter Deyke
mailto:[EMAIL PROTECTED] mailto:[EMAIL PROTECTED]
Vs lbh pna ernq guvf, lbh unir jnl gbb zhpu gvzr.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's CRT licensing on Windows <-- FUD

2006-10-25 Thread sturlamolden

Fredrik Lundh wrote:

I am not intentionally posting FUD.

>"As long as you're using a standard Python build, you don't need to
>buy VC7 to [legally redistribute the C runtime]. The python.org team
>use a properly licensed VC7 to build Python, which turns Python into
>"licensee software" and you into a "distributor" doing "further
>distribution" of Python to end users (with your own stuff added on
>top, of course).

That makes sence. One does not need a VC7 license to sell (aka
"distribute") software from a store either.

>And further distribution is perfectly okay, as long
>as you only ship the MS components together with proper "licensee
>software" (=Python), and that all parties respect the relevant
>portions of the original EULA

Is further "distribution" okay if it is only accompanied by the python
runtime DLL (as is the case when using Py2Exe) or should the entire
python-2.4.4.msi from python.org be "distributed"?

>"(If in doubt, consult a real lawyer. If you do, make sure that he/she
>understands the various levels here -- i.e. that "you" in the MS
>EULA applies to the Python developers, not yourself)."

I certainly don't understand the EULA, and thus I cannot make sure that
I lawyer understands it either. But I can certainly find a lawyer that
charges  an hour and pretends to understand it. I am sure buying a
copy of VC7 is a lot cheaper.

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


Re: Current stackdepth outside PyEval_EvalFrameEx

2006-10-25 Thread Fabiano Sidler
On Tuesday 24 October 2006 17:05, Neil Cerutti wrote:
> Perhaps the inspect module will help?  See 3.11.4 The Interpreter
> Stack.

No, sorry if I didn't eplain it well enough. I meant the object stack
of the current frame, not the frame stack. In my function, I wanted to
return the list of objects on the object stack (f_valuestack) in the caller's 
frame. For this, I must have or compute the number of objects on this stack,
but don't have an idea how to do it.

Thanks in advance!
Fips
-- 
http://mail.python.org/mailman/listinfo/python-list


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

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

Thanks.

Cliff

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


Re: Python's CRT licensing on Windows <-- FUD

2006-10-25 Thread manuelg
sturlamolden wrote:

> I certainly don't understand the EULA, and thus I cannot make sure that
> I lawyer understands it either. But I can certainly find a lawyer that
> charges  an hour and pretends to understand it. I am sure buying a
> copy of VC7 is a lot cheaper.

When you buy that copy of VC7, buy me one too.  By your logic, it will
_still_ be cheaper than  for a lawyer, so you win!

Thanks in advance!

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Martin v. Löwis
Robin Becker schrieb:
> def add32(x, y):
> "Calculate (x + y) modulo 2**32"
> return ((x&0xL)+(y&0xL)) & 0xL

That's redundant; it is sufficient to write

  return (x+y) & 0x

> def calcChecksum(data):
> """Calculates TTF-style checksums"""
> if len(data)&3: data = data + (4-(len(data)&3))*"\0"
> sum = 0
> for n in unpack(">%dl" % (len(data)>>2), data):
> sum = add32(sum,n)
> return sum

That's also redundant; I'd write

def calcChecksum(data):
   data += "\0\0\0\0"[:len(data)&3]
   return sum(unpack(">%dl" % (len(data)>>2), data)) & 0x

I.e. it is sufficient to truncate to 32 bits at the end, instead of
doing so after each addition.

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread Martin v. Löwis
Robin Becker schrieb:
> Of course the actual semantics is dependent on what C unsigned
> arithmetic does so we're relying on that being the same everywhere.

Assuming that ULONG has the same width on all systems, the outcome
is actually mandated by the C standard: unsigned arithmetic is
defined to operate modulo (max_uint+1) (even if that is not a power
of two).

> This algorithm was pretty simple in Python until 2.3 when shifts over
> the end of ints started going wrong.

Actually, they start going *right* :-) Addition of two positive numbers
never gives a negative result, in mathematics.

> where while it might be reasonable to do testing it seems the tests
> aren't very sensible eg what is -6 doing in a u32 test? This stuff just
> about works on a 32 bit machine, but is failing miserably on a 64bit
> AMD. As far as I can see I just need to use masked longs throughout.

Exactly.

> In a C extension I can still do the computation exfficiently on a 32bit
> machine, but I need to do masking for a 64 bit machine.

Well, no. You just need to find a 32-bit unsigned integer type on the
64-bit machine. Typically, "unsigned int" should work fine (with
only the Cray being a notable exception, AFAIK). IOW, replace ULONG
with uint32_t wherever you really mean an unsigned 32-bit type,
then use stdint.h where available, else define it to unsigned int
(with a build-time or run-time test whether sizeof(unsigned int)==4).

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread sturlamolden

Robin Becker wrote:
>
> > ULONG CalcTableChecksum(ULONG *Table, ULONG Length)
> > {
> > ULONG Sum = 0L;
> > ULONG *Endptr = Table+((Length+3) & ~3) / sizeof(ULONG);
> >
> > while (Table < EndPtr)
> > Sum += *Table++;
> > return Sum;
> > }

Is this what you want?

import numpy
def CalcTableChecksum(Table, Length=None):
   tmp = numpy.array(Table,dtype=numpy.uint32)
   if Length == None: Length = tmp.size
   endptr = ((Length+3) & ~3) / 4
   return (tmp[0:endptr]).sum()





as nx
type(nx.array([1,2,3],dtype=nx.uint32)[0])



> so effectively we're doing only additions and letting bits roll off the end.
>
> Of course the actual semantics is dependent on what C unsigned arithmetic does
> so we're relying on that being the same everywhere.
>
> This algorithm was pretty simple in Python until 2.3 when shifts over the end 
> of
> ints started going wrong. For some reason we didn't do the obvious and just do
> everything in longs and just mask off the upper bits. For some reason 
> (probably
> my fault) we seem to have accumulated code like
>
> def _L2U32(L):
>  '''convert a long to u32'''
>  return unpack('l',pack('L',L))[0]
>
>
> if sys.hexversion>=0x0203:
>  def add32(x, y):
>  "Calculate (x + y) modulo 2**32"
>  return _L2U32((long(x)+y) & 0xL)
> else:
>  def add32(x, y):
>  "Calculate (x + y) modulo 2**32"
>  lo = (x & 0x) + (y & 0x)
>  hi = (x >> 16) + (y >> 16) + (lo >> 16)
>  return (hi << 16) | (lo & 0x)
>
> def calcChecksum(data):
>  """Calculates TTF-style checksums"""
>  if len(data)&3: data = data + (4-(len(data)&3))*"\0"
>  sum = 0
>  for n in unpack(">%dl" % (len(data)>>2), data):
>  sum = add32(sum,n)
>  return sum
>
> and also silly stuff like
>
> def testAdd32(self):
>  "Test add32"
>  self.assertEquals(add32(10, -6), 4)
>  self.assertEquals(add32(6, -10), -4)
>  self.assertEquals(add32(_L2U32(0x8000L), -1), 0x7FFF)
>  self.assertEquals(add32(0x7FFF, 1), _L2U32(0x8000L))
>
> def testChecksum(self):
>  "Test calcChecksum function"
>  self.assertEquals(calcChecksum(""), 0)
>  self.assertEquals(calcChecksum("\1"), 0x0100)
>  self.assertEquals(calcChecksum("\x01\x02\x03\x04\x10\x20\x30\x40"), 
> 0x11223344)
>  self.assertEquals(calcChecksum("\x81"), _L2U32(0x8100L))
>_L2U32(0x8000L))
>
> where while it might be reasonable to do testing it seems the tests aren't 
> very
> sensible eg what is -6 doing in a u32 test? This stuff just about works on a 
> 32
> bit machine, but is failing miserably on a 64bit AMD. As far as I can see I 
> just
> need to use masked longs throughout.
>
> In a C extension I can still do the computation exfficiently on a 32bit 
> machine,
> but I need to do masking for a 64 bit machine.
> -- 
> Robin Becker

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


Re: unsigned 32 bit arithmetic type?

2006-10-25 Thread sturlamolden

Robin Becker wrote:

> > ULONG CalcTableChecksum(ULONG *Table, ULONG Length)
> > {
> > ULONG Sum = 0L;
> > ULONG *Endptr = Table+((Length+3) & ~3) / sizeof(ULONG);
> >
> > while (Table < EndPtr)
> > Sum += *Table++;
> > return Sum;
> > }

Is this what you want?

import numpy
def CalcTableChecksum(Table, Length=None):
   tmp = numpy.array(Table,dtype=numpy.uint32)
   if Length == None: Length = tmp.size
   endptr = ((Length+3) & ~3) / 4
   return (tmp[0:endptr]).sum()

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


Re: python html 2 image (png)

2006-10-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
>> what tools are you using to do that today?
> 
> where are many of EXE programs
> but i need python solution for adding it to my automate program under
> lunix

Whatever lunix is, under linux, a popular free OS you could e.g. use 
PyKDE and let Qt render a KHTML-component into an image.



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


  1   2   3   >