creating a block file for file-like object

2008-11-06 Thread Iain
Hi,

I have a function that only accepts filenames, rather than file-like
objects (because its a wrapper around a C++ function, I think).

I want to feed some potentially large "files" into this function, but
they are coming in as streams (eg from a url) and so are only
represented in my code as file-like objects.

Can someone give me some pointers as to how I might create some sort
of blocking device file or named pipe or something that will give this
stream a filename without having to actually write the data to disk
and then read it back in before deleting it?

I've sort of tried the FIFO thing, but I think I'm getting caught by
its blocking behaviour on open so as soon as I try to open the named
pipe (whether for reading or writing) my script just hangs.

Any help would be appreciated.

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


Re: creating a block file for file-like object

2008-11-07 Thread Iain
On Nov 7, 4:42 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>, Iain
> wrote:
>
> > Can someone give me some pointers as to how I might create some sort
> > of blocking device file or named pipe ...
>
>     mkfifo /path/to/named/pipe

Thanks.

I did get that far myself with os.mkfifo - my problem is actually
using it. To me it seemed like I wanted to do something like

streamobj = urllib.urlopen("http://whereever.com/file";)
fifoobj = open("/path/to/named/pipe","w")
fifoobj.write(streamobj.read())
TroublesomeFunction("/path/to/named/pipe")

But as soon as you get to the second line the code hangs (apparently
because of the blocking behaviour of the named pipe).

Any pointers here would be much appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating a block file for file-like object

2008-11-09 Thread Iain
On Nov 8, 10:00 am, Iain <[EMAIL PROTECTED]> wrote:
> On Nov 7, 4:42 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
>
> central.gen.new_zealand> wrote:
> > In message
> > <[EMAIL PROTECTED]>, Iain
> > wrote:
>
> > > Can someone give me some pointers as to how I might create some sort
> > > of blocking device file or named pipe ...
>
> >     mkfifo /path/to/named/pipe
>
> Thanks.
>
> I did get that far myself with os.mkfifo - my problem is actually
> using it. To me it seemed like I wanted to do something like
>
> streamobj = urllib.urlopen("http://whereever.com/file";)
> fifoobj = open("/path/to/named/pipe","w")
> fifoobj.write(streamobj.read())
> TroublesomeFunction("/path/to/named/pipe")
>
> But as soon as you get to the second line the code hangs (apparently
> because of the blocking behaviour of the named pipe).
>
> Any pointers here would be much appreciated.

Well I did work out *a* solution this way:

  pipename = os.tmpnam()
  os.mkfifo(pipename)
  pid = os.fork()
  if pid==0:
fifoobj = open(pipename,"w")
fifoobj.write(streamobj.read())
fifoobj.close()
os.unlink(pipename)
  else:
TroublesomeFunction(pipename)

I'd have to say it doesn't strike me as the BEST solution, but it
works. In particular the use of os.tmpnam() gives a warning that its
use is a potential security vulnerability, but this is inevitable if
taking the named pipe approach (any other suggestions are most
welcome, of course). And it doesn't fail very gracefully in that if
TroublesomeFunction stops before attempting to open/read the pipe,
then the child process stays hung waiting for the other end of the
pipe to open. In an interactive python shell you also get some weird
behaviour in this situation, but I'm not entirely sure what the exact
cause of that is.
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating a block file for file-like object

2008-11-10 Thread Iain

> Perhaps the parent should open the pipe for reading, before calling
> TroublesomeFunction. If the parent then dies, the child will get a "broken
> pipe" signal, which by default should kill it.

Yeah, that seems to work well, I think. Thanks for the help! I also
realised the child process was continuing and returning when I didn't
really want it to. So for anyone else who stumbles across this, it
ended up being

pipename = os.tmpnam()
os.mkfifo(pipename)
pid = os.fork()
if pid==0:
  fifoobj = open(pipename,"w")
  fifoobj.write(streamobj.read())
  fifoobj.close()
  os.unlink(pipename)
  os._exit(os.EX_OK)
else:
  fifoopen = open(pipename,"r")
  TroublesomeFunction(pipename)
--
http://mail.python.org/mailman/listinfo/python-list


Polling a net address

2009-08-20 Thread Iain
Hi All,

I'm writing a system tray application for windows, and the app needs
to poll a remote site at a pre-defined interval, and then process any
data returned.

The GUI needs to remain responsive as this goes on, so the polling
needs to be done in the background. I've been looking into Twisted as
a way of achieving this, but can't seem to get anything to loop
successfully.

Does anyone have any pointers that they might be able to give me?

