Re: tiny script has memory leak

2012-05-17 Thread Iain King
On Friday, 11 May 2012 22:29:39 UTC+1, gry  wrote:
 sys.version -- '2.6 (r26:66714, Feb 21 2009, 02:16:04) \n[GCC 4.3.2
 [gcc-4_3-branch revision 141291]]
 I thought this script would be very lean and fast, but with a large
 value for n (like 15), it uses 26G of virtural memory, and things
 start to crumble.
 
 #!/usr/bin/env python
 '''write a file of random integers.  args are: file-name how-many'''
 import sys, random
 
 f = open(sys.argv[1], 'w')
 n = int(sys.argv[2])
 for i in xrange(n):
 print f, random.randint(0, sys.maxint)
 f.close()
 
 What's using so much memory?
 What would be a better way to do this?  (aside from checking arg
 values and types, I know...)

Ran OK for me, python 2.4.1 on Windows 7

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


Re: Python Gotcha's?

2012-04-05 Thread Iain King
A common one used to be expecting .sort() to return, rather than mutate (as it 
does).  Same with .reverse() - sorted and reversed have this covered, not sure 
how common a gotcha it is any more.


Iain


On Wednesday, 4 April 2012 23:34:20 UTC+1, Miki Tebeka  wrote:
 Greetings,
 
 I'm going to give a Python Gotcha's talk at work.
 If you have an interesting/common Gotcha (warts/dark corners ...) please 
 share.
 
 (Note that I want over http://wiki.python.org/moin/PythonWarts already).
 
 Thanks,
 --
 Miki

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


Re: Code Review

2011-05-25 Thread Iain King
On May 25, 2:44 pm, ad adsquai...@gmail.com wrote:
 On May 25, 4:06 am, Ulrich Eckhardt ulrich.eckha...@dominolaser.com
 wrote:



  ad wrote:
   Please review the code pasted below. I am wondering what other ways
   there are of performing the same tasks.

  On a unix system, you would call find with according arguments and then
  handle the found files with -exec rm ... or something like that, but I see
  you are on MS Windows.

   args = parser.parse_args()

   dictKeys = (vars(args))

  The first of these looks okay, while I don't get the additional brackets in
  the second one. Another habit I observe here is the Hungarian notation of
  prefixing the type to the name and using camelCaps. PEP 8 (IIRC) has
  something to say on the preferred naming. I'm not 100% against encoding the
  type in the variable name in Python, since it lacks static type checking, I
  would have chosen key_dict here though, or, due to the small size of the
  overall program just keys.

   print (HowManyDays)

  This puzzled me at first, again the useless additional brackets I thought.
  However, in Python 3, print is a function, so that is correct. Still, it
  should be print(foo) not print (foo).

   for files in DirListing:

       # Get the absolute path of the file name
       abspath = (os.path.join(WhatDirectory, files))

  files is just the name of a single file, right? In that case the name is a
  bit confusing.

       # Get the date from seven days ago
       WeekOldFileDate = CurrentTime - DaysToDelete

  You are repeating this calculation for every file in the loop.

       if FileCreationTime  WeekOldFileDate:
           #check if the object is a file
           if os.path.isfile(abspath): os.remove(abspath)
           # It is not a file it is a directory
           elif os.path.isdir(abspath): shutil.rmtree(abspath)

  I'm not sure, but I believe you could use shutil.rmtree() for both files and
  directories. In any case, be prepared for the file still being open or
  otherwise read-only, i.e. for having to handle errors.

  Also, what if a directory is old but the content is new? Would this cause
  the non-old content to be deleted?

  Cheers!

  Uli

  --
  Domino Laser GmbH
  Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

 Thank you guys very much for the excellent points. I will use this
 information as a reference as I write more code and fix up the
 existing script.

 Chris, thank you for putting so much time into your post!

 Until we type again...


Wrote something to do the same basic thing a little while ago.  Less
verbose than yours, and it only does files, not folders.  If I was
going to do folders though, I'd do them by recursing into them and
pruning files, and not go by the folder modify date, which I don't
think changes the way you think it changes (for example, if a file
inside a folder got updated such that it shouln't be deleted it still
will be with your code if the folder modify date is old [this is on
Windows])

import os, glob, time, sys

if len(sys.argv)  3:
print USAGE: %s PATTERN DAYS % sys.argv[0]
sys.exit(1)

pattern = sys.argv[1]
days = int(sys.argv[2])
threshold = days * 24 * 60 * 60
t = time.time()

for f in glob.glob(pattern):
if t - os.stat(f)[9]  threshold:
print f
os.remove(f)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: use of index (beginner's question)

2011-04-28 Thread Iain King
On Apr 28, 2:45 am, Chris Angelico ros...@gmail.com wrote:
 Incidentally, you're allowed to put the comma on the last item too:

  lists = [
   ['pig', 'horse', 'moose'],
   ['62327', '49123', '79115'],
 ]

 Often makes for easier maintenance, especially when you append
 array/list elements.

 Chris Angelico

I did not know this.  Very useful!

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


Re: Using nested lists and tables

2010-10-28 Thread Iain King
On Oct 28, 2:19 pm, Zeynel azeyn...@gmail.com wrote:
 On Oct 28, 4:49 am, Peter Otten __pete...@web.de wrote:

 Thank you this is great; but I don't know how to modify this code so
 that when the user types the string 's' on the form in the app he sees
 what he is typing. So, this will be in GAE. But I have a couple of
 other questions, for learning purposes. Thanks again, for the help.

  ...     if columns and columns[-1][0] == s:

 Here, how do you compare columns (a list?) and columns[-1][0] (an
 item in a list)?


It's equivalent to:

if columns:
if columns[-1][0] == s:
dostuff()

i.e. check columns is not empty and then check if the last item
startswith 's'.

(a) I don't know if the order of resolution is predicated left-to-
right in the language spec of if it's an implementation detail
(b) columns[-1].startswith('s') would be better

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


Re: Using nested lists and tables

2010-10-28 Thread Iain King
On Oct 28, 2:35 pm, Iain King iaink...@gmail.com wrote:
...
 (a) I don't know if the order of resolution is predicated left-to-
 right in the language spec of if it's an implementation detail
 (b) columns[-1].startswith('s') would be better

...

Ignore (b), I didn't read the original message properly.

Iain


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


Re: replacing words in HTML file

2010-04-29 Thread Iain King
On Apr 29, 10:38 am, Daniel Fetchinson fetchin...@googlemail.com
wrote:
  |  Any idea how I can replace words in a html file? Meaning only the
  |  content will get replace while the html tags, javascript,  css are
  |  remain untouch.
  |
  | I'm not sure what you tried and what you haven't but as a first trial
  | you might want to
  |
  | untested
  |
  | f = open( 'new.html', 'w' )
  | f.write( open( 'index.html' ).read( ).replace( 'replace-this', 'with-that'
  ) )
  | f.close( )
  |
  | /untested

  If 'replace-this' occurs inside the javascript etc or happens to be an
  HTML tag name, it will get mangled. The OP didn't want that.

 Correct, that is why I started with I'm not sure what you tried and
 what you haven't but as a first trial you might. For instance if the
 OP wants to replace words which he knows are not in javascript and/or
 css and he knows that these words are also not in html attribute
 names/values, etc, etc, then the above approach would work, in which
 case BeautifulSoup is a gigantic overkill. The OP needs to specify
 more clearly what he wants, before really useful advice can be given.

 Cheers,
 Daniel


Funny, everyone else understood what the OP meant, and useful advice
was given.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Usable street address parser in Python?

2010-04-20 Thread Iain King
On Apr 20, 8:24 am, John Yeung gallium.arsen...@gmail.com wrote:
 My response is similar to John Roth's.  It's mainly just sympathy. ;)

 I deal with addresses a lot, and I know that a really good parser is
 both rare/expensive to find and difficult to write yourself.  We have
 commercial, USPS-certified products where I work, and even with those
 I've written a good deal of pre-processing and post-processing code,
 consisting almost entirely of very silly-looking fixes for special
 cases.

 I don't have any experience whatsoever with pyparsing, but I will say
 I agree that you should try to get the street type from the end of the
 line.  Just be aware that it can be valid to leave off the street type
 completely.  And of course it's a plus if you can handle suites that
 are on the same line as the street (which is where the USPS prefers
 them to be).

 I would take the approach which John R. seems to be suggesting, which
 is to tokenize and then write a whole bunch of very hairy, special-
 case-laden logic. ;)  I'm almost positive this is what all the
 commercial packages are doing, and I have a tough time imagining what
 else you could do.  Addresses inherently have a high degree of
 irregularity.

 Good luck!

 John Y.

Not sure on the volume of addresses you're working with, but as an
alternative you could try grabbing the zip code, looking up all
addresses in that zip code, and then finding whatever one of those
address strings most closely resembles your address string (smallest
Levenshtein distance?).

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


Re: Code redundancy

2010-04-20 Thread Iain King
On Apr 20, 2:43 pm, Alan Harris-Reid aharrisr...@googlemail.com
wrote:
 Hi,

 During my Python (3.1) programming I often find myself having to repeat
 code such as...

 class1.attr1 = 1
 class1.attr2 = 2
 class1.attr3 = 3
 class1.attr4 = 4
 etc.

 Is there any way to achieve the same result without having to repeat the
 class1 prefix?  Before Python my previous main language was Visual
 Foxpro, which had the syntax...

 with class1
    .attr1 = 1
    .attr2 = 2
    .attr3 = 3
    .attr4 = 4
    etc.
 endwith

 Is there any equivalent to this in Python?

 Any help would be appreciated.

 Alan Harris-Reid

The pythonic equivalent of VB 'with' is to assign to a short variable
name, for example '_':

_ = class1
_.attr1 = 1
_.attr2 = 2
_.attr3 = 3
_.attr4 = 4

alternatively, you could use the __setattr__ method:

for attr, value in (
('attr1', 1),
('attr2', 2),
('attr3', 3),
('attr4', 4)):
class1.__setattr__(attr, value)

and to get a bit crunchy, with this your specific example can be
written:

for i in xrange(1, 5):
class1.__setattr__('attr%d' % i, i)

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


Re: why (1, 2, 3) [1, 2, 3] is true?

2010-02-25 Thread Iain King
On Feb 25, 2:03 pm, fat bold cyclop fat.bold.cyc...@gmail.com wrote:
  Both are not equal, so the comparison returns an arbitrary result in Py2.

 Thanks, Stefan. If I understand you correctly the comparison is not
 valid.
 But I wonder if there is any logic behind this (in 2.x).
 Is it possible to predict result of this comparison?

 Thanks again,
 fbc

I haven't looked in the source to check (and I'm almost 100% certain
that tuple  list is an implementation detail), but I have not found
any pair of tuple and list in which the list is treated as the
greater.  Possibly related: type(tuple()) is  type(list()). Or, to
let the interpreter tell you why (1,2,3)  [1,2,3]:

 tuple  list
True

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


Re: Ad hoc lists vs ad hoc tuples

2010-01-27 Thread Iain King
On Jan 27, 10:20 am, Floris Bruynooghe floris.bruynoo...@gmail.com
wrote:
 One thing I ofter wonder is which is better when you just need a
 throwaway sequence: a list or a tuple?  E.g.:

 if foo in ['some', 'random', 'strings']:
     ...
 if [bool1, bool2, boo3].count(True) != 1:
    ...

 (The last one only works with tuples since python 2.6)

 Is a list or tuple better or more efficient in these situations?

 Regards
 Floris

 PS: This is inspired by some of the space-efficiency comments from the
 list.pop(0) discussion.

I tend to use tuples unless using a list makes it easier to read.  For
example:

if foo in ('some', 'random', 'strings'):

draw.text((10,30), WHICH IS WHITE, font=font)
draw.line([(70,25), (85,25), (105,45)])

I've no idea what the performance difference is; I've always assumed
it's negligible.

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


Re: Symbols as parameters?

2010-01-21 Thread Iain King
On Jan 21, 7:43 am, Martin Drautzburg martin.drautzb...@web.de
wrote:
 Hello all,

 When passing parameters to a function, you sometimes need a paramter
 which can only assume certain values, e.g.

         def move (direction):
                 ...
 If direction can only be up, down, left or right, you can solve
 this by passing strings, but this is not quite to the point:

         - you could pass invalid strings easily
         - you need to quote thigs, which is a nuisance
         - the parameter IS REALLY NOT A STRING, but a direction

 Alternatively you could export such symbols, so when you import * you
 have them available in the caller's namespace. But that forces you
 to import * which pollutes your namespace.

 What I am really looking for is a way

         - to be able to call move(up)
         - having the up symbol only in the context of the function call

 So it should look something like this

 ... magic, magic ...
 move(up)
 ... unmagic, unmagic ...
 print up

 This should complain that up is not defined during the print call,
 but not when move() is called. And of course there should be as little
 magic as possible.

 Any way to achieve this?

class Direction(object):
  pass

def is_direction(d):
  return type(d)==Direction

up = Direction()
down = Direction()
left = Direction()
right = Direction()

Now you can do your move(up), print up, etc. You can also check a
valid direction was passed in by calling is_direction.  'Course, you
can extend this so it does something a little more useful:

class Direction(object):
  def __init__(self, vx=0, vy=0):
self.vx = vx
self.vy = vy

up = Direction(0, -1)
down = Direction(0, 1)
left = Direction(-1, 0)
right = Direction(1, 0)

def move(direction):
  spaceship.x += direction.vx
  spaceship.y += direction.vy

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


Re: substitution

2010-01-21 Thread Iain King
On Jan 21, 2:18 pm, Wilbert Berendsen wbs...@xs4all.nl wrote:
 Op maandag 18 januari 2010 schreef Adi:

  keys = [(len(key), key) for key in mapping.keys()]
  keys.sort(reverse=True)
  keys = [key for (_, key) in keys]

  pattern = (%s) % |.join(keys)
  repl = lambda x : mapping[x.group(1)]
  s = fooxxxbazyyyquuux

  re.subn(pattern, repl, s)

 I managed to make it even shorted, using the key argument for sorted, not
 putting the whole regexp inside parentheses and pre-compiling the regular
 expression:

 import re

 mapping = {
         foo : bar,
         baz : quux,
         quuux : foo

 }

 # sort the keys, longest first, so 'aa' gets matched before 'a', because
 # in Python regexps the first match (going from left to right) in a
 # |-separated group is taken
 keys = sorted(mapping.keys(), key=len)

 rx = re.compile(|.join(keys))
 repl = lambda x: mapping[x.group()]
 s = fooxxxbazyyyquuux
 rx.sub(repl, s)

 One thing remaining: if the replacement keys could contain non-alphanumeric
 characters, they should be escaped using re.escape:

 rx = re.compile(|.join(re.escape(key) for key in keys))

 Met vriendelijke groet,
 Wilbert Berendsen

 --http://www.wilbertberendsen.nl/
 You must be the change you wish to see in the world.
         -- Mahatma Gandhi

Sorting it isn't the right solution: easier to hold the subs as tuple
pairs and by doing so let the user specify order.  Think of the
following subs:

fooxx - baz
oxxx - bar

does the user want bazxbazyyyquuux or fobarbazyyyquuux?

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


Re: substitution

2010-01-18 Thread Iain King
On Jan 18, 10:21 am, superpollo ute...@esempio.net wrote:
 superpollo ha scritto:

  hi.

  what is the most pythonic way to substitute substrings?

  eg: i want to apply:

  foo -- bar
  baz -- quux
  quuux -- foo

  so that:

  fooxxxbazyyyquuux -- barxxxquuxyyyfoo

  bye

 i explain better:

 say the subs are:

 quuux -- foo
 foo -- bar
 baz -- quux

 then i cannot apply the subs in sequence (say, .replace() in a loop),
 otherwise:

 fooxxxbazyyyquuux -- fooxxxbazyyyfoo -- barxxxbazyyybar --
 barxxxquuxyyybar

 not as intended...


Not sure if it's the most pythonic, but I'd probably do it like this:

def token_replace(string, subs):
subs = dict(subs)
tokens = {}
for i, sub in enumerate(subs):
tokens[sub] = i
tokens[i] = sub
current = [string]
for sub in subs:
new = []
for piece in current:
if type(piece) == str:
chunks = piece.split(sub)
new.append(chunks[0])
for chunk in chunks[1:]:
new.append(tokens[sub])
new.append(chunk)
else:
new.append(piece)
current = new
output = []
for piece in current:
if type(piece) == str:
output.append(piece)
else:
output.append(subs[tokens[piece]])
return ''.join(output)

 token_replace(fooxxxbazyyyquuux, [(quuux, foo), (foo, bar), 
 (baz, quux)])
