Re: iterating over two arrays in parallel?

2008-08-29 Thread Terry Reedy



[EMAIL PROTECTED] wrote:

I want to interate over two arrays in parallel, something like this:

a=[1,2,3]
b=[4,5,6]

for i,j in a,b:
print i,j

where i,j would be 1,4,2,5,   3,6  etc.

Is this possible?


How to fish for yourself:
search 'Python loop two arrays parallel' and second hit with Google is
http://docs.python.org/tut/node7.html
which has this entry
To loop over two or more sequences at the same time, the entries can be 
paired with the zip() function.


 questions = ['name', 'quest', 'favorite color']
 answers = ['lancelot', 'the holy grail', 'blue']
 for q, a in zip(questions, answers):
... print 'What is your %s?  It is %s.' % (q, a)
... 
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.


Or go to the Tutorial directly, expand the chapter headings, and notice 
that 5. Data Structures has section 5.6 Looping Techniques.


Indeed, I recommend that you read thru at least the first 9 chapters.

tjr

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


Re: Lining Up and PaddingTwo Similar Lists

2008-08-29 Thread castironpi
On Aug 29, 12:29 am, W. eWatson [EMAIL PROTECTED] wrote:
 castironpi wrote:

  This gets you your list.  What do you mean by 'missing member of

 (a.dat, a.txt) is a pair. (None, a.txt) has a.dat missing. I just need to
 issue a msg to the user that one member of a file pair is missing. Both
 files need to be present to make sense of the data. pairs'?  If you mean, 
 'set of elements that appear in both' or 'set
  that appears in one but not both', you can short circuit it at line
  14.

  -warning, spoiler-

 It looks like you went beyond the call of duty, but that's fine. It looks
 like I have a few new features to learn about in Python. In particular,
 dictionaries. Thanks.

 Actually, the file names are probably in order as I pick them up in XP. I
 would think if someone had sorted the folder, that as one reads the folder
 they are in alpha order, low to high.

 --
                                     W. Watson
               (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
                Obz Site:  39° 15' 7 N, 121° 2' 32 W, 2700 feet

I don't think that's guaranteed by anything.  I realized that
'dat.sort()' and 'txt.sort()' weren't necessary, since their contents
are moved to a dictionary, which isn't sorted.

both= set( datD.keys() ) set( txtD.keys() )

This will get you the keys (prefixes) that are in both.  Then for
every prefix if it's not in 'both', you can report it.

Lastly, since you suggest you're guaranteed that 'txt' will all share
the same extension, you can do away with the dictionary and use sets
entirely.  Only if you can depend on that assumption.

I took a look at this.  It's probably more what you had in mind, and
the dictionaries are overkill.

import os.path
dat= ['a.dat', 'c.dat', 'g.dat', 'k.dat', 'p.dat']
datset= set( [ os.path.splitext( x )[ 0 ] for x in dat ] )
print datset
txt= ['a.txt', 'b.txt', 'g.txt', 'k.txt', 'r.txt', 'w.txt']
txtset= set( [ os.path.splitext( x )[ 0 ] for x in txt ] )
print txtset
both= txtset  datset
for d in datset- both:
print '%s.dat not matched'% d
for t in txtset- both:
print '%s.txt not matched'% t

OUTPUT:

set(['a', 'p', 'c', 'k', 'g'])
set(['a', 'b', 'g', 'k', 'r', 'w'])
p.dat not matched
c.dat not matched
r.txt not matched
b.txt not matched
w.txt not matched
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple values for one key

2008-08-29 Thread Willi Richert
Hi,

try defaultdict:

In [1]: from collections import defaultdict

In [2]: d=defaultdict(list)

In [3]: d[1].append(7)

In [4]: d[1].append(8)

In [5]: d
Out[5]: defaultdict(type 'list', {1: [7, 8]})

In [6]: d[1]
Out[6]: [7, 8]

Regards,
wr

Am Donnerstag 28 August 2008 19:02:55 schrieb Ron Brennan:
 I have another question.

 How would like to be able to add the contents on the values for one key.

 key['20001']:[978, 345]

 How can I do this?

 Thanks,
 Ron

 On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers

 [EMAIL PROTECTED] wrote:
  norseman a écrit :
   Terry Reedy wrote:
  Ron Brennan wrote:
  Hello,
How would I create a dictionary that contains multiple values for
  one key.
 
  Make the value a collection object (set or list if you plan to add and
  delete).
 
   I'd also like the key to be able to have duplicate entries.
 
 
  Dict keys must be hashable and unique.
 
  tjr
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 
  
 
  First part I understand, second is still giving me a problem.
 
  For some reason I still want keys to be dbf column headers.
  like:
 
  name:address:zip so forth
   --- --- --
  guy: unknown:0
  girl: 123 tiny street:12345
  boy:321 here:3
  gal:999 over there: 5
  so forth
 
  Thus one key has many values. And you can then index on whatever key(s)
  you wish - name,zip...
 
  You can either use 1/ a list of dicts, or 2/ a dict mapping keys to
  lists.
 
  1/
  records = [
{name:guy, address:unknown,zip:0},
{name:girl, address:123 tiny street,zip:12345},
{name:boy, address:321 here,zip:3},
{name:gal, address:999 over there,zip:5},
  ]
 
  keys = (name, address, zip)
 
  print :.join(keys)
  print - * len(:.join(keys))
  for record in records:
 data = [record[key] for key in keys]
 print :.join(data)
 
 
  2/
  records = dict(
 name=[guy, girl, boy, gal],
 address=[unknown,123 tiny street,321 there,999 over there],
 zip=[0, 12345, 3, 5]
 )
 
  keys = (name, address, zip)
  nb_records = len(records[keys[0]])
 
  print :.join(keys)
  print - * len(:.join(keys))
  for i in xrange(nb_records):
 data = [data[key][i] for key in keys]
 print :.join(data)
 
 
  You are of course entitled the right to prefer the second solution, but
  then I hope I'll never have to maintain your code, since it's obviously
  not an appropriate data structure.
 
  With billions plus records,
 
 
  With billions plus records, it may be time to move to a serious RDBMS.
  Which btw will provide solution 1, or a lighter version of it using a
  list of tuples, ie:
 
  cursor = connection.cursor()
  cursor.execute(select name, address, zip from peoples)
  records = cursor.fetchall()
 
  # at this time, you have :
  #records = [
  #   (guy, unknown,0,),
  #   (girl, 123 tiny street,12345,),
  #   (boy, 321 here,3,),
  #   (gal, 999 over there, 5,),
  #]
 
 
  (snip)
 
  OK - I know I missed the whole concept of a Python Dictionary.
 
 
  Bad thing for you, since it's the central datastructure in Python.
 
  I haven't read anything as yet that gives a clear picture of what it is
  and
 
  what it is for.
 
  Then you failed to read the FineManual's tutorial, which is where you
  should have started:
 
  http://docs.python.org/tut/node7.html#SECTION00750
 
  Do yourself a favour : read the above first, then if you still have
  questions about dicts, we'll gladly try to help.
 
  And do yourself another favour : learn about SQL, relational model and
  RDBMS.
 
  (snip description of why the OP *really* wants a RDBMS)
 
  --
  http://mail.python.org/mailman/listinfo/python-list


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

Re: Tough Guy Competition

2008-08-29 Thread alex23
On Aug 29, 3:45 pm, W. eWatson [EMAIL PROTECTED] wrote:
 Something to do on your weekends. [non-related link clipped]

Another thing to do with your weekends would be to -not spam-.

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


Re: Lining Up and PaddingTwo Similar Lists

2008-08-29 Thread Paul Rubin
W. eWatson [EMAIL PROTECTED] writes:
 [a.dat, c.dat, g.dat, k.dat, p.dat]
 [a.txt, b.txt, g.txt, k.txt r.txt, w.txt]
 
 What I need is to pair up items with the same prefix and use None,
 or some marker, to indicate the absence of the opposite item. 

This is functionally influenced but should be straightforward:

dat = ['a.dat', 'c.dat', 'g.dat', 'k.dat', 'p.dat']
txt = ['a.txt', 'b.txt', 'g.txt', 'k.txt', 'r.txt', 'w.txt']

# just get the portion of the filename before the first period
def prefix(filename):
return filename[:filename.find('.')]

# make a dictionary mapping prefixes to filenames
def make_dict(plist):
return dict((prefix(a),a) for a in plist)

pdat = make_dict(dat)
ptxt = make_dict(txt)

# get a list of all the prefixes, use set to remove
# duplicates, then sort the result and look up each prefix.
for p in sorted(set(pdat.keys() + ptxt.keys())):
print pdat.get(p), ptxt.get(p)
--
http://mail.python.org/mailman/listinfo/python-list


Python-2.3.4 on OSF1 V4.0?

2008-08-29 Thread Ivo Raisr
Hi Edmond and any interested reader,
I've successfully patched _socket extension of python 2.5.1 to build
on OSF1 V4.0 with gcc 4.1.2.
The following construct is put right after #include Python.h and
#include structmember.h:
#define _POSIX_PII_SOCKET
#define _LIBC_POLLUTION_H_

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


computer support

2008-08-29 Thread atrooja1998
hello every body in the group
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with list.insert

2008-08-29 Thread SUBHABRATA
Dear group,
Thanx for your idea to use dictionary instead of a list. Your code is
more or less, OK, some problems are there, I'll debug them. Well, I
feel the insert problem is coming because of the Hindi thing.
And Python2.5 is supporting Hindi quite fluently.
I am writing in Python2.5.1.
Best Regards,
Subhabrata.

Terry Reedy wrote:
 SUBHABRATA, I recommend you study this excellent response carefully.

 castironpi wrote:
  On Aug 28, 11:13 am, SUBHABRATA [EMAIL PROTECTED] wrote:
 -.
 
  Instead split up your inputs first thing.
 
  trans= { 'a': 'A', 'at': 'AT', 'to': 'TO' }
  sample= 'a boy at the park walked to the tree'
  expected= 'A boy AT the park walked TO the tree'

 It starts with a concrete test case -- an 'executable problem
 statement'.  To me, this is cleared and more useful than the 20 lines of
 prose you used.  A single line English statement would be Problem:
 Replace selected words in a text using a dictionary.  Sometimes, less
 (words) really is more (understanding).

 If the above is *not* what you meant, then give a similarly concrete
 example that does what you *do* mean.

  sample_list= sample.split( )
  for i, x in enumerate( sample_list ):
  if x in trans:
  sample_list[ i ]= trans[ x ]

 Meaningful names make the code easy to understand.  Meaningless numbered
 'a's require each reader to create meaningful names and associate them
 in his/her head.  But that is part of the job of the programmer.

  result= ' '.join( sample_list )
  print result
  assert result== expected

 It ends with an automated test that is easy to rerun should the code in
 between need to be modified.  Assert only prints something if there is
 an error.  With numerous tests, that is what one often wants.  But with
 only one, your might prefer 'print' instead of 'assert' to get a more
 reassuring and satisfying 'True' printed.

  Then replace them as you visit each one, and join them later.

 If you are using Hindi characters, you might want to use Python3 when it
 arrives, since it will use Unicode strings as the (default) string type.
   But for posting here, stick with the ascii subset.

 Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list


Re: computer support

2008-08-29 Thread andrew
On 2008-08-29, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 hello every body in the group

Hello Dr Nick :-)

-- 
http://www.andrews-corner.org
--
http://mail.python.org/mailman/listinfo/python-list


u just click, u get some dollars

2008-08-29 Thread pavi
http://www.onlineincomess.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fastest way to write huge files

2008-08-29 Thread Tim Golden

Terry Reedy wrote:



Mohamed Yousef wrote:

let's say , I'm moving large files through network between devices
what is the fastest way to do this ?
what i came up with :-


Use your OS's network copy command.  On unix, that was once uucp.  On 
Windows, I drag-and-drop to/from a Network Neighborhood location, 
including to a printer, so I don't know whether you can use copy and if 
so how.


For completeness' sake, on Windows you could use any of the following
techniques with a UNC as the destination (and/or source):

http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html

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


PyDoc in Windows Vista

2008-08-29 Thread Tyler Shopshire
I can't seem to access the pydoc sever from my web browser. I start the 
server from the command prompt and everything seems to be working fine, 
then I got to http://localhost:/ and it doesn't work. I also tried 
starting the graphical mode with the -g parameter but I still cannot use 
PyDoc. It works on my Ubuntu Partition so I do know how to use it. Any 
help is appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


PyDoc in Vista