TIA.
-- 
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: 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: use of index (beginner's question)

2011-04-28 Thread Iain King
On Apr 28, 2:45 am, Chris Angelico  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: Code Review

2011-05-25 Thread Iain King
On May 25, 2:44 pm, ad  wrote:
> On May 25, 4:06 am, Ulrich Eckhardt 
> 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  " % 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: How can I set the size of a window with tkinter?

2005-09-28 Thread Iain King

Tor Erik Sønvisen wrote:
> Hi
>
> I create a canvas that is to big for the default window-size, so it gets cut
> to fit...
> How can I increase the window-size to make sure the canvas fits?
>
> regards tores

root=Tk()
root.minsize(300,300)
root.geometry("500x500")

will limit the window to be at least 300x300, and set it straight away
to 500x500.

Iain

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


Re: backreferences

2005-09-28 Thread Iain King

Amy Dillavou wrote:
> Can someone help me with understanding how python uses backreferences?
> I need to remember the item that was last matched by the re engine but i
> cant seem to understand anything that I find on backreferences.  if I
> want to access the last match do i use \number or is there something
> else i have to do?
>
> heres part of my code:
> renDate = re.compile("$((\d){4}-(\d){2}-(\d){2}))")
> renDate.search(l)
> if(exist.search(l) and str(lastmodDate) < \1): #i need help here with \1
>
> Thanks in advance
> A.D

I haven't had to use backreferences yet, so I don't know offhand how to
go about it.  What I do know is that this online book is very useful:

http://gnosis.cx/TPiP/


Chapter 3 covers REs:

http://gnosis.cx/TPiP/chap3.txt

>From what I remember, in python you can use numbered backreferences (up
to 99), or named ones.

Iain

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


Re: [PIL]: Question On Changing Colour

2005-10-14 Thread Iain King

Andrea Gavana wrote:
> I have tried your solution, Terry:
>
> > new_hue   # your 'basic color', just the hue part
> > rgb_base  # color from the basic button image
> > rgb_new   # the new color you want to replace rgb_base with
> >
> > rgb_new = hsv_to_rgb( (new_hue,) + rgb_to_hsv(rgb_base)[1:])
>
>
> thanks a lot for your suggestion! However, either I did not understand it
> correctly or I am doing something stupid in my code. Here is a small
> example:
>
> from colorsys import *
>
> # that is the old colour --> GREY
> rgb_old = (0.7, 0.7, 0.7)
>
> # Transform the new colour in HSV
> hsv_old = rgb_to_hsv(rgb_old[0], rgb_old[1], rgb_old[2])
>
> # this is the new colour --> BLUE
> rgb_new = (0.0, 0.0, 1.0)
>
> # Transform the new colour in HSV
> hsv_new = rgb_to_hsv(rgb_new[0], rgb_new[1], rgb_new[2])
>
> # I take only the Hue part of the new colour
> new_hue = hsv_new[0]
>
> # Get the new colour
> rgb_new = hsv_to_rgb(new_hue, hsv_old[1], hsv_old[2])
>
> print rgb_old
> print rgb_new
> print rgb_old == rgb_new
>
>
> This prints:
>
> (0.69996, 0.69996, 0.69996)
> (0.69996, 0.69996, 0.69996)
> True
>
> So, no matter what colour I choose as a "new" colour, the Hue part of the
> new colour doesn't change in RGB. In other words, leaving the old value for
> "Saturation" and "Value" makes the presence of the "Hue" part useless. But
> why in the world does this happen? If a colour is defined by 3 values,
> changes in every single value should change the colour too...

Not with HSV.  The hue determines which 'color' it will be - red, blue,
indigo, whatever.  That Saturation determined how vibrant this 'color'
will be.  V is brightness (I can't remember what the V actually stands
for).  Each of these values scales from 0 to 1, or 0% to 100%, however
you want to thiink about it.   If you try and picture the gradient
you'd get by plotting this range as a line, then:
The H line would be a spectrum of colours, like a rainbow.
Say we pick H to be RGB #FF - Red
The S line would be a gradient ranging from grey (absense of color) to
red.
The V line would be a gradient ranging from black (completely dark) to
red.

So on the HSV scale, grey is represented by a saturation of 0 - meaning
none of H is present in the color; the color in question being
determined purely by it's brightness (V).  So when you pick your HSV
triplet for a grey color, you have to set S to 0.  You can set H to
anything at all - because S is 0, no tint of H will appear in the color
at all.

Iain http://www.snakebomb.com

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


Re: Python vs Ruby

2005-10-24 Thread Iain King

Tom Anderson wrote:
> On Fri, 21 Oct 2005, vdrab wrote:
>
> > You can tell everything is well in the world of dynamic languages when
> > someone posts a question with nuclear flame war potential like "python
> > vs. ruby" and after a while people go off singing hymns about the beauty
> > of Scheme...
>
> +1 QOTW
>
> > I love this place.
>
> Someone should really try posting a similar question on c.l.perl and
> seeing how they react ...
> 
> tom

SSsh! Xah Lee might be listening!

Iain

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


Re: more than 100 capturing groups in a regex

2005-10-25 Thread Iain King

Fredrik Lundh wrote:
> Joerg Schuster wrote:
>
> > I just want to use more than 100 capturing groups.
>
> define "more" (101, 200, 1000, 10, ... ?)
>
> 

The Zero-One-Infinity Rule:

http://www.catb.org/~esr/jargon/html/Z/Zero-One-Infinity-Rule.html

Iain

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


Re: more than 100 capturing groups in a regex

2005-10-25 Thread Iain King

Steven D'Aprano wrote:
> On Tue, 25 Oct 2005 05:17:52 -0700, Iain King wrote:
>
> >
> > Fredrik Lundh wrote:
> >> Joerg Schuster wrote:
> >>
> >> > I just want to use more than 100 capturing groups.
> >>
> >> define "more" (101, 200, 1000, 10, ... ?)
> >>
> >> 
> >
> > The Zero-One-Infinity Rule:
> >
> > http://www.catb.org/~esr/jargon/html/Z/Zero-One-Infinity-Rule.html
>
>
> Nice in principle, not always practical. Sometimes the choice is, "do you
> want it today with arbitrary limits, or six months from now with bugs
> but no limits?"
>
> If assigning arbitrary limits prevents worse problems, well, then go for
> the limit. For instance, anyone who has fought browser pops ups ("close
> one window, and ten more open") may have wished that the browser
> implemented an arbitrary limit of, say, ten pop ups. Or even zero :-)
>

Well, exactly.  Why limit to ten?  The user is either going to want to
see pop-ups, or not.  So either limit to 0, or to infinity (and indeed,
this is what most browsers do).
Note the jargon entry defines infinity in this case to me the largest
possible amount given whatever ram/disk space/processing power you have
available.

Also: These arbitrary limits tend to stem from languages which
predominantly use fixed size arrays - DIM in basic, or malloc in C.
The native python component is the list, which doesn't have a max size,
so these problems should be encountered less in python code; by it's
nature, python steers you away from this mistake.

Iain

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


Re: more than 100 capturing groups in a regex

2005-10-25 Thread Iain King

Steven D'Aprano wrote:
> On Tue, 25 Oct 2005 06:30:35 -0700, Iain King wrote:
>
> >
> > Steven D'Aprano wrote:
> >> On Tue, 25 Oct 2005 05:17:52 -0700, Iain King wrote:
> >>
> >> >
> >> > Fredrik Lundh wrote:
> >> >> Joerg Schuster wrote:
> >> >>
> >> >> > I just want to use more than 100 capturing groups.
> >> >>
> >> >> define "more" (101, 200, 1000, 10, ... ?)
> >> >>
> >> >> 
> >> >
> >> > The Zero-One-Infinity Rule:
> >> >
> >> > http://www.catb.org/~esr/jargon/html/Z/Zero-One-Infinity-Rule.html
> >>
> >>
> >> Nice in principle, not always practical. Sometimes the choice is, "do you
> >> want it today with arbitrary limits, or six months from now with bugs
> >> but no limits?"
> >>
> >> If assigning arbitrary limits prevents worse problems, well, then go for
> >> the limit. For instance, anyone who has fought browser pops ups ("close
> >> one window, and ten more open") may have wished that the browser
> >> implemented an arbitrary limit of, say, ten pop ups. Or even zero :-)
> >>
> >
> > Well, exactly.  Why limit to ten?  The user is either going to want to
> > see pop-ups, or not.  So either limit to 0, or to infinity (and indeed,
> > this is what most browsers do).
>
> I haven't been troubled by exponentially increasing numbers of pop up
> windows for a long, long time. But consider your question "why limit to
> ten?" in a wider context.
>
> Elevators always have a weight limit: the lift will operate up to N
> kilograms, and stop at N+1. This limit is, in a sense, quite arbitrary,
> since that value of N is well below the breaking point of the elevator
> cables. Lift engineers, I'm told, use a safety factor of 10 (if the
> cable will carry X kg without breaking, set N = X/10). This safety
> factor is obviously arbitrary: a more cautious engineer might use a
> factor of 100, or even 1000, while another might choose a factor of 5 or
> 2 or even 1.1. If engineers followed your advice, they would build lifts
> that either carried nothing at all, or accepted as much weight until the
> cable stretched and snapped.
>
> Perhaps computer programmers would have fewer buffer overflow security
> exploits if they took a leaf out of engineers' book and built in a few
> more arbitrary safety factors into their data-handling routines. We can
> argue whether 256 bytes is long enough for a URL or not, but I think we
> can all agree that 3 MB for a URL is more than any person needs.
>
> When you are creating an iterative solution to a problem, the ending
> condition is not always well-specified. Trig functions such as sine and
> cosine are an easy case: although they theoretically require an infinite
> number of terms to generate an exact answer, the terms will eventually
> underflow to zero allowing us to stop the calculation.
>
> But unfortunately that isn't the case for all mathematical calculations.
> Often, the terms of our sequence do not converge to zero, due to round-off
> error. Our answer cycles backwards and forwards between two or more
> floating point approximations, e.g. 1.276805 <-> 1.276804. The developer
> must make an arbitrary choice to stop after N iterations, if the answer
> has not converged. Zero iterations is clearly pointless. One is useless.
> And infinite iterations will simply never return an answer. So an
> arbitrary choice for N is the only sensible way out.
>
> In a database, we might like to associate (say) multiple phone numbers
> with a single account. Most good databases will allow you to do that, but
> there is still the question of how to collect that information: you have
> to provide some sort of user interface. Now, perhaps you are willing to
> build some sort of web-based front-end that allows the user to add new
> fields, put their phone number in the new field, with no limit. But
> perhaps you are also collecting data using paper forms. So you make an
> arbitrary choice: leave two (or three, or ten) boxes for phone numbers.
>
> There are many other reasons why you might decide rationally to impose an
> arbitrary limit on some process -- arbitrary does not necessarily mean
> "for no good reason". Just make sure that the reason is a good one.
>
>
> --
> Steven.


I think we are arguing at cross-purposes, mainly because the term'
arbitrary' has snuck in.  The actual rule:

 "Allow none of foo, one of foo, or any number of foo." A rule of
thumb for software design, which instructs

Re: more than 100 capturing groups in a regex

2005-10-26 Thread Iain King

Fredrik Lundh wrote:
> Iain King wrote:
>
> > Anyway, back to the OP: in this specific case, the cap of 100 groups in
> > a RE seems random to me, so I think the rule applies.
>
> perhaps in the "indistinguishable from magic" sense.
>
> if you want to know why 100 is a reasonable and non-random choice, I
> suggest checking the RE documentation for "99 groups" and the special
> meaning of group 0.
>
> 

Ah, doh!  Of course.  Oh well then...  still, doesn't python's RE
engine support named groups?  That would be cumbersome, but would allow
you to go above 100...

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


Re: Looping Problem (Generating files - only the last record generates a file)

2005-10-26 Thread Iain King

[EMAIL PROTECTED] wrote:
> Hello All,
>
> I have a problem with the program that should generate x number of txt
> files (x is the number of records in the file datafile.txt).
>
> Once I execute the program (see below) only one file (instead of x
> files) is created. The file created is based on the last record in
> datafile.txt.
>
> The program is as follows:
> 
> #!  python
>
> HEADER = "This page displays longitude-latitude information"
> SUBHEADER = "City"
>
> for line in open("datafile.txt"):
>
>
> town, latlong = line.split('\t')
>
> f = open(town + ".txt", "w+")
>
> f.write(HEADER + "\n")
> f.write(SUBHEADER + ": " + town + "\n")
> f.write("LAT/LONG" + ": " + latlong + "\n")
> f.close()
>
>
> # end
> 
>
>
>
>
> The datafile.txt is as follows (tab separated columns):
> 
>
> NYC   -
> Lima  -
> Rome  -
>
> 
>
> Once executed, the program will create a single file (named Rome.txt)
> and it would not create files NYC.txt and Lima.txt as I would expect it
> to do.
>
> I'd appreciate if you can pinpoint my error.
> 
> Best, 
> 
> Vasa