'barxxxquuxyyyfoo'

I'm sure someone could whittle that down to a handful of list comps...
Iain
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: substitution

2010-01-18 Thread Iain King
On Jan 18, 12:41 pm, Iain King iaink...@gmail.com wrote:
 On Jan 18, 10:21 am, superpollo ute...@esempio.net wrote:



  superpollo ha scritto:

   hi.

   what is the most pythonic way to substitute substrings?

   eg: i want to apply:

   foo -- bar
   baz -- quux
   quuux -- foo

   so that:

   fooxxxbazyyyquuux -- barxxxquuxyyyfoo

   bye

  i explain better:

  say the subs are:

  quuux -- foo
  foo -- bar
  baz -- quux

  then i cannot apply the subs in sequence (say, .replace() in a loop),
  otherwise:

  fooxxxbazyyyquuux -- fooxxxbazyyyfoo -- barxxxbazyyybar --
  barxxxquuxyyybar

  not as intended...

 Not sure if it's the most pythonic, but I'd probably do it like this:

 def token_replace(string, subs):
         subs = dict(subs)
         tokens = {}
         for i, sub in enumerate(subs):
                 tokens[sub] = i
                 tokens[i] = sub
         current = [string]
         for sub in subs:
                 new = []
                 for piece in current:
                         if type(piece) == str:
                                 chunks = piece.split(sub)
                                 new.append(chunks[0])
                                 for chunk in chunks[1:]:
                                         new.append(tokens[sub])
                                         new.append(chunk)
                         else:
                                 new.append(piece)
                 current = new
         output = []
         for piece in current:
                 if type(piece) == str:
                         output.append(piece)
                 else:
                         output.append(subs[tokens[piece]])
         return ''.join(output)

  token_replace(fooxxxbazyyyquuux, [(quuux, foo), (foo, bar), 
  (baz, quux)])

 'barxxxquuxyyyfoo'

 I'm sure someone could whittle that down to a handful of list comps...
 Iain

Slightly better (lets you have overlapping search strings, used in the
order they are fed in):

def token_replace(string, subs):
tokens = {}
if type(subs) == dict:
for i, sub in enumerate(subs):
tokens[sub] = i
tokens[i] = subs[sub]
else:
s = []
for i, (k,v) in enumerate(subs):
tokens[k] = i
tokens[i] = v
s.append(k)
subs = s
current = [string]
for sub in subs:
new = []
for piece in current:
if type(piece) == str:
chunks = piece.split(sub)
new.append(chunks[0])
for chunk in chunks[1:]:
new.append(tokens[sub])
new.append(chunk)
else:
new.append(piece)
current = new
output = []
for piece in current:
if type(piece) == str:
output.append(piece)
else:
output.append(tokens[piece])
return ''.join(output)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: substitution

2010-01-18 Thread Iain King
On Jan 18, 2:17 pm, Adi Eyal a...@digitaltrowel.com wrote:
  From: superpollo ute...@esempio.net
  To:
  Date: Mon, 18 Jan 2010 11:15:37 +0100
  Subject: substitution
  hi.

  what is the most pythonic way to substitute substrings?

  eg: i want to apply:

  foo -- bar
  baz -- quux
  quuux -- foo

  so that:

  fooxxxbazyyyquuux -- barxxxquuxyyyfoo

  bye

 Using regular expressions the answer is short (and sweet)

 mapping = {
         foo : bar,
         baz : quux,
         quuux : foo

 }

 pattern = (%s) % |.join(mapping.keys())
 repl = lambda x : mapping.get(x.group(1), x.group(1))
 s = fooxxxbazyyyquuux
 re.subn(pattern, repl, s)

Winner! :)

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


Re: substitution

2010-01-18 Thread Iain King
On Jan 18, 4:26 pm, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:
 On Mon, 18 Jan 2010 06:23:44 -0800, Iain King wrote:
  On Jan 18, 2:17 pm, Adi Eyal a...@digitaltrowel.com wrote:
 [...]
  Using regular expressions the answer is short (and sweet)

  mapping = {
          foo : bar,
          baz : quux,
          quuux : foo

  }

  pattern = (%s) % |.join(mapping.keys())
  repl = lambda x : mapping.get(x.group(1), x.group(1))
  s = fooxxxbazyyyquuux
  re.subn(pattern, repl, s)

  Winner! :)

 What are the rules for being declared Winner? For the simple case
 given, calling s.replace three times is much faster: more than twice as
 fast.

 But a bigger problem is that the above winner may not work correctly if
 there are conflicts between the target strings (e.g. 'a'-'X',
 'aa'-'Y'). The problem is that the result you get depends on the order
 of the searches, BUT as given, that order is non-deterministic.
 dict.keys() returns in an arbitrary order, which means the caller can't
 specify the order except by accident. For example:

  repl = lambda x : m[x.group(1)]
  m = {'aa': 'Y', 'a': 'X'}
  pattern = (%s) % |.join(m.keys())
  subn(pattern, repl, 'aaa')  # expecting 'YX'

 ('XXX', 3)

 The result that you get using this method will be consistent but
 arbitrary and unpredictable.

 For those who care, here's my timing code:

 from timeit import Timer

 setup = 
 mapping = {foo : bar, baz : quux, quuux : foo}
 pattern = (%s) % |.join(mapping.keys())
 repl = lambda x : mapping.get(x.group(1), x.group(1))
 repl = lambda x : mapping[x.group(1)]
 s = fooxxxbazyyyquuux
 from re import subn
 

 t1 = Timer(subn(pattern, repl, s), setup)
 t2 = Timer(
 s.replace('foo', 'bar').replace('baz', 'quux').replace('quuux', 'foo'),
 s = 'fooxxxbazyyyquuux')

 And the results on my PC:

  min(t1.repeat(number=10))
 1.1273870468139648
  min(t2.repeat(number=10))

 0.49491715431213379

 --
 Steven

Adi elicited that response from me because his solution was vastly
more succinct than everything else that had appeared up til that point
while still meeting the OP's requirements.  The OP never cared about
overlap between 2 'find' strings, just between the 'find' and
'replace' strings (though I did take it into account in my second post
for the sake of completeness).  His code could have been a little
cleaner, I'd have trimmed it to:

mapping = {foo: bar, baz: quux, quuux: foo}
pattern = (%s) % |.join(mapping)
repl = lambda x : mapping[x.group(1)]
s = fooxxxbazyyyquuux
re.subn(pattern, repl, s)

but apart from that was very pythonic: explicit, succinct, and all the
heavy work is done by the module (i.e. in compiled c code in the
majority case of CPython).  It can be 'upgraded' to cover the find-
find overlap if you really want (I *believe* regexps will match the
leftmost option in a group first):

subs = [(foo, bar), (baz, quux), (quuux, foo)]
pattern = (%s) % |.join((x[0] for x in subs))
mapping = dict(subs)
repl = lambda x : mapping[x.group(1)]
s = fooxxxbazyyyquuux
re.subn(pattern, repl, s)

Anyway, there's no prize for winning, but by all means: if you think
someone else's code and not a variation on this should win for most
pythonic, then make your nomination :)

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


Re: Writing a string.ishex function

2010-01-14 Thread Iain King
On Jan 14, 3:52 pm, chandra chyav...@gmail.com wrote:
 Folks,

 I am new to Python and could not find a function along the lines of
 string.ishex in Python. There is however, a string.hexdigits constant
 in the string module. I thought I would enhance the existing modlue
 but am unsure how I should go about it. Specifically, I have attempted
 this much:
 ---cut---
 #! /usr/bin/python
 # -*- coding: utf-8 -*-

 import string

 def ishex(string):
     ishex = False
     for i in string:
         if i in string.hexdigits:
             ishex = True
         else:
             ishex = False
             break
     return ishex
 ---cut---

 Can someone help me get further along please?

 Thanks.

better would be:
def ishex(s):
for c in s:
if c not in string.hexdigits:
return False
return True

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


Re: Different number of matches from re.findall and re.split

2010-01-11 Thread Iain King
On Jan 11, 3:35 pm, Jeremy jlcon...@gmail.com wrote:
 Hello all,

 I am using re.split to separate some text into logical structures.
 The trouble is that re.split doesn't find everything while re.findall
 does; i.e.:



  found = re.findall('^ 1', line, re.MULTILINE)
  len(found)
    6439
  tables = re.split('^ 1', line, re.MULTILINE)
  len(tables)
  1

 Can someone explain why these two commands are giving different
 results?  I thought I should have the same number of matches (or maybe
 different by 1, but not 6000!)

 Thanks,
 Jeremy

re.split doesn't take re.MULTILINE as a flag: it doesn't take any
flags. It does take a maxsplit parameter, which you are passing the
value of re.MULTILINE (which happens to be 8 in my implementation).
Since your pattern is looking for line starts, and your first line
presumably has more splits than the maxsplits you are specifying, your
re.split never finds more than 1.

 a
'split(pattern, string, maxsplit=0)\nSplit the source string by
the occurren
ces of the pattern,\nreturning a list containing the resulting
substrings.\n
'
 re.split( , a, re.MULTILINE)