2008-08-29 Thread Tyler Shopshire
I can't seem to get Pydoc up and running in windows Vista. I can search 
for modules manually by using the pydoc module_name command but if i 
try to set up an http server, it says the server is up and running but I 
can't access it in FF or IE. Any help is appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Syntax error in .py file and globals variable values not available.

2008-08-29 Thread Alexis Boutillier

Timothy Grant a écrit :

On Thu, Aug 28, 2008 at 1:40 AM, Alexis Boutillier
[EMAIL PROTECTED] wrote:

Timothy Grant a écrit :

On Wed, Aug 27, 2008 at 2:49 AM, Alexis Boutillier
[EMAIL PROTECTED] wrote:

Hi,

I have a strange behaviour of python with pdb and import statement.
Here is the example code :

file my1.py:
import my2

file my2.py:
a=5
toto

I intentionnaly put a syntax error in file my2.py.

If I run python -i my2.py and run pdb I got :
NameError: name 'toto' is not defined

import pdb
pdb.pm()

- toto

print a

5

If I run python -i my1.py and run pdb I got :
NameError: name 'toto' is not defined

import pdb
pdb.pm()

- toto

print a

None

Why can't I get access to variable a in pdb when the process generating
the
error came from an import statement ?

With python 2.3.5, it works fine and in the two cases I get the correct
value of 5 for variable a.
with python 2.43,2.5.1,2.5.2, it doesn't work and I get None value for
variable a.

Somebody can explain me this behaviour ?


Thanks.
--
Boutillier Alexis
Methodology engineer

Arteris SA
The Network-on-Chip Company TM
www.arteris.net

6 par Ariane Immeuble Mercure
78284 Guyancourt Cedex
France
Office: (+33) 1 61 37 38 71
Fax:(+33) 1 61 37 38 41
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list



Because of the syntax error the module wasn't loaded.

What kind of behaviour would you expect on code that has been flagged
as not executable?


I got the same behaviour with :
file my2.py:
a=5
raise SystemError,

In pdb, I can't have the value of attribute a.
So this is not linked to the fact that it is a SyntaxError or a SystemError.

I expect to be able to have the value of all attributes that have been used
before the error occured.
This is problematic because in a more complicated code, you can't have the
value of the attribute that was used before the error occured.
Python know that this attribute exist, it only don't have its value. other
attribute affected are : __name__,__doc__,__file__.

--
Boutillier Alexis
Methodology engineer

Arteris SA
The Network-on-Chip Company TM
www.arteris.net

6 par Ariane Immeuble Mercure
78284 Guyancourt Cedex
France
Office: (+33) 1 61 37 38 71
Fax:(+33) 1 61 37 38 41
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list



So if you were writing C code and the file failed to compile you would
still expect to have a working executable that just worked up until
the point of the syntax error?

I'm not sure why you just don't fix the syntax error and move on.




As you can see in my last response, this problem is not linked to the 
type of error, If I raise a SystemError instead of creating a 
SyntaxError I still can't access variable defined before the error.



--
Boutillier Alexis
Methodology engineer

Arteris SA
The Network-on-Chip Company TM
www.arteris.net

6 par Ariane Immeuble Mercure
78284 Guyancourt Cedex
France
Office: (+33) 1 61 37 38 71
Fax:(+33) 1 61 37 38 41
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking if the file is a symlink fails

2008-08-29 Thread [EMAIL PROTECTED]
On Aug 28, 10:20 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  Do you mean the following is deprecated ?
 http://docs.python.org/lib/module-stat.html

 From the documentation -

  S_ISLNK( mode)
      Return non-zero if the mode is from a symbolic link.

 As that page states, that's a function used to interpret a mode flag
 returned by os.stat, os.fstat, or os.lstat.  It obviously won't give you
 the result you're looking for if you use a stat function that *follows*
 symbolic links.

 /F

Thank you Fredrick and Miles,

stat() is on the actual file and not on the symlink. That explains.

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


os.ChDir() not thread-safe; was : Is tempfile.mkdtemp() thread-safe?

2008-08-29 Thread Gabriel Rossetti

Gabriel Rossetti wrote:

Hello,

I'm using tempfile.mkdtemp() in a multithreading program and I've been 
having problems with it. Sometimes it tells me the file I'm trying to 
access (in the directory created with tempfile.mkdtemp()) doesn't 
exist. I suspect that tempfile.mkdtemp() returns the same directory to 
different threads sometimes. Does anyone know anything about this or 
have a solution? I have to create unique and temp. directories to use 
an external program that creates a temp. file with the same name every 
time, thus if I want to call it from several threads, each call has to 
be from a different directory.


Thank you,
Gabriel


I think I found what was wrong, I was using os.chDir(), and the current 
directory is shared by all threads :


http://www.biais.org/blog/index.php/2007/01/23/19-python-threads-and-oschdir
http://bugs.python.org/issue1367

I hope this helps anyone that ever has such a problem!

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


microsoft terminal server

2008-08-29 Thread yqyq22
HI,
i would like to know if there is a way to create a python script for
automate mstsc.exe username and pwd credential, i mean i would create
a script that first open mstsc.exe and in the same time is able to
fill [computer+username+pwd].
Regards
thanks a lot in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python svn bindings for Subversion?

2008-08-29 Thread Mike B
On Thu, 28 Aug 2008 19:58:10 GMT, Matthew Woodcraft [EMAIL PROTECTED]
wrote:

Mike B writes:
 I'm trying to get Subversion 'hook scripts' working on an Ubuntu box and the
 following fails.

 from svn import fs, repos, core, delta
[...]
 'svn' appears to be a SWIG wrapper and could be what I'm looking for, but I
 cannot find it anywhere.

 Can anyone point me in the right direction.


It's maintained as part of the main Subversion distribution.

http://svn.collab.net/viewvc/svn/trunk/subversion/bindings/swig/

In Ubuntu, it should be in the python-subversion package.

That fixed it.

Thanks

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


Re: subclassing complex

2008-08-29 Thread Patrick Maupin
On Aug 29, 12:17 am, BiDi [EMAIL PROTECTED] wrote:
 I have been trying to subclass complex, but I am not able to get the
 right-hand arithmetic operators working.

 As shown below, if an object of my subclass 'xcomplex' is added on the
 right of a 'comlex' object, the type returned is 'complex', not
 'xcomplex'.

 I've tried subclassing float and it works fine (don't even need to
 define __coerce__ in that case)

 Is this a bug, or am I missing something?

I think the issue is that Python first tries to use the __add__ method
of the left-most object, and only attempts to use __radd__ with the
right-most object if that fails.  Because you have subclassed the
complex class, the __add__ method of the complex number will work
fine, returning a complex result.

If you want to keep that from working, you probably want to just
inherit from 'object' rather than 'complex', and reimplement all the
methods you care about (possibly with a very simple wrapper around an
internal complex number).

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


help needed with dictionary

2008-08-29 Thread lee
  hi all,
i am a newbie in python.  i was trying to work with dictionaries.  i
wanted to input values  through command line and store the values in a
dictionary. i mean for the same key , multiple values. can any1
suggest me how can i do it.thank you

i tried this, but the old value is replaced by new one, but i want to
store al values entered by user.
kev = {}
if kev.has_key('Name'):
kev['Name'].append(person_name)
print 'name is ', kev['Name']
else:
kev['Name'] = [person_name]
print kevin's name is %s % kev['Name']

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


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-29 Thread Ken Starks

[EMAIL PROTECTED] wrote:

x=[1,2,3]
and
x=[1,2,3,]

are exactly the same, right?

I'm generating some python data, and it's less error prone
to not treat the last element specially, but I want to be
sure I'm generating an equivalent data structure.

Many TIA!
Mark


 x=[1,2,3,]
 repr(x)
[1,2,3]

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


Re: help needed with dictionary

2008-08-29 Thread Bruno Desthuilliers

lee a écrit :

  hi all,
i am a newbie in python.  i was trying to work with dictionaries.  i
wanted to input values  through command line and store the values in a
dictionary. i mean for the same key , multiple values. can any1
suggest me how can i do it.thank you

i tried this, but the old value is replaced by new one, but i want to
store al values entered by user.
kev = {}
if kev.has_key('Name'):
kev['Name'].append(person_name)
print 'name is ', kev['Name']
else:
kev['Name'] = [person_name]
print kevin's name is %s % kev['Name']



Please post the minimal *running* code exhibiting your problem. The 
above snippet raises a NameError about person_name on line 3.


Anyway, looking at my crystal ball, I'd say that you're (re)binding the 
variable 'kev' to a new empty dict each time.


Here's a working snippet:

import sys

kev = {}
try:
while True:
answer = raw_input(type a name :)
answer = answer.strip()
if answer:
try:
kev['name'].append(answer)
except KeyError:
kev['name'] = [answer]
print name is now : %s %  .join(kev['name'])
print 

except KeyboardInterrupt:
sys.exit(bye)
--
http://mail.python.org/mailman/listinfo/python-list


Re: subclassing complex

2008-08-29 Thread Peter Otten
BiDi wrote:

 I have been trying to subclass complex, but I am not able to get the
 right-hand arithmetic operators working.
 
 As shown below, if an object of my subclass 'xcomplex' is added on the
 right of a 'comlex' object, the type returned is 'complex', not
 'xcomplex'.
 
 I've tried subclassing float and it works fine (don't even need to
 define __coerce__ in that case)
 
 Is this a bug, or am I missing something?

A minimal example is

 class Complex(complex):
... def __radd__(self, other): print radd
...
 1j + Complex()
1j

versus

 class Int(int):
... def __radd__(self, other): print radd
...
 1 + Int()
radd

I think the complex subclass should behave like the int subclass.
To get an authoritative answer you should file a bug report.

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


problem with execv command

2008-08-29 Thread dudeja . rajat
Hi,

I'm facing problem with the execv command:

my command is :
os.execv(' C:\Program Files\Subversion\bin\svn ', ( 'list', ' \
http://subversion.stv.abc.com/svn/Eng \ ' ) )

The error I'm getting is :
OSError: [Errno 22] Invalid argument


I tried using a variable for http path but still I'm getting the same error

Please help.
-- 
Regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: help needed with dictionary

2008-08-29 Thread Miles
On Fri, Aug 29, 2008 at 5:02 AM, lee wrote:
 i wanted to input values  through command line and store the values in a
 dictionary. i mean for the same key , multiple values.

http://mail.python.org/pipermail/python-list/2008-August/505509.html
http://mail.python.org/pipermail/python-list/2008-August/505584.html

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


class definition syntax

2008-08-29 Thread harryos
hi
i have seen some class definitions like

class MyClass(object):
def __init__(self):
   

what does the object keyword inside the braces in MyClass() mean?
Has it got any significance?

thanks in advance
harry
--
http://mail.python.org/mailman/listinfo/python-list


Re: class definition syntax

2008-08-29 Thread Diez B. Roggisch
harryos wrote:

 hi
 i have seen some class definitions like
 
 class MyClass(object):
 def __init__(self):

 
 what does the object keyword inside the braces in MyClass() mean?
 Has it got any significance?

It indicates a so-called new-style-class. The new style classes have been
available since python2.2:

http://docs.python.org/ref/node33.html

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


Re: microsoft terminal server

2008-08-29 Thread Tim Golden

[EMAIL PROTECTED] wrote:

HI,
i would like to know if there is a way to create a python script for
automate mstsc.exe username and pwd credential, i mean i would create
a script that first open mstsc.exe and in the same time is able to
fill [computer+username+pwd].


Haven't tried it, but in principle you should be
able to use the win32cred package from pywin32
to store your username / password and use an .rdp
file to automate the rest of the settings, including
the server.

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


Re: problem with execv command

2008-08-29 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 Hi,
 
 I'm facing problem with the execv command:
 
 my command is :
 os.execv(' C:\Program Files\Subversion\bin\svn ', ( 'list', ' \
 http://subversion.stv.abc.com/svn/Eng \ ' ) )
 
 The error I'm getting is :
 OSError: [Errno 22] Invalid argument
 
 
 I tried using a variable for http path but still I'm getting the same
 error
 
 Please help.

You need to either escape the backslashes in your path using \\, or use
python raw string literals like this:

rC:\foo

or use forward-slashes, which windows accepts as well.

Diez

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


Re: class definition syntax

2008-08-29 Thread Wojtek Walczak
On Fri, 29 Aug 2008 02:50:57 -0700 (PDT), harryos wrote:

 class MyClass(object):
 def __init__(self):


 what does the object keyword inside the braces in MyClass() mean?
 Has it got any significance?

It's inheritance. MyClass class inherits from object class.
Check out point 9.5 in the tutorial.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyImport_ImportModule deadlocks