Did you try indenting the last five lines?

Iain

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


Re: Microsoft Hatred FAQ

2005-10-26 Thread Iain King

David Blomstrom wrote:
> A bit off topic, but it amazes me that people in the
> web design/Internet industry don't take a more active
> stance against Microsoft.
>
> Think about it: The health care industry has been
> privatized in the U.S. I spent sixteen years in
> education, another institution that has been
> privatized. (It has largely become another Microsoft
> subsidiary.)
>
> So here we have web designers, who are among the
> freest people in the world, able to choose their
> specialties, hours, fees and even where they work. Yet
> they surrender to Microsoft's "standards" without a
> fight.
>
> Frankly, I think every self-respecting webmaster ought
> to be campaigning against Microsoft on their websites.
> Tiny, simple messages like "Microsoft-Free" or "If you
> like George AWOL Bush, you'll love Bill Gates," could
> go a long ways in educating the public.
>

Or, you know, just code your website to be W3C compliant, which IE will
invariably choke on. 

Iain

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


Double replace or single re.sub?

2005-10-26 Thread Iain King
I have some code that converts html into xhtml.  For example, convert
all  tags into .  Right now I need to do to string.replace calls
for every tag:

html = html.replace('','')
html = html.replace('','')

I can change this to a single call to re.sub:

html = re.sub('<([/]*)i>', r'<\1em>', html)

Would this be a quicker/better way of doing it?

Iain

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


Re: Top-quoting defined [was: namespace dictionaries ok?]

2005-10-26 Thread Iain King

Duncan Booth wrote:
> James Stroud wrote:
>
> > On Tuesday 25 October 2005 00:31, Duncan Booth wrote:
> >> P.S. James, *please* could you avoid top-quoting
> >
> > Were it not for Steve Holden's providing me with a link off the list,
> > I would have never known to what it is you are referring. I have read
> > some relevant literature to find that this is more widely known as
> > "top-posting". I'll go with majority rules here, but I would like to
> > say that my lack of "netiquette" in this matter comes from
> > practicality and not malice.
>
> No, I didn't think it was malice which is why I just added what I
> considered to be a polite request at the end of my message. I assumed that
> most people either knew the phrase or could find out in a few seconds using
> Google so there wasn't much point in rehashing the arguments. Probably I
> should have equally lambasted Ron for the heinous crime of bottom-quoting.
>
> In general, there are three ways to quote a message: top-quoting, which
> forces people to read the message out of order; bottom-quoting which is
> nearly as bad because it hides the new comments; and proper quoting in
> context where you trim the message and put specific points under brief bits
> of context.
>

Just to continue this off-topic argument :)  -

I've never heard the terms top-quoting, bottom-quoting.  I've heard
top-posting and bottom-posting before (lots).  But regardless of
however many people use top-quoting and bottom-quoting, surely you're
using them the wrong way around?  If I top-post, then that means that
the quote is at the bottom, no?

To quote someone's sig block:
 "To top-post is human, to bottom-post and snip is sublime."

Iain

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


Re: Double replace or single re.sub?

2005-10-26 Thread Iain King

Mike Meyer wrote:
> "Iain King" <[EMAIL PROTECTED]> writes:
>
> > I have some code that converts html into xhtml.  For example, convert
> > all  tags into .  Right now I need to do to string.replace calls
> > for every tag:
> >
> > html = html.replace('','')
> > html = html.replace('','')
> >
> > I can change this to a single call to re.sub:
> >
> > html = re.sub('<([/]*)i>', r'<\1em>', html)
> >
> > Would this be a quicker/better way of doing it?
>
> Maybe. You could measure it and see. But neither will work in the face
> of attributes or whitespace in the tag.
>
> If you're going to parse [X]HTML, you really should use tools that are
> designed for the job. If you have well-formed HTML, you can use the
> htmllib parser in the standard library. If you have the usual crap one
> finds on the web, I recommend BeautifulSoup.
>

Thanks.  My initial post overstates the program a bit - what I actually
have is a cgi script which outputs my LIveJournal, which I then
server-side include in my home page (so my home page also displays the
latest X entries in my livejournal).  The only html I need to convert
is the stuff that LJ spews out, which, while bad, isn't terrible, and
is fairly consistent.  The stuff I need to convert is mostly stuff I
write myself in journal entries, so it doesn't have to be so
comprehensive that I'd need something like BeautifulSoup.  I'm not
trying to parse it, just clean it up a little.

Iain

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


Re: Microsoft Hatred FAQ

2005-10-27 Thread Iain King

David Schwartz wrote:
> Roedy Green wrote:
>
> > On Sun, 16 Oct 2005 16:31:41 GMT, Roedy Green
> > <[EMAIL PROTECTED]> wrote, quoted or
> > indirectly quoted someone who said :
>
> >> I used to be a retailer of custom computers.  MS used a dirty trick
> >> to compete with IBM's OS/2.  They said to me as a retailer. You must
> >> buy a copy of our OS for EVERY machine you sell.  The alternative is
> >> to pay full retail for the OSes.
>
> > Through intimidation, MS managed to control the entire retail computer
> > market  in Vancouver BC to the extent you could not buy even the most
> > stripped down computer  without having to buy a copy of Windows with
> > it, whether you wanted it or not.
> >
> > You might not want it because you bought OS/2.
> >
> > You might not want it because you already owned Windows from your
> > older machine you were upgrading.
> >
> > You might not want it because somebody stole your machine and they did
> > not steal all your software masters.
>
> Tell me, can you buy a new car without seats? Guess what, you have to
> buy those seats whether you want them or not.
>
> Try to start a business selling competing seats for a new car. Your
> seats may be cheaper, better, but how can you possibly compete when people
> have to pay for factory car seats whether they want them or not?
>
> The real reason PCs were not available without Windows was because not
> enough people wanted them that way to justify setting up a business to
> provide them that way, and Microsoft was not going to let a business
> parasitically use Windows to build a business that touted the advantages of
> competing products. (Just as Burger King corporate will not you sell Big
> Macs in the same store in which you sell Whoppers.)
>
> DS

Don't you see how your metaphor doesn't work?  It would only be fitting
if Microsoft OWNED the outlet.  Places which sell Whoppers are Burger
King franchises, so of course they aren't going to sell Big Mac's.  PC
hardware stores do not belong to microsoft.  There just isn't any
correlation.

Iain

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


Re: Microsoft Hatred FAQ

2005-10-27 Thread Iain King

David Schwartz wrote:
> Roedy Green wrote:
>
> > The particular way MS threatened to put me out of business was by
> > threatening to arm twist all wholesalers to refuse to sell MS product
> > to me, which any retailer needed to survive in those days.
>
> Right, I get that. You owed your entire business to Microsoft. Without
> their products, you would have had nothing, by your own admission. The way
> you repay them is by trying to screw them -- attract people who come in only
> because you offer Windows and then say "here's an OS that's better and
> cheaper".

Oh right.  You're actually just a troll.  Oh well.

*plonk*

Iain

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


Re: need help extracting data from a text file

2005-11-07 Thread Iain King

[EMAIL PROTECTED] wrote:
> Hey there,
> i have a text file with a bunch of values scattered throughout it.
> i am needing to pull out a value that is in parenthesis right after a
> certain word,
> like the first time the word 'foo' is found, retrieve the values in the
> next set of parenthesis (bar) and it would return 'bar'
>
> i think i can use re to do this, but is there some easier way?
> thanks

well, you can use string.find with offsets, but an re is probably a
cleaner way to go.  I'm not sure which way is faster - it'll depend on
how many times you're searching compared to the overhead of setting up
an re.

start = textfile.find("foo(") + 4 # 4 being how long 'foo(' is
end = textfile.find(")", start)
value = textfile[start:end]

Iain

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


Re: need help extracting data from a text file

2005-11-07 Thread Iain King

[EMAIL PROTECTED] wrote:
> this is cool, it is only going to run about 10 times a day,
>
> the text is not written out like foo(bar) its more like
> foo blah blah blah (bar)
>

then I guess you worked this out, but just for completeness:

keywordPos = textfile.find("foo")
start = textfile.find("(", keywordPos)
end = textfile.find(")", start)
value = textfile[start:end]


Iain

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


PNG processing with only base python install

2005-11-08 Thread Iain King
My web server supports python CGI scripts, but I can't install anything
else there - I can just use what they've provided.  I want to process
some PNG images - any ideas how I can do this with just the basic
modules?  Is there an image processing module written purely in Python?