['split(pattern,', 'string,', 'maxsplit=0)\n', '', '', '', 'Split',
'the', 'sour
ce string by the occurrences of the pattern,\nreturning a list
containing th
e resulting substrings.\n']
 re.split( , a)
['split(pattern,', 'string,', 'maxsplit=0)\n', '', '', '', 'Split',
'the', 'sour
ce', 'string', 'by', 'the', 'occurrences', 'of', 'the', 'pattern,\n',
'', '', ''
, 'returning', 'a', 'list', 'containing', 'the', 'resulting',
'substrings.\n']


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


Re: The rap against while True: loops

2009-10-20 Thread Iain King
On Oct 19, 7:51 am, Hendrik van Rooyen hend...@microcorp.co.za
wrote:
 On Sunday, 18 October 2009 11:31:19 Paul Rubin wrote:

  Hendrik van Rooyen hend...@microcorp.co.za writes:
   Standard Python idiom:

   if key in d:
     d[key] += value
   else:
     d[key] = value

  The issue is that uses two lookups.  If that's ok, the more usual idiom is:

    d[key] = value + d.get(key, 0)

 I was actually just needling Aahz a bit.  The point I was trying to make
 subliminally, was that there is a relative cost of double lookup for all
 cases versus exceptions for some cases. - Depending on the frequency
 of some, I would expect a breakeven point.

 - Hendrik

Indeed - the method I use for this (picked up from this newsgroup), is
to work out roughly how often you need to make a new record instead of
altering a current one, and depending on that use either:

if key in d:
d[key] += value
else:
d[key] = value

or

try:
d[key] += value
except KeyError:
d[key] = value


I find both to be easily readable (and the similarity between the two
blocks is obvious and, to me at least, pleasing).

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


Re: Simple if-else question

2009-09-30 Thread Iain King
On Sep 30, 7:12 am, Steven D'Aprano
ste...@remove.this.cybersource.com.au wrote:
 On Tue, 29 Sep 2009 22:29:10 -0700, John Yeung wrote:
  On Sep 29, 1:15 pm, Carl Banks pavlovevide...@gmail.com wrote:
  Hmm, I wonder if Python should emit a warning if an else is used on a
  for block with no break inside.  I don't think the else can be invoked
  in any other way.  As a bonus it could catch some cases where people
  mistakenly use it thinking it will execute [only] when there are no
  iterations.

  [Edit from Duncan Booth]

  I would definitely be in favor of a warning.  Yes, people should read
  the docs more carefully, and yes, it would cost a certain amount of
  annoyance to implement this.  But I don't think it would get in people's
  way if they do know how to use else,

 Of course it would. It would mean that everybody who knows how to use
 for...else correctly would have to deal with a totally useless warning.

  and I think it would cut down on
  the number of questions from mystified beginners, some of whom are much
  more aggressive than this particular OP about claiming that Python is
  broken (when it's actually behaving as designed).

 By raising a warning, you are implying that the behaviour is broken, or
 at least suspicious. Warnings mean something needs to be warned against
 -- don't do this. Warnings shouldn't be perfectly legitimate behaviours
 on the off-chance that the user is confused. Warning, are you sure you
 want to put the car into reverse? Perhaps you meant neutral?

 What would the warning say?

 Warning, you have used a legitimate Python control structure but you
 might be confused by it.

 Warning, did you mean if...else instead of for...else?

 Then we can add a whole lot of extra warnings to protect newbies who
 don't read docs (and probably won't read the warnings either) from
 themselves:

 Warning, did you mean obj(1) instead of obj[1]?

 Warning, did you mean def f(object) instead of class f(object)?

 Warning, did you mean class f(object) instead of def f(object)?

 Warning, did you mean 2*3 instead of 2**3?

 Warning, did you mean %s instead of %x?

 Warning, we think you're helpless and don't know what you want, perhaps
 you should be programming in PHP?

 I'm sympathetic to the desire to educate the n00bs, and in fact I've even
 suggested similar warnings myself. But I've been convinced that this is
 the wrong approach. Certainly the language shouldn't assume the
 programmer is confused. If this sort of warning belongs anywhere (and
 that's a big if), it belongs in an IDE.

 --
 Steven

Read the suggestion again - it's not a warning on the for-else
structure, it's a warning when the for-else doesn't contain a break;
he's theorising that a for-else without a break will always trigger
the else, in which case it's almost certainly an error, and having the
warning is not a bad idea.
However, I assume you can get past the else by raising an exception,
so the idea becomes a little muddled - do you warn when there is no
break and no explicit raise caught outside the loop?  What about an
implicit exception?  I would guess that code intentionally using an
implicit exception to break out of a for loop is in need of a warning
(and the author in need of the application of a lart), but I'm sure
you could construct a plausible situation where it wouldn't be that
bad...

Anyway, I'm ambivalently on the fence.

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


Re: easy question, how to double a variable

2009-09-24 Thread Iain King
On Sep 23, 7:36 pm, David C Ullrich dullr...@sprynet.com wrote:
 On Tue, 22 Sep 2009 02:34:53 +, Steven D'Aprano wrote:
  On Mon, 21 Sep 2009 13:50:23 -0500, David C Ullrich wrote:

  But you actually want to return twice the value. I don't see how to do
  that.

  What?

  Seriously?

 You're saying it _can_ be done in Python? They must have added
 something to the standard library again. I mean how can you return
 twice a value without a twice function to start with? I've tried.
 You'd think

 def twice(n):
   return twice(n)

 would work, but I get this really long error message.

  You're not just yanking the OP's chain???

 That would be cruel. I mean the guy has enough problems already...

Sorry, there is no 'twice' builtin.  I think what you are looking for
is:

def twice(n):
return return n


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


Re: remove last 76 letters from string

2009-08-06 Thread Iain King
  print nucleotides, seq[-76]

      last_part = line.rstrip()[-76 : ]

You all mean:   seq[:-76]   , right? (assuming you've already stripped
any junk off the end of the string)

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


Re: remove last 76 letters from string

2009-08-06 Thread Iain King
On Aug 6, 11:34 am, MRAB pyt...@mrabarnett.plus.com wrote:
 Iain King wrote:
       print nucleotides, seq[-76]

       last_part = line.rstrip()[-76 : ]

  You all mean:   seq[:-76]   , right? (assuming you've already stripped
  any junk off the end of the string)

 The OP said cut out the last 76 letters (nucleotides) from each
 individual sequence and send them to a new txt file with a similar
 format., ie extract the last 76 letters (in the same format) to a file.

So he did.  Excuse me while I go eat my other foot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confessions of a Python fanboy

2009-07-31 Thread Iain King
On Jul 31, 8:28 am, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:
 On Thu, 30 Jul 2009 18:06:31 -0500, Robert Kern wrote:
  On 2009-07-30 16:44, r wrote:
  On Jul 30, 4:29 pm, Emmanuel Surleauemmanuel.surl...@gmail.com wrote:
  1.) No need to use () to call a function with no arguments. Python
  --  obj.m2().m3() --ugly
     Ruby --  obj.m1.m2.m3  -- sweeet!
  Man, i must admit i really like this, and your code will look so much
  cleaner.
  It has benefits - code does look better. It has also significant cons
  - it is ambiguous.
  For instance:

  a = b

  Is b a variable or a method called without parameter?

  Hello Emanuel,
  Again, who so ever names a method with such a non-descriptive name will
  get whats coming to him. And if you did for some reason use such a
  cryptic name as b, do yourself (and everyone else) a favor and follow
  it with () to denote the method call. Remember when something is
  optional that means you have an option to use it OR not use it.

  I believe his point is that it is ambiguous to the compiler, not humans
  reading the code. Python functions and methods are first class objects.
  They can be passed around. If they were auto-called, then you could not
  do this.

 Oh my, r is still around is he??? And now he's singing the praises of
 Ruby, the language which he treated as the Devil's Spawn when he first
 arrived. That's hilarious.

 But back on topic... r has missed the point. It's not that a=b is hard
 to understand because b is a poor name. The example could have been:

 def factory_function():
     magic = time.time()  # or whatever
     def inner():
         return magic
     return inner

 my_function = factory_function

 It's still ambiguous. Does the programmer intend my_function to become
 factory_function itself, or the output of factory_function?

Not only that - does 'return inner' return the function inner or the
result of function inner?

How does ruby pass a function as an object?

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


Re: Confessions of a Python fanboy

2009-07-31 Thread Iain King
On Jul 31, 4:08 pm, Ethan Furman et...@stoneleaf.us wrote:
 Steven D'Aprano wrote:
  On Thu, 30 Jul 2009 18:47:04 +0100, Tim Rowe wrote:

 That and the fact that I couldn't stop laughing for long enough to learn
 any more when I read in the Pragmatic Programmer's Guide that Ruby,
 unlike less flexible languages, lets you alter the value of a constant.
 Yep, as they say Bug = Undocumented feature!

  That's no different from Python's constant by convention. We don't even
  get a compiler warning!

 That's quite different, actually.  Python doesn't claim to have
 constants!  Can't misinterpret what you can't have, can you?

 [Holds breath while awaiting counter-example... :]

 ~Ethan~

The convention being detailed in PEP8: http://www.python.org/dev/peps/pep-0008/
basically, anything in ALL_CAPS is a constant, assuming you follow
those style guidelines.

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


Re: string character count

2009-07-01 Thread Iain King
On Jun 30, 6:27 pm, noydb jenn.du...@gmail.com wrote:
 If I have a string for a file name such that I want to find the number
 of characters to the left of the dot, how can that be done?

 I did it this way:
 x = text12345.txt
 dot = x.find('.')
 print dot

 Was curious to see what method others would use - helps me learn.  I
 guess I was most curious to see if it could be done in one line.

 And, how would a char count be done with no dot -- like if the string
 were textstringwithoutdot or no dot in text string?

import os
root, ext = os.path.splitext(x)
print len(root)

or in one line (assuming you've imported os):
print len(os.path.splitext(x)[0])


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


Re: do replacement evenly

2009-06-02 Thread Iain King
On Jun 2, 12:10 pm, oyster lepto.pyt...@gmail.com wrote:
 I have some strings, and I want to write them into a text files, one
 string one line
 but there is a requirement: every line has a max length of a certain
 number(for example, 10), so I have to replace extra SPACE*3 with
 SPACE*2, at the same time, I want to make the string looks good, so,
 for I am123456line123456three(to show the SPACE clearly, I type it
 with a number), the first time, I replace the first SPACE, and get I
 am23456line123456three, then I must replace at the second SPACE
 block, so I get  I am23456line23456three, and so on, if no SPACE*3
 is found, I have to aString.replace(SPACE*2, SPACE).
 I hope I have stated my case clear.

 Then the question is, is there a nice solution?

 thanx

Assuming you want to crush all spaces into single space, you can:

whilein s:
s = s.replace(  ,  )

readable but not efficient.  Better:

s =  .join((x for x in s.split( ) if x))

Note that this will strip leading and trailing spaces.

Or you can use regexps:

import re
s = re.sub( {2,},  , s)


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


Re: Adding a Par construct to Python?

2009-05-20 Thread Iain King
On May 19, 10:24 am, Steven D'Aprano
ste...@remove.this.cybersource.com.au wrote:
 On Mon, 18 May 2009 02:27:06 -0700, jeremy wrote:
  Let me clarify what I think par, pmap, pfilter and preduce would mean
  and how they would be implemented.

 [...]

 Just for fun, I've implemented a parallel-map function, and done a couple
 of tests. Comments, criticism and improvements welcome!

 import threading
 import Queue
 import random
 import time

 def f(arg):  # Simulate a slow function.
     time.sleep(0.5)
     return 3*arg-2

 class PMapThread(threading.Thread):
     def __init__(self, clients):
         super(PMapThread, self).__init__()
         self._clients = clients
     def start(self):
         super(PMapThread, self).start()
     def run(self):
         while True:
             try:
                 data = self._clients.get_nowait()
             except Queue.Empty:
                 break
             target, where, func, arg = data
             result = func(arg)
             target[where] = result

 class VerbosePMapThread(threading.Thread):
     def __init__(self, clients):
         super(VerbosePMapThread, self).__init__()
         print Thread %s created at %s % (self.getName(), time.ctime())
     def start(self):
         super(VerbosePMapThread, self).start()
         print Thread %s starting at %s % (self.getName(), time.ctime())
     def run(self):
         super(VerbosePMapThread, self).run()
         print Thread %s finished at %s % (self.getName(), time.ctime())

 def pmap(func, seq, verbose=False, numthreads=4):
     size = len(seq)
     results = [None]*size
     if verbose:
         print Initiating threads
         thread = VerbosePMapThread
     else:
         thread = PMapThread
     datapool = Queue.Queue(size)
     for i in xrange(size):
         datapool.put( (results, i, f, seq[i]) )
     threads = [PMapThread(datapool) for i in xrange(numthreads)]
     if verbose:
         print All threads created.
     for t in threads:
         t.start()
     # Block until all threads are done.
     while any([t.isAlive() for t in threads]):
         if verbose:
             time.sleep(0.25)
             print results
     return results

 And here's the timing results:

  from timeit import Timer
  setup = from __main__ import pmap, f; data = range(50)
  min(Timer('map(f, data)', setup).repeat(repeat=5, number=3))
 74.999755859375
  min(Timer('pmap(f, data)', setup).repeat(repeat=5, number=3))

 20.490942001342773

 --
 Steven

I was going to write something like this, but you've beat me to it :)
Slightly different though; rather than have pmap collate everything
together then return it, have it yield results as and when it gets
them and stop iteration when it's done, and rename it to par to keep
the OP happy and you should get something like what he initially
requests (I think):

total = 0
for score in par(f, data):
total += score


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


Re: Any idea to emulate tail -f

2009-05-05 Thread Iain King
On May 5, 7:00 am, Joel Juvenal Rivera Rivera joel...@gmail.com
wrote:
 I want to make something very similar to  the command tail -f (follow a
 file), i have been trying  with some while True and some microsleeps
 (about .1 s); did someone has already done something like this?

 And about the file is the apache acceslog  of a site with a lot of
 traffic.

 Regards    

 joe / Joel Rivera

This is very interesting, about using Generator Expressions:
http://209.85.229.132/search?q=cache:ZHrV4E0eTI8J:www.dabeaz.com/generators/Generators.pdf

Relevant stuff about 'tail -f' is on page 39, but I'd read the whole
thing if you can.

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


Re: Scraping a web page

2009-04-08 Thread Iain King
On Apr 7, 1:44 pm, Tim Chase python.l...@tim.thechases.com wrote:
  f = urllib.urlopen(http://www.google.com;)
  s = f.read()

  It is working, but it's returning the source of the page. Is there anyway I
  can get almost a screen capture of the page?

 This is the job of a browser -- to render the source HTML.  As
 such, you'd want to look into any of the browser-automation
 libraries to hook into IE, FireFox, Opera, or maybe using the
 WebKit/KHTML control.  You may then be able to direct it to
 render the HTML into a canvas you can then treat as an image.

 Another alternative might be provided by some web-services that
 will render a page as HTML with various browsers and then send
 you the result.  However, these are usually either (1)
 asynchronous or (2) paid services (or both).

 -tkc

WX can render html.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is lambda allowed as a key in a dict?

2009-03-10 Thread Iain King
On Mar 10, 6:38 am, Daniel Fetchinson fetchin...@googlemail.com
wrote:
 On 3/9/09, bearophileh...@lycos.com bearophileh...@lycos.com wrote:

  See here Daniel Fetchinson:

 http://groups.google.com/group/comp.lang.python/browse_thread/thread/...

  But be quite careful in using that stuff, it has some traps.

 Thanks a lot for all the helpful replies!
 Yes, I should name the unnamed lambda function, or better, just use 'def'.

 Cheers,
 Daniel

 --
 Psss, psss, put it down! -http://www.cafepress.com/putitdown


Sort of tangenitally; is there any real difference between the outcome
of the two following pieces of code?

a = lambda x: x+2

def a(x):
return x+2

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


Re: RELEASED Python 3.0 final

2008-12-04 Thread Iain King
On Dec 4, 1:51 am, Barry Warsaw [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 On behalf of the Python development team and the Python community, I
 am happy to announce the release of Python 3.0 final.

 Python 3.0 (a.k.a. Python 3000 or Py3k) represents a major
 milestone in Python's history, and was nearly three years in the
 making.  This is a new version of the language that is incompatible
 with the 2.x line of releases, while remaining true to BDFL Guido van
 Rossum's vision.  Some things you will notice include:

 * Fixes to many old language warts
 * Removal of long deprecated features and redundant syntax
 * Improvements in, and a reorganization of, the standard library
 * Changes to the details of how built-in objects like strings and
 dicts work
 * ...and many more new features

 While these changes were made without concern for backward
 compatibility, Python 3.0 still remains very much Pythonic.

 We are confident that Python 3.0 is of the same high quality as our
 previous releases, such as the recently announced Python 2.6.  We will
 continue to support and develop both Python 3 and Python 2 for the
 foreseeable future, and you can safely choose either version (or both)
 to use in your projects.  Which you choose depends on your own needs
 and the availability of third-party packages that you depend on.  Some
 other things to consider:

 * Python 3 has a single Unicode string type; there are no more 8-bit
 strings
 * The C API has changed considerably in Python 3.0 and third-party
 extension modules you rely on may not yet be ported
 * Tools are available in both Python 2.6 and 3.0 to help you migrate
 your code
 * Python 2.6 is backward compatible with earlier Python 2.x releases

 We encourage you to participate in Python 3.0's development process by
 joining its mailing list:

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

 If you find things in Python 3.0 that are broken or incorrect, please
 submit bug reports at:

http://bugs.python.org/

 For more information, links to documentation, and downloadable
 distributions, see the Python 3.0 website:

http://www.python.org/download/releases/3.0/

 Enjoy,
 - -Barry

 Barry Warsaw
 [EMAIL PROTECTED]
 Python 2.6/3.0 Release Manager
 (on behalf of the entire python-dev team)

 -BEGIN PGP SIGNATURE-
 Version: GnuPG v1.4.9 (Darwin)

 iQCVAwUBSTc3pXEjvBPtnXfVAQI69wP/dPHh8IL3GxziEV9QzlveKG+KyZb2X16x
 fxJnTCiXAbiAhT5C+m43OEnbF1PJgMDKtcZ5b7aQb4TQ0mJxISTQh0RfLCpArmlo
 tdTbzCLnh13KzB+3sUHCx+MeQNXERoWDV8hLz+4Ae71UsuUGynhtyP7ZJMJDue8j
 so2gv3fOMSs=
 =vkiy
 -END PGP SIGNATURE-

Props.  I just looked through the What's New and the change log, but I
couldn't find the answer to something:  has any change been made to
how tabs and spaces are used as indentation?  Can they still be
(inadvisably) mixed in one file?  Or, more extremely, has one or the
other been abolished?

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


Re: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility

2008-12-03 Thread Iain King
On Dec 3, 10:16 am, [EMAIL PROTECTED] wrote:
 On Dec 3, 12:53 am, Bryan Olson [EMAIL PROTECTED] wrote:



  [EMAIL PROTECTED] wrote:
   This message is not about the meaningless computer printout called

  More importantly, it's not about Python. I'm setting follow-ups to
  talk.politics.

   Certification of Live Birth that Obama propaganda machine calls his
   Birth Certificate. The American people are still waiting for a copy
   of Obama's original birth certificate that includes all his birth
   information.

  The document is what Hawaii provides as certified copy of birth record.
  It contains all the information the federal government requires to prove
  citizenship by birth, and it shows that Barack Hussein Obama was born 04
  August 1961 in Honolulu. See:

 http://www.factcheck.org/elections-2008/born_in_the_usa.html

 This garbage on factcheck.org is a worthless piece of paper
 insufficient to prove a US citizenship much less a natural born one.
 You need to have a long version of legitimate birth certificate that
 includes all birth information. Hawaii officials never even confirmed
 this piece of garbage on factcheck.org

   Remind your US presidential electors of their constitutional duty to
   investigate Obama's natural-born citizen status.

   No federal agency like FBI or Secret Service, no Hawaii bureaucrats
   have ever investigated Obama's birth in Hawaii. Many illegal aliens in
   USA have official birth certificates issued by state bureaucrats on
   the basis of falsified birth records.

  Janice Okubo of Hawaii's Department of Health confirmed that the state
  has Obama’s original birth certificate on record:

 http://hawaii.gov/health/about/pr/2008/08-93.pdf

  [...]

 Do you have a sufficient IQ to actually grasp what this news release
 says?

 All it says is that Hawaii has Obama’s original birth certificate.
 It does not say anything whether this Obama’s original birth
 certificate is from Hawaii or Kenya or from Indonesia. Under the
 Hawaii laws, a parent could use an original birth certificate from
 another country to register a child in Hawaii and get today
 Certification of Live Birth. People actually born in Hawaii do not
 get such Certification of Live Birth, they get another document with
 different name.

 Considering all the public pressure on Hawaii officials to confirm
 Obama's birth in Hawaii, they would start any response with
 confirmation that Obama was born in Hawaii. Instead, they give you
 carefully worded garbage so that your low IQ brain can swallow it and
 Obama propaganda machine can beat into your worthless brain until you
 repeat it like a low IQ moron.





   Remind your US presidential electors that they have the legal standing
   and constitutional duty to investigate Obama's birth in Hawaii by
   demanding that Obama provide all his original birth records, and a
   federal agency like FBI or Secret Service fully investigate them.

  That's not what the Constitution says. US Constitution, Article IV,
  Section 1: Full Faith and Credit shall be given in each State to the
  public Acts, Records, and judicial Proceedings of every other State. And
  the Congress may by general Laws prescribe the Manner in which such
  Acts, Records and Proceedings shall be proved, and the Effect thereof.

  These haters seek to make Obama prove his records in ways others have
  not had to, and beyond any manner prescribed by Congress within its
  constitutional authority.

 You do not have enough brain cells to understand anything you just
 quoted.

 Get one thing straight for your own self interest! THERE ARE TENS OF
 MILLIONS OF GUN OWNERS IN USA ONLY WAITING TO USE THEM ON ANYBODY WHO
 THREATENS THE US CONSTITUTION - so better use all your brain cells in
 your own self interest to resolve this matter now and not later. Run
 to Obama and beg him to release all birth records or things will not
 get any better. You are playing with fire.

Heh, you're awesome.  Keep it up!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple equates

2008-11-25 Thread Iain King
On Nov 17, 7:41 pm, Tim Chase [EMAIL PROTECTED] wrote:
  It doesn't matter as none of this is valid Python. In Python you have to
  write

  array[x1] = False
  array[x2] = False

 Uh...not so much...

a = [1,2,3,4,5]
x1, x2 = 1, 3
a[x1] = a[x2] = False
a
   [1, False, 3, False, 5]

 Works for me.

 To the OP, I think rather than cluttering my code, I'd just
 create a loop

for i in [x1,x2,x3,x4,...x1024]:
  a[i] = False

  From Diez's disassembly of it (as an aside, nifty little intro
 to dis.dis()...thanks, Diez!), it looks like it boils down to is
 DUP_TOP faster than LOAD_CONST because the rest of the
 operations.  At this point, it's pretty nitty-gritty.

 Unless the code is in an inner loop somewhere, the simple loop
 should be more than fast enough.  Without knowing the source of
 the [x1,...] index variables, it's hard to tell if there's a more
 optimal way to do this.

 -tkc

The loop is much nicer, especially as your array gets longer.  The
generic:

for i in xrange(array):
array[i] = False

will set the entire array.

Regarding your original question:

array[x1] = array[x2] = False

array[x1] = False
array[x2] = False

These two blocks are functionally the same when you are setting to
True or False (or any immutable), but are not if  setting to
immutables, which could give you some real head-scratching bugs if you
were unaware of the difference - the first version assigns the same
object to both names:

 array[x1] = array[x2] = []
 array[x1].append(Hi)
 array[x2]
['Hi']


Iain

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


Re: Multiple equates

2008-11-25 Thread Iain King
On Nov 25, 11:29 am, Iain King [EMAIL PROTECTED] wrote:
 On Nov 17, 7:41 pm, Tim Chase [EMAIL PROTECTED] wrote:



   It doesn't matter as none of this is valid Python. In Python you have to
   write

   array[x1] = False
   array[x2] = False

  Uh...not so much...

 a = [1,2,3,4,5]
 x1, x2 = 1, 3
 a[x1] = a[x2] = False
 a
[1, False, 3, False, 5]

  Works for me.

  To the OP, I think rather than cluttering my code, I'd just
  create a loop

 for i in [x1,x2,x3,x4,...x1024]:
   a[i] = False

   From Diez's disassembly of it (as an aside, nifty little intro
  to dis.dis()...thanks, Diez!), it looks like it boils down to is
  DUP_TOP faster than LOAD_CONST because the rest of the
  operations.  At this point, it's pretty nitty-gritty.

  Unless the code is in an inner loop somewhere, the simple loop
  should be more than fast enough.  Without knowing the source of
  the [x1,...] index variables, it's hard to tell if there's a more
  optimal way to do this.

  -tkc

 The loop is much nicer, especially as your array gets longer.  The
 generic:

 for i in xrange(array):
 array[i] = False

 will set the entire array.

 Regarding your original question:

 array[x1] = array[x2] = False

 array[x1] = False
 array[x2] = False

 These two blocks are functionally the same when you are setting to
 True or False (or any immutable), but are not if  setting to
 immutables, which could give you some real head-scratching bugs if you
 were unaware of the difference - the first version assigns the same
 object to both names:

  array[x1] = array[x2] = []
  array[x1].append(Hi)
  array[x2]

 ['Hi']

 Iain


...and of course, the second time I say 'immutable' I mean 'mutable'.
Hopefully the example was clearer than the text.

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


Re: Accessing Modification Time of an Outlook Mail in Python

2008-11-25 Thread Iain King
On Nov 25, 5:11 am, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 Hi all,
I am writing a small application which reads the contents of an
 Outlook Mail using python. I am able to read the contents, subject
 along with senders and receivers of a mail using MAPI objects. But may
 I know how can I get access to the modification time or the
 receiving time of an outlook mail in Python. For the others I have
 used message object of MAPI session. Here I am pasting a sample code
 to get an idea of what am I doing.

 session = Dispatch(MAPI.session)
 session.Logon('outlook')  # MAPI profile name
 inbox = session.Inbox

 print Inbox name is:, inbox.Name
 print Number of messages:, inbox.Messages.Count

 for i in range(inbox.Messages.Count):
 message = inbox.Messages.Item(i + 1)

 objSender = message.Sender.Address
 objRecip = message.Recipients.Item(j+1)

 Now here I want to access the modification time of each mail. And if
 possible if you can guide me to a place where I can get the elements
 of that message object, that would be helpful.

  Please mail back for further information.
 Thanks in advance,
 Venu.

This looks like the API for the Message object:
http://msdn.microsoft.com/en-us/library/ms526130(EXCHG.10).aspx
Looks like you want TimeLastModified

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


Re: How to update value in dictionary?

2008-08-27 Thread Iain King
On Aug 27, 2:40 pm, ssecorp [EMAIL PROTECTED] wrote:
 dict.update({a:1}) SETS the dict item a 's value to 1.

 i want to increase it by 1. isnt that possible in an easy way? I
 should use a tuple for this?

dict[a] += 1

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


Re: use of Queue

2008-08-27 Thread Iain King
On Aug 27, 1:17 pm, Alexandru  Mosoi [EMAIL PROTECTED] wrote:
 On Aug 27, 12:45 pm, Alexandru  Mosoi [EMAIL PROTECTED] wrote:



  how is Queue intended to be used? I found the following code in python
  manual, but I don't understand how to stop consumers after all items
  have been produced. I tried different approaches but all of them
  seemed incorrect (race, deadlock or duplicating queue functionality)

  def worker():
  while True:
  item = q.get()
  do_work(item)
  q.task_done()

  q = Queue()
  for i in range(num_worker_threads):
   t = Thread(target=worker)
   t.setDaemon(True)
   t.start()

  for item in source():
  q.put(item)

  q.join()   # block until all tasks are done

 ok. I think I figured it out :). let me know what you think

 global num_tasks, num_done, queue
 num_tasks = 0
 num_done = 0
 queue = Queue()

 # producer
 num_tasks += 1
 for i in items:
   num_tasks += 1
   queue.put(i)

 num_tasks -= 1
 if num_tasks == num_done:
   queue.put(None)

 # consumer
 while True:
   i = queue.get()
   if i is None:
 queue.put(None)
 break

   # do stuff

   num_done += 1
   if num_done == num_tasks:
 queue.put(None)
 break

Are you sure you want to put the final exit code in the consumer?
Shouldn't the producer place a None on the queue when it knows it's
finished?  The way you have it, the producer could make 1 item, it
could get consumed, and the consumer exit before the producer makes
item 2.

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


Re: gridSizer inside a panel element

2008-08-22 Thread Iain King
On Aug 22, 2:09 pm, Gandalf [EMAIL PROTECTED] wrote:
 why when I try to insert gridSizer to a panel which already inside
 another panel the gridSizer doesn't work?

 this is the code:

 panel3= wx.Panel(self, -1, (0, 60), size=(400, 240) ,
 style=wx.SIMPLE_BORDER);
 panel3.SetBackgroundColour('#dadadb')
 panel = wx.Panel(panel3, wx.ID_ANY, style=wx.SIMPLE_BORDER,
 size=(150, 60))
 panel.SetBackgroundColour(#fffFFF)

 bmp = wx.ArtProvider.GetBitmap(wx.ART_TIP, wx.ART_OTHER, (16,
 16))
 inputIco = wx.StaticBitmap(panel, wx.ID_ANY, bmp)

 labelThree= wx.StaticText(panel, wx.ID_ANY, 'Hello')

 label2=wx.StaticText(panel, wx.ID_ANY, 'Pease, Quite, Hello, Shalom')
 topSizer  = wx.BoxSizer(wx.VERTICAL)
 gridSizer = wx.GridSizer(rows=2, cols=1, hgap=5, vgap=5)
 input = wx.BoxSizer(wx.HORIZONTAL)
 output = wx.BoxSizer(wx.HORIZONTAL)

 input.Add((20,20), 1, wx.EXPAND) # this is a spacer
 input.Add(inputIco, 0, wx.ALL, 5)
 input.Add(labelThree, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)

 output.Add((20,20), 1, wx.EXPAND) # this is a spacer

 output.Add(label2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)

 gridSizer.Add(input, 0, wx.ALIGN_LEFT)
 gridSizer.Add(output, 0, wx.ALIGN_RIGHT)

 topSizer.Add(gridSizer, 0, wx.ALL|wx.EXPAND, 5)
 panel.SetSizer(topSizer)

I'm not sure you can just add sizers together like that.  When I'm
doing this I'd make panels for each sub-sizer; so input and output
would be panels rather than the sizers themselves.  For example
(untested):

grid = wx.Panel(panel, wx.ID_ANY)

input = wx.Panel(grid, wx.ID_ANY)
inputIco = wx.StaticBitmap(input, wx.ID_ANY, bmp)
labelThree= wx.StaticText(input, wx.ID_ANY, 'Hello')
sz = wx.BoxSizer(wx.HORIZONTAL)
sz.Add((20,20), 1, wx.EXPAND) # this is a spacer
sz.Add(inputIco, 0, wx.ALL, 5)
sz.Add(labelThree, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
input.SetSizer(sz)

output = = wx.Panel(grid, wx.ID_ANY)
label2=wx.StaticText(output, wx.ID_ANY, 'Pease, Quite, Hello, Shalom')
sz = wx.BoxSizer(wx.HORIZONTAL)
sz.Add((20,20), 1, wx.EXPAND) # this is a spacer
sz.Add(label2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
output.SetSizer(sz)

sz = wx.GridSizer(rows=2, cols=1, hgap=5, vgap=5)
sz.Add(input, 0, wx.ALIGN_LEFT)
sz.Add(output, 0, wx.ALIGN_RIGHT)
grid.SetSizer(sz)

sz = wx.BoxSizer(wx.VERTICAL)
sz.Add(grid, 0, wx.ALL|wx.EXPAND, 5)
panel.SetSizer(sz)

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


Re: Limits of Metaprogramming

2008-08-08 Thread Iain King
On Aug 4, 5:13 pm, Tomasz Rola [EMAIL PROTECTED] wrote:
 On Mon, 4 Aug 2008, Wilson wrote:
   Every sufficiently large application has a poor/incomplete
  implementation ofLISPembedded within it .

 Yep, this is either exact or very close copy of what I have read.


It's Greenspun's Tenth Rule of Programming:

Any sufficiently complicated C or Fortran program contains an ad-hoc,
informally-specified bug-ridden slow implementation of half of Common
Lisp.

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


Re: Boolean tests [was Re: Attack a sacred Python Cow]

2008-07-31 Thread Iain King
On Jul 31, 7:08 am, Russ P. [EMAIL PROTECTED] wrote:
 On Jul 30, 10:43 pm, Erik Max Francis [EMAIL PROTECTED] wrote:



  Russ P. wrote:
   On Jul 30, 9:27 pm, Erik Max Francis [EMAIL PROTECTED] wrote:
   You're sure going on about a distinction without a difference for a guy
   who childishly likes to call other people names.  A reasonable person
   would have long ago moved on instead of blaming others for not
   immediately intuiting your thoughts, rather than straightforwardly
   reading your words.  Which, by the way, includes at least three people
   other than myself.

   But I'll bet the mindless namecalling is really working out for you.
   Go, team, go!

   You earned the childish name calling by acting like a child -- with
   your petty little game of trying to show that I don't understand a
   basic concept in Python. As I said, your initial misunderstanding,
   while silly, was at least forgivable. But your insistence on repeating
   it time after time is not. It is truly pathetic.

  Sis, boom, rah rah rah!

  You're kind of skipping over the point where three other people had the
  same misunderstanding about your original statement and correction, so

 Another whopper, but who's counting?

  maybe the reader is not the problem but rather the writer, but hey,
  don't let that get in the way of a good public shitfit.

  You're winning!

 And you're a professional of some sort? Man, I can't even imagine
 working in an environment with people like you. I guess I'm pretty
 lucky to work with real professionals who don't play petty little
 games like the one you played here -- and are still playing. Go ahead,
 have the last word, loser -- then get lost.

You understand this is usenet, right?  Where we can all read the
entire thread?  So trying to spin the situation just doesn't work?
Just checking...

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


Re: Attack a sacred Python Cow

2008-07-29 Thread Iain King
On Jul 29, 5:33 am, Russ P. [EMAIL PROTECTED] wrote:
 On Jul 28, 8:44 pm, alex23 [EMAIL PROTECTED] wrote:

  On Jul 29, 4:46 am, Russ P. [EMAIL PROTECTED] wrote:

   As I said, I could write a pre-processor myself to
   implement it in less than a day.

  So WHY DON'T YOU WRITE IT ALREADY?

 I'm working on something else right now if you don't mind, but I'll
 get to it in good time.

 Conceptually, the matter is simple. All I need to do is to grab the
 first formal argument of each def, then search for occurrences of any
 word in the body of the def that starts with a dot, and insert that
 first argument in front of it.

 I expect the hard part will be breaking up the body of the def into
 words. I could just split each line on white space, except for
 situations like

 x+=.zzz

 So I need to account for the fact that operators do not need to be
 surrounded by spaces. That's the hardest part I can think of off the
 top of my head.

 Maybe I'll encounter an insurmountable problem and realize that the
 idea can't work in general. If so, then so be it. Certainly, no one on
 this thread has anticipated such a problem. Had someone pointed out an
 actual technical problem with the idea, I would have gladly thanked
 them. But I got a load of irrelevant crap instead, not to mention
 being addressed as boy.

  If you're meeting so much resistance to your idea, why not scratch
  your own damn itch and just do it?

  Or doesn't that afford you as many chances to insult others while
  feeling smugly superior?

 This coming from a guy who insulted my reading comprehension ability
 -- when he was the one who was wrong!

Are you actually this stupid?  I mean, you were entertaining while you
were mouthing of and insulting your betters, but now you're gonna
complain the second anyone insults you (and I mean, 'boy' - what an
insult!).  Never mind that you're never gonna get off your ass to
write a PEP, which would be rejected on language design grounds anyway
(as demonstrated by alex23's link - the one you aren't
comprehending).  The most irritating thing is that I like the idea of
being able to use '.x = 10' type notation (and have been for a long
time), but the person arguing for it is an insufferable buffoon who's
too dense to understand a cogent argument, never mind make one.  So
great, thanks, the chances of this (or a VB 'with'-like 'using'
keyword) ever making it into the language get smaller every time you
fire up your keyboard.  Nice work.

Iain

p.s. am looking forward to your post whining about the invalid reasons
your PEP got rejected, in the slim hope you actually write one.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Execution speed question

2008-07-25 Thread Iain King
On Jul 25, 10:57 am, Suresh Pillai [EMAIL PROTECTED] wrote:
 I am performing simulations on networks (graphs).  I have a question on
 speed of execution (assuming very ample memory for now).  I simplify the
 details of my simulation below, as the question I ask applies more
 generally than my specific case.  I would greatly appreciate general
 feedback in terms of computing and of course considerations specific to
 implementation in Python.

 The nodes in my network may be ON or OFF.  The network starts off with
 all nodes in the OFF state.  I loop through the nodes.  For each node
 that is OFF, I consider some probability of it turning ON based on the
 states of its neighbours.  I MUST GO THROUGH ALL NODES BEFORE DECIDING
 WHICH ONES TO TURN ON.

 So my question is whether it is faster to

 1. loop through a list of ALL nodes and check for OFF nodes using ifs

 or to

 2. loop through a container of OFF nodes and remove from this when they
 turn ON

or 3. build a new list every iteration intead of deleting from the old
one:

while processing:
new_off_list = []
for x in off_list:
if goes_on(x):
on_list.append(x)
else:
new_off_list.append(x)
off_list = new_off_list
generation += 1

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


Re: Execution speed question

2008-07-25 Thread Iain King
On Jul 25, 1:46 pm, Iain King [EMAIL PROTECTED] wrote:
 On Jul 25, 10:57 am, Suresh Pillai [EMAIL PROTECTED] wrote:



  I am performing simulations on networks (graphs).  I have a question on
  speed of execution (assuming very ample memory for now).  I simplify the
  details of my simulation below, as the question I ask applies more
  generally than my specific case.  I would greatly appreciate general
  feedback in terms of computing and of course considerations specific to
  implementation in Python.

  The nodes in my network may be ON or OFF.  The network starts off with
  all nodes in the OFF state.  I loop through the nodes.  For each node
  that is OFF, I consider some probability of it turning ON based on the
  states of its neighbours.  I MUST GO THROUGH ALL NODES BEFORE DECIDING
  WHICH ONES TO TURN ON.

  So my question is whether it is faster to

  1. loop through a list of ALL nodes and check for OFF nodes using ifs

  or to

  2. loop through a container of OFF nodes and remove from this when they
  turn ON

 or 3. build a new list every iteration intead of deleting from the old
 one:

 while processing:
 new_off_list = []
 for x in off_list:
 if goes_on(x):
 on_list.append(x)
 else:
 new_off_list.append(x)
 off_list = new_off_list
 generation += 1

 Iain

I was curious to what extent the different methods varied in time, so
I checked it out.  Here there are three procedures: test_every which
matches your (1), destructive which matches your (2), and constructive
which is (3) as I've outlined above.

On varying the size of the dataset I get this (probability a node goes
on = 50%):

Length of initial list: 10
Test every: 1.16085492357
Destructive: 2.592310272
Constructive: 0.850312458886

Length of initial list: 20
Test every: 2.48013843287
Destructive: 9.20894689718
Constructive: 1.73562198439

Length of initial list: 40
Test every: 5.00652267447
Destructive: 44.9696004134
Constructive: 3.51687329373

Length of initial list: 80
Test every: 9.67657648655
Destructive: 220.57583941
Constructive: 7.06614485537


and changing the probability that a nodes goes on (dataset size =
20):


Probability goes on: 1/2
Test every: 2.24765364513
Destructive: 9.28801971614
Constructive: 1.62770773816

Probability goes on: 1/4
Test every: 4.77387350904
Destructive: 13.4432467571
Constructive: 3.45467140006

Probability goes on: 1/8
Test every: 11.0514899721
Destructive: 18.4026878278
Constructive: 6.86778036177

Probability goes on: 1/16
Test every: 22.5896021593
Destructive: 25.7784044083
Constructive: 13.8631404605

Probability goes on: 1/32
Test every: 49.7667941179
Destructive: 39.3652502735
Constructive: 27.2527219598

Probability goes on: 1/64
Test every: 91.0523955153
Destructive: 65.7747103963
Constructive: 54.4087322936

Code:

import random
from timeit import Timer

SIZE = 10
MAX = 2

def goes_on(x):
global MAX
return random.randint(1,MAX) == 1

def test_every():
global SIZE
print Test every:,
nodes = range(SIZE)
is_on = [False for x in xrange(SIZE)]
count = SIZE
while count:
for i,x in enumerate(nodes):
if not is_on[i] and goes_on(x):
is_on[i] = True
count -= 1

def destructive():
global SIZE
print Destructive:,
off_list = range(SIZE)
on_list = []
count = SIZE
while count:
for i in xrange(len(off_list)-1, -1, -1):
x = off_list[i]
if goes_on(x):
on_list.append(x)
del(off_list[i])
count -= 1

def constructive():
global SIZE
print Constructive:,
off_list = range(SIZE)
on_list = []
count = SIZE
while count:
new_off_list = []
for x in off_list:
if goes_on(x):
on_list.append(x)
count -= 1
else:
new_off_list.append(x)
off_list = new_off_list

#SIZE = 20
while True:
print Length of initial list:, SIZE
#print Probability goes on: 1/%d % MAX
print Timer(test_every(), from __main__ import
test_every).timeit(1)
print Timer(destructive(), from __main__ import
destructive).timeit(1)
print Timer(constructive(), from __main__ import
constructive).timeit(1)
print
SIZE *= 2
#MAX *= 2



Conclusions:

On size, (2) really doesn't like bigger datasets, taking exponentially
longer as it increases, while (1) and (3) happily increase linearly.
(3) is faster.

On probability it's (1) who's the loser, while (2) and (3) are happy.
(3) is once again faster.

I think (2)'s poor performance is being amplified by how python
handles lists and list deletions; the effect may be stymied in other
languages, or by using other data constructs in python (like a
dictionary or a user made list class).  If you were short on memory
then (2) would have an advantage, but as it is, (3) is the clear
winner.
I'm a fan of list

Re: Execution speed question

2008-07-25 Thread Iain King
On Jul 25, 3:39 pm, Suresh Pillai [EMAIL PROTECTED] wrote:
 That's a good comparison for the general question I posed.  Thanks.
 Although I do believe lists are less than ideal here and a different data
 structure should be used.

 To be more specific to my case:
 As mentioned in my original post, I also have the specific condition that
 one does not know which nodes to turn ON until after all the
 probabilities are calculated (lets say we take the top m for example).
 In this case, the second and third will perform worse as the second one
 will require a remove from the list after the fact and the third will
 require another loop through the nodes to build the new list.

So you need to loops through twice regardless?  i.e. loop once to
gather data on off nodes, do some calculation to work out what to turn
on, then loop again to turn on the relevant nodes?  If so, then I
think the functions above remain the same, becoming the 2nd loop.
Every iteration you do a first loop over the off_nodes (or them all
for (1)) to gather the data on them, perform your calculation, and
then perform one of the above functions (minus the setup code at the
begining; basically starting at the 'for') as a second loop, with the
goes_on function now returning a value based on the calculation
(rather than the calculation itself as I had it).  Performance should
be similar.

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


Re: Execution speed question

2008-07-25 Thread Iain King
On Jul 25, 4:22 pm, Matthew Fitzgibbons [EMAIL PROTECTED] wrote:
 It seems like the probability calculation applies to all three equally,
 and can therefore be ignored for the simulations.

The probability affects (1) more.  My reasoning for this being:  as
probability gets lower the number of times you have to loop over the
list increases.  (1) always loops over the full list, but with each
successive iteration (2) and (3) are looping over smaller and smaller
lists.  In the end this adds up, with (1) becoming slower than (2),
even though it starts out quicker.

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


Re: Python Written in C?

2008-07-21 Thread Iain King
On Jul 21, 6:58 am, Krishnakant Mane [EMAIL PROTECTED] wrote:


 First off all c# is absolute rubbish waist of time.  if I need to
 learn it then I better lern java or pythonfor that matter.  and by the
 way what is a real programmer?

The story of a Real Programmer:

http://www.pbm.com/~lindahl/mel.html

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


Re: Best Python packages?

2008-07-19 Thread Iain King
On Jul 19, 8:56 am, Stefan Behnel [EMAIL PROTECTED] wrote:
 Iain King wrote:
  Well, if you're looking for a list of excellent 3rd party Python
  libraries, then I can give you the ones I like and use a lot:
 [...]
  BeautifulSoup : for real-world (i.e. not-at-all-recommendation-
  compliant) HTML processing

 You forgot lxml.html, which is much faster, more memory friendly and more
 feature-rich than BS.

 Stefan

Never heard of it :)

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


Re: Best Python packages?

2008-07-18 Thread Iain King
On Jul 18, 11:23 am, Ben Sizer [EMAIL PROTECTED] wrote:
 On Jul 16, 3:31 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:

  Ben Sizer wrote:
   make my development a lot easier.

  Knowing what kind of development you do might help, of course.  Some
  libraries are excellent in some contexts and suck badly in others...

 Sure. Mostly I'm just interested in what's out there though. In C++
 you have Boost which everybody knows are a source of high quality
 libraries, covering a fairly wide set of applications. Obviously
 that's more low-level and less application specific, and the Python
 standard libs do pretty much everything that is in Boost, but it's
 that sort of peer-reviewed and widely-applicable list that I'd like to
 see.

 I (attempt to) use TurboGears for web development and that depends on
 a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch,
 SimpleJson, FormEncode, etc - and I would never have heard of these if
 TurboGears' exposure of its internals wasn't so common. Some of these
 are web-specific but some are not. And I'd never know to look for them
 specificially, because in many cases it wouldn't occur to me that they
 exist. (eg. Object-Relational Mappers like SQLObject may be obvious if
 you come from certain areas of IT, but I'd never heard of them before
 I started with TurboGears.)

 For what it's worth, my main areas of interest are gaming, multimedia,
 and web development. But I just like to hear about anything that
 people might use which makes their life a lot easier and which perhaps
 is not application specific - like ORMs or something similar.

  Looking at things that larger projects and distributions use can also be
  a good idea.  For example, if you're doing scientific stuff, go directly
  to enthought.com.  If you're doing web stuff, look at the libraries big
  Django applications use.  Etc.

 Sadly, I know just as little about what major applications are out
 there as I do about what libraries are out there!

 --
 Ben Sizer

Well, if you're looking for a list of excellent 3rd party Python
libraries, then I can give you the ones I like and use a lot:
wxPython :  powerful GUI library which generates native look 
feel
PIL :   Imaging Library - if you need to manipulate bitmaps
pyGame :SDL for python
BeautifulSoup : for real-world (i.e. not-at-all-recommendation-
compliant) HTML processing

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


Re: start reading from certain line

2008-07-10 Thread Iain King
On Jul 10, 2:45 pm, jstrick [EMAIL PROTECTED] wrote:
 Here's a simple way to do it with a minimum amount of loopiness (don't
 forget to use 'try-except' or 'with' in real life):

 f = open(item1.txt)

 for preline in f:
     if Item 1 in preline:
         print preline,
         for goodline in f:
             # could put an end condition with a 'break' here
             print goodline,

 f.close()

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


Re: start reading from certain line

2008-07-10 Thread Iain King
On Jul 10, 4:54 pm, Iain King [EMAIL PROTECTED] wrote:
 On Jul 10, 2:45 pm, jstrick [EMAIL PROTECTED] wrote:

  Here's a simple way to do it with a minimum amount of loopiness (don't
  forget to use 'try-except' or 'with' in real life):

  f = open(item1.txt)

  for preline in f:
      if Item 1 in preline:
          print preline,
          for goodline in f:
              # could put an end condition with a 'break' here
              print goodline,

  f.close()

 No

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


Re: How to make python scripts .py executable, not bring up editor

2008-07-08 Thread Iain King
On Jul 7, 10:56 pm, korean_dave [EMAIL PROTECTED] wrote:
 From command Prompt, i type in a script,  tryme.py.

 This, instead, brings up PythonWin editor and Interactive Window.

 Path variable is C:\Python24. (I need Python 2.4 installed, not 2.5)

 How do I make it so that the script runs?

find a .py file in windows explorer.  Right click it-Open With-
Choose Program...
Now find your python.exe file (should be in c:\python24), select it,
and tick the box that says Always use the selected program

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


Re: How to bypass Windows 'cooking' the I/O? (One more time, please) II

2008-07-07 Thread Iain King
On Jul 7, 10:18 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 On Mon, 07 Jul 2008 01:03:10 -0700, norseman [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:



    Normal file I/O sequence:

    fp = open(target, 'wb')

    fp.seek(-1, 2)

    fp.write(record)

     Except it doesn't do that in Windows. See below.

         I wouldn't expect that sequence to work on any system... The w
 implies create new file, or truncate existing file to 0-bytes, then
 write data to it -- with no seeking permitted. You must include the +
 to do seeking, and if you want to retain the existing file contents you
 probably need to open with a+ (a for append).

         The rest of your situation I won't touch. Other than to wonder why
 the situation hasn't hit any of the various database servers which must
 be operating in binary mode, and perform lots of seeking... Surely
 somewhere out someone else must have encountered a seek crossing an
 apparent creof mark (which isn't a normal Windows sequence anyway --
 since Windows uses crlf for EOL, I'd have expected to see a problem
 if backing over a crlfeof)
 --
         Wulfraed        Dennis Lee Bieber               KD6MOG
         [EMAIL PROTECTED]             [EMAIL PROTECTED]
                 HTTP://wlfraed.home.netcom.com/
         (Bestiaria Support Staff:               [EMAIL PROTECTED])
                 HTTP://www.bestiaria.com/


lol @ op not finding the answer to his question in the archives, then
being answered again by someone who doesn't let his answer go in the
archive.  How useful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Win32.client, DAO.DBEngine and exceeding the file sharing count lock

2008-07-03 Thread Iain King
On Jul 2, 8:13 pm, Tim Golden [EMAIL PROTECTED] wrote:
 In case it helps, there's a recipe just shown up
 on the Python Cookbook which at least illustrates
 DAO use:

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

 TJG

On Jul 2, 6:30 pm, M.-A. Lemburg [EMAIL PROTECTED] wrote:
 You could try to use the Access ODBC driver and access the database
 that way via mxODBC. That would be faster as well:

 http://www.microsoft.com/technet/prodtechnol/windows2000serv/technolo...
 (scroll down to table 7.1)

 Apart from that option and if you are really in need for larger
 transactions, I'd suggest that you move to SQL Server for processing
 (if you can). Access is not really made for heavy-lifting and big
 transactions.

Thanks for the help.  I'll check those out, in case there's a
performance gain to be had, but I found that ADO can in fact do
exactly what I want; on the comments of the page I previously linked
to which said ADO couldn't was a posting which refuted some of the
OP's claims;  ADO can set some options on it's open connection,
including Max Locks Per Record.  My code now looks like this:

self._connection.Open(self._DSN)
if MAX_LOCKS != None:
self._connection.Properties(Jet OLEDB:Max Locks Per File).Value
= MAX_LOCKS
rs = win32com.client.Dispatch(r'ADODB.Recordset')

N.B. I'm writing tools software for a 3rd party app which uses an
Access db as it's output format, so I'm locked in.  No way to switch
to SQL server.

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


Win32.client, DAO.DBEngine and exceeding the file sharing count lock

2008-07-02 Thread Iain King
Hi.  I'm using the win32 module to access an Access database, but I'm
running into the File Sharing lock count as in 
http://support.microsoft.com/kb/815281
The solution I'd like to use is the one where you can temporarily
override the setting using (if we were in VB):

DAO.DBEngine.SetOption dbmaxlocksperfile,15000

Can I do this in win32com?  I've been using ADO, not DAO, but I have
to confess to not knowing exactly what the difference is.  I set up my
recordset thusly:

rs = win32com.client.Dispatch(r'ADODB.Recordset')

can I jigger it to increase it's max locks?

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


Re: Win32.client, DAO.DBEngine and exceeding the file sharing count lock

2008-07-02 Thread Iain King
On Jul 2, 3:29 pm, Tim Golden [EMAIL PROTECTED] wrote:
 Iain King wrote:
  Hi.  I'm using the win32 module to access an Access database, but I'm
  running into the File Sharing lock count as 
  inhttp://support.microsoft.com/kb/815281
  The solution I'd like to use is the one where you can temporarily
  override the setting using (if we were in VB):

  DAO.DBEngine.SetOption dbmaxlocksperfile,15000

 Really hurried answer:

 code
 import win32com.client

 dao = win32com.client.gencache.EnsureDispatch (DAO.DBEngine.36)
 dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, 
 Value=15000)

 /code
 TJG

Thanks.  I found this: 
http://blogs.msdn.com/michkap/archive/2007/07/13/3849288.aspx
which outlines some difference between DAO and ADO, including:
Capability to set and change Jet options without making registry
changes (works in DAO through DBEngine.GetOption and
DBEngine.SetOption, fails in ADO, which has no such analogue).

Now, I'm pretty sure I tried to use DAO before and failed to get it to
work, but maybe you could look at my code and suggest the DAO
equivalent?

---

self._connection = win32com.client.Dispatch(r'ADODB.Connection')
self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE='+dbfile+';'

self._connection.Open(self._DSN)
rs = win32com.client.Dispatch(r'ADODB.Recordset')
query = 'SELECT '+field+' FROM '+self.__TABLE
rs.Open(query, self._connection, 1, 3)
while not rs.EOF:
v = function(rs.Fields.Item(0).Value)
if v != RETAIN_VALUE:
rs.Fields.Item(0).Value = v
rs.MoveNext()
rs.Close()

---

aTdHvAaNnKcSe,
Iain
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interesting Math Problem

2008-06-05 Thread Iain King
On Jun 4, 9:03 am, BEES INC [EMAIL PROTECTED] wrote:
 I've been awfully busy programming lately. My Django-based side
 project is coming along well and I hope to have it ready for use in a
 few weeks. Please don't ask more about it, that's really all I can say
 for now. Anyways, I came across an interesting little math problem
 today and was hoping some skilled programmers out there could come up
 with a more elegant solution than mine.
 Problem: Star Ratings

 People can rate cheeseburgers on my website with a star rating of 0-5
 stars (whole stars only), 5 being mighty tasty and 0 being disgusting.
 I would like to show the average of everyone's ratings of a particular
 cheeseburger to the nearest half star. I have already calculated the
 average rating as a float (star_sum) and the total number of people
 that rated the particular cheeseburger (num_raters). The result should
 be stored as a float in a variable named stars.
 My Solution (in Python):

 # round to one decimal place and
 # separate into whole and fractional parts
 parts = str(round(star_sum/num_raters, 1)).split('.')
 whole = int(parts[0])
 frac = int(parts[1])
 if frac  3:
 ___frac = 0
 elif frac  7:
 ___frac = 0
 ___whole += 1
 else:
 ___frac = 5
 # recombine for a star rating rounded to the half
 stars = float(str(whole)+'.'+str(frac))

 Mmmm… In-N-Out Burgers… Please reply if you've got a better solution.

It'd be easier just to do the whole thing with ints.  Represents your
stars by counting half-stars (i.e. 0 = no stars, 1 = half a star, 2 =
1 star, etc).  Then you just need to divide by 2 at the end.

stars = round(star_sum/num_raters, 0) / 2.0

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


Re: Creating A Tuple From A List, Adding To Tuple As You Do

2008-06-05 Thread Iain King
On Jun 5, 1:41 pm, Jeff Nyman [EMAIL PROTECTED] wrote:
 Greetings all.

 The subject line of this thread is probably one of the worst ever. I
 was trying to encapsulate what I am doing. Based on my new-found
 knowledge from another thread, I'm able to get a list of directories
 and they come to me in the form of a list. Here is an example:

 from glob import glob
 DC_List = glob('vcdcflx006\\Flex\\Sites\\*\\')
 DC_List = ['Baltimore', 'Birmingham', 'Cincinnati', 'Cleveland',
 LosAngeles']

 (Each element in the DC_List is actually a full directory path, but I
 shortened that in the interest of clarity.)

 The problem is that I need to pass this list to a list control in a
 wxWidgets application. In order to do that, I need to pass in a list
 like this:

 [ ('Baltimore', ''), ('Birmingham', ''), ('Cincinnati', ''),
 ('Cleveland', ''), ('LosAngeles', '') ]

 In other words, each element in the list is a tuple that has an empty
 second string. The problem I'm having is in converting my list above
 to be of this type. I can't do append because that (logically) puts
 everything at the end. I did try this:

 for count in range(0, len(DC_List)):
 DC_List.insert(count, '')

 Here I was thinking I could insert a '' into the right place after
 each entry in the list. That doesn't quite work. Does anyone have an
 idea of a good approach here? (I did search on tuples and lists and
 while I found a lot of information about both, I couldn't find a
 solution that did what I'm discussing above.)

 - Jeff

I know a ton of people have already replied with list comprehensions,
but I figured I'd chime in with one that also strips out the path of
your folders for you (since I'm not sure how you are managing that
just now)

cities = [(os.path.basename(x), '') for x in glob('vcdcflx006\\Flex
\\Sites\\*\\')]

I tend to use / instead of \\ as a folder seperator, it should work
for you (I think):
cities = [(os.path.basename(x), '') for x in glob('//vcdcflx006/Flex/
Sites/*')]

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


Re: Python and Flaming Thunder

2008-05-23 Thread Iain King
On May 23, 3:35 am, Charles Hixson [EMAIL PROTECTED] wrote:
 On Thursday 22 May 2008 13:30:07 Nick Craig-Wood wrote:

  ...
  From Armstrong's book: The expression Pattern = Expression causes

  Expression to be evaluated and the result matched against Pattern. The
  match either succeeds or fails. If the match succeeds any variables
  occurring in Pattern become bound.

  It is a very powerful idea and one which (along with the concurrency
  and message passing from Erlang) has been implemented for python :-

   http://candygram.sourceforge.net/

  I've been reading the Erlang book and I have to say it has given me a
  lot of insight into python...

 Although when comparing Candygram with Erlang it's worth noting that Candygram
 is bound to one processor, where Erlang can operate on multiple processors.
 (I'd been planning on using Candygram for a project at one point, but this
 made it unusable.)

lol, nice name.  Also surprisingly relevant to the thread:

candygrammar: n.

A programming-language grammar that is mostly syntactic sugar; the
term is also a play on ‘candygram’. COBOL, Apple's Hypertalk language,
and a lot of the so-called ‘4GL’ database languages share this
property. The usual intent of such designs is that they be as English-
like as possible, on the theory that they will then be easier for
unskilled people to program. This intention comes to grief on the
reality that syntax isn't what makes programming hard; it's the mental
effort and organization required to specify an algorithm precisely
that costs. Thus the invariable result is that ‘candygrammar’
languages are just as difficult to program in as terser ones, and far
more painful for the experienced hacker.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in floating-point addition: is anyone else seeing this?

2008-05-22 Thread Iain King
On May 22, 1:14 am, bukzor [EMAIL PROTECTED] wrote:
 On May 21, 3:28 pm, Dave Parker [EMAIL PROTECTED] wrote:

  On May 21, 4:21 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:

   Which is exactly what the python decimal module does.

  Thank you (and Jerry Hill) for pointing that out.  If I want to check
  Flaming Thunder's results against an independent program, I'll know to
  use Python with the decimal module.

 Utterly shameless.

You may find a more appreciative (and less antagonised) audience for
your language in comp.lang.cobol
--
http://mail.python.org/mailman/listinfo/python-list


Re: wxpython dialog - do something after ShowModal()?

2008-05-15 Thread Iain King
On May 14, 9:37 pm, David C. Ullrich [EMAIL PROTECTED] wrote:
 In article
 [EMAIL PROTECTED],
  Iain King [EMAIL PROTECTED] wrote:

  Hi.  I have a modal dialog whcih has a Browse... button which pops
  up a file selector.  This all works fine, but the first thing the user
  has to do when they open the dialog is select a file, so I would like
  the dialog to automatically call the onBrowse function as soon as the
  dialog opens.  However, I don't know how to do this.

  dlg.ShowModal()
  onBrowse()

  obviously doesn't work, and neither does the reverse.  I was hoping
  that the dialog would throw some kind of I have been shown event,
  but it doesn't (as far as I can tell).  How do I make the dialog do
  something as soon as it's been shown?

 It's too bad that you found an answer. You _shouldn't_ have your
 dialog pop up a file-selection box as soon as it's shown! That's
 not the way dialogs usually work, so you're going to confuse
 people.

 Instead, first pop up the file-selection box, and then pop up
 the dialog (without the Browse button) to do whatever else it
 does after you've got the filename.


That's actually what happens - the dialog throws EVT_INIT_DIALOG
before it displays itself.  Not that I really agree with you.  I don't
think that a do such-and-such dialog appearing with a Select file
for such-and-such file selector on top of it, the file selector being
in focus, is confusing for the user.  Actually, I think it'd be
friendlier - the user can see where the data from the file is going,
so has an immediate reminder of what the (generic) file selector is
for.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rename field in Access DB

2008-05-15 Thread Iain King
On May 14, 4:29 pm, Tim Golden [EMAIL PROTECTED] wrote:
 Iain King wrote:
  I'm manipulating an MS Access db via ADODB with win32com.client.  I
  want to rename a field within a table, but I don't know how to.  I
  assume there is a line of SQL which will do it, but nothing I've tried
  (from searching) has worked.
  Basic code:

  import win32com.client
  connection = win32com.client.Dispatch(r'ADODB.Connection')
  DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=dbfile.mdb;'
  connection.Open(DSN)
  connection.Execute(ALTER TABLE tablename CHANGE from to)   #this sql
  doesn't work
  connection.Close()

 code
 import os, sys
 from win32com.client.gencache import EnsureDispatch as Dispatch

 DATABASE_FILEPATH = rc:\temp\test.mdb
 CONNECTION_STRING = Provider=Microsoft.Jet.OLEDB.4.0; data Source=%s % \
   DATABASE_FILEPATH

 if os.path.exists (DATABASE_FILEPATH):
os.remove (DATABASE_FILEPATH)

 adox = Dispatch (ADOX.Catalog)
 adox.Create (CONNECTION_STRING)
 adox = None

 db = Dispatch ('ADODB.Connection')
 db.Open (CONNECTION_STRING)
 try:
   db.Execute ('CREATE TABLE dtest (id INT, data INT)')
   db.Execute ('INSERT INTO dtest (id, data) VALUES (1, 2)')

   try:
 db.Execute ('SELECT id, newdata FROM dtest')
   except:
 print FAILED as expected
   else:
 print SUCCEEDED unexpectedly

   try:
 db.Execute ('SELECT id, data FROM dtest')
   except:
 print FAILED unexpectedly
   else:
 print SUCCEEDED as expected

   adox = Dispatch (ADOX.Catalog)
   adox.ActiveConnection = db
   adox.Tables (dtest).Columns (data).Name = newdata
   adox.Tables.Refresh ()
 finally:
   db.Close ()

 db = Dispatch ('ADODB.Connection')
 db.Open (CONNECTION_STRING)
 try:

   try:
 db.Execute ('SELECT id, data FROM dtest')
   except:
 print FAILED as expected
   else:
 print SUCCEEDED unexpectedly

   try:
 db.Execute ('SELECT id, newdata FROM dtest')
   except:
 print FAILED unexpectedly
   else:
 print SUCCEEDED as expected

 finally:
db.Close ()

 /code

 TJG


Excellent, many thanks.

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


Rename field in Access DB

2008-05-14 Thread Iain King
I'm manipulating an MS Access db via ADODB with win32com.client.  I
want to rename a field within a table, but I don't know how to.  I
assume there is a line of SQL which will do it, but nothing I've tried
(from searching) has worked.
Basic code:

import win32com.client
connection = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=dbfile.mdb;'
connection.Open(DSN)
connection.Execute(ALTER TABLE tablename CHANGE from to)   #this sql
doesn't work
connection.Close()

Anyone know how to get this to work?

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


wxpython dialog - do something after ShowModal()?

2008-05-13 Thread Iain King
Hi.  I have a modal dialog whcih has a Browse... button which pops
up a file selector.  This all works fine, but the first thing the user
has to do when they open the dialog is select a file, so I would like
the dialog to automatically call the onBrowse function as soon as the
dialog opens.  However, I don't know how to do this.

dlg.ShowModal()
onBrowse()

obviously doesn't work, and neither does the reverse.  I was hoping
that the dialog would throw some kind of I have been shown event,
but it doesn't (as far as I can tell).  How do I make the dialog do
something as soon as it's been shown?

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


Re: wxpython dialog - do something after ShowModal()?

2008-05-13 Thread Iain King
On May 13, 2:20 pm, Larry Bates [EMAIL PROTECTED] wrote:
 Iain King wrote:
  Hi.  I have a modal dialog whcih has a Browse... button which pops
  up a file selector.  This all works fine, but the first thing the user
  has to do when they open the dialog is select a file, so I would like
  the dialog to automatically call the onBrowse function as soon as the
  dialog opens.  However, I don't know how to do this.

  dlg.ShowModal()
  onBrowse()

  obviously doesn't work, and neither does the reverse.  I was hoping
  that the dialog would throw some kind of I have been shown event,
  but it doesn't (as far as I can tell).  How do I make the dialog do
  something as soon as it's been shown?

  Iain

 If the only things on your modal dialog are Browse and cancel, just call the
 wx.FileDialog directly and eliminate the intermediate modal dialog.  If not
 don't bind the FileDialog to a button, just create an instance of it as the 
 last
   you do in the __init__ method of the modal dialog code.

 If this doesn't help, you will have better luck posting to wxpython newsgroup.

 -Larry

The dialog doesn't only let you call the file dialog, it does other
stuff too.  Your suggestion of __init__ sounded promising, but neither
giving the dialog an __init__() method nor an OnInit() method worked.
Thanks anyway.

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


Re: wxpython dialog - do something after ShowModal()?

2008-05-13 Thread Iain King
On May 13, 2:43 pm, Iain King [EMAIL PROTECTED] wrote:
 On May 13, 2:20 pm, Larry Bates [EMAIL PROTECTED] wrote:



  Iain King wrote:
   Hi.  I have a modal dialog whcih has a Browse... button which pops
   up a file selector.  This all works fine, but the first thing the user
   has to do when they open the dialog is select a file, so I would like
   the dialog to automatically call the onBrowse function as soon as the
   dialog opens.  However, I don't know how to do this.

   dlg.ShowModal()
   onBrowse()

   obviously doesn't work, and neither does the reverse.  I was hoping
   that the dialog would throw some kind of I have been shown event,
   but it doesn't (as far as I can tell).  How do I make the dialog do
   something as soon as it's been shown?

   Iain

  If the only things on your modal dialog are Browse and cancel, just call the
  wx.FileDialog directly and eliminate the intermediate modal dialog.  If not
  don't bind the FileDialog to a button, just create an instance of it as the 
  last
you do in the __init__ method of the modal dialog code.

  If this doesn't help, you will have better luck posting to wxpython 
  newsgroup.

  -Larry

 The dialog doesn't only let you call the file dialog, it does other
 stuff too.  Your suggestion of __init__ sounded promising, but neither
 giving the dialog an __init__() method nor an OnInit() method worked.
 Thanks anyway.

 Iain

After having a hunt through the wxpython mailing list archives I found
the answer:  the event is EVT_INIT_DIALOG:

dlg.Bind(wx.EVT_INIT_DIALOG, onInit, dlg)

work.  Thanks for the pointer.

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


Splitting MainWindow Class over several modules.

2008-04-16 Thread Iain King
Until recently almost all my python programs were held 1 file for 1
program.  This had grown unwieldy for one of my projects, so i decided
to refactor it, and ended up with something like this:

---

import wx

import options
import gui
import scf

class MainWindow(wx.Frame):
def __init__(self):
self.title = SFtools v%s % VERSION
wx.Frame.__init__(self, None, wx.ID_ANY, self.title, 
size=(800,600))
self.SetMinSize((800,600))

readOptions  = options.readOptions
writeOptions = options.writeOptions

createBindings  = gui.createBindings
createControls  = gui.createControls
createMenus = gui.createMenus
reportError = gui.reportError

loadSCF   = scf.loadSCF
onOpen= scf.onOpen
reloadSCF = scf.reloadSCF
setMenuMode   = scf.setMenuMode
unloadSCF = scf.unloadSCF

---

Now, this works fine.  I like how it reads and that everything being
imported can be clearly seen.  I have this funny feeling though, that
this isn't the standard way of doing this.  What is?  And is there
anything about doing it this way which could be detrimental?

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


Re: Wxpython. Is it possible to change layout in a running application? Selfmade listbox

2008-04-07 Thread Iain King
On Apr 7, 12:50 pm, Soren [EMAIL PROTECTED] wrote:
 Hi,

 Id like to make my own special listbox.. I want to able (at the push
 of a button) to add another item to my special listbox... each item is
 a panel with a label, some buttons and maybe a text control.

 I've tried adding a new panel object with the stuff i want to the
 sizer i'm using for my listbox (which is a panel which can contain
 other panels)... and then run update() and refresh() on everything...
 But it doesn't work.. i see a panel appearing, but it's just a small
 square in the corner of my listbox panel, and it only works the
 first time... nothing new appears when I push the button again.

 Is it at all possible to do this? Has anyone created something
 similar? Does anyone know what i'm doing wrong?

 Thanks,
 Soren

Without your code can only really guess, but I'd check that the new
panel you are trying to add to the sizer has the listbox as a parent.

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


Re: String To List

2008-03-17 Thread Iain King
On Mar 17, 6:56 am, Dan Bishop [EMAIL PROTECTED] wrote:
 On Mar 17, 1:15 am, Girish [EMAIL PROTECTED] wrote:

  I have a string a = ['xyz', 'abc'].. I would like to convert it to a
  list with elements 'xyz' and 'abc'. Is there any simple solution for
  this??
  Thanks for the help...

 eval(a) will do the job, but you have to be very careful about using
 that function.  An alternative is

 [s.strip('\'') for s in a.strip('[]').split(', ')]

This will fall over if xyz or abc include any of the characters your
stripping/splitting on (e.g if xyz is actually To be or not to be,
that is the question).  Unless you can guarantee they won't, you'll
need to write (or rather use) a parser that understands the syntax.

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


Re: String To List

2008-03-17 Thread Iain King
On Mar 17, 9:27 am, Iain King [EMAIL PROTECTED] wrote:
 On Mar 17, 6:56 am, Dan Bishop [EMAIL PROTECTED] wrote:

  On Mar 17, 1:15 am, Girish [EMAIL PROTECTED] wrote:

   I have a string a = ['xyz', 'abc'].. I would like to convert it to a
   list with elements 'xyz' and 'abc'. Is there any simple solution for
   this??
   Thanks for the help...

  eval(a) will do the job, but you have to be very careful about using
  that function.  An alternative is

  [s.strip('\'') for s in a.strip('[]').split(', ')]

 This will fall over if xyz or abc include any of the characters your
 stripping/splitting on (e.g if xyz is actually To be or not to be,
 that is the question).  Unless you can guarantee they won't, you'll
 need to write (or rather use) a parser that understands the syntax.

 Iain


Thinking about this some more; could the string module not use a
simple tokenizer method?  I know that relentlessly adding features to
built-ins is a bad idea, so I'm not sure if this falls within
batteries-included, or is actually just adding bulk.  On the one hand,
it's not difficult to write a simple state-based token parser
yourself, but on the other it is also quite easy to include a pile of
bugs when you do.  By simple I mean something like:

def tokenize(string, delim, closing_delim=None, escape_char=None)

which would return a list (or a generator) of all the parts of the
string enclosed by delim (or which begin with delim and end with
closing_delim if closing_delim is set), ignoring any delimiters which
have been escaped by escape_char.   Throw an exception if the string
is malformed? (odd number of delimiters, or opening/closing delims
don't match)

In the OP's case, he could get what he want's with a simple:   l =
a.tokenize(')

The point of this ramble not being that this is a how to solve the
OP's question, but wondering if it would be a good inclusion to the
language in general.  Or there's actually a module which already does
it that I couldn't find and I'm an idiot...

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


Re: the annoying, verbose self

2007-11-27 Thread Iain King
On Nov 27, 9:20 am, Roy Smith [EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED],
  Bruno Desthuilliers [EMAIL PROTECTED]



  wrote:
  Steven D'Aprano a écrit :
   On Mon, 26 Nov 2007 21:48:36 +0100, Ton van Vliet wrote:

   On Mon, 26 Nov 2007 20:14:50 +0100, Bruno Desthuilliers
   [EMAIL PROTECTED] wrote:

   However, I was more thinking in terms of attributes only
   Too bad : in Python, everything's an object, so 'methods' are attributes
   too.
   Right, but I'm sure *you* know a way to distinguish between them

  Yes : reading the doc. But that's something the compiler will have hard
  time doing.

   (I'm
   just a beginner ;-)

   All methods are attributes. Not all attributes are methods. The usual way
   to see if something is a method is to try calling it and see what
   happens, but if you want a less informal test, try type():

   type(''.join)
   type 'builtin_function_or_method'
   type(Foo().foo)  # with the obvious definition of Foo
   type 'instancemethod'

  Fine. Now since Python let you define your own callable types and your
  own descriptors, you can as well have an attribute that behave just like
  a method without being an instance of any of the method types - so the
  above test defeats duck typing. And since you can have callable
  attributes that are definitively not methods, you can't rely on the fact
  that an attribute is callable neither.

 If you want to have a little fun:

 class peverse:
 def __call__(self):
 raise AttributeError (peverse instance has no __call__ method)

 x = peverse()
 x()


Horrific cluge:
--

def noself(func):
def t(*args, **kwargs):
self = args[0]
g = globals()
delete = []
for varname in dir(self):
if not varname.startswith(__) and varname not in g:
g[varname] = self.__getattribute__(varname)
delete.append(varname)
func(*args, **kwargs)
for varname in delete:
del(g[varname])
return t


class Test(object):
x = 1

@noself
def test(self):
print x


 foo = Test()
 foo.test()
1

--

FTR, I won't be using this :)  I do like this syntax though:

class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def abs(self):
using self:
return math.sqrt(.x*.x + .y*.y + .z*.z)

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


Re: the annoying, verbose self

2007-11-27 Thread Iain King
On Nov 27, 12:03 pm, Duncan Booth [EMAIL PROTECTED]
wrote:
 Iain King [EMAIL PROTECTED] wrote:
  FTR, I won't be using this :)  I do like this syntax though:

  class Vector:
  def __init__(self, x, y, z):
  self.x = x
  self.y = y
  self.z = z
  def abs(self):
  using self:
  return math.sqrt(.x*.x + .y*.y + .z*.z)

 It is a bit verbose though. This variant is shorter on my system[*]:

 class Vector:
 def __init__(self, x, y, z):
 self.x = x
 self.y = y
 self.z = z
 def abs(self):
 return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)

 [*] Windows, they are the same length on Linux.

 :)

Yeah, in this example.  Another would be

using NetworkConnection:
.address = 127.0.0.1
.port = 8080
.connect()
using .connection
   while .read():
   do something
.disconnect()

I doubt anything like this will take though, since you can write
similar code with 'with' and assigning a long name to a short one.

Iain

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


Re: Best way to generate alternate toggling values in a loop?

2007-10-18 Thread Iain King
On Oct 18, 2:29 am, Grant Edwards [EMAIL PROTECTED] wrote:
 On 2007-10-17, Debajit Adhikary [EMAIL PROTECTED] wrote:

  # Start of Code

  def evenOdd():
  values = [Even, Odd]
  state = 0
  while True:
  yield values[state]
  state = (state + 1) % 2

 I'd replace the last line with

   state ^= 1

 to save a couple instructions, but I spend too much time
 working with micoroprocessors running on clocks measured in the
 KHz.

 There are probably other more Pythonic ways...



I always use:

   state = 1 - state

for toggles.  I doubt it's much more pythonic though :)

Iain

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


Re: Difference between two times (working ugly code, needs polish)

2007-09-12 Thread Iain King
On Sep 12, 1:31 am, Shawn Milochik [EMAIL PROTECTED] wrote:
  I suppose really oneDay should be a global (i.e. outside the function
  definition). Apart from that it would be hard to improve on: obvious,
  easy to read, in short - pythonic.

  Are you concerned about daylight savings? That could certainly introduce
  a whole new level of complexity into the problem. Let's hope not ...

 I'm not concerned with DST; this is a script which checks my Ebay
 auctions (I have some things for sale), and sends me e-mail whenever
 someone bids. It's run by cron every half hour -- it keeps me from
 compulsively checking my auctions. ^_^

 In any case, DST isn't an issue because the same machine generates
 both timestamps, and all I use it for is to stop displaying auctions
 after they are 10 days old, so I don't get all my old crap filling up
 the alert e-mail or skewing the total dollar amount for all active
 auctions.

 Thanks.
 Shawn

Just to be picky - your function returns the number of days between
two dates, but it's called isOld, which looks like it should return a
boolean.  i.e.  it looks like it would be used as:

if not isOld(auctionDate, currentTime):
checkForBid()

rather than how I assume it is used:

if isOld(auctionDate, currentTime) = 10:
checkForBid()

I'd call it daysDiff or something similar, or make it more specific so
that it works like the first block of code above:

ONEDAY = 60*60*24
OLDNESS_THRESHOLD = 10

def isOld(lastUpdate, runTimeStamp):
lastUpdate = time.mktime(time.strptime(lastUpdate, %Y-%m-%d_%H:
%M))
runTimeStamp = time.mktime(time.strptime(runTimeStamp, %Y-%m-%d_
%H:%M))
return (runTimeStamp - lastUpdate) / ONEDAY  =  OLDNESS_THRESHOLD

if not isOld(auctionDate, currentTime):
checkForBid()

Iain

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


Re: wxPython and threads

2007-07-19 Thread Iain King
On Jul 18, 3:41 am, Benjamin [EMAIL PROTECTED] wrote:
 I'm writing a search engine in Python with wxPython as the GUI. I have
 the actual searching preformed on a different thread from Gui thread.
 It sends it's results through a Queue to the results ListCtrl which
 adds a new item. This works fine or small searches, but when the
 results number in the hundreds, the GUI is frozen for the duration of
 the search. I suspect that so many search results are coming in that
 the GUI thread is too busy updating lists to respond to events. I've
 tried buffer the results so there's 20 results before they're sent to
 the GUI thread and buffer them so the results are sent every .1
 seconds. Nothing helps. Any advice would be great.

I do something similar - populating a bunch of comboboxes from data
takes a long time so I run the generator for the comboboxes in another
thread (and let the user use some textboxes in the mean time).  A
rough edit toward what you might be doing:

import thread

class Processor(object):
def __init__(self):
self.lock = thread.allocate_lock()
self.alive = False
self.keepalive = False

def start(self):
if not self.alive:
self.alive = True
self.keepalive = True
thread.start_new_thread(self.Process, (None,))

def stop(self):
self.keepalive = False

def process(self, dummy=None):
self.alive = False


class SearchProcessor(Processor):
def __init__(self, entries, lookfor, report):
Processor.__init__(self)
self.entries = entries
self.lookfor = lookfor
self.report = report

def process(self, dummy=None):
for entry in self.entries:
if lookfor in entry:
self.report(entry)
if not self.keepalive:
break
self.report(None)
self.alive = False


results = []

def storeResult(result):
if result != None:
results.append(result)
else:
notifySomeMethod(results)

sp = SearchProcessor(someListOfData, someTextToSearchFor, storeResult)
sp.start()

when the search is done it will call notifySomeMethod with the
results.  Meanwhile you could, for example, bind sp.stop() to a cancel
button to stop the thread, or add a counter to the storeResult
function and set a status bar to the total found, or whatever else you
want to do.

Iain

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


Re: edit a torrent file with python

2006-10-13 Thread Iain King

di0rz` wrote:
 hi,
 I am looking for a python script to edit .torrent files
 if anybody know one thx

Not sure exactly what you are looking for, but the original bittorrent
client is written in Python, so you could grab a copy of it and check
the code.

Iain

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


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread Iain King

[EMAIL PROTECTED] wrote:
 Hi,

 I have a program which will continue to run for several days. When it is
 running, I can't do anything except waiting because it takes over most
 of the CUP time.

 Is it possible that the program can save all running data to a file when
 I want it to stop, and can reload the data and continue to run from
 where it stops when the computer is free ?

 Regards,

 xiaojf

Can't you just use time.sleep to put your program to, uh, sleep?  For
example, time.sleep(10) will effectively pause your program for ten
seconds, making it use very few CPU cycles.  I don't know what
interface you have, but assuming you can pick up a button or a key
press, you can ask for a length of time, or just put your code into a
holding pattern:

def pause():
  paused = True
  while paused:
time.sleep(1)
if wake_up_key_pressed:
  paused = False

or with a gui:

paused = False

def pause():
  global paused
  paused = True
  while paused:
time.sleep(1)

def onWakeUpButton():  #bind this to button
  global paused
  paused = False


Iain

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


Re: PIL cannot open TIFF image in Windows

2006-09-11 Thread Iain King

Michele Petrazzo wrote:
 Rob Williscroft wrote:

  I downloaded some test images from:
 
  url:http://www.remotesensing.org/libtiff/images.html
 

 I do the same and modified your code for try FreeImagePy and the results
 are:

 ok: 41  error: 20   total: 61

 Better than PIL, but a lot of problems with

 lower-rgb-planar-  8 and flower-rgb-contig-  8

 IrfanView seem that can load all the images...

  Rob.

 Bye,
 Michele

I've been working with tifs a lot, and I've yet to find a perfect
python solution to them.  The usual images to screw things up for me
are jpeg encoded pages.  Best solution I've found is a try/except fall
through:
try:
  open image with PIL
except:
try:
  open image with FreeImagePy
except:
  try:
open image with wxPython
  except:
fail

Right now my program to compile multipage tiffs no longer does any of
the image work itself - it processes the index file, and then generates
a batch file.  The batch file is a lot of calls to irfanview /append.
I've yet to find a tiff irfanview can't open.

Iain

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


Re: Looking For mp3 ID Tag Module

2006-08-18 Thread Iain King

Tim Daneliuk wrote:
 Iñigo Serna wrote:
  On 8/18/06, Tim Daneliuk [EMAIL PROTECTED] wrote:
   try mutagen.
  http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen
 
  This module is more-or-less exactly what I needed.  However, I am running
  into problems when the filenames or ID tags have unicode characters in
  them.
 
  Typically, I do something like:
 
  from mutagen.easyid3 import EasyID3
 
  audio[title'] = Something based on the filename that has unicode
  chars in it
 
  I then get this:
 
  UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position
  56: ordinal not in range(128)
 
  From the docs:
  Mutagen has full Unicode support for all formats. When you assign
  text strings, we strongly recommend using Python unicode objects
  rather than str objects. If you use str objects, Mutagen will assume
  they are in UTF-8.
 
  So I suppose the value you try to assign as title is not unicode,
  check the encoding used in the file system.
 
  Iñigo

 I am trying to set the title based on the filename.  The file is in a Win32
 NTFS filesystem, so it could have non-ASCII chars in it.  What I am stumbling
 on it how to coerce it into unicode.  I have tried:

 name = filename.split() blah blah blah
 audio[title] = unicode(name)

 But I still get this error.  I am not real up to speed on the whole unicode
 end of things, so any kind suggestions would be most welcome.

 By the way, I believe the offending string contains a German umlaut, at least 
 in one
 of the cases.



To get the MP3's name, use os.path.basename (I'm guessing that's what
your split() is for?)
Looking at the mutagen tutorial, most of the tags are lists of unicode
strings, so you might want to try audio[title] = [unicode(name)],
instead of audio[title] = unicode(name).  This might be your problem
when reading the tags, too.

Iain

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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread Iain King

Xah Lee wrote:
 Of interest:

 • The Semicolon Wars, by Brian Hayes. 2006.
  http://www.americanscientist.org/template/AssetDetail/assetid/51982

 in conjunction to this article, i recommend:

 • Software Needs Philosophers, by Steve Yegge, 2006
 http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html

 • What Languages to Hate, Xah Lee, 2002
 http://xahlee.org/UnixResource_dir/writ/language_to_hate.html

   Xah
   [EMAIL PROTECTED]
 ∑ http://xahlee.org/

I'm confused - I thought Xah Lee loved Perl?  Now he's bashing it?
Huh?

Iain

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

Re: FOR LOOPS

2006-08-01 Thread Iain King

OriginalBrownster wrote:
 I am using a class called UploadedFile.
 I want to create a for loop to itterate through the objects within file
 name

 class UploadedFile(SQLObject):
   filename = StringCol(alternateID=True)
   abspath = StringCol()
   uniqueid = IntCol()

 I'll show you a snippit of the code I am trying to use it in::


 zip= [zip.txt]
 file_path = [myfile.filename for myfile in
 UploadedFile.select(orderBy=UploadedFile.q.filename)]

 if kw:
 for filename in file_path:
 zip.append(filename)
 flash('Options selected'+ str(kw) + str(zip))
 else:
 pass

 When i run this the flash displays all the values for kw...however zip
 only shows up as zip.txt using the str function. Meaning that the FOR
 LOOP is not working correctly.

After your 'file_path =' line, try adding a 'print file_path', and see
if it's creating it correctly.  Your for loop looks fine, assuming that
file_path is a list of filenames.

Iain

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


Re: random shuffles

2006-07-21 Thread Iain King

Dustan wrote:
 Boris Borcic wrote:
  does
 
  x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
 
  pick a random shuffle of x with uniform distribution ?
 
  Intuitively, assuming list.sort() does a minimal number of comparisons to
  achieve the sort, I'd say the answer is yes. But I don't feel quite 
  confortable
  with the intuition... can anyone think of a more solid argumentation ?

 Why not use the supplied shuffle method?

 random.shuffle(x)

or check out this thread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/766f4dcc92ff6545?tvc=2q=shuffle

Iain

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


Re: using names before they're defined

2006-07-20 Thread Iain King

[EMAIL PROTECTED] wrote:
 Iain, thanks - very helpful.

 Really I'm trying to write a simulation program that goes through a
 number of objects that are linked to one another and does calculations
 at each object. The calculations might be backwards or fowards (i.e.
 starting at the supply or demand ends of the system and then working
 through the objects). And also, I might have multiple objects linked to
 a single object (upstream or downstream) - e.g. compressor -- multiple
 combusters - turbine

 I like your idea of using something like a setStreams method to
 establish the linking. The streams do reflect each other, although
 having many-to-one and vice versa will complicate that. I have not
 quite got my head around having multiple links. In C++ I would be
 thinking about something like a linked-list but I'm not sure that's the
 right approach here.

 Dave

You don't need linked-lists : python has a list type built in.
Example:

class Component():

upstream = []
downstream = []

def addUpstream(self, c):
self.upstream.append(c)
if not self in c.downstream:
c.addDownstream(self)

def addDownstream(self, c):
self.downstream.append(c)
if not self in c.upstream:
c.addUpstream(self)

def remUpstream(self, c):
c.downstream.remove(self)
self.upstream.remove(c)

def remDownstream(self, c):
c.upstream.remove(self)
self.downstream.remove(c)

def cascadeDownTest(self):
print self
# this could run forever if you connect components in a circle:
for c in self.downstream:
c.cascadeDownTest() 

Iain

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


Re: question about what lamda does

2006-07-19 Thread Iain King

Steve Holden wrote:
 tac-tics wrote:
  [EMAIL PROTECTED] wrote:
 
 Hey there,
 i have been learning python for the past few months, but i can seem to
 get what exactly a lamda is for. What would i use a lamda for that i
 could not or would not use a def for ? Is there a notable difference ?
 I only ask because i see it in code samples on the internet and in
 books.
 
 
  Lambda is just as powerful as a function, but totally useless =-P
 
  Lambda used to be handy before the introduction of list comprehensions.
  Now, though, there primary use is obfuscating your code.
 
 I do wish you could hold yourself back and stop muddying the waters.
 Lambdas and list comprehensions have little or nothing to do with each
 other. Unless you know something I don't ...


I think he meant that lambda's main use before was inside map and
filter;  as stated earlier in the thread, lambda's main use was for
passing simple functions as arguments, and of these map and filter must
have made up a majority (and then I'd guess TKinter would be next).
List comprehensions replace map and filter, so...

I wouldn't put it as explosively as he has, but I find a lambda less
clear than a def too.

Iain


 regards
   Steve



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

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


Re: using names before they're defined

2006-07-19 Thread Iain King

[EMAIL PROTECTED] wrote:
 I have a problem. I'm writing a simulation program with a number of
 mechanical components represented as objects. When I create instances
 of objects, I need to reference (link) each object to the objects
 upstream and downstream of it, i.e.

 supply = supply()
 compressor = compressor(downstream=combustor, upstream=supply)
 combuster = combuster(downstream=turbine, upstream=compressor)
 etc.

 the problem with this is that I reference 'combustor' before is it
 created. If I swap the 2nd and 3rd lines I get the same problem
 (compressor is referenced before creation).


 aargh!!! any ideas on getting around this?

 Dave

At the top of your code you could put:

supply = None
compressor = None
combuster = None
turbine = None

It might be better, though, to arrange your code like:
supply = Supply()
compressor = Compressor()
combuster = Combuster()
turbine = Turbine()
compressor.setStreams(down=combuster, up=supply)
combuster.setStreams(down=turbine, up=compressor)

Do the streams reflect each other?  That is, if supply.down is
compressor, is compressor.up supply?  In that case you probably want to
do something like:

class Component():

upstream = None
downstream = None

def setUpstream(self, c):
self.upstream = c
if c.downstream != self:
c.setDownstream(self)

def setDownstream(self, c):
self.downstream = c
if c.upstream != self:
c.setUpstream(self)

class Supply(Component):
pass

etc.

Iain

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


Re: Full splitting of a file's pathname

2006-07-10 Thread Iain King

tac-tics wrote:
 I know about os.path.split(), but Is there any standard function for
 fully splitting a file's pathname? A function that is the opposite of
 the os.path.join() function? For example:

  ret = myster_function(./foo/bar/moo/lar/myfile.txt)
  print ret
 ['.', 'foo', 'bar', 'moo', 'lar', 'myfile.txt']

 In the meanwhile, I'll do this by hand. I'm just curious if there is a
 standard way to do this.

Simple function using os.path.split (so it should be fairly
compatible):

def split(path):
h,t = os.path.split(path)
if h == path:
return [h]
else:
return split(h) + [t]

You could throw in os.path.splitdrive and os.path.splitunc, if you
wanted to be really complete.

Iain

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


Re: List Manipulation

2006-07-05 Thread Iain King

Mike Kent wrote:
 Roman wrote:
  Thanks for your help
 
  My intention is to create matrix based on parsed csv file.  So, I would
  like to have a list of columns (which are also lists).
 
  I have made the following changes and it still doesn't work.
 
 
  cnt = 0
  p=[[], [], [], [], [], [], [], [], [], [], []]
  reader = csv.reader(file(f:\webserver\inp.txt), dialect=excel,
   quotechar=', delimiter='\t')
  for line in reader:
  if cnt  6:
 break
  j = 0
  for col in line:
 p[j].append(col)
 j=j+1
  cnt = cnt + 1
 
  print p

 p[j] does not give you a reference to an element inside p.  It gives
 you a new sublist containing one element from p.  You then append a
 column to that sublist.  Then, since you do nothing more with that
 sublist, YOU THROW IT AWAY.

 Try doing:

 p[j] = p[j].append(col)


No, this doesn't work.  append is an in-place operation, and you'll end
up setting p[j] to it's return, which is None.

Iain

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


Re: List Manipulation

2006-07-04 Thread Iain King

Roman wrote:
 I would appreciate it if somebody could tell me where I went wrong in
 the following snipet:

 When I run I get no result

 cnt = 0
 p=[]
 reader = csv.reader(file(f:\webserver\inp.txt), dialect=excel,
  quotechar=', delimiter='\t')
 for line in reader:
 if cnt  6:
break
 for col in line:
p[:0].append(str(col))

What are you trying to do here?  p[:0]  returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere.  If you want to
insert str(col) then use p.insert


Iain

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


Re: String Question

2006-06-30 Thread Iain King

Tim Roberts wrote:
 Iain King [EMAIL PROTECTED] wrote:
 
 You probably want:
 
 s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03,
  sttr04, str05, str06))*16, ('192.168.1.255', 80))

 You probably should TRY suggestions before you post them.  That will get an
 invalid \x escape.  \x must be followed by exactly two hex digits.  You
 can't build up an escape sequence like this.
 --
 - Tim Roberts, [EMAIL PROTECTED]
   Providenza  Boekelheide, Inc.

You're right.  I'd foolishly assumed that \x was just another character
code, like \t or \n.  Apologies.

Iain

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


Re: conecting with a MsAcces DB by dao

2006-06-30 Thread Iain King

luis wrote:
 Hi
 I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002
 (reading first http://starship.python.net/crew/bwilk/access.html)
 I have writed the following code

 def append_from_Access(self):
try:
   import ...
   conn = win32com.client.Dispatch(r'ADODB.Connection')
   DSN = PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA
 SOURCE=C:/Afile.mdb;
   conn.Open(DSN)
except Exception, inst:
...
try:
   sql_statement='SELECT * FROM  Mytable'
   rs = win32com.client.Dispatch(r'ADODB.Recordset')
   rs.Open(sql_statement, conn, 1, 3)
   while not rs.EOF:
  id=rs.Fields(colName.Value) #colName, valid column name
  ...
   rs.MoveNext()
   rs.Close()
   conn.Close()

  except Exception, inst:
  ...

 I'm using it for reading tables or queries in a mdb file.
 With some mdb it works fine and return a no empty recordset, but with
 others mdb files, the recordsets are void (opening the tables or
 recorsets with Ms Access are not void).
 Some help is welcome,
 Thanks in advance
 Luis

I don't know if it's the problem your asking about, but your
rs.MoveNext() should be inside the while loop, no?

Iain

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


Re: conecting with a MsAcces DB by dao

2006-06-30 Thread Iain King

luis wrote:
 Iain King ha escrito:

  luis wrote:
 while not rs.EOF:
id=rs.Fields(colName.Value) #colName, valid column name
...
 rs.MoveNext()
 rs.Close()
 conn.Close()
 
  I don't know if it's the problem your asking about, but your
  rs.MoveNext() should be inside the while loop, no?
 Yes, is inside
 

You mean, it is inside the while loop in your code, but you made a
mistake copying it into your post?  In the code you posted it is not
inside the while loop - it would have to be indented one more level for
that.

Iain

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


Re: conecting with a MsAcces DB by dao

2006-06-30 Thread Iain King

luis wrote:
 Iain King ha escrito:

  luis wrote:
   Iain King ha escrito:
  
luis wrote:
   while not rs.EOF:
  id=rs.Fields(colName.Value) #colName, valid column name
  ...
   rs.MoveNext()
   rs.Close()
   conn.Close()
   
I don't know if it's the problem your asking about, but your
rs.MoveNext() should be inside the while loop, no?
   Yes, is inside
   
 
  You mean, it is inside the while loop in your code, but you made a
  mistake copying it into your post?  In the code you posted it is not
  inside the while loop - it would have to be indented one more level for
  that.
 
  Iain

 this is te correct identation

 def append_from_Access(self):
try:
   import ...
   conn = win32com.client.Dispatch(r'ADODB.Connection')
   DSN = PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA
 SOURCE=C:/Afile.mdb;
   conn.Open(DSN)
except Exception, inst:
...
try:
   sql_statement='SELECT * FROM  Mytable'
   rs = win32com.client.Dispatch(r'ADODB.Recordset')
   rs.Open(sql_statement, conn, 1, 3)
   while not rs.EOF:
  id=rs.Fields(colName.Value) #colName, valid column name
  ...
  rs.MoveNext()
   rs.Close()
   conn.Close()

  except Exception, inst:
  ...

 I think my problem must be with ado and dao.
 Now I have run makepy utility and select Microsoft ActiveX Data Objects
 2.5 Library, perhaps I must also select Microsoft DAO3.5 Object Library
 and write
 win32com.client.Dispatch(DAO.DBEngine.35) for Access 97 or
 win32com.client.Dispatch(r'ADODB.Connection') for Acess 2000
 Do you know is it possible ?
 luis

Well, without being able to test on your system I don't think I can
give you any real advice.  This is the module I use to interface with
Access:

Access.py
---
import win32com.client
from win32com.client import constants

def isWriteable(field):
Is given Field writeable?
return field.Attributes  4


class Access(object):
def __init__(self, filename, password=):
self._filename = filename
self._connection = win32com.client.Dispatch(r'ADODB.Connection')
if password:
self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA 
SOURCE=%s;Jet
OLEDB:Database Password=%s;' % (filename, password)
else:
self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA 
SOURCE=%s;' %
(filename)

def Query(self, query):
self._connection.Open(self._DSN)
rs = win32com.client.Dispatch(r'ADODB.Recordset')
rs.Open(query, self._connection, 1, 3)
fields = []
for x in xrange(rs.Fields.Count):
fields.append(rs.Fields(x).Name)
if rs.EOF:
data = []
else:
data = rs.GetRows()
rs.Close()
self._connection.Close()
return fields, data


def Add(self, table, records):
Adds records to table.
self._connection.Open(self._DSN)
rs = win32com.client.Dispatch(r'ADODB.Recordset')
rs.Open(table, self._connection, 1, 3)
unwriteables = []
for record in records:
rs.AddNew()
unwriteable = []
for i in xrange(len(record)):
if isWriteable(rs.Fields(i)):
rs.Fields(i).Value = record[i]
else:
unwriteable.append(rs.Fields(i).Value)
unwriteables.append(unwriteable)
rs.Update()
rs.Close()
self._connection.Close()
return unwriteables


def Update(self, query, function):
Updates all records found in query with function(record)
self._connection.Open(self._DSN)
rs = win32com.client.Dispatch(r'ADODB.Recordset')
rs.Open(query, self._connection, 1, 3)
columns = rs.Fields.Count
while not rs.EOF:
record = []
for i in xrange(columns):
record.append(rs.Fields(i).Value)
newRecord = function(record[:])
for i in xrange(columns):
if isWriteable(rs.Fields(i)):
rs.Fields(i).Value = newRecord[i]
rs.MoveNext()
rs.Close()
self._connection.Close()


def Delete(self, query):
Deletes all records found in query
self._connection.Open(self._DSN)
rs

Re: String Question

2006-06-28 Thread Iain King

[EMAIL PROTECTED] wrote:
 mac_string = '001485e55503'  (This is the mac address of a computer.)

 I am using wake on LAN python script to start computer remote.It uses
 format like this 

 s.sendto('\xff'*6 + '\x00\x014\x85\xe5\x55\x03'*16, ('192.168.1.255',
 80))

 where '\x00\x14\x85\xe5\x55\x03' is the MAC address to be used.


 What I do is break the string into 6 parts like this,

 str01=mac_string[0:2]
 str02=mac_string[2:4]
 str03=mac_string[4:6]
 str04=mac_string[6:8]
 str05=mac_string[8:10]
 str06=mac_string[10:12]

 and if I use it like this

 s.sendto('\xff'*6 + '\xstr01\xstr02\xstr03\xstr04\xstr05\xstr06'*16,
 ('192.168.1.255', 80))
 I get an error


 I also tried like this
 s.sendto('\xff'*6 + 'mac_string'*16, ('192.168.1.255', 80))

 Thiis also didnt work.


 Since the MAC adddress are hexadecimal, how should I go about it here.

 Please help, every help is appreciated. Thanks

See http://docs.python.org/lib/typesseq-strings.html

You probably want:

s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03,
 sttr04, str05, str06))*16, ('192.168.1.255', 80))

Iain

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


Re: Feed wxComboBox with dictionary/hash

2006-06-22 Thread Iain King

Roland Rickborn wrote:
 Hi folks,

 I am relatively new to Python. Although I read a lot of howtos,
 introductions and wikis, I am still having trouble ;-)

 My querstion:
 As the subject says, I'd like to feed a wx.ComboBox with a
 dictionary/hash. According to the posting of Stano Paska (wxComboBox
  combobox, 20 Jul. 2004), there seems to be a way to do this:

  You must use something like
  combo.Append('aaa', 'a')
  combo.Append('bbb', 'b')
  ...

 My problem is:
 my data has thousands of entries. Therefore, I'd like to feed the
 combobox with a dictionary (which itself is fed by a database query).

 My first question:
 how can a wx.ComboBox be fed by a dictionary?

 For further help, Stano says:

  read manual for more details...

 Ok, I'd like to. But which one?
 I was reading http://www.wxpython.org/docs/api/wx.ComboBox-class.html
 and didn't even find the above mentioned append method :-(

 TIA,
 Roland R.

wxComboBox inherits from wxControlWithItems (as does wx.ListBox, and
other controls which hold lists).  See:
http://wxwidgets.org/manuals/2.6.3/wx_wxcontrolwithitems.html#wxcontrolwithitems

Iain

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


Re: .py and running in Windows:

2006-06-13 Thread Iain King

Andrew Gwozdziewycz wrote:
 You'll have better results posting this to it's own thread.


He certainly should have, but since I've read it here anyway:


 On Jun 13, 2006, at 9:29 AM, Michael Yanowitz wrote:

  Hello:
 
Presently in my Windows 2000 system, when I double-click on a
  .py file (open it) it automatically runs it in Python. I would
  like to change that behavour. That is fine for .pyc file, but
  for .py files, I would either like to have it run in Python but
  return to the Python shell prompt when finished rather than
  exit the shell. How do I do that?
Or would it cause a problem (so that Python no longer works) if
  I change the default .py extension to open in an editor rather
  than execute it if I open it?
 

In an explorer window, go to Tools-Folder Options
Go to the File Types tab, find the PY extension, then click on
Advanced*
Select the 'open' action, and click Edit...
change the 'Application used to perform action', inserting a '-i'
between the exe and the first parameter.  For example, I changed mine
to:

C:\Python\python.exe -i %1 %*

The exact line will depend on where your python.exe is.
OK all the dialogs you've opened, then double click a .py file to test
it.

*I'm using WinXP, so the exact name of some of the buttons may be
different for you.

Iain

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


Bug in list comprehensions?

2006-06-07 Thread Iain King
I was playing with list comprehensions, to try and work out how doubled
up versions work (like this one from another thread: [i for i in
range(9) for j in range(i)]).  I think I've figured that out, but I
found something strange along the way:

 alpha = [one, two, three]
 beta = [A, B, C]
 [x for x in alpha for y in beta]
['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']
 [x for x in y for y in beta]
['C', 'C', 'C']
 beta = [alpha, alpha, alpha]
 beta
[['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two',
'three']]
 [x for x in y for y in beta]
['C', 'C', 'C']
 [y for y in beta]
[['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two',
'three']]
 [x for x in y for y in beta]
['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']

Shoudn't both lines '[x for x in y for y in beta]' produce the same
list?
I'm guessing I'm the one confused here... but I'm confused!  What's
going on?

Iain

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


Re: pyqt show wizard

2006-06-07 Thread Iain King

David Boddie wrote:
 Summary of the usual mess made by the Google Groups web interface:


 I suspect that you really want to call w.exec_loop() instead, since
 this will only return control to the method after the user has finished
 interacting with the wizard.


 Take a look at the QWizard documentation for more information:
 
 
 http://doc.trolltech.com/3.3/qwizard.html
 
 
 David

test

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


Re: Trying to get FreeImagePy to work.

2006-06-05 Thread Iain King

Michele Petrazzo wrote:
 Iain King wrote:
  I'll try out FIPY's resizing tomorrow too.  OTOH, I have functions
  to convert between PIL and wxPython, and functions to convert
  betweem PIL and FIPY, but I don't see a function to convert FIPY to
  wxPython?
 
 
  Image at:  http://www.snakebomb.com/misc/example.tif
 
  Iain
 

 Yes it's min-is-white::

 michele:~$ tiffinfo example.tif
 TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680
 (0x9330) encountered.
 TIFF Directory at offset 0x1520 (5408)
Subfile Type: (0 = 0x0)
Image Width: 1696 Image Length: 1162
Resolution: 200, 200 pixels/inch
Bits/Sample: 1
Compression Scheme: CCITT Group 4
Photometric Interpretation: min-is-white# --
FillOrder: msb-to-lsb
Samples/Pixel: 1
Rows/Strip: 1162
Planar Configuration: single image plane
ImageDescription: DS
 michele:~$

 So you *need* to invert it to work correctly with PIL!

 P.s. Added the convertToWx function, that return a wx.Image, to the
 Image class.
 
 Michele

Most excellent!

Iain

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


Re: Large Dictionaries

2006-06-05 Thread Iain King

Lawrence D'Oliveiro wrote:
 In article [EMAIL PROTECTED],
  Scott David Daniels [EMAIL PROTECTED] wrote:

 For example, time timsort (Python's internal sort) on pre-sorted
 data; you'll find it is handled faster than random data.

 But isn't that how a reasonable sorting algorithm should behave? Less
 work to do if the data is already sorted?

An already sorted list can be pathological for Quicksort, depending on
how you code it.

Iain

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


  1   2   >