2008-08-29 Thread Gabriel Genellina
En Thu, 28 Aug 2008 11:22:50 -0300, [EMAIL PROTECTED]  
[EMAIL PROTECTED] escribi�:



I have an embedded Python shell and everything works fine, however, in
my stdout catcher (in C to grab tracebacks) for some reason when I do
a :

PyImport_ImportModule( sys )

It deadlocks the process, is there a need for me to acquire locks
inside of my stdout catching function before calling that import?


The deadlock might be due to the import lock. But instead of analyzing  
that issue: why do you want to import sys? The sys module is always  
available. To access its attributes, use PySys_GetObject Co.


--
Gabriel Genellina

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

Iterating two arrays at once

2008-08-29 Thread mathieu
Hi there,

  just trying to figure out how to iterate over two array without
computing the len of the array:

  A = [1,2,3]
  B = [4,5,6]
  for a,b in A,B: # does not work !
print a,b

It should print:

  1,4
  2,5
  3,6

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


Re: Iterating two arrays at once

2008-08-29 Thread Matthias Bläsing
Am Fri, 29 Aug 2008 03:35:51 -0700 schrieb mathieu: 
   A = [1,2,3]
   B = [4,5,6]
   for a,b in A,B: # does not work !
 print a,b
 
 It should print:
 
   1,4
   2,5
   3,6

Hey,

zip is your friend:

for a,b in zip(A,B):
print a,b

does what you want. If you deal with big lists, you can use izip from 
itertools, which returns a generator.

from itertools import izip
for a,b in izip(A,B):
print a,b

HTH

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


Re: help needed with dictionary

2008-08-29 Thread lee
hi,
thank you, ur code was helpful   :)




On Aug 29, 2:18 pm, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 lee a écrit :



hi all,
  i am a newbie in python.  i was trying to work with dictionaries.  i
  wanted to input values  through command line and store the values in a
  dictionary. i mean for the same key , multiple values. can any1
  suggest me how can i do it.thank you

  i tried this, but the old value is replaced by new one, but i want to
  store al values entered by user.
  kev = {}
  if kev.has_key('Name'):
 kev['Name'].append(person_name)
 print 'name is ', kev['Name']
  else:
 kev['Name'] = [person_name]
  print kevin's name is %s % kev['Name']

 Please post the minimal *running* code exhibiting your problem. The
 above snippet raises a NameError about person_name on line 3.

 Anyway, looking at my crystal ball, I'd say that you're (re)binding the
 variable 'kev' to a new empty dict each time.

 Here's a working snippet:

 import sys

 kev = {}
 try:
  while True:
  answer = raw_input(type a name :)
  answer = answer.strip()
  if answer:
  try:
  kev['name'].append(answer)
  except KeyError:
  kev['name'] = [answer]
  print name is now : %s %  .join(kev['name'])
  print 

 except KeyboardInterrupt:
  sys.exit(bye)

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


Re: Iterating two arrays at once

2008-08-29 Thread Bruno Desthuilliers

mathieu a écrit :

Hi there,

  just trying to figure out how to iterate over two array without
computing the len of the array:

  A = [1,2,3]
  B = [4,5,6]
  for a,b in A,B: # does not work !
print a,b

It should print:

  1,4
  2,5
  3,6


for a, b in zip(A, B):
print a, b

or, using itertools (which might be a good idea if your lists are a bit 
huge):


from itertools import izip
for a, b in izip(A, B):
print a, b


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


Re: Iterating two arrays at once

2008-08-29 Thread mathieu
On Aug 29, 12:46 pm, Matthias Bläsing [EMAIL PROTECTED]
aachen.de wrote:
 Am Fri, 29 Aug 2008 03:35:51 -0700 schrieb mathieu:

A = [1,2,3]
B = [4,5,6]
for a,b in A,B: # does not work !
  print a,b

  It should print:

1,4
2,5
3,6

 Hey,

 zip is your friend:

 for a,b in zip(A,B):
 print a,b

 does what you want. If you deal with big lists, you can use izip from
 itertools, which returns a generator.

 from itertools import izip
 for a,b in izip(A,B):
 print a,b

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


problem with plotting

2008-08-29 Thread Anish Chapagain
hi,
I'm getting problem with the code below which after displaying graph
plotted in external window, doesnot closes itself, even after closing
the window of plotting the main python window shows processing.
code goes like this...

plot(col1, col2, linewidth=1.0)
xlabel('col1')
ylabel('col2')
title('Values from List created with file read')
grid(True)
savefig('col1 col2.pdf')
show()


is there any other function to be called after show() to close it
properly.

thank's for any help.

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


Re: class definition syntax

2008-08-29 Thread Ken Starks

harryos wrote:

hi
i have seen some class definitions like

class MyClass(object):
def __init__(self):
   

what does the object keyword inside the braces in MyClass() mean?
Has it got any significance?

thanks in advance
harry


It is a syntax used for 'new type' classes, not so new any more.

If you google that phrase, you get many references.

Here is a tutorial dating back to 2005.
http://www.geocities.com/foetsch/python/new_style_classes.htm


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


Re: class definition syntax

2008-08-29 Thread Bruno Desthuilliers

harryos a écrit :

hi
i have seen some class definitions like

class MyClass(object):
def __init__(self):
   

what does the object keyword


It's not a keyword.


inside the braces in MyClass() mean?


Answer is here:

http://docs.python.org/tut/node11.html#SECTION001150
http://docs.python.org/ref/class.html



Has it got any significance?


ironic
Nope, why ? It just look better that way...
/ironic

Harry, this neswgroup is - as you may have noticed by now - very newbie 
friendly. But this is not a reason for not reading *at least* the 
FineManual's tutorial.

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


Re: problem with plotting

2008-08-29 Thread [EMAIL PROTECTED]
On Aug 29, 6:01 am, Anish Chapagain [EMAIL PROTECTED] wrote:
 hi,
 I'm getting problem with the code below which after displaying graph
 plotted in external window, doesnot closes itself, even after closing
 the window of plotting the main python window shows processing.
 code goes like this...

 plot(col1, col2, linewidth=1.0)
 xlabel('col1')
 ylabel('col2')
 title('Values from List created with file read')
 grid(True)
 savefig('col1 col2.pdf')
 show()

 is there any other function to be called after show() to close it
 properly.

 thank's for any help.

 anish

what library/system are you using???
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating two arrays at once

2008-08-29 Thread Bruno Desthuilliers

mathieu a écrit :
(snip solution)


Thanks all !


FWIW, this has been discussed here *very* recently (a couple hours ago). 
Look for a thread named iterating over two arrays in parallel?, and 
pay special attention to Terry Reedy's answer.

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


translating create Semaphore to Linux

2008-08-29 Thread GHUM
hello,

in my application I am using

hSem = win32event.CreateSemaphore (None, 1,
1,stringincludinginterfaceandport)
rt=win32event.WaitForSingleObject (hSem, 0)
if rt != win32event.WAIT_TIMEOUT:
   really_do_start_my_app()
else:
   print application allready running

to make sure that only ONE instance of the application is running at a
time. (as it implements a local webserver, that is necessary. Two
webservers listening on one port is bad)

Now I am going to make this application run on Linux. How can I get
similiar behaviour on Linux?

I know of the .pid files that get written by some server processes ...
BUT they do not get cleaned up on unclean shutdown of the application.

is there some better method?

Or some module which wraps the details of .pid-files quite nicely?
(like trying to remove to check if other instance is still
running, failing properly on missing write privs etc.)

best wishes,

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


Re: translating create Semaphore to Linux

2008-08-29 Thread Diez B. Roggisch
GHUM wrote:

 hello,
 
 in my application I am using
 
 hSem = win32event.CreateSemaphore (None, 1,
 1,stringincludinginterfaceandport)
 rt=win32event.WaitForSingleObject (hSem, 0)
 if rt != win32event.WAIT_TIMEOUT:
really_do_start_my_app()
 else:
print application allready running
 
 to make sure that only ONE instance of the application is running at a
 time. (as it implements a local webserver, that is necessary. Two
 webservers listening on one port is bad)
 
 Now I am going to make this application run on Linux. How can I get
 similiar behaviour on Linux?
 
 I know of the .pid files that get written by some server processes ...
 BUT they do not get cleaned up on unclean shutdown of the application.
 
 is there some better method?
 
 Or some module which wraps the details of .pid-files quite nicely?
 (like trying to remove to check if other instance is still
 running, failing properly on missing write privs etc.)

You might consider using a cooperative file locking for that. I do this as
follows:


#---

class LockFileCreationException(Exception):
pass


#---

class LockObtainException(Exception):
pass


#---

class LockFile(object):

def __init__(self, name, fail_on_lock=False, cleanup=True):
self.name = name
self.cleanup = cleanup
try:
self.fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_APPEND)
except OSError, e:
if e[0] == 2:
raise LockFileCreationException()
self.file = os.fdopen(self.fd, w)
lock_flags = fcntl.LOCK_EX
if fail_on_lock:
lock_flags |= fcntl.LOCK_NB
try:
fcntl.flock(self.file, lock_flags)
except IOError, e:
if e[0] == 11:
raise LockObtainException()
raise


def __enter__(self):
return self.file


def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb):
self.file.close()
# we are told to cleanup after ourselves,
# however it might be that another process
# has done so - so we don't fail in that
# case.
if self.cleanup:
try:
os.remove(self.name)
except OSError, e:
if not e[0] == 2:
raise


You can use the LockFile as context, and either block until the lock is
released (which is most probably not what you want), or fail with
LockObtainException.

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


Re: problem with plotting

2008-08-29 Thread Anish Chapagain
On Aug 29, 12:24 pm, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:
 On Aug 29, 6:01 am, Anish Chapagain [EMAIL PROTECTED] wrote:





  hi,
  I'm getting problem with the code below which after displaying graph
  plotted in external window, doesnot closes itself, even after closing
  the window of plotting the main python window shows processing.
  code goes like this...

  plot(col1, col2, linewidth=1.0)
  xlabel('col1')
  ylabel('col2')
  title('Values from List created with file read')
  grid(True)
  savefig('col1 col2.pdf')
  show()

  is there any other function to be called after show() to close it
  properly.

  thank's for any help.

  anish

 what library/system are you using???- Hide quoted text -

 - Show quoted text -



Hi..
am using pylab

and have added the
 print plotting finished
after show() which get's printed in python main window but then
doesnot return to prompt and have to kill the window again.

regard's#
anish
--
http://mail.python.org/mailman/listinfo/python-list


Beginner's question about string's join() method

2008-08-29 Thread Macygasp
Hi,

Can anybody tell me why and how this is working:

 ','.join(str(a) for a in range(0,10))
'0,1,2,3,4,5,6,7,8,9'

I find this a little weird because join takes a sequence as argument;
so, it means that somehow, from the str(a) ...  expression, a
sequence can be generated.

If I write this:
 (str(a) for a in range(0,10))
generator object at 0x7f62d2e4d758
it seems i'm getting a generator.

Can anybody explain this to me, please?

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


Re: Python in a Nutshell -- Book vs Web

2008-08-29 Thread Cameron Laird
In article [EMAIL PROTECTED],
Fredrik Lundh  [EMAIL PROTECTED] wrote:
Cameron Laird wrote:

 No.  No, to an almost libelous extent.  

No matter what you write about, there's always a certain subcategory of 
potential readers who insist that collection, editing, filtering, 
structuring, clarification, and the author's real-life experience of the 
topic he's writing about has no value at all.  My guess is that they 
don't value their own time very highly.

/F


Insightful.  Well, I find it insightful; perhaps it's
a personal blindness on my part.  I expect programmers
to understand, for example, that two lines of code can
be a good day's production, in some circumstances,
while it's civilians and managers who scorn their
value on quantitative grounds.  It's hard for me to 
conceive of an expert programmer who doesn't esteem
what a high-quality book provides.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python in a Nutshell -- Book vs Web

2008-08-29 Thread Michele Simionato
On Aug 29, 1:44 pm, [EMAIL PROTECTED] (Cameron Laird) wrote:
 Insightful.  Well, I find it insightful; perhaps it's
 a personal blindness on my part.  I expect programmers
 to understand, for example, that two lines of code can
 be a good day's production, in some circumstances

My best days are the ones were I have a negative count of lines, i.e.
I am able to remove cruft ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: translating create Semaphore to Linux