Iain

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


Re: How to paste python code on wordpress?

2005-11-22 Thread Iain King

Dan Lowe wrote:
> On Nov 22, 2005, at 12:30 AM, could ildg wrote:
>
> > Thank you~
> > It works!
> > but how can paste "<" and ">", please?
> > these 2 symbols will also confuse wordpress and I can't publish
> > what I want.
>
> Replace < with <
>
> Replace > with >
>
> (where those abbreviations stand for "less than" and "greater than")
>
> Before: if x < 5:
>
> After: if x < 5:
>
> Another common character in code that you "should" do similarly is
> the double quote ("). For that, use "
>
> Before: if x == "foo":
>
> After: if x == "foo":
>
>   -dan
>
> --
> Any society that needs disclaimers has too many lawyers.  -Erik Pepke

You don't *need* to replace with "
However, you will need to replace any ampersands with & ( <, >, and
& are characters with intrinsic qualities in html).  You need to
replace & before you replace anything else: if you do it after
repalcing < and > you'll catch your < and >, ending up with
&lt; and &gt; which is not what you want.

Iain

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


Re: Documentation suggestions

2005-12-07 Thread Iain King
> The library reference has so many modules that the table of contents
> is very large.  Again, not really a problem that we can fix; splitting
> it up into separate manuals doesn't seem like it would help.

I like the Global Module Index in general - it allows quick access to
exactly what I want.
I would like a minor change to it though - stop words starting with a
given letter rolling over to another column (for example, os.path is at
the foot of one column, while ossaudiodev is at the head of the next),
and provide links to each initial letter at the top of the page.

Iain

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


Re: Documentation suggestions

2005-12-07 Thread Iain King

[EMAIL PROTECTED] wrote:
> >> The library reference has so many modules that the table of contents
> >> is very large.  Again, not really a problem that we can fix;
> >> splitting it up into separate manuals doesn't seem like it would
> >> help.
>
> Iain> I like the Global Module Index in general - it allows quick access
> Iain> to exactly what I want.  I would like a minor change to it though
> Iain> - stop words starting with a given letter rolling over to another
> Iain> column (for example, os.path is at the foot of one column, while
> Iain> ossaudiodev is at the head of the next), and provide links to each
> Iain> initial letter at the top of the page.
>
> I know it's not what you asked for, but give
>
> http://staging.musi-cal.com/modindex/
>
> a try.  See if by dynamically migrating the most frequently requested
> modules to the front of the section it becomes more manageable.
>
> Skip

Well, the point of the GMI is to lookup whatever module you are
currently having to use for the first time (at least it is for me).
Giving easy access to the modules I've already had to look up (because
they are common) doesn't really help - I've already accessed those.
It'll be nice when I have to find some obscure feature I haven't used
in them before, but really, all I'd like is an easy to use index :)

Iain

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


Re: Documentation suggestions

2005-12-07 Thread Iain King

[EMAIL PROTECTED] wrote:
> Iain> Well, the point of the GMI is to lookup whatever module you are
> Iain> currently having to use for the first time (at least it is for
> Iain> me).  Giving easy access to the modules I've already had to look
> Iain> up (because they are common) doesn't really help - I've already
> Iain> accessed those.  It'll be nice when I have to find some obscure
> Iain> feature I haven't used in them before, but really, all I'd like is
> Iain> an easy to use index :)
>
> Reorganizing the global module index isn't all that straightforward.  It is
> generated by latex2html.  To change its layout would probaly require some
> additional markup and mods to latex2html (not a pretty piece of code as I
> understand it).
>
> OTOH, I find myself returning to the same module docs over and over again to
> look up function arguments, regular expression syntax, that sort of thing.
> Having to page down past dozens and dozens of modules I don't care about to
> click on "sys" or "datetime" motivated me to write my little hack.
>
> Skip

Argh, you made me look at the html again - at least now I know *why* it
is so disgusting.  I understand there's a new version coming out soon,
hopefully in html 4 strict or xhtml.  I'm sure at that point it'll be
easier to use.  I can wait. :)

Iain

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


Re: overload builtin operator

2005-08-29 Thread Iain King

Robert Kern wrote:
> Shaun wrote:
> > Thanks for your replies, obviously this isn't a simple thing to do so
> > I'll take a different tack.
> >
> > The exact problem I am trying to solve here is to avoid the
> > ZeroDivisionError in division.
> > I have c++ code which delegates to python to calculate expressions on
> > table cells. The values of the table cell are arbitary numbers and the
> > expressions to be calculated are fairly simple python arithmetic and
> > math functions.
> >
> > The problem being that some users want an expression like '(100/x)+ 3'
> > where x=0 to return 3. So that dividing a number by zero results in 0.
>
> You have silly users.

You mean you don't?  Damn.  Can I have some of yours?

Iain

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


Re: how to join two Dictionary together?

2005-08-30 Thread Iain King

DENG wrote:
> dict1={...something...}
>
> dict2={...somethind else ..}
>
> dict1 + dict2
>
>
> that's does works ..:(, it's not like List...
>
>
> anyone can tell me how to get it?
>

Uh, I'm just learning python too, so there may be a much simpler way to
do this, but you could:

dict3 = {}
for k,i in dict1.iteritems():
dict3[k] = i
for k,i in dict2.iteritems():
dict3[k] = i

Think this should work.  Obviously, if the same key appears in both
dict1 and dict2 then dict2's value will overwrite dict1's.

Iain

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


Re: how to join two Dictionary together?

2005-08-30 Thread Iain King

Iain King wrote:
> DENG wrote:
> > dict1={...something...}
> >
> > dict2={...somethind else ..}
> >
> > dict1 + dict2
> >
> >
> > that's does works ..:(, it's not like List...
> >
> >
> > anyone can tell me how to get it?
> >
>
> Uh, I'm just learning python too, so there may be a much simpler way to
> do this, but you could:
>
> dict3 = {}
> for k,i in dict1.iteritems():
> dict3[k] = i
> for k,i in dict2.iteritems():
> dict3[k] = i
>
> Think this should work.  Obviously, if the same key appears in both
> dict1 and dict2 then dict2's value will overwrite dict1's.
>
> Iain

Or, on reading the tutorial a bit more thoroughly, you can do:

dict1.update(dict2)

which will add all of dict2's key:value pairs to dict1

Iain

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


Re: how to join two Dictionary together?

2005-08-30 Thread Iain King

[EMAIL PROTECTED] wrote:
> update works like append for lists
>
> a = {}
> a['a']='a'
> a['c']='c'
> b={}
> b['b'] = 'b'
> c={}
> c.update(a)
> c.update(b)
>


So what do you think is the better way to do it, based on speed or
aesthetics?

(1)
c=a.copy()
c.update(b)

or

(2)
c={}
c.update(a)
c.update(b)

Iain

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


wxPython, using sizers.

2005-09-16 Thread Iain King
I'm making a program to view log files.  The main display is a multi
column listbox.  I want to add combobox filters above the listbox
headers.  The filters contain each unique instance in the list column
below it, and if any filter has text selected in it then the listbox
will only display rows in which the relevant column contains that text
(MS Excel's Autofilter, basically).  I need to get the comboboxes to be
positioned directly above the column headers, and be the same width,
and I've had no luck.  I tried with a horizontal boxsizer, but it
resets the widths automatically (as I imagine it is supposed to).  Any
tips?

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: 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: 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=2&q=shuffle

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: 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: 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: 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: Trying to get FreeImagePy to work.

2006-06-01 Thread Iain King

Michele Petrazzo wrote:
> Iain King wrote:
> > Michele Petrazzo wrote:
> >
> > I downloaded and installed 0.9.9.3, and it now works.  Thanks!
> >
>
> I advice you to don't use that ctypes version... Better is to use the
> newest one and update freeimagepy!
>
> > Iain
> >
>
> Michele

OK, Ive installed the latest versions I can find, which are FreeImagePy
1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had earlier.  Do
you know what's wrong?

Iain

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


Re: Trying to get FreeImagePy to work.

2006-06-01 Thread Iain King

Michele Petrazzo wrote:
> Iain King wrote:
> > Michele Petrazzo wrote:
> >> Iain King wrote:
> >>> Michele Petrazzo wrote:
> >>>
> >>> I downloaded and installed 0.9.9.3, and it now works.  Thanks!
> >>>
> >> I advice you to don't use that ctypes version... Better is to use
> >> the newest one and update freeimagepy!
> >>
> >>> Iain
> >>>
> >> Michele
> >
> > OK, Ive installed the latest versions I can find, which are
> > FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had
> >  earlier.  Do you know what's wrong?
> >
> > Iain
> >
>
> Can you download the last svn version from sf.net? Otherwise I'll send
> you the last sources privately.
>
> Bye,
> Michele

Sorry, I hadn't heard of SVN before, so I didn't know what you were
talking about earlier :).  I got the TortoiseSVN client though, and
checked out your newest build, copied it over the top of
site-packages/freeimagepy, updated my ctypes back to 0.9.9.6 (I'd
regressed again), ran my program, and it worked.  Thanks!