2008-08-29 Thread Francesco Bochicchio
On 29 Ago, 13:28, GHUM [EMAIL PROTECTED] wrote:
 hello,

 in my application I am using

 hSem = win32event.CreateSemaphore (None, 1,
 1,stringincludinginterfaceandport)
 rt=win32event.WaitForSingleObject (hSem, 0)
 if rt != win32event.WAIT_TIMEOUT:
    really_do_start_my_app()
 else:
    print application allready running

 to make sure that only ONE instance of the application is running at a
 time. (as it implements a local webserver, that is necessary. Two
 webservers listening on one port is bad)

 Now I am going to make this application run on Linux. How can I get
 similiar behaviour on Linux?

 I know of the .pid files that get written by some server processes ...
 BUT they do not get cleaned up on unclean shutdown of the application.

 is there some better method?

 Or some module which wraps the details of .pid-files quite nicely?
 (like trying to remove to check if other instance is still
 running, failing properly on missing write privs etc.)

 best wishes,

 Harald

The best way I know to do it is to use fnctl.flock or fcntl.lockf
functions. I never used it, so can just point you to the
official documentation. The idea is that your applications should take
exclusive access to one of the application files, so that if it is
started a second time, the second run will find the file locked and
understand that there is an instance started.
AFAIK, if the process locking a files dies, the OS releases the lock,
so there is no possibility of stale locks (check this!).

Anyway, you could simply use your server socket as lock. It is not
possible to have two processes accepting connections on the same port,
the second process would receive an error 'Address already in use'.
You could use it as signal that there is
already an instance of the application running. This method should be
available in both Windows and Linux (and various
Unix flavours too), so your code would be more portable.

Ciao

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


Re: importing from .pyd

2008-08-29 Thread moijes12
On Jul 14, 4:11 pm, Kay Schluehr [EMAIL PROTECTED] wrote:
 On 14 Jul., 06:03, moijes12 [EMAIL PROTECTED] wrote:

  hi

  there is a .pyd file present in the same folder as the script abc.py
  by the name foo.pyd .I don't have foo.py .In the script abc.py I try

  import foo

  Error i get is
  ImportError: DLL load failed: The specified module could not be found.

 It looks like the module that was accessed is either corrupt
 ( unavailable entry point ) or it contains dependencies to other
 modules which are not available.

 At least the latter can be checked without access to the source using
 the DependencyWalker:

 http://www.dependencywalker.com/

 Notice that the message clearly indicates that Python found the module
 but failed to load it i.e. performing a LoadLibrary() which yielded a
 NULL pointer.

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


Re: translating create Semaphore to Linux

2008-08-29 Thread Tim Golden

GHUM wrote:

hSem = win32event.CreateSemaphore (None, 1,
1,stringincludinginterfaceandport)
rt=win32event.WaitForSingleObject (hSem, 0)
if rt != win32event.WAIT_TIMEOUT:
   really_do_start_my_app()
else:
   print application allready running

to make sure that only ONE instance of the application is running at a
time. 



Running a serious risk of teaching my grandmother, but...

... why use a Semaphore rather than a Mutex? Or why not
simply use the bound socket as its own mutex? I know
Windows won't allow you to rebind the same socket to the
same addr/port in two different processes (unless perhaps
you play some trickery with the socket options).

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


Re: eval() == evil? --- How to use it safely?

2008-08-29 Thread Fett
On Aug 28, 7:57 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:

So long story short: if I am expecting a dictionary of strings, I
should make a parser that only accepts a dictionary of strings then.
There is no safe way to use an existing construct.

That is what I was afraid of. I know I will have to deal with the
possibility of bad data, but considering my use (an acronym legend for
a database), and the fact that the site I plan to use should be
secure, these issues should be minimal. The users should be able to
spot any obvious false data, and restoring it should be simple.

Many thanks to all of you for your alarmist remarks. I certainly don't
want to, in any way, put my clients computers at risk by providing
unsafe code.

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


Re: translating create Semaphore to Linux

2008-08-29 Thread GHUM
Tim,

 ... why use a Semaphore rather than a Mutex?

as much as I understood the documentation at MSDN

http://msdn.microsoft.com/en-us/library/ms686927(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms686946(VS.85).aspx

a mutex seems to be nothing else than a special case of a semaphore?
That is, a semaphore can be created to allow  MAX_SEM_COUNT concurrent
runners, and MUTEX defaults to one and only one ...

The other api-spells are identical, like wait_for_...; so propably
I stumbled on the working Semaphore Code before, or in some ancient
win32 wrapper createMutex was not documented or something in that
aspect:)

 Or why notsimply use the bound socket as its own mutex? I know
 Windows won't allow you to rebind the same socket to the
 same addr/port in two different processes (unless perhaps
 you play some trickery with the socket options).

My experience was that this is correct for certain values of allow
and trickery. Sometimes the binding seems to get allowed but does
not work. Main reason is that the socket-bind happens somewhere in
medusa or someotherhttpsserverframeworkiuse; so to use it as a
semaphore I would have to dig there. I am not totally sure what
trickery on socket is played down there; and I prefer to stay as far
away as possible from that area.

Harald


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


Re: Beginner's question about string's join() method

2008-08-29 Thread Diez B. Roggisch
Macygasp wrote:

 Hi,
 
 Can anybody tell me why and how this is working:
 
 ','.join(str(a) for a in range(0,10))
 '0,1,2,3,4,5,6,7,8,9'
 
 I find this a little weird because join takes a sequence as argument;
 so, it means that somehow, from the str(a) ...  expression, a
 sequence can be generated.
 
 If I write this:
 (str(a) for a in range(0,10))
 generator object at 0x7f62d2e4d758
 it seems i'm getting a generator.
 
 Can anybody explain this to me, please?

string.join takes an iterable. A generator is an iterable. Expressions of
the form exp for vars in iterable are called generator
expressions, and yield a generator.

Thus your code works.

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


Re: translating create Semaphore to Linux

2008-08-29 Thread Tim Golden

GHUM wrote:

Tim,


... why use a Semaphore rather than a Mutex?


as much as I understood the documentation at MSDN

http://msdn.microsoft.com/en-us/library/ms686927(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms686946(VS.85).aspx

a mutex seems to be nothing else than a special case of a semaphore?
That is, a semaphore can be created to allow  MAX_SEM_COUNT concurrent
runners, and MUTEX defaults to one and only one ...

The other api-spells are identical, like wait_for_...; so propably
I stumbled on the working Semaphore Code before, or in some ancient
win32 wrapper createMutex was not documented or something in that
aspect:)


I think it hardly matters except that someone (like me :) )
coming to your code who's familiar with the uses of mutex
and semaphore elsewhere -- they're not Microsoft inventions
as I'm sure you realise -- will be a little stumped by the
fact that a mutex is pretty much the canonical recipe for
allowing only one instance of an app, yet you're using a
semaphore which can be used for slightly different
purposes. I'd be wondering whether you had some more
sophisticated model in mind which I was unable to fathom...




Or why notsimply use the bound socket as its own mutex? I know
Windows won't allow you to rebind the same socket to the
same addr/port in two different processes (unless perhaps
you play some trickery with the socket options).


My experience was that this is correct for certain values of allow
and trickery. Sometimes the binding seems to get allowed but does
not work. 


Fair enough.

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


Re: Lining Up and PaddingTwo Similar Lists

2008-08-29 Thread Boris Borcic

D,T=[dict((x.split('.')[0],x) for x in X) for X in (dat,txt)]
for k in sorted(set(D).union(T)) :
for S in D,T :
print '%-8s' % S.get(k,'None'),
print

HTH

W. eWatson wrote:
Maybe there's some function like zip or map that does this. If not, it's 
probably fairly easy to do with push and pop. I'm just checking to see 
if there's not some known simple single function that does what I want. 
Here's what I'm trying to do.


I have a list dat like (assume the items are strings even thought I'm 
omitting quotes.):

[a.dat, c.dat, g.dat, k.dat, p.dat]

I have another list called txt that looks like:
[a.txt, b.txt, g.txt, k.txt r.txt, w.txt]

What I need is to pair up items with the same prefix and use None, or 
some marker, to indicate the absence of the opposite item. That is, in 
non-list form, I want:

a.dat a.txt
None  b.txt
c.dat None
g.dat g.txt
k.dat k.txt
p.dat  None
None  r.txt
None  w.txt

Ultimately, what I'm doing is to find the missing member of pairs.


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


Re: eval() == evil? --- How to use it safely?

2008-08-29 Thread Fett
On Aug 29, 7:42 am, Fett [EMAIL PROTECTED] wrote:
 On Aug 28, 7:57 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:

 So long story short: if I am expecting a dictionary of strings, I
 should make a parser that only accepts a dictionary of strings then.
 There is no safe way to use an existing construct.

 That is what I was afraid of. I know I will have to deal with the
 possibility of bad data, but considering my use (an acronym legend for
 a database), and the fact that the site I plan to use should be
 secure, these issues should be minimal. The users should be able to
 spot any obvious false data, and restoring it should be simple.

 Many thanks to all of you for your alarmist remarks. I certainly don't
 want to, in any way, put my clients computers at risk by providing
 unsafe code.

On a related note, what if I encrypted and signed the data, then only
ran eval() on the string after it was decrypted and the signature
verified?

It has occurred to me that posting this data on a site might not be
the best idea unless I can be sure that it is not read by anyone that
it shouldn't be. So I figure an encrypting is needed, and as long as I
can sign it as well, then only people with my private signing key
could pass bad data, much less harmful strings.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fastest way to write huge files

2008-08-29 Thread Mohamed Yousef
Thanks all ,
but there is still something i forget to state -sorry - all
communication will be via Http with a server
so data is received via Http
so local network solutions won't work
the problem really starts after receiving data in storing them without
much of a CPU/Memory usage and with a good speed

@James Mills : didn't understand fully what you mean and how it will
improve writting effciency

Thanks,

Regards,
Mohamed Yousef

2008/8/29 Tim Golden [EMAIL PROTECTED]:
 Terry Reedy wrote:


 Mohamed Yousef wrote:

 let's say , I'm moving large files through network between devices
 what is the fastest way to do this ?
 what i came up with :-

 Use your OS's network copy command.  On unix, that was once uucp.  On
 Windows, I drag-and-drop to/from a Network Neighborhood location, including
 to a printer, so I don't know whether you can use copy and if so how.

 For completeness' sake, on Windows you could use any of the following
 techniques with a UNC as the destination (and/or source):

 http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html

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

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


Re: file data to list

2008-08-29 Thread Sion Arrowsmith
Emile van Sebille  [EMAIL PROTECTED] wrote:
data = zip(*[xx.split() for xx in open('data.txt').read().split(\n)])

Files are iterable:

data = zip(*[xx.rstrip().split() for xx in open('data.txt')])

saves you creating the extra intermediate list resulting from split(\n).

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

Re: iterating over two arrays in parallel?

2008-08-29 Thread Cousin Stanley

 I want to interate over two arrays in parallel, 
 something like this:

 a=[1,2,3]
 b=[4,5,6]

 for i,j in a,b:
 print i,j

 where i,j would be 1,4,2,5,   3,6  etc.

 Is this possible?

 Many TIA!
 Mark


 list_1 = range( 1 , 4 )
 list_2 = range( 4 , 7 )

 list12 = zip( list_1 , list_2 )

 for this in list12 :
... print '   ' , this
...
(1, 4)
(2, 5)
(3, 6)

 for i , j in list12 :
... print '   ' , i , j
...
1 4
2 5
3 6


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Ensure only single application instance.

2008-08-29 Thread Heston James
Good afternoon all.
 
I have an application/script which is launched by crontab on a regular basis. I 
need an effective and accurate way to ensure that only one instance of the 
script is running at any one time.
 
After a short look around the internet I found a couple of examples, such as 
this one (http://code.activestate.com/recipes/474070/), however they both seem 
to be focused on a windows based environment.
 
Can anyone offer their advice on how best to do this on a linux based system?
 
I have been contemplating the idea of creating a pidfile which is destroyed at 
the end of the script, will this suffice? is it fool proof? My only concern 
with this is that if the script crashes or is stopped halfway through 
processing for whatever reason, I'll be left with a dead pidfile on the system 
and no successive runs will work.
 
I'm really interested to get your ideas guys, Thanks.
 
Heston
_
Win a voice over part with Kung Fu Panda  Live Search   and   100’s of Kung Fu 
Panda prizes to win with Live Search
http://clk.atdmt.com/UKM/go/107571439/direct/01/--
http://mail.python.org/mailman/listinfo/python-list

Re: Ensure only single application instance.

2008-08-29 Thread Alex
SOP is to write the actual PID of the running process into the pidfile, then
check to a) that the pidfile exists, and b) that the process referenced in
the pidfile exists.  if the pidfile exists, but the process does not, take
over the pidfile and carry on.

On Fri, Aug 29, 2008 at 9:51 AM, Heston James [EMAIL PROTECTED]wrote:

 Good afternoon all.

 I have an application/script which is launched by crontab on a regular
 basis. I need an effective and accurate way to ensure that only one instance
 of the script is running at any one time.

 After a short look around the internet I found a couple of examples, such
 as this one (http://code.activestate.com/recipes/474070/), however they
 both seem to be focused on a windows based environment.

 Can anyone offer their advice on how best to do this on a linux based
 system?

 I have been contemplating the idea of creating a pidfile which is destroyed
 at the end of the script, will this suffice? is it fool proof? My only
 concern with this is that if the script crashes or is stopped halfway
 through processing for whatever reason, I'll be left with a dead pidfile on
 the system and no successive runs will work.

 I'm really interested to get your ideas guys, Thanks.

 Heston

 --
 Get Hotmail on your mobile from Vodafone Try it 
 Now!http://clk.atdmt.com/UKM/go/107571435/direct/01/

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

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

Re: PyDoc in Windows Vista

2008-08-29 Thread Mike Driscoll
On Aug 28, 5:45 pm, Tyler Shopshire [EMAIL PROTECTED] wrote:
 I can't seem to access the pydoc sever from my web browser. I start the
 server from the command prompt and everything seems to be working fine,
 then I got tohttp://localhost:/and it doesn't work. I also tried
 starting the graphical mode with the -g parameter but I still cannot use
 PyDoc. It works on my Ubuntu Partition so I do know how to use it. Any
 help is appreciated.

My guess is that either your hosts file isn't pointing to the loopback
address or you have a firewall issue. See the following website for
one solution to the hosts issue: http://bytes.com/forum/thread645776.html

As for the firewall, you'll have to check Windows Firewall and / or
your own firewall, if you use ZoneAlarm or Norton 360 or some such.

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


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-29 Thread Roy Smith
Terry Reedy [EMAIL PROTECTED] wrote:
 Yes, so you can write something like either your second example or
 
 l = [
kjasldfjs,
kjsalfj,
ksjdflasj,
 ]
 
 and insert items without worrying about leaving out the comma (less of a 
 problem with 'horizontal' list), or delete the last line and not have to 
 worry about deleting the comma on the line before.

Exactly.  This is one of those little pieces of syntactic sugar which makes 
python so nice to work with.  The alternative is (in C, for example) 
abominations like this:

const char* l[] = {foo
 , bar
 , baz
 };

and even those are not quite as good because you still have to special-case 
the first entry.
--
http://mail.python.org/mailman/listinfo/python-list


Re: importing from .pyd

2008-08-29 Thread John Machin
On Jul 14, 9:11 pm, Kay Schluehr [EMAIL PROTECTED] wrote:
 On 14 Jul., 06:03, moijes12 [EMAIL PROTECTED] wrote:
[snip]
  Error i get is
  ImportError: DLL load failed: The specified module could not be found.

 Notice that the message clearly indicates that Python found the module
 but failed to load it i.e. performing a LoadLibrary() which yielded a
 NULL pointer.

The specified module could not be found clearly indicates that
Python found the module???

I suggest a more descriptive and (Monty) Pythonic error message: I
found a foo.pyd which looks like a DLL but it contains no 'initfoo'
entrypoint therefore I throw an ImportError and a bucketful of pig
slops in your general direction.
--
http://mail.python.org/mailman/listinfo/python-list


Re: eval() == evil? --- How to use it safely?

2008-08-29 Thread Bruno Desthuilliers

Fett a écrit :

On Aug 28, 7:57 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:

So long story short: if I am expecting a dictionary of strings, I
should make a parser that only accepts a dictionary of strings then.


or use an existing parser for an existing and documented format, as many 
posters (including myself) already suggested.



There is no safe way to use an existing construct.


Nothing coming from the outside world is safe.


That is what I was afraid of. I know I will have to deal with the
possibility of bad data, but considering my use (an acronym legend for
a database), and the fact that the site I plan to use should be
secure, these issues should be minimal.


If you feel like opening the door to any script-kiddie, then please 
proceed. It's *your* computer, anyway...


Else, use a known format with a known working parser (xml, json, yaml, 
csv, etc...), and possibly https if your data are to be protected.


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


Re: Identifying the start of good data in a list

2008-08-29 Thread Jorgen Grahn
On 27 Aug 2008 15:50:14 GMT, Steven D'Aprano [EMAIL PROTECTED] wrote:
 On Tue, 26 Aug 2008 17:04:19 -0700, tdmj wrote:

 On Aug 26, 5:49 pm, [EMAIL PROTECTED] wrote:
 I have a list that starts with zeros, has sporadic data, and then has
 good data. I define the point at  which the data turns good to be the
 first index with a non-zero entry that is followed by at least 4
 consecutive non-zero data items (i.e. a week's worth of non-zero data).
 For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], I
 would define the point at which data turns good to be 4 (1 followed by
 2, 3, 4, 5).

 ...

 With regular expressions:

 Good grief. If you're suggesting that as a serious proposal, and not just 
 to prove it can be done, that's surely an example of when all you have 
 is a hammer, everything looks like a nail thinking.

Maybe I'm stumbling into a REs are evil flamewar here. Anyway:

He has a point though: this *can* be seen as a regex problem. Only a
solution which builds a string first is only good for laughs or
(possibly) quick hacks. What's missing is an RE library for lists of
objects, rather than just strings and Unicode strings.

Not sure such a library would be worth implementing -- problems like
this one are rare, I think.

/Jorgen

-- 
  // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se  R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-29 Thread Grant Edwards
On 2008-08-29, Roy Smith [EMAIL PROTECTED] wrote:

 Exactly.  This is one of those little pieces of syntactic
 sugar which makes python so nice to work with.  The
 alternative is (in C, for example) abominations like this:

 const char* l[] = {foo
  , bar
  , baz
  };

 and even those are not quite as good because you still have to
 special-case the first entry.

It's probably a spec violation, but I've never seen a C
compiler that objected to a comma after the last item in an
initializer list.  (At least not at the warning levels I use,
which tend to be on the picky side.)

-- 
Grant Edwards   grante Yow! There's enough money
  at   here to buy 5000 cans of
   visi.comNoodle-Roni!
--
http://mail.python.org/mailman/listinfo/python-list


Re: eval() == evil? --- How to use it safely?

2008-08-29 Thread Steven D'Aprano
On Fri, 29 Aug 2008 05:42:46 -0700, Fett wrote:

 On Aug 28, 7:57 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:
 
 So long story short: if I am expecting a dictionary of strings, I should
 make a parser that only accepts a dictionary of strings then. There is
 no safe way to use an existing construct.

You may find the code here useful:

http://effbot.org/zone/simple-iterator-parser.htm


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

Python graphics question:pixel scrolling

2008-08-29 Thread Raymond Luxury-Yacht
To learn python, I've been trying to write a simple graphics program
which displays a 1D cellular automaton's evolution.  The last time I
wrote this program, it was in C for a CGA adaptor (!) in which the
display was mapped to two interlaced blocks of memory, and scrolling
up two lines of pixels was very simple and very smooth.  The code
below works, and uses pygame for the graphics.  But the scrolling is
quite flickery when using large windows.  I'm sure that the code
contains various neophyte python errors, and I'd appreciate any
comments on that, but my main question is how I ought to have coded it
in order to have the scrolling be smooth.  I did see a comment on a
pygame site saying that pygrame should not be used for side-scrollers,
to which this is similar.  Is there a better way with python?

p.s. It can be run without any args and will select an interesting
rule. To change resolution to see the flickering get worse, change
HEIGHT and WIDTH.

# Simple 1D Cellular Automaton
#
# The world is a line of cells in which each cell has a state of 0 - 3
# The states change according to a rule that specifies a new state as
a function
# of the sum of a cell's state and those of its nearest neighbors
# Since the sum can be between 0 = 0+0+0 and 9 = 3+3+3, the rule can
be represented
# by an array of 10 integers, each between 0 and 3.
#
# To represent this graphically, each state will correspond to a color
on a row
# of window.
#
# The first generation is initialized to have a single 1 in the middle
of the bottom row
# When a new generation is computed, the preceding generations will be
scrolled up and the
# new generation displayed on the bottom line.

import pygame
from pygame.locals import *
import numpy
import sys
#import pdb

WIDTH = 300  #width of screen
HEIGHT = 300 #height of screen
MIDDLE = WIDTH/2

COLORS =   [  0x00, 0xFF,  0x00FF00,  0xFF ]
COLORNUM = {}
for i in range(len(COLORS)):
COLORNUM[ COLORS[i]] = i

#pdb.set_trace()
pygame.surfarray.use_arraytype ('numpy')

def main():
# Default to an interesting rule if none is given
if len(sys.argv)  2:
rule_string = 0322301013
else:
rule_string = sys.argv[1]  # assume it's there
rule = [ COLORS[int(d)] for d in rule_string ]

pygame.display.init()

screen = pygame.display.set_mode((WIDTH,HEIGHT),DOUBLEBUF)
pixels = pygame.surfarray.pixels2d(screen)

max_width = len(pixels)-1
max_height = len(pixels[0])-1

pixels[MIDDLE,-1] =  COLORS[1]
trpix = numpy.transpose( pixels )
old = trpix[-1]
while True:
new = numpy.zeros( max_width + 1)

# Note wrap-around allows us to avoid having 0 be a special
case
for i in range(0, max_width):
new[i] = rule [COLORNUM[ old[i-1] ] + COLORNUM[ old[i] ] +
COLORNUM[ old[i+1] ]]

new[max_width] =   rule[COLORNUM[ old[max_width-1] ] +
COLORNUM[ old[max_width] ] + COLORNUM[ old[0] ]]

# Exit if 'q' is pressed
for e in pygame.event.get():
if e.type == KEYDOWN:
if e.key == K_q:
exit(0)

# Scroll and update the bottom row. Note that we don't have to
assign
# pixels to be transpose(trpix).
trpix[0:-1] = trpix[1:]
trpix[-1] = new
pygame.display.update()


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


Python - ubuntu

2008-08-29 Thread azrael
Hy folks

A friend of mine told me something about Guido and google developing
an Ubuntu distribution based and totaly oriented for the Python
appliction development. I googled for it with no results. Is it
possible that My Buddy is trying to foole me or is it possible that
someone knows something about that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-29 Thread Steven D'Aprano
On Thu, 28 Aug 2008 16:28:03 -0700, Paul McNett wrote:

 [EMAIL PROTECTED] wrote:
 x=[1,2,3]
 and
 x=[1,2,3,]
 
 are exactly the same, right?
 
 When confronted with this type of question, I ask the interpreter:
 
 {{{
 mac:~ pmcnett$ python
 Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple
 Computer, Inc. build 5363)] on darwin Type help, copyright,
 credits or license for more information.
   [1,2,3] == [1,2,3,]
 True
 }}}



Putting on my pedantic hat...

In this case you're right about the two lists being the same, and I'm a 
great believer in checking things in the interactive interpreter, but you 
need to take care. Just because two objects compare as equal doesn't 
*necessarily* mean they are the same:


 1.0 == 1
True
 1.0 == decimal.Decimal('1.0')
False
 1.0 == float(decimal.Decimal('1.0'))
True
 collections.defaultdict(999) == {}
True



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


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-29 Thread Roy Smith
In article [EMAIL PROTECTED],
 Grant Edwards [EMAIL PROTECTED] wrote:

 On 2008-08-29, Roy Smith [EMAIL PROTECTED] wrote:
 
  Exactly.  This is one of those little pieces of syntactic
  sugar which makes python so nice to work with.  The
  alternative is (in C, for example) abominations like this:
 
  const char* l[] = {foo
   , bar
   , baz
   };
 
  and even those are not quite as good because you still have to
  special-case the first entry.
 
 It's probably a spec violation, but I've never seen a C
 compiler that objected to a comma after the last item in an
 initializer list.  (At least not at the warning levels I use,
 which tend to be on the picky side.)

Yowza, you're right (at least for the one case I tried).  This must be a 
new development (where new development is defined as, It wasn't legal in 
the original KR C I learned when I was a pup).

Still, I have seem people do that in code.
--
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2008-08-29 Thread bruce
Hi.

I'm using mechanize to parse a page/site that uses the meta http-equiv tag
in order to perform a refresh/redirect of the page. I've tried a number of
settings, and read different posts on various threads, but seem to be
missing something.