Next question (and what I'm using FreeImagePy for):  I'm loading a pile
of TIF's as thumbnails into a wx list control.  I load the image with
FIPY, convert it to PIL, use PIL's antialiasing thumbnail function,
then load it from there into wx.  However, when I'm do the
fipy.convertToPil(), it inverts the image?  I've inserted a
fipy.invert() before the conversion as a temporary fix, but is there a
reason for this?
relevant code:

def getHeaders(files):
thumbs = []
for f in files:
print "Adding %s" % f
fi = FIPY.Image(f)
fi.setCurrentPage(0)
    fi.invert() #temp fix
thumb = fi.convertToPil()
thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
thumbs.append((os.path.basename(f), pilToBitmap(thumb)))
thumbs.sort()
return thumbs

Iain

p.s. thanks again

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


Re: Trying to get FreeImagePy to work.

2006-06-01 Thread Iain King

Michele Petrazzo wrote:
> Iain King wrote:
> > However, when I'm do the
> > fipy.convertToPil(), it inverts the image?
>
> No, it not invert the image... It only return the image as is.
>
> > I've inserted a
> > fipy.invert() before the conversion as a temporary fix, but is there a
> > reason for this?
>
> If you are have a min-is-white image (fax ?) that isn't the standard,
> you will have an "inverted" image, because PIl expect a min-is-black
> image!
>


This is probably what is happening.  I'll upload one of the images
tomorrow, and you can check it out to make sure.


> > relevant code:
> >
> > def getHeaders(files):
> > thumbs = []
> > for f in files:
> > print "Adding %s" % f
> > fi = FIPY.Image(f)
> > fi.setCurrentPage(0)
> > fi.invert() #temp fix
> > thumb = fi.convertToPil()
> > thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
> > thumbs.append((os.path.basename(f), pilToBitmap(thumb)))
> > thumbs.sort()
> > return thumbs
>
> Just a question, why "thumbs.sort" ? Inside this list you have only
> images!

Ah, look closer!  It's a list of tuples:  (filename, image)
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?

Iain

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


Re: Trying to get FreeImagePy to work.

2006-06-02 Thread Iain King

Iain King wrote:
> Michele Petrazzo wrote:
> > Iain King wrote:
> > > However, when I'm do the
> > > fipy.convertToPil(), it inverts the image?
> >
> > No, it not invert the image... It only return the image as is.
> >
> > > I've inserted a
> > > fipy.invert() before the conversion as a temporary fix, but is there a
> > > reason for this?
> >
> > If you are have a min-is-white image (fax ?) that isn't the standard,
> > you will have an "inverted" image, because PIl expect a min-is-black
> > image!
> >
>
>
> This is probably what is happening.  I'll upload one of the images
> tomorrow, and you can check it out to make sure.
>
>
> > > relevant code:
> > >
> > > def getHeaders(files):
> > >   thumbs = []
> > >   for f in files:
> > >   print "Adding %s" % f
> > >   fi = FIPY.Image(f)
> > >   fi.setCurrentPage(0)
> > >   fi.invert() #temp fix
> > >   thumb = fi.convertToPil()
> > >   thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
> > >   thumbs.append((os.path.basename(f), pilToBitmap(thumb)))
> > >   thumbs.sort()
> > >   return thumbs
> >
> > Just a question, why "thumbs.sort" ? Inside this list you have only
> > images!
>
> Ah, look closer!  It's a list of tuples:  (filename, image)
> 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

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


Re: shuffling elements of a list

2006-06-02 Thread Iain King

David C. Ullrich wrote:
> On 30 May 2006 21:53:32 -0700, "greenflame" <[EMAIL PROTECTED]>
> wrote:
>
> That's DSU for _sorting_ a list. I read about this, thought
> it was pretty neat. I thought that the fact that you
> could use the same trick for _shuffling_ a list was
> my idea, gonna make me rich and famous. I guess I'm
> not the only one who thought of it. Anyway, you can
> use DSU to _shuffle_ a list by decorating the list
> with random numbers.
>
> In fairly old-fashioned Python:
>
> from random import random
>
> def shuffle(data):
>   decorated = map(lambda x: (random(), x), data)
>   decorated.sort()
>   return map(lambda x: x[1], decorated)
>
> print shuffle(range(10))
>
> This prints
>
> [4, 2, 7, 8, 9, 3, 5, 1, 6, 0]
>
> . Seems kinda neat - I have no idea how the efficiency
> compares with the standard sort of "bubble shuffle"
> you were trying to use in your OP, but the point is
> that various off-by-one errors simply don't come up.
>
> (The same thing in extremely awful Python, in case
> you're mystified by map and lambda:
>
> from random import random
>
> def shuffle(data):
>   decorated = []
>   for x in data:
> decorated.append((random(), x))
>   decorated.sort()
>   res = []
>   for x in decorated:
> res.append(x[1])
>   return res
>
> .)

or in nicer python, but still when you're mysitified by map and lambda
(like me):

def shuffle(data):
decorated = [(random(), x) for x in data]
decorated.sort()
return [x[1] for x in decorated]

or shorter but possible less readable (and only in 2.4+):

def shuffle(data):
return [y[1] for y in sorted([(random(), x) for x in data])]

Iain

-- 
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


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: .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


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: 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: 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.

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: 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: 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: 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:
> >
> > 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: 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


"wxPython in Action" book

2006-01-24 Thread Iain King
New book on wxPython: http://www.manning.com/books/rappin

Release date of this month.  Does anyone know if it's out yet / has
anyone read it and has an opinion?

Iain

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


Re: wxPython Conventions

2006-02-01 Thread Iain King

Jared Russell wrote:

> To mess around with it, I decided to create a small app to check my
> Gmail.  I want something that will just sit in my system tray checking
> for new emails every ten minutes or so.

How do you gain access to the system tray?

Iain

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


Re: Create dict from two lists

2006-02-10 Thread Iain King

py wrote:
> Thanks, itertools.izip and just zip work great.  However, I should have
> mentioned this, is that I need to keep the new dictionary sorted.
>
> d = {1:'first', -5 : 'negative 5', 6:'six', 99:'ninety-nine',
> 3:'three'}
> keys = d.keys()
> keys.sort()
> vals = map(d.get, keys)
>
> At this point keys is sorted [-5, 1, 3, 6, 99] and vals is sorted
> ['negative 5', 'first', 'three', 'six', 'ninety-nine']
>
> Using zip does not create the dictionary sorted in this order.
> new_d = dict(zip(keys, vals))
>
> How can I use the two lists, keys and vals to create a dictionary such
> that the items keep their order?
>
> Thanks.

Short answer - you can't.  Dictionaries aren't sequential structures,
so they have no sorted form.  You can iterate through it in a sorted
manner however, as long as you keep your list of keys:

keys.sort()
for k in keys:
print d[k]

Iain

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


Re: Self-identifying functions and macro-ish behavior

2006-02-15 Thread Iain King

[EMAIL PROTECTED] wrote:
> Hi, I was wondering how I may get a python function to know what its
> name is without me having to write it manually?  For example:
>
> def func1():
> 
> print 'func1'
> return True
>
> def func2():
> 
> print 'func2'
> return True
>
> should be more like
> def func1():
> 
> print 
> return True
>
> def func2():
> 
> print 
> return True
>
> I imagine this means things like closures which I'm not familiar with
> (I'm not a CS person).  In this case, each function is part of a class,
> so I imagine I can take a dir() of the class if necessary.

Yeah, I think these are closures (though when I learnt CS we didn't get
taught them).  Try this:

def makeFunction(name):
def func():

print name
return True
return func

func1 = makeFunction('func1')
func2 = makeFunction('func2')

>
> This leads into my next related question, which is How do I get some
> sort of macro behavior so I don't have to write the same thing over and
> over again, but which is also not neatly rolled up into a function,
> such as combining the return statements with a printing of ?

I think I've answered this too?

Iain

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


looping over more than one list

2006-02-16 Thread Iain King
When I loop over one list I use:

for item in items:
print item

but often I want to loop through two lists at once, and I've been doing
this like I would in any other language - creating an index counter and
incrementing it.
For example, (completely arbitrary), I have two strings of the same
length, and I want to return a string which, at each character
position, has the letter closest to 'A' from each of the original
strings:

def lowest(s1,s2):
s = ""
for i in xrange(len(s1)):
s += lowerChar(s1[i],s2[i])
return s

this seems unpythonic, compared to something like:

def lowest(s1,s2):
s = ""
for c1,c2 in s1,s2:
s += lowerChar(c1,c2)
return s

this doesn't work - s1,s2 becomes a tuple.  Is there a way to do this
that I'm missing?  I don't see it in the docs.

This works:

def lowest(s1,s2):
s = ""
for c1,c2 in [x for x in zip(s1,s2)]:
s += lowerChar(c1,c2)
return s

but it's hardly any more elegant than using a loop counter, and I'm
guessing it's performance is a lot worse - I assume that the zip
operation is extra work?

Iain

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


Re: Python CGI not working in Firefox but does in IE

2006-02-22 Thread Iain King

Harlin Seritt wrote:
> I have this Python CGI script running:
>
> [CODE]
> print 'Content-type: text/plain\n'
>
> location = 'http://server1.com'
>
> page = '''
> 
> 
> 
> 
> 
> '''
>
> print page
> [/CODE]
>
> It works fine and redirects perfectly when using Internet Explorer but
> only shows this in a Firefox window:
>
> [OUTPUT]
> 
> 
> http://server1.com";>
> 
> 
> [/OUTPUT]
>
> Is there anything I can do to fix this?
>
> Also, is there a redirect command somewhere within Python CGI that can
> get this done instead as I would actually prefer to have the CGI code
> execute this rather than depend on the HTML to do it.
>
> Thanks,
>
> Harlin Seritt

this snippet works (from code I wrote to implement a shoutbox):

print '''




Please wait...

'''

I assume your version doesn't work because of the uppercase 'R'.

Iain

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


Re: Python CGI not working in Firefox but does in IE

2006-02-22 Thread Iain King

Iain King wrote:
> Harlin Seritt wrote:
> > I have this Python CGI script running:
> >
> > [CODE]
> > print 'Content-type: text/plain\n'
> >
> > location = 'http://server1.com'
> >
> > page = '''
> > 
> > 
> > 
> > 
> > 
> > '''
> >
> > print page
> > [/CODE]
> >
> > It works fine and redirects perfectly when using Internet Explorer but
> > only shows this in a Firefox window:
> >
> > [OUTPUT]
> > 
> > 
> > http://server1.com";>
> > 
> > 
> > [/OUTPUT]
> >
> > Is there anything I can do to fix this?
> >
> > Also, is there a redirect command somewhere within Python CGI that can
> > get this done instead as I would actually prefer to have the CGI code
> > execute this rather than depend on the HTML to do it.
> >
> > Thanks,
> >
> > Harlin Seritt
>
> this snippet works (from code I wrote to implement a shoutbox):
>
> print '''
> 
>   
> 
> 
> Please wait...
> 
> '''
>
> I assume your version doesn't work because of the uppercase 'R'.
> 
> Iain

There's a well known phrase about the word 'assume'...

Iain

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


Re: string stripping issues

2006-03-03 Thread Iain King

Ben Cartwright wrote:
> Ben Cartwright wrote:
> > orangeDinosaur wrote:
> > > I am encountering a behavior I can think of reason for.  Sometimes,
> > > when I use the .strip module for strings, it takes away more than what
> > > I've specified.  For example:
> > >
> > > >>> a = 'Hughes. John\r\n'
> > >
> > > >>> a.strip('')
> > >
> > > returns:
> > >
> > > 'ughes. John\r\n'
> > >
> > > However, if I take another string, for example:
> > >
> > > >>> b = 'Kim, Dong-Hyun\r\n'
> > >
> > > >>> b.strip('')
> > >
> > > returns:
> > >
> > > 'Kim, Dong-Hyun\r\n'
> > >
> > > I don't understand why in one case it eats up the 'H' but in the next
> > > case it leaves the 'K' alone.
> >
> >
> > That method... I do not think it means what you think it means.  The
> > argument to str.strip is a *set* of characters, e.g.:
> >
> >   >>> foo = 'abababaXabbaXababa'
> >   >>> foo.strip('ab')
> >   'XabbaX'
> >   >>> foo.strip('aabababaab') # no difference!
> >   'XabbaX'
> >
> > For more info, see the string method docs:
> > http://docs.python.org/lib/string-methods.html
> > To do what you're trying to do, try this:
> >
> >   >>> prefix = 'hello '
> >   >>> bar = 'hello world!'
> >   >>> if bar.startswith(prefix): bar = bar[:len(prefix)]
> >   ...
> >   >>> bar
> >   'world!'
>
>
> Apologies, that should be:
>>>> prefix = 'hello '
>>>> bar = 'hello world!'
>>>> if bar.startswith(prefix): bar = bar[len(prefix):]
>...
>>>> bar
>'world!'
>

or instead of:

 a.strip('')

use:

a.replace('','')

Iain

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


Re: object's list index

2006-03-03 Thread Iain King

William Meyer wrote:
> hi,
>
> I need to get the index of an object in a list. I know that no two objects
> in the list are the same, but objects might evaluate as equal. for example
>
> list = [obj1, obj2, obj3, obj4, obj5]
> for object in list:
> objectIndex = list.index(object)
> print objectIndex
>
> prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could 
> loop
> through the list a second time comparing id()'s
>
> for object in list:
> objectIndex = 0
> for i in list:
> if id(object) == id(i):
> break
> objectIndex += 1
> print objectIndex
>
> but that seems like a real ugly pain. Somewhere, someplace python is keeping
> track of the current index in list, does anyone know how to access it? Or have
> any other suggestions?

Um, one of us is being really really dense today :)  I hope it's not
me...
 what's wrong with:

i = 0
for object in list:
objectIndex = i
print objectIndex
i += 1

Iain

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


Re: object's list index

2006-03-03 Thread Iain King

Iain King wrote:
> William Meyer wrote:
> > hi,
> >
> > I need to get the index of an object in a list. I know that no two 
> > objects
> > in the list are the same, but objects might evaluate as equal. for example
> >
> > list = [obj1, obj2, obj3, obj4, obj5]
> > for object in list:
> > objectIndex = list.index(object)
> > print objectIndex
> >
> > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could 
> > loop
> > through the list a second time comparing id()'s
> >
> > for object in list:
> > objectIndex = 0
> > for i in list:
> > if id(object) == id(i):
> > break
> > objectIndex += 1
> > print objectIndex
> >
> > but that seems like a real ugly pain. Somewhere, someplace python is keeping
> > track of the current index in list, does anyone know how to access it? Or 
> > have
> > any other suggestions?
>
> Um, one of us is being really really dense today :)  I hope it's not
> me...
>  what's wrong with:
>
> i = 0
> for object in list:
> objectIndex = i
> print objectIndex
> i += 1
>
> Iain