the test.html page is the page that the url returns, however, i was
expecting the test.py app to go ahead and perform the redirect/refresh
automatically.

does the page (test.html) need to be completely valid html?

Any thoughts on what's screwed up here??


thanks



test.py

import re
import libxml2dom
import urllib
import urllib2
import sys, string
from  mechanize import Browser
import mechanize
#import tidy
import os.path
import cookielib
from libxml2dom import Node
from libxml2dom import NodeList
import subprocess
import time


#
# Parse pricegrabber.com

cj = p
COOKIEFILE = 'cookies.lwp'
#cookielib = 1


urlopen = urllib2.urlopen
#cj = urllib2.cookielib.LWPCookieJar()
cj = cookielib.LWPCookieJar()
Request = urllib2.Request
br = Browser()
br2 = Browser()

if cj != None:
  print sss
#install the CookieJar for the default CookieProcessor
  if os.path.isfile(COOKIEFILE):
  cj.load(COOKIEFILE)
  print foo\n
  if cookielib:
  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  urllib2.install_opener(opener)
  print foo2\n

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

url=http://schedule.psu.edu/;
#===


if __name__ == __main__:
# main app

txdata = None

#

##br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(True)
br.addheaders = [('User-Agent', 'Firefox')]

#url=str(url)+str(act_main_search.cfm)+?
#url=url+Semester=FALL%202008%20%20%20
#url=url+CrseLoc=OZ%3A%3AAbington%20Campus
#url=url+CECrseLoc=AllOZ%3A%3AAbington%20Campus
#url=url+CourseAbbrev=ACCTGCourseNum=CrseAlpha=Search=View+schedule

#url=http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20
%20%20CrseLoc=OZ%3A%3AAbington%20CampusCECrseLoc=AllOZ%3A%3AAbington%20Cam
pusCourseAbbrev=ACCTGCourseNum=CrseAlpha=



url=http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20%
20%20CrseLoc=OZ%3A%3AAbington%20CampusCECrseLoc=AllOZ%3A%3AAbington%20Camp
usCourseAbbrev=ACCTGCourseNum=CrseAlpha=CFID=543143CFTOKEN=71842529


print url =,url
br.open(url)
#cj.save(COOKIEFILE)# resave cookies

res = br.response()  # this is a copy of response
s = res.read()
print slen=,len(s)
print s

=
test.html
html
head
TITLE/TITLE
/head

BODY BGCOLOR=#FF

TD NOWRAP WIDTH=45 VALIGN=topA
HREF=javascript:openAWindow('http://www.registrar.psu.edu/faculty_staff/enr
oll_services/clsrooms.html#C','Intent',625,425,1)FONT FACE=Arial,
Helvetica, sans-serif SIZE=2strongTech Type/strong/FONT/A/TD


META HTTP-EQUIV=Refresh CONTENT=0;url=/soc/fall/Alloz/a-c/acctg.html#

-




sys.exit()




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


python/mechanize - redirect/refresh question

2008-08-29 Thread bruce
Hi.

I'm using mechanize to parse a page/site that uses the meta http-equiv tag
in order to perform a refresh/redirect of the page. I've tried a number of
settings, and read different posts on various threads, but seem to be
missing something.

the test.html page is the page that the url returns, however, i was
expecting the test.py app to go ahead and perform the redirect/refresh
automatically.

does the page (test.html) need to be completely valid html?

Any thoughts on what's screwed up here??


thanks



test.py

import re
import libxml2dom
import urllib
import urllib2
import sys, string
from  mechanize import Browser
import mechanize
#import tidy
import os.path
import cookielib
from libxml2dom import Node
from libxml2dom import NodeList
import subprocess
import time


#
# Parse pricegrabber.com

cj = p
COOKIEFILE = 'cookies.lwp'
#cookielib = 1


urlopen = urllib2.urlopen
#cj = urllib2.cookielib.LWPCookieJar()
cj = cookielib.LWPCookieJar()
Request = urllib2.Request
br = Browser()
br2 = Browser()

if cj != None:
  print sss
#install the CookieJar for the default CookieProcessor
  if os.path.isfile(COOKIEFILE):
  cj.load(COOKIEFILE)
  print foo\n
  if cookielib:
  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  urllib2.install_opener(opener)
  print foo2\n

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

url=http://schedule.psu.edu/;
#===


if __name__ == __main__:
# main app

txdata = None

#

##br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(True)
br.addheaders = [('User-Agent', 'Firefox')]

#url=str(url)+str(act_main_search.cfm)+?
#url=url+Semester=FALL%202008%20%20%20
#url=url+CrseLoc=OZ%3A%3AAbington%20Campus
#url=url+CECrseLoc=AllOZ%3A%3AAbington%20Campus
#url=url+CourseAbbrev=ACCTGCourseNum=CrseAlpha=Search=View+schedule

#url=http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20
%20%20CrseLoc=OZ%3A%3AAbington%20CampusCECrseLoc=AllOZ%3A%3AAbington%20Cam
pusCourseAbbrev=ACCTGCourseNum=CrseAlpha=



url=http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20%
20%20CrseLoc=OZ%3A%3AAbington%20CampusCECrseLoc=AllOZ%3A%3AAbington%20Camp
usCourseAbbrev=ACCTGCourseNum=CrseAlpha=CFID=543143CFTOKEN=71842529


print url =,url
br.open(url)
#cj.save(COOKIEFILE)# resave cookies

res = br.response()  # this is a copy of response
s = res.read()
print slen=,len(s)
print s

=
test.html
html
head
TITLE/TITLE
/head

BODY BGCOLOR=#FF

TD NOWRAP WIDTH=45 VALIGN=topA
HREF=javascript:openAWindow('http://www.registrar.psu.edu/faculty_staff/enr
oll_services/clsrooms.html#C','Intent',625,425,1)FONT FACE=Arial,
Helvetica, sans-serif SIZE=2strongTech Type/strong/FONT/A/TD


META HTTP-EQUIV=Refresh CONTENT=0;url=/soc/fall/Alloz/a-c/acctg.html#

-




sys.exit()




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


Module __file__ attribute in Python 3

2008-08-29 Thread Steven D'Aprano
On the python-dev mailing list, a question has be raised about a change 
to module.__file__ in Python 3.

http://www.gossamer-threads.com/lists/python/dev/674923#674923

In Python 2.x, m.__file__ is the name of the file that the module was 
imported from. That file might end with .py, .pyc, .pyo, or even more 
exotic extensions if Python's import mechanism has been customized.

For reasons explained here:
http://bugs.python.org/issue1762972

Python 3.0 will introduce a patch that makes m.__file__ always specify 
the source file (.py) if it exists, and only if that file doesn't exist 
will it specify the actual file used (.pyc or .pyo).

That will mean that there will be no (easy?) way to determine after the 
import whether the module was imported from a source file or a compiled 
file. I've suggested that the original justification for the patch no 
longer applies, and that the secondary purpose of the patch is better 
solved by leaving __file__ as it is in Python 2.x, and introducing a new 
attribute __source__. 

What do people think? There seems to be a little interest on the python-
dev list from a couple of people, but not enough to actually lead to any 
action. Does anyone care what m.__file__ is? Does anyone else feel that 
this issue is worth pursuing?


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


Re: Python graphics question:pixel scrolling

2008-08-29 Thread Paul Boddie
On 29 Aug, 16:57, Raymond Luxury-Yacht [EMAIL PROTECTED] wrote:
 The code below works, and uses pygame for the graphics.  But the scrolling is
 quite flickery when using large windows.  I'm sure that the code
 contains various neophyte python errors, and I'd appreciate any
 comments on that, but my main question is how I ought to have coded it
 in order to have the scrolling be smooth.  I did see a comment on a
 pygame site saying that pygrame should not be used for side-scrollers,
 to which this is similar.  Is there a better way with python?

There are side-scrollers written in Python including impressive
games like these:

http://www.pygame.org/project/406/
http://www.pygame.org/project/381/

I see that you're using the surfarray module, which is probably what
you want to do if you're accessing the screen at a pixel level (as
opposed to blitting sprites). My experiences with Numeric/numpy and
Pygame are limited to recolouring bitmaps, but it's certainly possible
to refresh a reasonable size of surface at a decent rate on reasonably
fast hardware. One important hint whose relevance I'm not sure about
here is that you should attempt to avoid frequent format and bit depth
conversions; for sprites and images this usually involves converting
them to the same format as the display surface, but I can imagine that
there may be implications for surfarrays, too.

I hope this gives you some ideas, anyway.

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


Re: Python - ubuntu

2008-08-29 Thread Fredrik Lundh

azrael wrote:


A friend of mine told me something about Guido and google developing
an Ubuntu distribution based and totaly oriented for the Python
appliction development.


not sure about a version tuned for python, but wikipedia claims that 
there's a custom packaging used internally:


http://en.wikipedia.org/wiki/Goobuntu

maybe he's mixing that one up with this one:

http://code.google.com/appengine/

/F

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


Re: Module __file__ attribute in Python 3

2008-08-29 Thread Jean-Paul Calderone

On 29 Aug 2008 15:21:53 GMT, Steven D'Aprano [EMAIL PROTECTED] wrote:

On the python-dev mailing list, a question has be raised about a change
to module.__file__ in Python 3.

http://www.gossamer-threads.com/lists/python/dev/674923#674923

In Python 2.x, m.__file__ is the name of the file that the module was
imported from. That file might end with .py, .pyc, .pyo, or even more
exotic extensions if Python's import mechanism has been customized.

For reasons explained here:
http://bugs.python.org/issue1762972

Python 3.0 will introduce a patch that makes m.__file__ always specify
the source file (.py) if it exists, and only if that file doesn't exist
will it specify the actual file used (.pyc or .pyo).


This seems particularly pointless.  If __file__ were changed to make it
easier to handle by making the value have a more consistent meaning, then
it might be useful.  It sounds like the change is just making the failure
case more obscure and less likely to be noticed during testing, though.

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


Re: Tkinter tkMessageBox problem - message box is displayed with an additional window

2008-08-29 Thread dudeja . rajat
On Thu, Aug 28, 2008 at 3:54 PM, Guilherme Polo [EMAIL PROTECTED] wrote:
 On Thu, Aug 28, 2008 at 10:29 AM,  [EMAIL PROTECTED] wrote:
 Hi,
 I'm working on Windows Platform

 I'm facing some problem with the tkMessageBox. My code is as below:

 import tkMessageBox
 import Tix
 from Tkinter import *

 if len(installedLibPath) != len(listOfLibraries):
if tkMessageBox.askyesno(Question, \
 type='yesno', icon='warning', \
 message=Some of the libraries are
 not installed. Do you wish to continue with the remaining?):
myRoot = Tix.Tk()
myAppGUIObject = myAppGUI(myRoot)#Class for my GUI
myRoot.mainloop()
 else:
sys.exit(0)


 It is good to post a short code sample that demonstrates the problem,
 but it has to run by itself at least.


 The Message Box is called before the Tix.Tk mainloop(). The problems
 are as under :

 1. Since the message box is displayed before the mainloop() is
 started, the message box is displayed with another window that is
 blank. This should not be displayed.

 2. As a results of this messagebox (called before the mainloop) the
 original Gui started by mainloop doesnot work as desired. Some of the
 checkbuttons are displayed as unset (i.e un-ticked). These
 checkbuttons used to be set at initialization before I stared using
 this messagebox.

 tkMessageBox blocks till you finish it, maybe that is what is causing
 your problem but it is hard to tell what you are doing wrong in that
 myAppGui without seeing it (preferably reduced code demonstrating the
 problem).

 Now.. an attempt to solve your problem. Tk always has a root window
 going on, so that another window is inevitable, but you can hide and
 show it again when needed. You could do something like this:

 import tkMessageBox
 import Tkinter

 class App(object):
def __init__(self, master):
self.master = master
print tkMessageBox is gone now

 root = Tkinter.Tk()
 root.withdraw()
 tkMessageBox.askyesno(Question, message=Do you use Python?,
type='yesno', icon='warning', master=root)
 root.deiconify()

 app = App(root)
 root.mainloop()



 Please help.

 Thanks and regards,
 Rajat
 --
 Regrads,
 Rajat
 --
 http://mail.python.org/mailman/listinfo/python-list




 --
 -- Guilherme H. Polo Goncalves


Thanks Guilherme, your suggestion helped solve the problem.

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


How to check is something is a list or a dictionary or a string?

2008-08-29 Thread dudeja . rajat
Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)


where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?


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


Re: eval() == evil? --- How to use it safely?

2008-08-29 Thread Lie
On Aug 29, 8:14 pm, Fett [EMAIL PROTECTED] wrote:
 On Aug 29, 7:42 am, Fett [EMAIL PROTECTED] wrote:

  On Aug 28, 7:57 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:

  So long story short: if I am expecting a dictionary of strings, I
  should make a parser that only accepts a dictionary of strings then.
  There is no safe way to use an existing construct.

  That is what I was afraid of. I know I will have to deal with the
  possibility of bad data, but considering my use (an acronym legend for
  a database), and the fact that the site I plan to use should be
  secure, these issues should be minimal. The users should be able to
  spot any obvious false data, and restoring it should be simple.

  Many thanks to all of you for your alarmist remarks. I certainly don't
  want to, in any way, put my clients computers at risk by providing
  unsafe code.

 On a related note, what if I encrypted and signed the data, then only
 ran eval() on the string after it was decrypted and the signature
 verified?

 It has occurred to me that posting this data on a site might not be
 the best idea unless I can be sure that it is not read by anyone that
 it shouldn't be. So I figure an encrypting is needed, and as long as I
 can sign it as well, then only people with my private signing key
 could pass bad data, much less harmful strings.

Your way of thinking is similar to Microsoft's. Encrypting and Signing
is a kludge, a real fix should fix the underlying cause. Anyway using
data parsers isn't that much harder than using eval/exec.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tough Guy Competition

2008-08-29 Thread W. eWatson

alex23 wrote:

On Aug 29, 3:45 pm, W. eWatson [EMAIL PROTECTED] wrote:

Something to do on your weekends. [non-related link clipped]


Another thing to do with your weekends would be to -not spam-.


Sorry, misdirected.

--
   W. Watson
 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7 N, 121° 2' 32 W, 2700 feet

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


Re: Date Comparison and Manipulation Functions?

2008-08-29 Thread W. eWatson

I just tried the following code, and got an unexpected result.

from pyfdate import *
t = Time()

ts = Time(2008, 8, 29,15,20,7)
tnew = ts.plus(months=6)
print new date: , tnew

Result:
new date:  2009-02-28 15:20:07

I believe that should be April 1, 2009. If I use months = 1 and day =31, I 
get Sept. 30, 2008 and not Oct. 1, 2008. Is there a way to get around this?


--
   W. Watson
 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7 N, 121° 2' 32 W, 2700 feet

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


Re: Lining Up and PaddingTwo Similar Lists

2008-08-29 Thread W. eWatson

castironpi wrote:
...



I don't think that's guaranteed by anything.  I realized that
'dat.sort()' and 'txt.sort()' weren't necessary, since their contents
are moved to a dictionary, which isn't sorted.
Actually, I'm getting the file names from listdir, and they appear to be 
sorted low to high. I tried it on a folder with lots of dissimilar files.


both= set( datD.keys() ) set( txtD.keys() )

This will get you the keys (prefixes) that are in both.  Then for
every prefix if it's not in 'both', you can report it.

Lastly, since you suggest you're guaranteed that 'txt' will all share
the same extension, you can do away with the dictionary and use sets
entirely.  Only if you can depend on that assumption.
Each dat file contains an image, and its description and related parameters 
are in the corresponding txt file.


I took a look at this.  It's probably more what you had in mind, and
the dictionaries are overkill.

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


Re: Sending e-mail

2008-08-29 Thread peter . jones . rpi
On Aug 28, 3:23 pm, gordyt [EMAIL PROTECTED] wrote:
 Peter here is an example.  I just tried it and it works fine.

 from smtplib import SMTP
 HOST = smtp.gmail.com
 PORT = 587
 ACCOUNT =   # put your gmail email account name here
 PASSWORD =   # put your gmail email account password here

 def send_email(to_addrs, subject, msg):
 server = SMTP(HOST,PORT)
 server.set_debuglevel(1)# you don't need this
 server.ehlo()
 server.starttls()
 server.ehlo()
 server.login(ACCOUNT, PASSWORD)
 server.sendmail(ACCOUNT, to_addrs,
 From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n.\r\n % (
 ACCOUNT, ,.join(to_addrs), subject, msg
 )
 )
 server.quit()

 if __name__ == __main__:
 send_email( ['[EMAIL PROTECTED]'], 'this is just a test',
 hello world! )

Thanks to everyone who's replied. gordyt, I didn't dare dream anyone
would hand me fully functional source code, so thank you very much for
that. Unfortunately, it doesn't work for me, likely because of some
complication from my company's firewall.

All things considered, going through Gmail is an unnecessary step if I
can run a server on my own PC. Is there any hope of this working? Can
it be done easily? Is there anything I should know about the
SMTPServer object, and are there any other modules I'd need?

Thanks again for all the help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-29 Thread castironpi
On Aug 29, 9:43 am, Jorgen Grahn [EMAIL PROTECTED] wrote:
 On 27 Aug 2008 15:50:14 GMT, Steven D'Aprano [EMAIL PROTECTED] wrote:



  On Tue, 26 Aug 2008 17:04:19 -0700, tdmj wrote:

  On Aug 26, 5:49 pm, [EMAIL PROTECTED] wrote:
  I have a list that starts with zeros, has sporadic data, and then has
  good data. I define the point at  which the data turns good to be the
  first index with a non-zero entry that is followed by at least 4
  consecutive non-zero data items (i.e. a week's worth of non-zero data).
  For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], I
  would define the point at which data turns good to be 4 (1 followed by
  2, 3, 4, 5).

 He has a point though: this *can* be seen as a regex problem. Only a
 solution which builds a string first is only good for laughs or
 (possibly) quick hacks. What's missing is an RE library for lists of
 objects, rather than just strings and Unicode strings.

 Not sure such a library would be worth implementing -- problems like
 this one are rare, I think.

Every now and then, you see a proposal or a package for a finite state
machine--- how would you encode comparing of values into a string, if
you're not comparing a string?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check is something is a list or a dictionary or a string?

2008-08-29 Thread Jason Scheirer
On Aug 29, 9:16 am, [EMAIL PROTECTED] wrote:
 Hi,

 How to check if something is a list or a dictionary or just a string?
 Eg:

 for item in self.__libVerDict.itervalues():
             self.cbAnalysisLibVersion(END, item)

 where __libVerDict is a dictionary that holds values as strings or
 lists. So now, when I iterate this dictionary I want to check whether
 the item is a list or just a string?

 Thanks,
 Rajat

type() and probably you want to import the types library as well.

In [1]: import types

In [2]: a = {1: {}, False: [], 'yes': False, None: 'HELLO'}

In [3]: a.values()
Out[3]: [[], {}, False, 'HELLO']

In [4]: [type(item) for item in a.itervalues()]
Out[4]: [type 'list', type 'dict', type 'bool', type 'str']

In [6]: for item in a.itervalues():
   ...: if type(item) is types.BooleanType:
   ...: print Boolean, item
   ...: elif type(item) is types.ListType:
   ...: print List, item
   ...: elif type(item) is types.StringType:
   ...: print String, item
   ...: else:
   ...: print Some other type, type(item), ':', item
   ...:
   ...:
List []
Some other type type 'dict' : {}
Boolean False
String HELLO
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python graphics question:pixel scrolling

2008-08-29 Thread Diez B. Roggisch
Raymond Luxury-Yacht wrote:

 To learn python, I've been trying to write a simple graphics program
 which displays a 1D cellular automaton's evolution.  The last time I
 wrote this program, it was in C for a CGA adaptor (!) in which the
 display was mapped to two interlaced blocks of memory, and scrolling
 up two lines of pixels was very simple and very smooth.  The code
 below works, and uses pygame for the graphics.  But the scrolling is
 quite flickery when using large windows.  I'm sure that the code
 contains various neophyte python errors, and I'd appreciate any
 comments on that, but my main question is how I ought to have coded it
 in order to have the scrolling be smooth.  I did see a comment on a
 pygame site saying that pygrame should not be used for side-scrollers,
 to which this is similar.  Is there a better way with python?

You need to to double-buffering. Just as in the old days... 

http://www.pygame.org/docs/tut/intro/intro.html

Look for pygame.display.flip()

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


Re: problem with packages and path

2008-08-29 Thread Daniel
On Aug 28, 2:28 am, Marco Bizzarri [EMAIL PROTECTED] wrote:
 On Wed, Aug 27, 2008 at 6:44 PM, Daniel [EMAIL PROTECTED] wrote:
  Hello,

  I'm writing some unit tests for my python software which uses
  packages.  Here is the basic structure:

  mypackage
   __init__.py
   module1
     __init__.py
     mod1.py
   module2
     __init__.py
     mod2.py
   unittests
     __init__.py
     alltests.py
     test1.py
     test2.py

  within alltests.py I would expect to be able to import
  mypackage.unittests.test1.  In fact within PyScripter this works as
  expected.  However, when I execute the code from the command line, I
  get the following error:

  ImportError: No module named mypackage.unittests.test1

 1) What is the command you're using to run the alltest.py module?

 2) what is the result of:
    - python -c import mypackage
   - python -c import mypackage.unittests

 Regards
 Marco

 --
 Marco Bizzarrihttp://iliveinpisa.blogspot.com/

I have tried running both commands above from the mypackage directory
and unittests directory.  I get the following response universtally.

C:\mypackagedir
 Volume in drive C is Default

 Directory of C:\mypackage

08/29/2008  11:04 AMDIR  .
08/29/2008  11:04 AMDIR  ..
08/29/2008  11:05 AMDIR  module1
08/29/2008  11:05 AMDIR  module2
08/29/2008  11:06 AMDIR  unittests
08/29/2008  11:04 AM 0 __init__.py
   1 File(s)  0 bytes
   5 Dir(s)  55,402,070,016 bytes free

C:\mypackagedir unittests
 Volume in drive C is Default

 Directory of C:\mypackage\unittests

08/29/2008  11:06 AMDIR  .
08/29/2008  11:06 AMDIR  ..
08/29/2008  11:05 AM 0 alltests.py
08/29/2008  11:05 AM 0 test1.py
08/29/2008  11:05 AM 0 test2.py
08/29/2008  11:04 AM 0 __init__.py
   4 File(s)  0 bytes
   2 Dir(s)  55,401,988,096 bytes free

C:\mypackagepython -c import mypackage
Traceback (most recent call last):
  File string, line 1, in module
ImportError: No module named mypackage

C:\mypackagepython -c import mypackage.unittests
Traceback (most recent call last):
  File string, line 1, in module
ImportError: No module named mypackage.unittests
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module __file__ attribute in Python 3

2008-08-29 Thread Diez B. Roggisch
 That will mean that there will be no (easy?) way to determine after the
 import whether the module was imported from a source file or a compiled
 file. I've suggested that the original justification for the patch no
 longer applies, and that the secondary purpose of the patch is better
 solved by leaving __file__ as it is in Python 2.x, and introducing a new
 attribute __source__.
 
 What do people think? There seems to be a little interest on the python-
 dev list from a couple of people, but not enough to actually lead to any
 action. Does anyone care what m.__file__ is? Does anyone else feel that
 this issue is worth pursuing?

I'm +1 on this. Introducing __source__ shouldn't break anything, and is a
minor change as the mapping of loaded file to defining file is already
done.

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


Re: Command lime code

2008-08-29 Thread Steven D'Aprano
On Fri, 29 Aug 2008 17:20:37 +0100, London wrote:

 I am new to python.
 I did find a page which listed some code - IE chdir type code but can
 not find it again.
 Can you supply an address?


http://www.google.com is a good address to use.


Seriously, did you think we've hacked your computer and are spying on 
your web browsing? How would we know what web page you have visited?



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


Re: Lining Up and PaddingTwo Similar Lists

2008-08-29 Thread George Sakkis
On Aug 29, 1:29 am, W. eWatson [EMAIL PROTECTED] wrote:

 It looks like I have a few new features to learn about in Python. In 
 particular,
 dictionaries.

In Python it's hard to think of many non-trivial problems that you
*don't* have to know about dictionaries.

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


Re: Tkinter event loop question

2008-08-29 Thread gordon
On Aug 29, 4:45 am, Russell E. Owen [EMAIL PROTECTED] wrote:
your Controller object should not create root nor should
 it call mainloop to start the event loop.

guys
thanks for the helpful replies..I rewrote the code as you advised. It
creates a controller object and a gui object from main script.However
i had to chain some method calls in my code.i am
wondering if that can be avoided in some way.