Reading it again, I'm thinking it probably is me...

If you aren't looking them up sequentially then I think your second
example is the only way.  You can make it a little prettier by using
'object is i' rather than 'id(object) == id(i)'.
I think python only stores lists one way - i.e. each index maps to it's
value, but no backwards trace is kept from value to index.

Iain

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


Re: object's list index

2006-03-03 Thread Iain King

Iain King wrote:
> Iain King wrote:
> > William Meyer wrote:
> > > hi,
> > >
> > > I need to get the index of an object in a list. I know that no two 
> > > objects
> > > in the list are the same, but objects might evaluate as equal. for example
> > >
> > > list = [obj1, obj2, obj3, obj4, obj5]
> > > for object in list:
> > > objectIndex = list.index(object)
> > > print objectIndex
> > >
> > > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I 
> > > could loop
> > > through the list a second time comparing id()'s
> > >
> > > for object in list:
> > > objectIndex = 0
> > > for i in list:
> > > if id(object) == id(i):
> > > break
> > > objectIndex += 1
> > > print objectIndex
> > >
> > > but that seems like a real ugly pain. Somewhere, someplace python is 
> > > keeping
> > > track of the current index in list, does anyone know how to access it? Or 
> > > have
> > > any other suggestions?
> >
> > Um, one of us is being really really dense today :)  I hope it's not
> > me...
> >  what's wrong with:
> >
> > i = 0
> > for object in list:
> > objectIndex = i
> > print objectIndex
> > i += 1
> >
> > Iain
>
> Reading it again, I'm thinking it probably is me...
>
> If you aren't looking them up sequentially then I think your second
> example is the only way.  You can make it a little prettier by using
> 'object is i' rather than 'id(object) == id(i)'.
> I think python only stores lists one way - i.e. each index maps to it's
> value, but no backwards trace is kept from value to index.
>
> Iain

OTOH, if memory is not an issue, you can create a lookup yourself:

def createLookup(l):
d = {}
for index in xrange(len(l)):
objID = id(l[index])
d[objID] = index
return d

lookup = createLookup(list)
for i in list:
objectIndex = lookup[id(i)]
print objectIndex


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: 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: 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: 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(Foo().foo)  # with the obvious definition of Foo
> > > 
>
> > 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: threading, how to?

2006-04-21 Thread Iain King
akrapus wrote:
> Thanks for reply.
>
> So would it be implemented as follows:
>
> Func 1
> Func 2
> Func 3
>
> Thread for Func 1
> Thread for Func 2
> Thread for Func 3
>
> Cheers
>
> Stevan

Here's how I'm doing it, using the thread module (there's a higher
level class-based module: threading, but I'm more comfortable with the
simple one):

import thread, time

class ThreadDemo:
def __init__(self):
self.data = []
self.lock = thread.allocate_lock()
self.alive = False


def Start(self):
self.alive = True
thread.start_new_thread(self.Process, (None,))


def Stop(self):
self.alive = False


def Process(self, dummy=None):
while self.alive:
self.lock.acquire()
self.data.sort()
self.lock.release()
time.sleep(0.05)


def Add(self, value):
self.lock.acquire()
self.data.append(value)
self.lock.release()

>>> from ThreadDemo import ThreadDemo
>>> demo = ThreadDemo()
>>> demo.Start()
>>> demo.Add(1)
>>> demo.Add(5)
>>> demo.Add(2)
>>> demo.data
[1, 2, 5]
>>> demo.Add(3)
>>> demo.data
[1, 2, 3, 5]
>>> demo.Stop()
>>> demo.Add(4)
>>> demo.data
[1, 2, 3, 5, 4]

Use the lock whenever you are going to modify data which is shared
between more than one thread.  Using time.sleep stops the thread from
hogging CPU cycles.  You only need to sleep a few milliseconds.  The
thread will clean itself up as soon as it's function (in this case
Process) finishes.  The ugly (None,) tuple in the start_new_thread /
dummy=None Process parameter are because the start_new_thread function
demands a tuple of arguments, even when none are required.
see http://www.python.org/doc/current/lib/module-thread.html for more
info.

Iain

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


Re: what has python added to programming languages? (lets be esoteric, shall we ; )

2006-04-21 Thread Iain King

Wildemar Wildenburger wrote:
> Over the time I've seen lots of remarks about python that read like "a
> lot like lists in lisp" or "like the hashtable in java" or any other
> form of "like  in ".
>
> Are there any concepts that python has not borrowed, concepts that were
> not even inspired by other languages? I'm just interested if it is
> "merely" a best-of collection of language features or if there are
> actually inventions that have not - or hardly - existed in programming
> before python?
>
> wildemar

I find slice notation consistent and elegant - did it come form another
language?

Iain

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


Re: Counting elements in a list wildcard

2006-04-25 Thread Iain King

hawkesed wrote:
> If I have a list, say of names. And I want to count all the people
> named, say, Susie, but I don't care exactly how they spell it (ie,
> Susy, Susi, Susie all work.) how would I do this? Set up a regular
> expression inside the count? Is there a wildcard variable I can use?
> Here is the code for the non-fuzzy way:
> lstNames.count("Susie")
> Any ideas? Is this something you wouldn't expect count to do?
> Thanks y'all from a newbie.
> Ed

Dare I suggest using REs?  This looks like something they'de be good
for:

import re

def countMatches(names, namePattern):
  count = 0
  for name in names:
if namePattern.match(name):
  count += 1
  return count

susie = re.compile("Su(s|z)(i|ie|y)")

print countMatches(["John", "Suzy", "Peter", "Steven", "Susie",
"Susi"], susie)


some other patters:

iain = re.compile("(Ia(i)?n|Eoin)")
steven = re.compile("Ste(v|ph|f)(e|a)n")
john = re.compile("Jo(h)?n")


Iain

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


Re: Counting elements in a list wildcard

2006-04-25 Thread Iain King

John Machin wrote:
> On 25/04/2006 6:26 PM, Iain King wrote:
> > hawkesed wrote:
> >> If I have a list, say of names. And I want to count all the people
> >> named, say, Susie, but I don't care exactly how they spell it (ie,
> >> Susy, Susi, Susie all work.) how would I do this? Set up a regular
> >> expression inside the count? Is there a wildcard variable I can use?
> >> Here is the code for the non-fuzzy way:
> >> lstNames.count("Susie")
> >> Any ideas? Is this something you wouldn't expect count to do?
> >> Thanks y'all from a newbie.

snip

> > steven = re.compile("Ste(v|ph|f)(e|a)n")
>
> What about Steffan, Etienne, Esteban, István, ... ?
>

well, obviously these could be included:
"(Ste(v|ph|f)(e|a)n|Steffan|Etienne|Esteban)", but the OP never said he
wanted to translate anything into another language.  He just wanted to
catch variable spellings.

> > john = re.compile("Jo(h)?n")
> >
>
> IMHO, the amount of hand-crafting that goes into a *general-purpose*
> phonetic matching algorithm is already bordering on overkill. Your
> method using REs would not appear to scale well at all.

Iain

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


Re: Counting elements in a list wildcard

2006-04-26 Thread Iain King

Edward Elliott wrote:
> John Machin wrote:
> > On 25/04/2006 6:26 PM, Iain King wrote:
> >> iain = re.compile("(Ia(i)?n|Eoin)")
> >> steven = re.compile("Ste(v|ph|f)(e|a)n")
> >
> > IMHO, the amount of hand-crafting that goes into a *general-purpose*
> > phonetic matching algorithm is already bordering on overkill. Your
> > method using REs would not appear to scale well at all.
>
> Also compare the readability of regular expressions in this case to a simple
> list:
> ["Steven", "Stephen", "Stefan", "Stephan", ...]

Somehow I'm the advocate for REs here, which: erg. But you have some
mighty convenient elipses there...
compare:

steven = re.compile("Ste(v|ph|f|ff)(e|a)n")
steven = ["Steven", "Stephen", "Stefen", "Steffen", "Stevan",
"Stephan", "Stefan", "Steffan"]

I know which I'd rather type.  'Course, if you can use a ready-built
list of names...

Iain

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


wxpython warnings

2006-04-26 Thread Iain King
I have a wxpython program that displays TIF images.  Sometimes it will
encounter a tag the tiff loader cant handle.  Rather than silently
ignoring it, it pops up a window:

Python Warning
unknown field with tag blah blah

I don't want it to do this, but I can't work out how to turn it off.
Anyone know?

Iain

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


Re: wxpython warnings

2006-04-26 Thread Iain King

Michele Petrazzo wrote:
> Philippe Martin wrote:
> > I had a similar but simple problem (the file was missing) and had to
> > check by hand before calling wxPython.
> >
> > Can you check the tag by hand before calling wxPython ?
> >
> >
> > Philippe
> >
> >
>
> Hi,
> also I have the same problem with g3/g4 images. My solution was convert
> that image *before* to .png before... Very bad hack, but work.
> I think that is an internal wxWidgets message (warning), passed to the
> wxPython subsystem.
>

This is actually exactly what I did. (well, I converted to jpg, because
they're going to end up as jpg anyway).  

bah

Iain

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


pytiff for windows

2006-04-27 Thread Iain King
Does anyone have a link for a compiled-for-windows version of pytiff?
(or alternatively tell me how to get PIL to save a multipage tiff).

Iain

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


Re: returning none when it should be returning a list?

2006-05-02 Thread Iain King

John Machin wrote:
>
> # Doh! Looks like recursion not necessary. Google 'eliminate tail
> recursion' :-)
>

I did, and found this:
http://www.biglist.com/lists/dssslist/archives/199907/msg00389.html
which explains that the Scheme compiler optimises (obvious) tail
recursion into iterative code.  I'm wondering if the python compiler
does the same?

Iain

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


Web framework comparison video

2006-05-08 Thread Iain King
http://compoundthinking.com/blog/index.php/2006/03/10/framework-comparison-video/

Thought this might be interesting to y'all.  (I can't watch it 'cos I'm
at work, so any comments about it would be appreciated :)

Iain

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


Re: Tabs versus Spaces in Source Code

2006-05-16 Thread Iain King
Oh God,  I agree with Xah Lee.  Someone take me out behind the chemical
sheds...

Iain


Xah Lee wrote:
> Tabs versus Spaces in Source Code
>
> Xah Lee, 2006-05-13
>
> In coding a computer program, there's often the choices of tabs or
> spaces for code indentation. There is a large amount of confusion about
> which is better. It has become what's known as “religious war” —
> a heated fight over trivia. In this essay, i like to explain what is
> the situation behind it, and which is proper.
>
> Simply put, tabs is proper, and spaces are improper. Why? This may seem
> ridiculously simple given the de facto ball of confusion: the semantics
> of tabs is what indenting is about, while, using spaces to align code
> is a hack.
>
> Now, tech geekers may object this simple conclusion because they itch
> to drivel about different editors and so on. The alleged problem
> created by tabs as seen by the industry coders are caused by two
> things: (1) tech geeker's sloppiness and lack of critical thinking
> which lead them to not understanding the semantic purposes of tab and
> space characters. (2) Due to the first reason, they have created and
> propagated a massive none-understanding and mis-use, to the degree that
> many tools (e.g. vi) does not deal with tabs well and using spaces to
> align code has become widely practiced, so that in the end spaces seem
> to be actually better by popularity and seeming simplicity.
>
> In short, this is a phenomenon of misunderstanding begetting a snowball
> of misunderstanding, such that it created a cultural milieu to embrace
> this malpractice and kick what is true or proper. Situations like this
> happens a lot in unix. For one non-unix example, is the file name's
> suffix known as “extension”, where the code of file's type became
> part of the file name. (e.g. “.txt”, “.html”, “.jpg”).
> Another well-known example is HTML practices in the industry, where
> badly designed tags from corporation's competitive greed, and stupid
> coding and misunderstanding by coders and their tools are so
> wide-spread such that they force the correct way to the side by the
> eventual standardization caused by sheer quantity of inproper but set
> practice.
>
> Now, tech geekers may still object, that using tabs requires the
> editors to set their positions, and plain files don't carry that
> information. This is a good question, and the solution is to advance
> the sciences such that your source code in some way embed such
> information. This would be progress. However, this is never thought of
> because the “unix philosophies” already conditioned people to hack
> and be shallow. In this case, many will simply use the character
> intended to separate words for the purpose of indentation or alignment,
> and spread the practice with militant drivels.
>
> Now, given the already messed up situation of the tabs vs spaces by the
> unixers and unix brain-washing of the coders in the industry... Which
> should we use today? I do not have a good proposition, other than just
> use whichever that works for you but put more critical thinking into
> things to prevent mishaps like this.
>
> Tabs vs Spaces can be thought of as parameters vs hard-coded values, or
> HTML vs ascii format, or XML/CSS vs HTML 4, or structural vs visual, or
> semantic vs format. In these, it is always easy to convert from the
> former to the latter, but near impossible from the latter to the
> former. And, that is because the former encodes information that is
> lost in the latter. If we look at the issue of tabs vs spaces, indeed,
> it is easy to convert tabs to spaces in a source code, but more
> difficult to convert from spaces to tabs. Because, tabs as indentation
> actually contains the semantic information about indentation. With
> spaces, this critical information is lost in space.
>
> This issue is intimately related to another issue in source code:
> soft-wrapped lines versus physical, hard-wrapped lines by EOL (end of
> line character). This issue has far more consequences than tabs vs
> spaces, and the unixer's unthinking has made far-reaching damages in
> the computing industry. Due to unix's EOL ways of thinking, it has
> created languages based on EOL (just about ALL languages except the
> Lisp family and Mathematica) and tools based on EOL (cvs, diff, grep,
> and basically every tool in unix), thoughts based on EOL (software
> value estimation by counting EOL, hard-coded email quoting system by
> “>” prefix, and silent line-truncations in many unix tools), such
> that any progress or development towards a “algorithmic code unit”
> concept or language syntaxes are suppressed. I have not written a full
> account on this issue, but i'v

Re: Tabs versus Spaces in Source Code

2006-05-17 Thread Iain King

Ant wrote:
> I think Duncan has hit the nail on the head here really. I totally
> agree that conceptually using tabs for indentation is better than using
> spaces. Pragmatically though, you can't tell in an editor where spaces
> are used and where tabs are used.
>

Um, I don't follow this.  If you can't tell the editor where
tabs/spaces are used, who does?

> Perhaps if editors colored the background of tab characters differently
> from spaces this wouldn't be a problem,

Some editors do.

> or if Python was more
> restrictive and did not actually allow a mix of tabs and spaces for
> indentation there would be no problem - the compiler could throw out an
> exception for mixed characters.

python -tt

> In reality, neither of these are likely
> to be implemented any time soon!

um

Iain

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


Re: noob import question

2006-05-19 Thread Iain King

Brian Blazer wrote:
> OK, I have a very simple class here:
>
> class Student:
>  """Defines the student class"""
>
>  def __init__(self, lName, fName, mi):
>  self.lName = lName
>  self.fName = fName
>  self.mi = mi
>
> Then I have a small script that I am using as a test:
>
> from Student import *
>
> s1 = Student("Brian", "Smith", "N")
>
> print s1.lName
>
> This works as expected.  However, if I change the import statement to:
> import Student
>
> I get an error:
> TypeError: 'module' object is not callable
>
> I have tried to look up what is going on, but I have not found
> anything.  Would it be possible for someone to take a minute and give
> an explanation?
>

I take it you are getting the error on the line
s1 = Student("Brian", "Smith", "N")

This is because when you use 'import Student', it loads the file
Student.py into a namespace called Student (unlike the 'from'
statement, which loads it into the main namespace).  to access anything
from your Student module, prepend with Student. , so your line becomes:
s1 = Student.Student("Brian", "Smith", "N")

Iain
> Thank you - your time is appreciated.
> 
> Brian
> [EMAIL PROTECTED]

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


Re: John Bokma harassment

2006-05-25 Thread Iain Chalmers
In article <[EMAIL PROTECTED]>,
 Tim X <[EMAIL PROTECTED]> wrote:

> I also seem to remember a page on his website from a couple of years
> back in which he admits enjoying trolling and starting flame wars -
> but I can't find it now, so maybe I'm mistaken. 

http://web.archive.org/web/20050204172641/www.xahlee.org/Netiquette_dir/troll.html

big

-- 
"Everything you love, everything meaningful with depth and history, 
all passionate authentic experiences will be appropriated, mishandled, 
watered down, cheapened, repackaged, marketed and sold to the people 
you hate."  Mr Jalopy quoting Hooptyrides (on jalopyjunktown.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Trying to get FreeImagePy to work.

2006-05-26 Thread Iain King
I've installed ctypes and FreeImagePy.  When I do this:

>>> import FreeImagePy
>>> f = FreeImagePy.Image()

I get:
find
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python\Lib\site-packages\FreeImagePy\FreeImagePy.py", line
1952, in _
_init__
super(Image, self).__init__(libraryName)
  File "C:\Python\Lib\site-packages\FreeImagePy\FreeImagePy.py", line
376, in __
init__
self.__lib = self.__internlLibrary(libraryName)
  File "C:\Python\Lib\site-packages\FreeImagePy\FreeImagePy.py", line
313, in __
init__
self.lib = C.windll.find(libraryName)
  File "ctypes\__init__.py", line 370, in __getattr__
dll = self._dlltype(name)
  File "ctypes\__init__.py", line 296, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Errno 126] The specified module could not be found

I put a 'print self._name' in the ctypes __init__ file, just before
line 296 - it's printing out the 'find' just before the error.
So, in what specific way have  I screwed up the install?

Iain

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


Re: Trying to get FreeImagePy to work.

2006-05-26 Thread Iain King

Michele Petrazzo wrote:
> Iain King wrote:
> > I've installed ctypes and FreeImagePy.  When I do this:
> >
> >>>> import FreeImagePy f = FreeImagePy.Image()
> >
> > I put a 'print self._name' in the ctypes __init__ file, just before
> > line 296 - it's printing out the 'find' just before the error. So, in
> > what specific way have  I screwed up the install?
>
> What's your ctypes version? Is 0.9.9.6? If yes, can you download the
> last svn version, that solve that problem (I hope) and add some
> functions? If you can't I'll release a new version (1.2.5)
> 

I downloaded and installed 0.9.9.3, and it now works.  Thanks!

Iain

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


Sine Wave Curve Fit Question

2008-01-30 Thread Iain Mackay
Python Folks

I'm a newbie to Python and am looking for a library / function that can help 
me fit a 1D data vector to a sine  wave. I know the frequency of the wave, 
so its really only phase and amplitude information  I need.

 I can't find anything in the most widely known libraries (they seem to be 
strong on polynomial fitting, but not, apparently, on trig functions) and I 
wondered if any one here had recommendations?

 Something that implemented IEEE 1057 , or similar, would be perfect.


TIA
Iain


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


Re: Sine Wave Curve Fit Question

2008-01-30 Thread Iain Mackay
Thanks folks - I'll have  a think about both of these options.


-- 
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


  1   2   >