this is the sequence
1.user enters some value in the textfield,and clicks OKbutton
2.on OKbuttonclick ,the gui takes userinput value and quits
eventloop.It then calls controller and pass the userinputvalue.
3.controller does some calculation(i shd have an external program to
do calculation,but for simplicity i just wrote a method inside
controller) with the given value,obtains the result and calls gui's
updateDisplay(), passing the result value.
4.the gui creates the result as text on a canvas.then the mainloop()
is called to resume event loop

again user enters some value in the textfield,and clicks OKbutton ...

I exit the application by clicking quitButton that calls destroy() on
top level window.
 I tried my application by entering some value on text field and then
clicking OKbutton ,the calculated result is displayed on canvas .I do
this process say 3 times ..Then i click the Quit button and the window
closes.
I have put a print statement inside the gui's updateDisplay()method
right after the resuming of event loop by parent.mainloop().This print
statement gets printed as many times as i had clicked
the OK button(here in this case 3 times).Is this due to clearing of
the stack ?
I feel that it was not a good design ..I would be grateful if someone
would tell me how i could improve it..can those chaining of method
calls be avoided?

this is how i restructured the code

moduleA.py
---
import moduleB
from Tkinter import Tk
class MyController(object):
def __init__(self):
print controller()
def validateSelection(self,userinputVal):
if(userinputVal  50 or userinputVal==0):
userinputVal=50
self.doSomeCalculation(userinputVal)

def doSomeCalculation(self,userinputVal):
resultvalue=2*userinputVal +10
self.updateResults(resultvalue)
def updateResults(self,resultvalue):
self.myapp.updateDisplay(resultvalue);

if __name__ == __main__:
controller=MyController()
root = Tk()
root.wm_title(MyUIApp)
controller.myapp =moduleB.MyUI(root,controller)
root.mainloop()

moduleB.py
---
from Tkinter import *
class MyUI(object):
def __init__(self, parent,controller):
self.myParent = parent
self.mainframe = Frame(parent,background=grey)
self.mainframe.pack(fill=BOTH,expand=YES)
self.controller=controller
added a canvas and OK,QUIT buttons

def okBtnClick(self):
print okBtnClicked
self.okButton.configure(state=DISABLED)
userinputvalue = self.getUserInputValue()
self.myParent.quit()  #quits event loop
self.controller.validateSelection(userinputvalue)

def quitBtnClick(self):
print Quit Btn clicked
self.myParent.destroy()
def updateDisplay(self,resultValue):
message='result is='+str(resultValue)
self.canvresult.delete(ALL)
self.canvresult.create_text(1, 40, anchor=W, text=message,
width=280)
self.okButton.configure(state=NORMAL)
self.myParent.mainloop() # resumes event loop
print 'in updateDisplay():called mainloop'

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


When to use try and except?

2008-08-29 Thread cnb
If I get zero division error it is obv a poor solution to do try and
except since it can be solved with an if-clause.

However if a program runs out of memory I should just let it crash
right? Because if not then I'd have to write exceptions everywhere to
prevent that right?

So when would I actually use try-except?

If there can be several exceptions and I just want to catch 1 or 2?
Like
try:
blahaba
except SomeError:
do something
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check is something is a list or a dictionary or a string?

2008-08-29 Thread George Sakkis
On Aug 29, 12:16 pm, [EMAIL PROTECTED] wrote:
 Hi,

 How to check if something is a list or a dictionary or just a string?
 Eg:

 for item in self.__libVerDict.itervalues():
 self.cbAnalysisLibVersion(END, item)

 where __libVerDict is a dictionary that holds values as strings or
 lists. So now, when I iterate this dictionary I want to check whether
 the item is a list or just a string?

if isinstance(item,basestring):
   # it's a string
...
else: # it should be a list
   # typically you don't have to check it explicitly;
   # even if it's not a list, it will raise an exception later anyway
if you call a list-specific method


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


Memory Leek, critique me. Thanks!!!

2008-08-29 Thread Kevin McKinley
#  I posted a few days ago about a memory leak that I think i'm having with my 
first Tkinter program.  
#  I've had trouble pinpointing what is wrong so i thought i would submit the 
code and see if anyone would
#  like to critique it.  
#  I have one more problem that i can't figure out either.  There are a bunch 
of Entry widgets that require number values.
#  My problem is if someone inputs a letter or space the program  will have 
error that makes part of the 
#  Program nonfunctional.  
#  Description Of The Program:  I made this program to help me with common 
calculations that i do on a day-to-day
#  basis.  I'm a outside sales rep and this program figures out Gross profit 
and price increase.  Oh, and where it
#  said to enter COG that stands for Cost of Goods.  I know it doesn't really 
matter but figure i would let you guys
#  in on the use of the program.

#  Thank you,
#  Kevin McKinley




from Tkinter import *

class MyApp:
def __tini__(self, parent):
self.myParent = parent

self.myFunctionContainer = Frame(parent)
self.myFunctionContainer.grid(row=0, column=0)

self.COG1 = DoubleVar()
self.COG2 = DoubleVar()
self.COG3 = DoubleVar()
self.COG4 = DoubleVar()
self.GP = DoubleVar()
self.increase = DoubleVar()
self.markup = DoubleVar()

self.gpRange(1)


# This Function is for the Markup Tab for a range of GP%
def gpRange(self, event):
self.clearScreen()

self.gpRangeTab = Button(self.myFunctionContainer, width=14, 
relief=FLAT, text=Multi-Markup)
self.gpRangeTab.bind(Button-1, self.gpRange)
self.gpRangeTab.grid(row=0, column=0)

self.gpExactTab = Button(self.myFunctionContainer, width=14, bg=dark 
grey, relief=SUNKEN, text=Single Markup)
self.gpExactTab.bind(Button-1, self.gpExact)
self.gpExactTab.grid(row=0, column=1)

self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, 
bg=dark grey, relief=SUNKEN, text=Product Increase)
self.priceIncreaseTab.bind(Button-1, self.priceIncrease)
self.priceIncreaseTab.grid(row=0, column=2)

self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg=dark 
grey, relief=SUNKEN, text=Calculate GP)
self.gpFinderTab.bind(Button-1, self.gpFinder)
self.gpFinderTab.grid(row=0, column=3)

self.markup1(1)

self.myContainer2 = Frame(self.myFunctionContainer, borderwidth=2, 
relief=GROOVE)
self.myContainer2.grid(padx=0, pady=2, row=4, column=0, columnspan=4, 
sticky=W+E)

self.title1 = Label(self.myFunctionContainer, font=bold, 
relief=GROOVE, text=Multi-Markup Calculator)
self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, 
sticky=W+E)

self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG1)
self.entry1.select_range(0, END)
self.entry1.bind(Return, self.markup1)
self.entry1.focus_force()
self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, 
sticky=W)

self.entryTitle = Label(self.myFunctionContainer, text=Enter COG:)
self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E)

self.title2 = Label(self.myContainer2, text=Gross Profit %)
self.title2.grid(padx=2, pady=2, row=1, column=1, sticky=W)

self.title3 = Label(self.myContainer2, text=   Markup Price)
self.title3.grid(padx=2, pady=2, row=1, column=2, sticky=E)

self.button1 = Button(self.myFunctionContainer, text=Calculate)
self.button1.bind(Button-1, self.markup1)
self.button1.grid(padx=2, pady=2, row=3, column=1, columnspan=2, 
sticky=W+E)


def gpExact(self, event):
self.clearScreen()

self.gpRangeTab = Button(self.myFunctionContainer, width=14, bg=dark 
grey, relief=SUNKEN, text=Multi-Markup)
self.gpRangeTab.bind(Button-1, self.gpRange)
self.gpRangeTab.grid(row=0, column=0)

self.gpExactTab = Button(self.myFunctionContainer, width=14, 
relief=FLAT, text=Single Markup)
self.gpExactTab.bind(Button-1, self.gpExact)
self.gpExactTab.grid(row=0, column=1)

self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, 
bg=dark grey, relief=SUNKEN, text=Product Increase)
self.priceIncreaseTab.bind(Button-1, self.priceIncrease)
self.priceIncreaseTab.grid(row=0, column=2)

self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg=dark 
grey, relief=SUNKEN, text=Calculate GP)
self.gpFinderTab.bind(Button-1, self.gpFinder)
self.gpFinderTab.grid(row=0, column=3)

self.markup2(1)

self.title1 = Label(self.myFunctionContainer, font=bold, 
relief=GROOVE, text=Single Markup Calculator)
self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, 
sticky=W+E)

self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG2)

Multipart - Counting the amount of Values for One key

2008-08-29 Thread Ron Brennan
hello,

I am trying to find the amount of values there are pertaining to one key.

For example:

- To find the average of the values pertaining to the key.
- Use the amount of values to calculate a histogram

Also, how do reference a specific value for a key in a multipart?

Thanks,
Ron



-- 
FYI, my email address is changing. My rogers account will be deactivated
shortly. From now on please use:
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Re: When to use try and except?

2008-08-29 Thread Daniel
On Aug 29, 11:23 am, cnb [EMAIL PROTECTED] wrote:
 If I get zero division error it is obv a poor solution to do try and
 except since it can be solved with an if-clause.

 However if a program runs out of memory I should just let it crash
 right? Because if not then I'd have to write exceptions everywhere to
 prevent that right?

 So when would I actually use try-except?

 If there can be several exceptions and I just want to catch 1 or 2?
 Like
 try:
     blahaba
 except SomeError:
     do something

I'm not sure whay you're trying to do, but I think catching a
ZeroDivisionError exception is a good use of try-except.

I'm also not sure that I would say you just let a program crash if it
runs out of memory.  I would think that from the user perspective, you
would want to check memory conditions and come up with an exception
indicating that some memory threshold has been reached.  When that
exception is raised you should indicate that to the user and exit
gracefully.
--
http://mail.python.org/mailman/listinfo/python-list


Re: When to use try and except?

2008-08-29 Thread George Sakkis
On Aug 29, 1:23 pm, cnb [EMAIL PROTECTED] wrote:

 If I get zero division error it is obv a poor solution to do try and
 except since it can be solved with an if-clause.

 However if a program runs out of memory I should just let it crash
 right? Because if not then I'd have to write exceptions everywhere to
 prevent that right?

 So when would I actually use try-except?

Whenever you can do something *meaningful* in the except block to
handle the exception (e.g. recover). Is there any meaningful action
you can take when you run out of memory ? If yes (e.g. write current
data to the disk and open a popup window that informs ths user), then
use try/except, otherwise don't. IOW code like the following

try:
...
except MemoryError:
print You ran out of memory!

is typically useless; better let the exception propagate to the top
level with a full traceback.

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


Re: Tkinter event loop question

2008-08-29 Thread Russell E. Owen
In article 
[EMAIL PROTECTED],
 gordon [EMAIL PROTECTED] wrote:

 On Aug 29, 4:45 am, Russell E. Owen [EMAIL PROTECTED] wrote:
 your Controller object should not create root nor should
  it call mainloop to start the event loop.
 
 guys
 thanks for the helpful replies..I rewrote the code as you advised. It
 creates a controller object and a gui object from main script.However
 i had to chain some method calls in my code.i am
 wondering if that can be avoided in some way.
 
 this is the sequence
 1.user enters some value in the textfield,and clicks OKbutton
 2.on OKbuttonclick ,the gui takes userinput value and quits
 eventloop.It then calls controller and pass the userinputvalue.
 3.controller does some calculation(i shd have an external program to
 do calculation,but for simplicity i just wrote a method inside
 controller) with the given value,obtains the result and calls gui's
 updateDisplay(), passing the result value.
 4.the gui creates the result as text on a canvas.then the mainloop()
 is called to resume event loop
 
 again user enters some value in the textfield,and clicks OKbutton ...
 
 I exit the application by clicking quitButton that calls destroy() on
 top level window.
  I tried my application by entering some value on text field and then
 clicking OKbutton ,the calculated result is displayed on canvas .I do
 this process say 3 times ..Then i click the Quit button and the window
 closes.
 I have put a print statement inside the gui's updateDisplay()method
 right after the resuming of event loop by parent.mainloop().This print
 statement gets printed as many times as i had clicked
 the OK button(here in this case 3 times).Is this due to clearing of
 the stack ?
 I feel that it was not a good design ..I would be grateful if someone
 would tell me how i could improve it..can those chaining of method
 calls be avoided?
 
 this is how i restructured the code

Why do you quite the event loop? Just leave it running.

On pressing the button you validate the input, perform the computation 
and display the result, all without leaving the event loop.

If your computation is very slow then you have other issues to deal with 
(in particular background threads cannot safely talk to Tkinter, but you 
can safely compute stuff with a background thread and display it from 
the main thread). But cross that bridge later.

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


  1   2   3   >