Re: Counting Threads

2005-10-28 Thread David Poundall
Sorry Denis - but could you give me an example.  I can't for the life
of me see how the syntax for that would go.

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


Re: a Haskell a Day

2005-10-28 Thread Wil Hadden

"steve" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
>
> Stupid newbi  wants $1 if you spend more  than 30 minutes on his webshite,
> looking at it you would be hard pressed to spend 30 seconds.
> Anyway at least we know where to find him.
>
>

Broadcasting his antics in Las Vegas is funny though.

Not from the text mind, more the ramifications is he were to say, quote his
website in a job interview, for example.


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


Re: Jpg

2005-10-28 Thread Juho Schultz
Tuvas wrote:
> I am building a GUI interface at the moment, and would like to have
> support for displaying a jpg file, and a FITS file if possible. Is
> there any way to do this? My interface has been written in Tkinter at
> the moment, especially because of it's great portability, I wouldn't
> have to install the other interface software on every computer that I
> use (At the moment it is 3, and will signifigantly increase). I'd
> prefer to only use built-in functions, but if it can't be done, I'm
> willing to look for something else. Is there any way I can do this?
> Thanks!
> 

For FITS file reading, an alternative to pCFITSIO is PyFITS 
(http://www.stsci.edu/resources/software_hardware/pyfits).
I guess both need numarray...

gifImage = Tkinter.PhotoImage(file="file.gif")
ima = yourCanvas.create_image(xpos,ypos,image=gifImage)

is the quickest way to display gifs. My version of Tkinter (1.177)
does not directly support jpg, but with PIL that should be possible.

Ugly but quick solution (for Linux): produce gifs from FITS/jpg
files with os.system("convert") and feed them to Tkinter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MSH (shell)

2005-10-28 Thread Paddy
Thanks, I'm enjoying reading the article.
So far I noticed how their select functionality is similar to our
comprehensions, but can also take a statement block. ( no wars please
;-).

I liked the tabular output format for lists of similar items, with the
automatic headings being displayed, e.g:
msh> get-childitem | select name, extension, {
  if ($_.LastWriteTime.year -lt 2004) { "old file" }
  else { "new file" }
}

Name   Extension  if
($_.LastWriteTime.year...
   -
-
examples.txt   .txt   new file
output1.html   .html  old file
output2.html   .html  old file
somefile.doc   .doc   new file


I tend to avoid xml but their xml example below was succinct and
relatively painless. Do python libraries allow a similarly readable
version of their:

  msh>   $x = [xml]"Albert"
msh> $x.zoo.animal

kindname

monkey  Albert

Their "Extract the title and author elements from every item in the
rss.channel tag" example is also impressive.

Looks like an innovative new shell.

- Paddy.

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


Spambayes modifications with web services

2005-10-28 Thread benmorganpowell
In the last few months many personal website owners (such as myself)
have found that spammers have been using their domain names to
masquerade as valid users to send spam, normally in the form of:

[EMAIL PROTECTED]

This new tactic has an annoying problem, which is that the bounced
emails end up back with the postmaster at the innocent persons domain.
This is normally the first time that the domain owner realises that
there is a problem.

I am one of those people and currently have nearly 3 thousand bounces
in my catch all POP3 box.

Solutions I can see to this are one of two things:

1) Delete the email as it arrives and ignore it. Realise that the
domain name might end up being blacklisted as a spammer's domain and be
done with it, or

2) Fight back! All of the bounced emails contain at least one URI to a
spammer website, in a effort to sell "Cheap Meds" or "Faked Rolexes" or
similar. The format is usually something like this:

http://www.sickmate.info/?a2fb9e415e74beS9cdee919d78Sa6a7d

The query part of the URI I believe provides the reference between the
email address and the visit. Hence if you visit the website with this
link, your email address is saved in a database as one that is a)
valid, and b) dumb enough to visit the website.

The spammers rely on the fact that some people will visit this website
and buy from them. In fact, Q.E.D., some people must buy from these
websites via spam, otherwise the spammers would have given up a long
time ago*.

So, as a web programmer and someone who specialises in getting good
results on Google, I realised that I could simply post every spammer
website on a Google optimized page, which if searched for on Google
would return something like:

"WARNING: DO NOT BUY FROM THIS WEBSITE. THE SPAMMER IS A RUSSIAN MAFIA
CROOK WHO WILL STEAL YOUR MONEY."

...Or something equally obvious along those lines. In this way we
attack the websites that are the link between the spam and the money.
The real necessity therefore is to:

a) Process the received bounced messages quickly and list them on the
website without delay.
b) Prevent the spammer using the domain

The answer to (b) I cannot find. I thought SPF might help, but it is
not a panacea. The answer to (a) I need help with!

So, I'm on Windows XP. I use Outlook 2002 and I already have the
excellent (and FREE) SpamBayes Outlook add-in** that blocks spam and
loves ham. Spambayes is open source and as such I can modify the source
code, recompile it and install it afresh. However, the problem is that
I'm not a python programmer, and I'm not sure where to start. This is
what I want to do, so if anyone would like to direct me, I'd be
grateful:

1) Add a menu option to the SpamBayes add-in - "Post Spam Site to Web
Service". I'm guessing I can add a new line to the addin.py such as
below, but how do I sink the event?

self._AddControl(popup,
constants.msoControlButton,
ButtonEvent, (PostSpamSite, self.manager,),
Caption="Post Spam Site to Web Service",
Enabled=True,
Visible=True,
Tag = "SpamBayesCommand.PostSpam")

2) Add a configuration setting, so that the web service location can be
set. I'm guessing this is in config.py. Pointers welcome.

4) Add a function to extract all links in a block of text. I have
written a good one of these for .NET, but I'm not sure if, or how it
would work in Python:

string hrefPattern =
@"(?(?:(?http(?:s?)|ftp)(?:\:\/\/))"
+ @"(?[^/\r\n\:]+)?"
+ @"(?\:\d+)?"
+ @"(?[^\?#]*)?"
+ @"(?\?\w*)?"
+ @"(?\#\w*)?)";

// Regular Expression
Regex hrefRegex = new Regex(hrefPattern, RegexOptions.Singleline |
RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);

Any help with this welcome. Do I need a specific Python regex library
or can I use the .NET regex library in Python?

4) Connect to web service using SOAP and consume that service. Service
will provide:

a) Authorise (username, password) - returns access
b) Submit (domain) - returns success or failure

Can I use SOAPpy for this? Can anyone give me any examples or point me
in the right direction?

5) Provide another option in the add in to "Scan folder and Post Spam
Sites to Web Service", in the same manner as "Filter messages" works
now. Can I use filter.py as a model to work from?

Summary
=
I am not a Python programmer per se but have no problem with getting my
hands dirty. I have already got the basics of this working as a
Windows.Forms application, but running both that and Outlook together
is daft. The Spambayes project already does the hard bit in classifying
the spam, so it makes sense to hang off the back of it.

Has anyone else had similar problems as me with these "phantom" email
addresses being using by spammers and would like to work with me on
this? Would anyone in the Spambayes team like to have a go at this, or
point me in the right direction? Has anyone had a go at hac

Re: Microsoft Hatred FAQ

2005-10-28 Thread Eike Preuss
David Schwartz wrote:
> "Eike Preuss" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
> 
>>>Right, except that's utterly absurd. If every vendor takes their tiny
>>>cut of the 95%, a huge cut of the 5% is starting to look *REALLY* good.
> 
> 
>>Sure, that would be true if the market would be / would have been really
>>global. In practice if you have a shop you have a limited 'region of
>>influence'. Optimally you are the only shop in this region that sells
>>the stuff, or perhaps there are a few shops that compete with you. Lets
>>say in your region are two shops competing with you, and you must decide
>>wether to sell product A (95%) or B (5%), but you may not sell both.
>>Decision 1: Sell A, share the 95% of the local market with two -> about
>>32% of the local market for all of you, if all perform equally good
>>Decision 2: Sell B -> you get the 5% of the market, the others 47% each
>>
>>This calculation is probably still a very bad approximation of the
>>truth, but things are definitely not as easy as you state them.
> 
> 
> It depends upon how different the products are and how easy it is to 
> shop out of your local market. If the products are equally good and 
> reasonably interchangeable and it's hard to shop out of your local market, 
> then you're right. The more the smaller product is better than the larger 
> product, the less interchangeable they are, and the easier it is to shop out 
> of your local market, the more wrong you are.
> 
> How often do you hear, "I'd like to use Linux, but I just can't get 
> ahold of it"?
> 
> And how many people do you hear saying, "I'd like to use Linux, but I'm 
> not willing to shell out the bucks to buy it since I already bought Windows 
> with my computer".
> 
> On the other hand, where you might be right is in the possibility that 
> Microsoft's lock on the market prevented other companies from making 
> operating systems at all. That is, that had Microsoft used different 
> policies, other companies would have introduced operating systems to compete 
> with Microsoft, and we'd all have better operating systems for it. If 
> Microsoft's conduct was legal, this argument establishes that the conduct 
> was necessary.
> 
> DS
> 
> 

Yes, as I said: It is much more complicated than your beautiful argument
'well, then, taking a huge portion of 5% would be much more preferable
anyway' suggests.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml.dom.minidom - parseString - How to avoid ExpatError?

2005-10-28 Thread Paul Dale

Hi Greg,

Not really an answer to your question but I've found 4Suite ( 
http://4suite.org/index.xhtml ) quite useful for my XML work and the 
articles linked to from there authored by Uche Ogbuji to be quite 
informative.

Best,

Paul

Gregory Piñero wrote:

> Thanks, John.  That was all very helpful.  It looks like one option 
> for me would be to put cdata[ around my text with all the weird 
> characters.  Otherwise running it through on of the SAX utilities 
> before parsing might work.
>
> I wonder if the sax utilities would give me a performance hit.  I have 
> 6000 xml files to parse at 100KB each.
>
> -Greg
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-28 Thread Lasse Vågsæther Karlsen
David Schwartz wrote:
> Lasse Vågsæther Karlsen wrote:
> 
> 
>>David Schwartz wrote:
> 
> 
>>>Burger King won't let you sell Whoppers or buy their burger
>>>patties wholesale no matter what you want to call your store unless
>>>you take the whole franchise deal. It's an all-or-nothing package.
>>>With very few limits, companies do get to choose how their products
>>>are branded, marketed, and sold.
> 
> 
>>Yes, and that's not what Microsoft has ever done. There have always
>>been lots of shops selling Microsoft merchandise without being a
>>Microsoft franchise in the sense Burger King shops are.
> 
> 
> Right, Microsoft imposed a lesser restriction. They allowed you to sell 
> competing products, but charged you a fee.
> 
> 
>>That's why I still say your comparison is a bad one.
> 
> 
> It shows that Microsoft's purportedly draconian restrictions are much 
> less than restrictions that people don't even bat an eye at.
> 
> DS
> 
> 

Ok, let me just make my opinion very clear on this and then I'll just 
leave this thread altogether.

I think you are comparing apples and oranges so whatever conclusion you 
manage to draw from that is in my eyes invalid. It doesn't matter, in my 
opinion, if you managed to conclude that Microsoft was the saints 
themselves because, in my opinion, your reasoning is not valid. I'm not 
saying one way or the other, I'm just picking at your reasoning.

To me it sounds like concluding that the prices of RAM will drop because 
the swallows are flying high this fall.

But enough, I'll just leave it.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestion for (re)try statement

2005-10-28 Thread Lasse Vågsæther Karlsen
Sori Schwimmer wrote:
> Hi,
> 
> I think that would be useful to have an improved
> version of the "try" statement, as follows:
> 
> try(retrys=0,timeout=0):

>   sleep(timeout)


At the very least, "timeout" is the wrong wording, "delay" would be more 
appropriate. A timeout is usually associated with starting a task and 
waiting for it to complete, and continuing if it fails to complete in a 
given timeframe, typically also aborting the task at the same time (ie. 
executing a database query, connecting to a server, waiting for an 
event/lock, etc.).

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Tk

2005-10-28 Thread Shi Mu
When I run the following code,
script kept running and I have to force it to stop.
Could you check the code to give suggestions how to improve it?
Thanks a lot!

from Tkinter import *
from Tkinter import _cnfmerge

class Dialog(Widget):
   def __init__(self, master=None, cnf={}, **kw):
   cnf = _cnfmerge((cnf, kw))
   self.widgetName = '__dialog__'
   Widget._setup(self, master, cnf)
   self.num = self.tk.getint(
   apply(self.tk.call,
 ('tk_dialog', self._w,
  cnf['title'], cnf['text'],
  cnf['bitmap'], cnf['default'])
 + cnf['strings']))
   try: Widget.destroy(self)
   except TclError: pass
   def destroy(self): pass

if __name__ == '__main__':

   q = Button(None, {'text': 'How are you',
 Pack: {}})
   b1 = Listbox()
   b1.pack()

   c1 = Checkbutton(text="Check")
   c1.pack()

   q.mainloop()

from Tkinter import *
root =Tk()
menu=Menu(root)
root.config(menu=menu)
filemenu=Menu(menu)
menu.add_cascade(label="Test", menu=filemenu)
filemenu.add_command(label="Just Try")
filemenu.add_separator()
mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating/altering the OpenOffice spredsheet docs

2005-10-28 Thread yepp
Andy Leszczynski  wrote:

> Any idea how to do that the way ActiveX would be used on M$?
> 

Fortunately, NO.

You know http://udk.openoffice.org/python/python-bridge.html ??

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


Re: Would there be support for a more general cmp/__cmp__

2005-10-28 Thread Antoon Pardon
Op 2005-10-26, Ron Adam schreef <[EMAIL PROTECTED]>:
>
> Adding complexity to cmp may not break code, but it could probably slow 
> down sorting in general.  So I would think what ever improvements or 
> alternatives needs to be careful not to slow down existing sorting cases.

As a result of Bengt's post, I rewrote my test program, this is the
program now.

from random import shuffle

from time import time

class UnequalValues(Exception):
  pass

__metaclass__ = type

class cla:
  def __init__(self, i):
self.value = int(i)

  def __cmp__(self, other):
return self.value - other.value

class clb:
  def __init__(self, i):
self.value = int(i)

  def __lt__(self, other):
return self.value < other.value

class clc:
  def __init__(self, i):
self.value = int(i)

  def __gt__(self, other):
return self.value > other.value

class cld:
  def __init__(self, i):
self.value = int(i)

  def __comp__(self, other):
return self.value - other.value

  def __lt__(self, other):
return self.__comp__(other) < 0

class cle:
  def __init__(self, i):
self.value = int(i)

  def __comp__(self, other):
return self.value - other.value

  def __lt__(self, other):
try:
  return self.__comp__(other) < 0
except UnequalValues:
  return False

def test(lng, rep):

  for cl in cla, clb, clc, cld, cle:
total = 0.0
for _ in xrange(rep):
  lst = [cl(i) for i in xrange(lng)]
  shuffle(lst)
  start = time()
  lst.sort()
  stop = time()
  total += stop - start
  for i in xrange(1,rep):
assert lst[i - 1] < lst[i]
print "%s: %d repeats, %d long, %9.6f secs" % (cl, rep, lng, total)

test(1000,1000)

---

These are the results.

: 1000 repeats, 1000 long, 10.061425 secs
: 1000 repeats, 1000 long,  9.544035 secs
: 1000 repeats, 1000 long, 10.450864 secs
: 1000 repeats, 1000 long, 15.566061 secs
: 1000 repeats, 1000 long, 15.776443 secs

Results on a longer sequence were:

: 1000 repeats, 1 long, 146.722443 secs
: 1000 repeats, 1 long, 139.480863 secs
: 1000 repeats, 1 long, 152.623424 secs
: 1000 repeats, 1 long, 224.630926 secs
: 1000 repeats, 1 long, 228.663825 secs

The most interesting result of this test is the difference between
cld and cle. IMO this difference is an indication of the cost
that my idea would have on sorting, should it be implemented.
That would be around 2%. I think that is bearable. Especially
since this were very simple routines. The moment the comparison
calculation become heavier, the relative contribution of the
try: except will diminuish.

If you are concerned about sorting times, I think you should
be more concerned about Guido's idea of doing away with __cmp__.
Sure __lt__ is faster. But in a number of cases writing __cmp__
is of the same complexity as writing __lt__. So if you then
need a __lt__, __le__, __eq__, __ne__, __gt__ and __ge__ it
would be a lot easier to write a __cmp__ and have all rich
comparisons methods call this instead of duplicating the code
about six times. So you would be more or less forced to write
your class as class cld or cle. This would have a bigger
impact on sorting times than my suggestion.

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


Re: how to associate files with application

2005-10-28 Thread Lasse Vågsæther Karlsen
Ashok wrote:
> hi,
> i want to know how to make a specific type of file open in an
> application i developed in python when the user clicks on the file.(in
> windows) for eg. a .txt file when clicked opens in notepad, a .doc file
> when clicked opens in MS-word. In the same way i want to make a .xyz
> file open in the application i developed when clicked.
> thanks in advance for any advice.
> 

You need to add several registry keys to do this, here's a short version 
of what you need to do:

Example assumes you want to:

1. associate .ext with C:\Program Files\MyProgram\prog.exe
2. pass on any extra arguments to prog.exe (ie. test.ext 1 2 3 would 
send 1 2 3 as well to prog.exe)
3. associate the icon of prog.exe to any file with a .ext extension

Ok, here's what you need to do:

1. Under HKEY_CLASSES_ROOT, add a key (folder) with the name .ext
2. Open that key, and set the (Default) value to MyProgramExtendedFile 
(this name is something you choose yourself and should be a "identifier" 
that identifies the file type. If your program supports several types of 
files, make up unique identifiers for each.)
3. Under HKEY_CLASSES_ROOT, add another key, this time with the same 
name you made up in 2. above, ie MyProgramExtendedFile
4. Open that key, and set the (Default) value to a textual description 
of the type of file. This is what will show up in explorer in the file 
type column. If you leave this empty, the description will be .EXT File
5. Inside MyProgramExtendedFile, add another key with the name shell 
(lower-case is typical, can probably be Shell or whatever)
6. Inside shell, create another key with the name open
7. Inside open, create another key with the name command
8. Inside command, Set the (Default) value to:
"C:\Program Files\MyProgram\prog.exe" "%1" %*

Note that you need the quotes as specified above, exactly like written

9. Go back to MyProgramExtendedFile and create another key with the name 
DefaultIcon
10. Inside DefaultIcon, set (Default) value to:
 "C:\Program Files\MyProgram\prog.exe", 0

 This will pick the first icon in prog.exe resource to show for the 
files. Use 1 for second, etc.

There are also other commands you can add. If you want to be able to 
right-click on the file and select a menu item to process the file in a 
specific way, for instance by passing along specific parameters to 
prog.exe, you can add more keys than "open" on the level open is 
created. The (Default) value inside the key is then the text of the menu 
item.

To find examples, just find a file extension in Windows that behaves the 
way you want your own to behave and look through HKEY_CLASSES_ROOT\.ext 
to find the details you want.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to replace all None values with the string "Null" in a dictionary

2005-10-28 Thread bruno at modulix
dcrespo wrote:
> Hi all,
> 
> How can I replace all None values with the string 'Null' in a
> dictionary?
> 
> For example:
> convert this:
> a = {'item1': 45, 'item2': None}
> 
> into this:
> a = {'item1': 45, 'item2': 'Null'}
> 

I think it would be time for you to read the Fine Manual...

for key in a:
  if a[key] is None:
a[key] = 'Null'


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


Re: db.DB_CREATE|db.DB_INIT_MPOOL|db.DB_THREAD|db.DB_INIT_CDB

2005-10-28 Thread Neville C. Dempsey
On Thu, 2005-10-27 at 12:30 -0400, Jean-Paul Calderone wrote:
> On Fri, 28 Oct 2005 00:17:54 +0800, "Neville C. Dempsey"  at 3ttechnology.com> wrote:
> >import bsddb # twiceopen.py

> >Maybe the solution needs one of:
> >  db.DB_CREATE|db.DB_INIT_MPOOL|db.DB_THREAD|db.DB_INIT_CDB

> Except I don't think btopen() supports half these operations.  You
> really want to use bsddb.db.DBEnv and bsddb.DB.  Or a library that
> wraps them more sensibly:
>  
> .
>   
> You probably don't want everything there, but the DatabaseEnvironment
> class (and supporting code) should be useful.

Hey thanks I saw a couple of other posting hinting at what your
"DB_INIT_TXN DB_CREATE DB_JOINENV" road map above  I posted because
I was wondering if there was an easier path... Your posting indicates
that you have already walked this path.

  I was getting errors like: 
o bsddb._db.DBPageNotFoundError: (-30988, 'DB_PAGE_NOTFOUND: Requested page not 
found')
o KeyError: 'xx'
o _bsddb.DBNotFoundError: (-30990, 'DB_NOTFOUND: No matching key/data pair 
found')

   For now the obvious work around is to only open the file once, and
with only one running program at a time.

  This gives me a chance to check out the alternatives.
> 
> Jp
Cheer
NevilleDNZ

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


problem with gnuplot in XP

2005-10-28 Thread Titi Anggono
Hi all,

I made 2 arrays, which are i and uzuy (both are
float). And I want to plot the graph between those
arrays.
 
I followed from the manual

==

from Gnuplot import Gnuplot, Data

g=Gnuplot()
results=Data(i,uzuy)

g.plot(results) 
=

here I got the message


Traceback (most recent call last):
  File "", line 1, in -toplevel-
g.plot(i,uzuy)
  File
"C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py",
line 274, in plot
self.refresh()
  File
"C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py",
line 215, in refresh
self(self.plotcmd + ' ' + string.join(plotcmds, ',
'))
  File
"C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py",
line 199, in __call__
self.gnuplot(s)
  File
"C:\Python23\Lib\site-packages\Gnuplot\gp_win32.py",
line 125, in __call__
self.write(s + '\n')
IOError: [Errno 22] Invalid argument
==

FYI, I use python2.3 and Gnuplot-py-1.7. Any problems
with my code ??

Thanks





__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


How to translate python into C

2005-10-28 Thread Johnny Lee
Hi,
   First, I want to know whether the python interpreter translate the
code directly into machine code, or translate it into C then into
machine code?
   Second, if the codes are translated directly into machine codes, how
can I translate the codes into C COMPLETELY the same? if the codes are
translated first into C, where can I get the C source?
   Thanks for your help.

Regards, 
Johnny

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


Re: XML Tree Discovery (script, tool, __?)

2005-10-28 Thread George Sakkis
"[EMAIL PROTECTED]" wrote:

> Hi all,
>
> Finally diving into XML programmatically.  Does anyone have a best
> practice recommendation for programmatically discovering the structure
> of an arbitrary XML document via Python?
>
> It seems like it is a common wheel I'd be re-inventing.
>
> Thanks and cheers


I was looking for something similar (XML to DTD inference) but I didn't
find anything related in python. Trang
(http://www.thaiopensource.com/relaxng/trang-manual.html#introduction),
on the other hand seems impressive after a few non-trivial tests. It
would be neat to have it ported in python, at least the inference part.

George

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


Re: Would there be support for a more general cmp/__cmp__

2005-10-28 Thread Antoon Pardon
Op 2005-10-28, Antoon Pardon schreef <[EMAIL PROTECTED]>:
> Op 2005-10-26, Ron Adam schreef <[EMAIL PROTECTED]>:
>>
>
> These are the results.
>
>: 1000 repeats, 1000 long, 10.061425 secs
>: 1000 repeats, 1000 long,  9.544035 secs
>: 1000 repeats, 1000 long, 10.450864 secs
>: 1000 repeats, 1000 long, 15.566061 secs
>: 1000 repeats, 1000 long, 15.776443 secs
>
> Results on a longer sequence were:
>
>: 1000 repeats, 1 long, 146.722443 secs
>: 1000 repeats, 1 long, 139.480863 secs
>: 1000 repeats, 1 long, 152.623424 secs
>: 1000 repeats, 1 long, 224.630926 secs
>: 1000 repeats, 1 long, 228.663825 secs
>
> The most interesting result of this test is the difference between
> cld and cle. IMO this difference is an indication of the cost
> that my idea would have on sorting, should it be implemented.
> That would be around 2%. I think that is bearable. Especially
> since this were very simple routines. The moment the comparison
> calculation become heavier, the relative contribution of the
> try: except will diminuish.
>
> If you are concerned about sorting times, I think you should
> be more concerned about Guido's idea of doing away with __cmp__.
> Sure __lt__ is faster. But in a number of cases writing __cmp__
> is of the same complexity as writing __lt__. So if you then
> need a __lt__, __le__, __eq__, __ne__, __gt__ and __ge__ it
> would be a lot easier to write a __cmp__ and have all rich
> comparisons methods call this instead of duplicating the code
> about six times. So you would be more or less forced to write
> your class as class cld or cle. This would have a bigger
> impact on sorting times than my suggestion.

And as an afterthought: Adding __slots__ increased the
sorting speed between 7.5 and 9.0%

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


Re: Spambayes modifications with web services

2005-10-28 Thread Neil Hodgson
benmorganpowell:

> So, as a web programmer and someone who specialises in getting good
> results on Google, I realised that I could simply post every spammer
> website on a Google optimized page, which if searched for on Google
> would return something like:
> 
> "WARNING: DO NOT BUY FROM THIS WEBSITE. THE SPAMMER IS A RUSSIAN MAFIA
> CROOK WHO WILL STEAL YOUR MONEY."

Spam may also contain the addresses of non-spamming businesses, 
sometimes in an effort to increase the apparent legitimacy of the spam. 
Attacking all of the web sites in spam will cost these businesses while 
having little effect on spammers who use temporary domains which may be 
cheaply abandoned. It also gives another attack vector for those 
criminals that attempt to extort money from web sites by threatening to 
damage them.

If you want to take action against spammers, first think through all 
the potential consequences of your actions.

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


Re: How to translate python into C

2005-10-28 Thread Szabolcs Nagy
python creates bytecode (like java classes)


you cannot translate python directly to c or machine code, but there
are some projects you probably want to look into


Pypy is a python implemetation in python and it can be used to
translate a python scrip to c or llvm code. (large project, work in
progress)
http://codespeak.net/pypy/dist/pypy/doc/news.html


Shedskin translates python code to c++ (not all language features
supported)
http://shed-skin.blogspot.com/


Pyrex is a nice language where you can use python and c like code and
it translates into c code. (it is useful for creating fast python
extension modules or a python wrapper around an existing c library)
http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/

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


Re: Spambayes modifications with web services

2005-10-28 Thread Lasse Vågsæther Karlsen
[EMAIL PROTECTED] wrote:
> In the last few months many personal website owners (such as myself)
> have found that spammers have been using their domain names to
> masquerade as valid users to send spam, normally in the form of:

> So, as a web programmer and someone who specialises in getting good
> results on Google, I realised that I could simply post every spammer
> website on a Google optimized page, which if searched for on Google
> would return something like:
> 
> "WARNING: DO NOT BUY FROM THIS WEBSITE. THE SPAMMER IS A RUSSIAN MAFIA
> CROOK WHO WILL STEAL YOUR MONEY."


So basically a DoS attack could now be simply performed by crafting a 
spam message and adding the url to your target and then sending it out 
to as many users you can think of ? (DoS not in the typical form, but 
the effect would be just as real, deny them of legitimate customers)

Nice plan sherlock.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to translate python into C

2005-10-28 Thread Johnny Lee

Szabolcs Nagy wrote:
> python creates bytecode (like java classes)
>
>
> you cannot translate python directly to c or machine code, but there
> are some projects you probably want to look into
>
>
> Pypy is a python implemetation in python and it can be used to
> translate a python scrip to c or llvm code. (large project, work in
> progress)
> http://codespeak.net/pypy/dist/pypy/doc/news.html
>
>
> Shedskin translates python code to c++ (not all language features
> supported)
> http://shed-skin.blogspot.com/
>
>
> Pyrex is a nice language where you can use python and c like code and
> it translates into c code. (it is useful for creating fast python
> extension modules or a python wrapper around an existing c library)
> http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/

Thanks, Szabolcs. In fact, I want to reproduce a crush on cygwin. I
used a session of python code to produce the crush, and want to
translate it into C and reproduce it. Is the tools provided by you help
with these issues? Of coz, I'll try them first. :)

Regards, 
Johnny

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


Re: How to translate python into C

2005-10-28 Thread Benjamin Niemann
Johnny Lee wrote:

> Hi,
>First, I want to know whether the python interpreter translate the
> code directly into machine code, or translate it into C then into
> machine code?

Neither this nor that. The interpreter first compiles the code into python
'byte code' - something similar to machine code, but not it is not targeted
at the CPU of your system, but for a portable virtual machine. This virtual
machine will then execute the byte code, just like a CPU would execute
machine code.

>Second, if the codes are translated directly into machine codes, how
> can I translate the codes into C COMPLETELY the same? if the codes are
> translated first into C, where can I get the C source?

You may have a look at PyPy. I do not know what it exactly can do, but this
might be interesting for you:
http://codespeak.net/pypy/dist/pypy/doc/faq.html#how-do-i-compile-my-own-programs

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-28 Thread imagespaul
http://www.idpz.net/wolfgang/

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


Re: How to translate python into C

2005-10-28 Thread Johnny Lee
Thanks for your tips Niemann:)

Regards, 
Johnny

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


Scanning a file

2005-10-28 Thread pinkfloydhomer
I want to scan a file byte for byte for occurences of the the four byte
pattern 0x0100. I've tried with this:

# start
import sys

numChars = 0
startCode = 0
count = 0

inputFile = sys.stdin

while True:
ch = inputFile.read(1)
numChars += 1

if len(ch) < 1: break

startCode = ((startCode << 8) & 0x) | (ord(ch))
if numChars < 4: continue

if startCode == 0x0100:
count = count + 1

print count
# end

But it is very slow. What is the fastest way to do this? Using some
native call? Using a buffer? Using whatever?

/David

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


Re: Scanning a file

2005-10-28 Thread Gerhard Häring
[EMAIL PROTECTED] wrote:
> I want to scan a file byte for byte [...]
> while True:
> ch = inputFile.read(1)
> [...] But it is very slow. What is the fastest way to do this? Using some
> native call? Using a buffer? Using whatever?

Read in blocks, not byte for byte. I had good experiences with block 
sizes like 4096 or 8192.

-- Gerhard

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


Re: Microsoft Hatred FAQ

2005-10-28 Thread JavaByExample_at_KickJava_com
> Part of their behavior really escape me.  The whole thing about
> browser wars confuses me.  Web browsers represent a zero billion
> dollar a year market.  Why would you risk anything to own it?

Wonder why MSN.com is one of the most visited sites, I speculate that
it is largely because it is the default home page of IE browser.

And now Firefox makes Google.com its default home page.

That is one area where they can make lots of money off billion's eye
balls years.

David
=
http://KickJava.com - Java Examples, Source Codes, Free Online Books,
News and Articles

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


Re: Scanning a file

2005-10-28 Thread pinkfloydhomer
Okay, how do I do this?

Also, if you look at the code, I build a 32-bit unsigned integer from
the bytes I read. And the 32-bit pattern I am looking for can start on
_any_ byte boundary in the file. It would be nice if I could somehow
just scan for that pattern explicitly, without having to build a 32-bit
integer first. If I could tell python "scan this file for the bytes 0,
0, 1, 0 in succession. How many 0, 0, 1, 0 did you find?"

/David

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


Re: Scanning a file

2005-10-28 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I want to scan a file byte for byte for occurences of the the four byte
> pattern 0x0100. I've tried with this:

use re.search or string.find.  The simplest way is just read the whole
file into memory first.  If the file is too big, you have to read it in
chunks and include some hair to notice if the four byte pattern straddles
two adjoining chunks.
-- 
http://mail.python.org/mailman/listinfo/python-list


x-plat gui development question Mac OS X

2005-10-28 Thread Georg Christmann
Hello everybody,

I have recently started tinkering about with Python.

If there are any Macintosh-based Python developers reading this 
newsgroup I would like to ask them one Macintosh-specific question:

If you want to write GUI scripts on the Mac, say with Tkinter, you need 
to invoke "pythonw" instead of "python" and use "#! /usr/bin/pythonw" 
for a shebang line in your saved scripts.
Of course, although a tiny problem, it is still less than welcome for 
cross-platform development.

As one obvious workaround, would it cause any problems if I would link 
"/usr/bin/python/" to "/usr/bin/pythonw" instead of "/usr/bin/python2.3" 
(in other words I would always be using "pythonw", even for non-GUI 
scripts) ?
So far I can't tell any difference in the interactive mode - invoking 
"pythonw" for non-GUI work seems to work just fine.
I am not sure though if there are any system processes, say during 
boot-up, that depend on "python" pointing to the original location, or 
if there could be problems with more complex code than "Hello world".

Any insights welcome

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


Re: How to replace all None values with the string "Null" in a dictionary

2005-10-28 Thread dcrespo
> I think it would be time for you to read the Fine Manual...

hi, thanks for your answer... I really did it the same way you
suggested, but I forgot to tell you that I wanted to get a better way
for doing it.

By the way, knowing your wisdom, what do I have to install to get the
following code work (Win XP, Python 2.4.2)

-
from OpenSSL import SSL
import config

KEY_FILE = config.SSL_KEY_FILE
CERT_FILE = config.SSL_CERT_FILE


I've been looking for OpenSSL for python. I found pyOpenSSL, but it
requires the OpenSSL library, which I only found on
http://www.openssl.org/, but don't know how to install.

Other thing is the "config" module... I'm lost. Someone knows? :-S

My main purpose is to enable XML-RPC SERVER over an SSL connection.

Thanks

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


Re: Microsoft Hatred FAQ

2005-10-28 Thread Shmuel (Seymour J.) Metz
In <[EMAIL PROTECTED]>, on 10/25/2005
   at 09:56 AM, [EMAIL PROTECTED] said:

>Yes, I know, they can do whatever they want, it's not a crime,

Actually, it is a crime and they've been convicted.

-- 
Shmuel (Seymour J.) Metz, SysProg and JOAT  

Unsolicited bulk E-mail subject to legal action.  I reserve the
right to publicly post or ridicule any abusive E-mail.  Reply to
domain Patriot dot net user shmuel+news to contact me.  Do not
reply to [EMAIL PROTECTED]

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


xml-rpc - adodb - None type - DateTime type

2005-10-28 Thread dcrespo
Hi to all,

I have functions defined in an xml-rpc server. Some functions query to
a Postgres database (using adodb) and return its recordset. So, if some
xml-rpc client runs the mentioned function, it will retrieve the
recordset. The problem is that if a retrieved field has the Null value
or the Date value (DateTime Database format), then, the retrieved
recordset in the python program will have the 'None' value or the
DateTime type object value.

xml-rpc isn't able to accept any type of value, so I have to solve it.

I can replace all None values with the string 'Null', there's no
problem, but I can't detect the DateTime type object I retrieve from
the database.

I have something like this:
def xmlrpc_function():
conn = adodb.NewADOConnection('postgres')
conn.Connect(host,user,password,database)
rs = conn.Exec("select * from table")
result = []
i = 0
while not rs.EOF:
row = rs.GetRowAssoc(False)
for key, value in row.items():
if value==None:
row[key]='Null'
result.append(row)
i = i + 1
rs.MoveNext()
rs.Close()

print result
return result

The problem here is that if row[key] == , then I don't know what to do for detect it and make the
appropriate change to string.

Console output:
[{'name': 'Null', 'date': }]

If you consult the python manual, you'll see that there's no 'DateTime'
type object, so I can't do something like:

if value==DateTimeType:
...

I only need to know which type of data is a field for make the change
according to what can I pass through the xml-rpc.

Any help?

Thanks

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


Re: How to replace all None values with the string "Null" in a dictionary

2005-10-28 Thread dcrespo
Thanks... I did it right that way, but asked it without telling how I
did it just to see what are the occurences of others. I thing there's
no better/faster solution.

Many thanks

Daniel

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


Re: Scanning a file

2005-10-28 Thread [EMAIL PROTECTED]
I'm now down to:

f = open("filename", "rb")
s = f.read()
sub = "\x00\x00\x01\x00"
count = s.count(sub)
print count

Which is quite fast. The only problems is that the file might be huge.
I really have no need for reading the entire file into a string as I am
doing here. All I want is to count occurences this substring. Can I
somehow count occurences in a file without reading it into a string
first?

/David

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


Re: Scanning a file

2005-10-28 Thread Björn Lindström
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> f = open("filename", "rb")
> s = f.read()
> sub = "\x00\x00\x01\x00"
> count = s.count(sub)
> print count

That's a lot of lines. This is a bit off topic, but I just can't stand
unnecessary local variables.

print file("filename", "rb").read().count("\x00\x00\x01\x00")

-- 
Björn Lindström <[EMAIL PROTECTED]>
Student of computational linguistics, Uppsala University, Sweden
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Scanning a file

2005-10-28 Thread Jorge Godoy
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Which is quite fast. The only problems is that the file might be huge.
> I really have no need for reading the entire file into a string as I am
> doing here. All I want is to count occurences this substring. Can I
> somehow count occurences in a file without reading it into a string
> first?

How about iterating through the file?  You can read it line by line, two lines
at a time.  Pseudocode follows:

line1 = read_line
while line2 = read_line:
  line_to_check = ''.join([line1, line2])
  check_for_desired_string
  line1 = line2

With that you always have two lines in the buffer and you can check all of
them for your desired string, no matter what the size of the file is.


Be seeing you,
-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning a file

2005-10-28 Thread Bernhard Herzog
Jorge Godoy <[EMAIL PROTECTED]> writes:

> How about iterating through the file?  You can read it line by line, two lines
> at a time.  Pseudocode follows:
>
> line1 = read_line
> while line2 = read_line:
>   line_to_check = ''.join([line1, line2])
>   check_for_desired_string
>   line1 = line2
>
> With that you always have two lines in the buffer and you can check all of
> them for your desired string, no matter what the size of the file is.

This will fail if the string to search for is e.g. "\n\n\n\n" and it
actually occcurs in the file.

   Bernhard

-- 
Intevation GmbH http://intevation.de/
Skencil   http://skencil.org/
Thuban  http://thuban.intevation.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to associate files with application

2005-10-28 Thread Colin J. Williams
Lasse Vågsæther Karlsen wrote:
> Ashok wrote:
> 
>> hi,
>> i want to know how to make a specific type of file open in an
>> application i developed in python when the user clicks on the file.(in
>> windows) for eg. a .txt file when clicked opens in notepad, a .doc file
>> when clicked opens in MS-word. In the same way i want to make a .xyz
>> file open in the application i developed when clicked.
>> thanks in advance for any advice.
>>
> 
> You need to add several registry keys to do this, here's a short version 
> of what you need to do:
> 
> Example assumes you want to:
> 
> 1. associate .ext with C:\Program Files\MyProgram\prog.exe
> 2. pass on any extra arguments to prog.exe (ie. test.ext 1 2 3 would 
> send 1 2 3 as well to prog.exe)
> 3. associate the icon of prog.exe to any file with a .ext extension
> 
> Ok, here's what you need to do:
> 
> 1. Under HKEY_CLASSES_ROOT, add a key (folder) with the name .ext
> 2. Open that key, and set the (Default) value to MyProgramExtendedFile 
> (this name is something you choose yourself and should be a "identifier" 
> that identifies the file type. If your program supports several types of 
> files, make up unique identifiers for each.)
> 3. Under HKEY_CLASSES_ROOT, add another key, this time with the same 
> name you made up in 2. above, ie MyProgramExtendedFile
> 4. Open that key, and set the (Default) value to a textual description 
> of the type of file. This is what will show up in explorer in the file 
> type column. If you leave this empty, the description will be .EXT File
> 5. Inside MyProgramExtendedFile, add another key with the name shell 
> (lower-case is typical, can probably be Shell or whatever)
> 6. Inside shell, create another key with the name open
> 7. Inside open, create another key with the name command
> 8. Inside command, Set the (Default) value to:
>"C:\Program Files\MyProgram\prog.exe" "%1" %*
> 
>Note that you need the quotes as specified above, exactly like written
> 
> 9. Go back to MyProgramExtendedFile and create another key with the name 
> DefaultIcon
> 10. Inside DefaultIcon, set (Default) value to:
> "C:\Program Files\MyProgram\prog.exe", 0
> 
> This will pick the first icon in prog.exe resource to show for the 
> files. Use 1 for second, etc.
> 
> There are also other commands you can add. If you want to be able to 
> right-click on the file and select a menu item to process the file in a 
> specific way, for instance by passing along specific parameters to 
> prog.exe, you can add more keys than "open" on the level open is 
> created. The (Default) value inside the key is then the text of the menu 
> item.
> 
> To find examples, just find a file extension in Windows that behaves the 
> way you want your own to behave and look through HKEY_CLASSES_ROOT\.ext 
> to find the details you want.
> 
I'm no Windows expert but I think that, using Windows Explorer, one can, 
with a right mouse click, select "Open With".

You can then choose the appropriate executable.  I believe that, if you 
had set the "Always open with this program" box, then the registry is 
automatically updated.

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


Re: Scanning a file

2005-10-28 Thread [EMAIL PROTECTED]
First of all, this isn't a text file, it is a binary file. Secondly,
substrings can overlap. In the sequence 0010010 the substring 0010
occurs twice.

/David

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


Typing tutor help script needed, please

2005-10-28 Thread Throw

G'day everyone!

I would like to design typing tutor exercises for Afrikaans (and other
languages possibly).  This is for a GPL project.  For this, I need a
script that can extract words from a long list of words, based on which
letters those words contain, and write then write output to a file.
Does anyone know of an existing script for this, or can anyone write me
one, please?

Preferably I must be able to extract words which contain only certain
letters (they need not contain all of those letters, but they may not
contain any other letters).  It would be nice if I can also extract
words which do not contain certain letters.

Any help will be greatly appreciated.  I'm on a Windows 2000 machine
with Perl, Python, Tcl/Tk and Java.

Thanks!
Samuel (throw aka voetleuce aka leuce)

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


Re: Scanning a file

2005-10-28 Thread Andrew McCarthy
On 2005-10-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I'm now down to:
>
> f = open("filename", "rb")
> s = f.read()
> sub = "\x00\x00\x01\x00"
> count = s.count(sub)
> print count
>
> Which is quite fast. The only problems is that the file might be huge.
> I really have no need for reading the entire file into a string as I am
> doing here. All I want is to count occurences this substring. Can I
> somehow count occurences in a file without reading it into a string
> first?

Yes - use memory mapping (the mmap module). An mmap object is like a
cross between a file and a string, but the data is only read into RAM
when, and for as long as, necessary. An mmap object doesn't have a
count() method, but you can just use find() in a while loop instead.

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


OEM character set issue

2005-10-28 Thread Ladv�nszky K�roly
On my hungarian Win2k, some of the accented characters of the file names
appear incorrectly when Python is driven from the command line. However,
they
appear okay when the same script is running within an IDE. The same problem
holds in the case of text files edited by GUI editors. Is there any solution
in the Python arsenal?

Thanks for any help,

Károly


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

Re: Scanning a file

2005-10-28 Thread Jeremy Sanders
Gerhard Häring wrote:

> [EMAIL PROTECTED] wrote:
>> I want to scan a file byte for byte [...]
>> while True:
>> ch = inputFile.read(1)
>> [...] But it is very slow. What is the fastest way to do this? Using some
>> native call? Using a buffer? Using whatever?
> 
> Read in blocks, not byte for byte. I had good experiences with block
> sizes like 4096 or 8192.

It's difficult to handle overlaps. The four byte sequence may occur at the
end of one block and beginning of the next. You'd need to check for these
special cases.

Jeremy

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


Re: Suggestion for (re)try statement

2005-10-28 Thread Rocco Moretti
Sori Schwimmer wrote:
> Hi,
> 
> I think that would be useful to have an improved
> version of the "try" statement, as follows:
> 
> try(retrys=0,timeout=0):
>   # things to try
> except:
>   # what to do if failed
> 
> and having the following semantic:
> 
> for i in range(retrys):
>   try:
> # things to try
>   except:
> if i < retrys:
>   i += 1
>   sleep(timeout)
> else:
>   # what to do if failed
>   else:
> break

The gold standard for language syntax changes is "compelling use cases" 
- if introduced, how often will the construct be used? Is there a python 
program out there (preferably in the standard library) which would be 
*markedly* improved by the change? What is so repugnant about the 
equivalent, currently valid way of writing it? -- Hypothetical and 
theoretical arguments don't carry much weight in the Python community 
("Practicality beats purity" and all that.)

And remember - your goal isn't ultimately to convince me or someother 
person on comp.lang.python, it's to convince Guido.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would there be support for a more general cmp/__cmp__

2005-10-28 Thread Ron Adam


Antoon Pardon wrote:
> Op 2005-10-26, Ron Adam schreef <[EMAIL PROTECTED]>:
> 
>>Adding complexity to cmp may not break code, but it could probably slow 
>>down sorting in general.  So I would think what ever improvements or 
>>alternatives needs to be careful not to slow down existing sorting cases.
> 
> As a result of Bengt's post, I rewrote my test program, this is the
> program now.

...

> These are the results.
> 
> : 1000 repeats, 1000 long, 10.061425 secs
> : 1000 repeats, 1000 long,  9.544035 secs
> : 1000 repeats, 1000 long, 10.450864 secs
> : 1000 repeats, 1000 long, 15.566061 secs
> : 1000 repeats, 1000 long, 15.776443 secs
> 
> Results on a longer sequence were:
> 
> : 1000 repeats, 1 long, 146.722443 secs
> : 1000 repeats, 1 long, 139.480863 secs
> : 1000 repeats, 1 long, 152.623424 secs
> : 1000 repeats, 1 long, 224.630926 secs
> : 1000 repeats, 1 long, 228.663825 secs
> 
> The most interesting result of this test is the difference between
> cld and cle. IMO this difference is an indication of the cost
> that my idea would have on sorting, should it be implemented.
> That would be around 2%. I think that is bearable. Especially
> since this were very simple routines. The moment the comparison
> calculation become heavier, the relative contribution of the
> try: except will diminuish.


class cle:
   def __init__(self, i):
 self.value = int(i)

   def __comp__(self, other):
 return self.value - other.value

   def __lt__(self, other):
 try:
   return self.__comp__(other) < 0
 except UnequalValues:
   return False


This would only work with numeric types. I believe that cmp is closer to 
the following.

 return ( self.value < other.value and -1
  or self.value > self.value and 1
  or 0 )

I don't think it effects the speed a great deal however.


> If you are concerned about sorting times, I think you should
> be more concerned about Guido's idea of doing away with __cmp__.
> Sure __lt__ is faster. But in a number of cases writing __cmp__
> is of the same complexity as writing __lt__. So if you then
> need a __lt__, __le__, __eq__, __ne__, __gt__ and __ge__ it
> would be a lot easier to write a __cmp__ and have all rich
> comparisons methods call this instead of duplicating the code
> about six times. So you would be more or less forced to write
> your class as class cld or cle. This would have a bigger
> impact on sorting times than my suggestion.

I haven't heard he was removing __cmp__, but I would think the sort or 
sorted functions would just use the available comparisons methods or 
equivalent C code for base types.  So I expect it would only matter if 
you need a custom or modified sort.

Although It is a thought that these cases could be improved by making 
the sort value available to the underlying C sort function.  Something 
on the order of:

 __sortvalue__ == self.value.

Cheers,
Ron





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


Re: Suggestion for (re)try statement

2005-10-28 Thread Grant Edwards
On 2005-10-27, Sori Schwimmer <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I think that would be useful to have an improved
> version of the "try" statement, as follows:
>
> try(retrys=0,timeout=0):
>   # things to try
> except:
>   # what to do if failed
>
> and having the following semantic:
>
> for i in range(retrys):
>   try:
> # things to try
>   except:
> if i < retrys:
>   i += 1
>   sleep(timeout)
> else:
>   # what to do if failed
>   else:
> break

The "i += 1" line is almost certainly wrong.

> Of course, "break" may be the last statement in the
> "try" branch, and "try"'s "else" may be ommited
> completely.

And that's pretty much exactly how I usually write it:

for i in range(retries):
   try:
   whatever
   break
   except retryableExceptionList:
   sleep(delay)

> Can't think of a syntax to keep it look like a statement
> rather than a function.
>
> Opinions?

I don't see what's wrong with the for loop construct.
You can add an else: clause to the for loop to detect the case
where you ran out of retries:

for i in range(retries):
   try:
   whatever
   break
   except retryableExceptionList:
   sleep(delay)
else:
   whatelse

> Is it worth for a PEP?

I don't think you can come up with a syntax that is really that
much better than the for loop, but give it a go if you like.

-- 
Grant Edwards   grante Yow!  My BIOLOGICAL ALARM
  at   CLOCK just went off... It
   visi.comhas noiseless DOZE FUNCTION
   and full kitchen!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to translate python into C

2005-10-28 Thread Szabolcs Nagy
python script crashed and you want to debug it?

if no trace back provided with the line number where the exception
raised, then the crash caused by an extension module (most likely
written in C), i don't know howto debug it, but at least you can find
the place where the crash occures by adding lots of print statements
with debug information.

i don't think compiling to c would make it easier.


there are python debuggers but i've never used one (these can only
debug python scripts not the binary extension modules).

pdb builtin module:
http://docs.python.org/lib/module-pdb.html

nice debugger with gui:
http://www.digitalpeers.com/pythondebugger/

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


Re: Would there be support for a more general cmp/__cmp__

2005-10-28 Thread Christopher Subich
Antoon Pardon wrote:
> If you are concerned about sorting times, I think you should
> be more concerned about Guido's idea of doing away with __cmp__.
> Sure __lt__ is faster. But in a number of cases writing __cmp__
> is of the same complexity as writing __lt__. So if you then
> need a __lt__, __le__, __eq__, __ne__, __gt__ and __ge__ it
> would be a lot easier to write a __cmp__ and have all rich
> comparisons methods call this instead of duplicating the code
> about six times. So you would be more or less forced to write
> your class as class cld or cle. This would have a bigger
> impact on sorting times than my suggestion.

Honestly, I don't really mind the idea of __cmp__ going away; for 
classes that behave Normally with respect to a single __cmp__ value, 
it's easily possible to write a CompareMixin that defines __lt__, 
__gt__, etc. for suitable __cmp__ values.

Much like DictMixin is part of the standard library.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-28 Thread Terry Hancock
Okay, I admit I'm wasting time answering this stupid thread, but
what the hey, what's usenet without a flame war now and then. ;-)

Into the fray ...

On Thursday 27 October 2005 05:17 pm, David Schwartz wrote:
> No. I have never received a dime from Microsoft, either directly or 
> indirectly. I am one of those people who believes that conduct that's 
> perfectly legal, moral and ethical before you can be said to have a monopoly 
> does not suddenly become immoral or unethical the day you acquire 51% of 
> what someone calls a market. I am not the only person with this view.

Yeah, and if you thought the world was flat or only 6000 years
old, you wouldn't be the only person with that view either. You'd
still be wrong. ;-)

This is an example of an established legal principle. Consider:

   If someone gets into a fight and someone gets injured, the court's
   determination will be entirely different depending on whether the
   person is untrained or has a blackbelt or other martial arts training.

   In the same vein, the exact same behavior will get very different
   treatment depending on whether there was "no harm done" or if
   one of the participants in the brawl died.

The *effect* of a monopolist's anti-competitive actions ARE a consideration
under law. We permit behavior from people who do not have effective control
of a marketplace that we do NOT permit from those who do.

We are not a "winner take all society".

You are perfectly free to dislike this fact about the American economy,
and you are welcome to move to some other country where they love
monopolism, anarchism, and corporate hegemony.  Except I think
America is the closest you're going to get to that, actually.
Tough luck there.

Meanwhile, the majority of people in this country are of
the opinion that this is a reasonable degree of economic
moderation.  So, get used to it.

Besides, no one ever argued that anti-competitive behavior
was ethically or morally acceptable even when it *is* legal.
You are the only one I've seen make that claim.  We only
assert however, that such behavior is *illegal* when the
perpetrator has monopoly power over the marketplace. This
is reasonable, because we may rely on market forces to
remove non-monopolists who try these tactics. The anti-trust
laws are there to protect us from a *failure* of the market
economy, which is what a monopoly is. Whether it is legal or
illegal is irrelevant -- capitalism has *failed* when a single
competitor beats all other competition and controls the marketplace,
because the market is then no longer free. We can respond either
through anti-trust laws, in an attempt to restore a capitalist
free market; or we can nationalize the company and put it under
taxpayer control (the latter solution is more popular in Europe,
but as a proponent of capitalism myself, I prefer the anti-trust
solution).  Its nonsensical to talk about free market rules in
a monopoly situation, because in that situation there IS NO
free market -- only a market controlled by the monopolist. Just
because the monopolist isn't a government doesn't make it any
better than a communist centrally controlled economy. Except
of course, that at *least* a government monopoly has a basis
*in principle* for serving the needs of society, which you
quite rightly argue that a corporation needn't have.

It might be nice to live in a fantasy dreamworld where
capitalism never fails, but the reality is that without
controlled boundary conditions, market failure is pretty
much inevitable.  That's why governments set boundary
conditions on the marketplace through legal regulation.

Too much regulation chokes the economy and makes massive
inefficiencies, but too little is just as bad.

Capitalist free markets *work* because it is an (interesting
and non-intuitive) fact that *many selfish people* are
collectively more efficient and fair that *one representative
power*. But *one selfish power* is far worse than either --
and that's what we call a "monopoly".

You are *somewhat* justified to question the choice of
market segmentation that makes Microsoft a monopoly, except
that 1) it IS a natural division in terms of customers, outlets,
advertising channels, and distribution, 2) it IS the way Microsoft
itself divides its services, 3) judged by people affected instead
of dollars exchanged, it would still be a monopoly overall even
if you included servers and other types of computers, and
4) hairsplitting or not it was that courts job to determine that
division, and they have ruled (end of story).  You may feel that
that was a discretionary decision, but it remains a fact that it
WAS at their discretion, not yours.

I don't really expect you to absorb this information, because
you are so obviously opposed to facing this reality, but
I also think it's dangerous to let extremists go unchallenged,
lest they be believed to lack opposition.

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.a

Opaque documentation

2005-10-28 Thread egbert
Once in a while you come acros aline of documentation
that you have to, or that invites you to, read it again.
This is what I found in PyGTK:

The set_screen method sets the 'screen" property to 
the gtk.gdk.Screen specified by screen. The "screen" property
contains the screen that the window is displayed on.

The screen on the second line, before the period, is in italics, 
if that helps.

I like these texts. Prose should not disclose its secrets at once.
If you have other examples, please let us know.
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Re: Microsoft Hatred FAQ

2005-10-28 Thread David Blomstrom
"Everytime someone compares MS's behavior with some
less controversial criminal behavior, you act like
they
accused MS of holding people up at gunpoint."

Screwing literally millions of consumers and taxpayers
and holding entire schools hostage is far worse than
holding up an individual at gunpoint. The name
Microsoft is virtually synonymous with crime, even if
many people are too stupid to recognize it as crime -
or the courts are too corrupt or inefficient to
convict Bill Gates for many of his crimes.




__ 
Start your day with Yahoo! - Make it your home page! 
http://www.yahoo.com/r/hs
-- 
http://mail.python.org/mailman/listinfo/python-list


Is bytecode machine (in)dependent?

2005-10-28 Thread Robert McLay
I'm trying to understand bytecodes generated on different machines.
I understand that the bytecodes can change between version.  But since
I'm told that .pyc files are version dependent but not machine
dependent, I'm wondering why the bytecodes are machine dependent.

my friend and I created this simple example to explore the problem.
The example code is:

   #!/usr/bin/env python
   #
   import sys, os

   def main():
 x = 1.234
 print x

   if ( __name__ == '__main__'): 
 main()


Using sib.py from Vendorid 1.0 generates different bytecodes under linux
and sgi.  At its core sib.py is using:

# Compile the code using prefix and marshall it.
compiled_code = compile(source_code, prefix, 'exec')
marshalled_code = marshal.dumps(compiled_code)

to get the bytecodes.

So why are the byte codes different?  Is it that the intel-linux is
little endian and the SGI is big endian and the numerical constant
(1.234) is stored different depending on the endian-ness?


This was generated under intel-linux using python 2.4.2




 
/*==*/
 /* Frozen main script for test 
 */
 /* Generated from test.py  
 */
 /* This is generated code; Do not modify it!   
 */
 
/*--*/
 unsigned char M___main__[] =
 {
 99,0,0,0,0,0,0,0,0,2,0,0,0,64,0,0,
 0,115,55,0,0,0,100,0,0,107,0,0,90,0,0,100,
 0,0,107,1,0,90,1,0,100,1,0,132,0,0,90,2,
 0,101,3,0,100,2,0,106,2,0,111,11,0,1,101,2,
 0,131,0,0,1,110,1,0,1,100,0,0,83,40,3,0,
 0,0,78,99,0,0,0,0,1,0,0,0,1,0,0,0,
 67,0,0,0,115,15,0,0,0,100,1,0,125,0,0,124,
 0,0,71,72,100,0,0,83,40,2,0,0,0,78,102,5,
 49,46,50,51,52,40,1,0,0,0,116,1,0,0,0,120,
 40,1,0,0,0,82,0,0,0,0,40,0,0,0,0,40,
 0,0,0,0,116,23,0,0,0,47,104,111,109,101,47,118, /* This 
line */
 112,97,114,114,47,115,105,98,47,116,101,115,116,46,112,121,
 116,4,0,0,0,109,97,105,110,5,0,0,0,115,4,0,
 0,0,0,1,6,1,116,8,0,0,0,95,95,109,97,105,
 110,95,95,40,4,0,0,0,116,3,0,0,0,115,121,115,
 116,2,0,0,0,111,115,82,2,0,0,0,116,8,0,0,
 0,95,95,110,97,109,101,95,95,40,3,0,0,0,82,4,
 0,0,0,82,2,0,0,0,82,5,0,0,0,40,0,0,
 0,0,40,0,0,0,0,82,1,0,0,0,116,1,0,0,
 0,63,3,0,0,0,115,6,0,0,0,18,2,9,4,13,
 1,
 };  x

 And under SGI (python 2.4.2) it created :


/*==*/
/* Frozen main script for test  
*/
/* Generated from test.py   
*/
/* This is generated code; Do not modify it!
*/

/*--*/
unsigned char M___main__[] =
{
99,0,0,0,0,0,0,0,0,2,0,0,0,64,0,0,
0,115,55,0,0,0,100,0,0,107,0,0,90,0,0,100,
0,0,107,1,0,90,1,0,100,1,0,132,0,0,90,2,
0,101,3,0,100,2,0,106,2,0,111,11,0,1,101,2,
0,131,0,0,1,110,1,0,1,100,0,0,83,40,3,0,
0,0,78,99,0,0,0,0,1,0,0,0,1,0,0,0,
67,0,0,0,115,15,0,0,0,100,1,0,125,0,0,124,
0,0,71,72,100,0,0,83,40,2,0,0,0,78,102,5,
49,46,50,51,52,40,1,0,0,0,116,1,0,0,0,120,
40,1,0,0,0,82,0,0,0,0,40,0,0,0,0,40,
0,0,0,0,116,23,0,0,0,47,87,111,114,107,47,118,  /* This 
line */
112,97,114,114,47,115,105,98,47,116,101,115,116,46,112,121,
116,4,0,0,0,109,97,105,110,5,0,0,0,115,4,0,
0,0,0,1,6,1,116,8,0,0,0,95,95,109,97,105,
110,95,95,40,4,0,0,0,116,3,0,0,0,115,121,115,
116,2,0,0,0,111,115,82,2,0,0,0,116,8,0,0,
0,95,95,110,97,109,101,95,95,40,3,0,0,0,82,4,
0,0,0,82,2,0,0,0,82,5,0,0,0,40,0,0,
0,0,40,0,0,0,0,82,1,0,0,0,116,1,0,0,
0,63,3,0,0,0,115,6,0,0,0,18,2,9,4,13,
1,
};


The difference between the two is very slight:

18c18
< 0,0,0,0,116,23,0,0,0,47,104,111,109,101,47,118,
---
> 0,0,0,0,116,23,0,0,0,47,87,111,114,107,47,118,


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


Re: Opaque documentation

2005-10-28 Thread Ben Sizer

egbert wrote:
> Once in a while you come acros aline of documentation
> that you have to, or that invites you to, read it again.
> This is what I found in PyGTK:
>
> The set_screen method sets the 'screen" property to
> the gtk.gdk.Screen specified by screen. The "screen" property
> contains the screen that the window is displayed on.

Clearly this is a violation of "once and only once". I'd reword it as:

The set_screen method sets the property to the gtk.gdk specified
by. The property contains the that the window is displayed on.

;)  Maybe if I was being less facetious, someone could reword it as:

The set_screen method sets the 'screen" property to
the supplied gtk.gdk.Screen object. This property
contains the screen that the window is displayed on.

Documentation is often a problem with Python and its libraries, sadly.
The same almost certainly goes for most open source projects.

-- 
Ben Sizer

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


[ANNOUNCE] EVENTS, HUMOUR, BOOKS related to SOFTWARE DEVELOPMENT

2005-10-28 Thread newswire_4_developers
CONTENTS:
** EVENTS ** EUROPE **
** BOOKS **
** EVENTS ** USA **
** CALL FOR SPEAKERS ** EUROPE
** CALL FOR SPEAKERS ** USA
** HUMOUR **
** OTHER INFORMATION - MAGAZINES, WHITEPAPERS ... **



** EVENTS ** EUROPE **
**

Enterprise Architect Conference
Arts Hotel, Barcelona - Nov 6-8 2005
http://www.ftponline.com/conferences/eas/barcelona/
Quote ref: EASMC

***

Architectural Reference Model for Enterprise Applications
2 Day Course.
Jan 2006
London UK
www.ratio.co.uk/ARM%20-%20Course%20Outline.pdf
email: info AT ratio.co.uk
See related article: 
http://www.ftponline.com/ea/magazine/summer2005/features/mcollinscope
/

***

8th International Conference on Enterprise Information Systems
23 - 27, May 2006 
Paphos - Cyprus 
http://www.iceis.org/cfp.htm

***

Fourth International Symposium on Formal Methods for Components and 
Objects (FMCO 2005)
DATES 1 - 4 November 2005
Amsterdam, The Netherlands
http://fmco.liacs.nl/fmco05.html


** BOOKS **
***

*** Essential Skills for Agile Development ***

This book has an elegant yet highly effective minimalist style. 
Rather than long theoretical discussion the book does what it does 
by example - and there's plenty of example code given. 
Overall the book covers many topics and issues related to agile 
software development, including: keeping code fit; 
handling inappropriate references; seperating database, UI and 
domain logic; 
unit testing and acceptance testing amongst others.The reason this 
book is to be recommended to developers, 
is that even if you're not doing full on "agile" development, 
there's still plenty of useful material in it. 
The lack of hype is also refreshing - the book focuses on examples 
and shows good solutions. You should get it!
http://www.amazon.com/exec/obidos/tg/detail/-
/9993776726/ratiogroupltd-20/qid=1128944604/sr=8-
1/ref=sr_8_xs_ap_i1_xgl14/002-3185742-7805624?
v=glance&s=books&n=507846


*** Agile Development with Iconix Process ***
"… because of this, we have been able to consistently deliver great 
software based on the original core time-after-time …"
"the authors … identify an `essential' list of agile practices to 
follow, including aggressive testing and frequent small releases …"
"… it is indeed rare for this level of detail to be given to a 
single example …"
"… finally a real world example with real-world solutions…"
(extracts from amazon.com)

http://www.amazon.com/exec/obidos/ASIN/1590594649/ratiogroupltd-20?
creative=327641&camp=14573&link_code=as1


*** Agile and Iterative Development, A Manager's Guide ***
Using statistically significant research and large-scale case 
studies, noted methods 
expert Craig Larman presents the most convincing case ever made for 
iterative development. 
Larman offers a concise, information-packed summary of the key ideas 
that drive all agile and iterative processes, 
with the details of four noteworthy iterative methods: Scrum, XP, 
RUP, and Evo. 
This book is a must if you need to get a grip on the spectrum of 
agile development techniques out there.
http://www.amazon.com/exec/obidos/tg/detail/-
/013558//ratiogroupltd-20/qid=1128944877/sr=1-1/ref=sr_1_1/002-
3185742-7805624?v=glance&s=books


** EVENTS ** USA **
***

29th Internationalization & Unicode Conference
March 6-8, 2006
San Francisco, California, USA
http://www.unicodeconference.org/IUC29call

***

SD WEST 2006
Santa Clara Convention Center
Santa Clara, CA
March 13-17, 2006
http://www.cmpevents.com/SDw6/a.asp?option=C

***

15th International Conference
on Software Engineering and Data Engineering
(SEDE-2006)
Los Angeles, California
July 6-8, 2006
http://www.cnsqa.com/spw2006/jsp/html/spw/callforpapers.jsp

***

Software Test and Performance Conference
http://www.stpcon.com/
NOVEMBER 1-3, 2005
ROOSEVELT HOTEL
New York City

***

IEEE Software Architecture Conference.
(WICSA)  November 6-9, 2005
http://sunset.usc.edu/~softarch/wicsa5/


** CALL FOR SPEAKERS ** EUROPE
**
Call for Speakers
Software Developer Conference
May 15 and 16, 2006
Papendal Convention Center
Arnhem, The Netherlands
http://www.sdc.nl/


** CALL FOR SPEAKERS ** USA
***
SD BEST PRACTICES 2006
Hynes Convention Center
Boston, MA
September 11-14, 2006
Call for Abstracts will open January 2006
http://www.sdexpo.com/

***

Call for Papers
International Symposium on
Software Testing and Analysis
Portland, Maine
July 17-20 2006
http://www.cis.udel.edu/~gibson/issta/cfp.html

***

Call for Papers
15th International Conference
on Software Engineering and Data Engineering
Software Process Change - Meeting the Challenge
(SEDE-2006)
Los Angeles, California
July 6-8, 2006
http://www.cnsqa.com/spw2006/jsp/html/spw/callforpapers.jsp



** HUMOUR **


"It is practically impossible to teach good programming style to 
students that have had prior exposure
to BASIC; as potential programmers they are mentally mutilated

Re: Scanning a file

2005-10-28 Thread Paul Watson
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I want to scan a file byte for byte for occurences of the the four byte
> pattern 0x0100. I've tried with this:
>
> # start
> import sys
>
> numChars = 0
> startCode = 0
> count = 0
>
> inputFile = sys.stdin
>
> while True:
>ch = inputFile.read(1)
>numChars += 1
>
>if len(ch) < 1: break
>
>startCode = ((startCode << 8) & 0x) | (ord(ch))
>if numChars < 4: continue
>
>if startCode == 0x0100:
>count = count + 1
>
> print count
> # end
>
> But it is very slow. What is the fastest way to do this? Using some
> native call? Using a buffer? Using whatever?
>
> /David

How about something like:

#!/usr/bin/env python

import sys

fn = 't.dat'
ss = '\x00\x00\x01\x00'

be = len(ss) - 1# length of overlap to check
blocksize = 4 * 1024# need to ensure that blocksize > overlap

fp = open(fn, 'rb')
b = fp.read(blocksize)
found = 0
while len(b) > be:
if b.find(ss) != -1:
found = 1
break
b = b[-be:] + fp.read(blocksize)
fp.close()
sys.exit(found) 


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


Re: Is bytecode machine (in)dependent?

2005-10-28 Thread Tim Peters
[Robert McLay]
> I'm trying to understand bytecodes generated on different machines.
> I understand that the bytecodes can change between version.  But since
> I'm told that .pyc files are version dependent but not machine
> dependent, I'm wondering why the bytecodes are machine dependent.

They aren't -- at least not particularly .

> my friend and I created this simple example to explore the problem.
> The example code is:
>
>   #!/usr/bin/env python
>   #
>   import sys, os
>
>   def main():
> x = 1.234
> print x
>
>   if ( __name__ == '__main__'):
> main()
>
>
> Using sib.py from Vendorid 1.0 generates different bytecodes under linux
> and sgi.  At its core sib.py is using:
>
># Compile the code using prefix and marshall it.
>compiled_code = compile(source_code, prefix, 'exec')
>marshalled_code = marshal.dumps(compiled_code)
>
> to get the bytecodes.

Why do you believe that `prefix` had the same value in both runs?  The
output suggests it did not, but can't guess more than that from here
since I don't know where `prefix` came from.

> So why are the byte codes different?  Is it that the intel-linux is
> little endian and the SGI is big endian

No; marshal format has fixed endianness.

> and the numerical constant (1.234) is stored different depending on the
> endian-ness?

Python defers to the platform C library for string->float conversions,
and it's *possible* that different platforms could convert "1.234" to
a C double in slightly different ways.  There's no evidence of that
here, though.

> This was generated under intel-linux using python 2.4.2
>
>
>
>
> 
> /*==*/
> /* Frozen main script for test
>   */
> /* Generated from test.py 
>   */
> /* This is generated code; Do not modify it!  
>   */
> 
> /*--*/
> unsigned char M___main__[] =
> {
> 99,0,0,0,0,0,0,0,0,2,0,0,0,64,0,0,
> 0,115,55,0,0,0,100,0,0,107,0,0,90,0,0,100,
> 0,0,107,1,0,90,1,0,100,1,0,132,0,0,90,2,
> 0,101,3,0,100,2,0,106,2,0,111,11,0,1,101,2,
> 0,131,0,0,1,110,1,0,1,100,0,0,83,40,3,0,
> 0,0,78,99,0,0,0,0,1,0,0,0,1,0,0,0,
> 67,0,0,0,115,15,0,0,0,100,1,0,125,0,0,124,
> 0,0,71,72,100,0,0,83,40,2,0,0,0,78,102,5,
> 49,46,50,51,52,40,1,0,0,0,116,1,0,0,0,120,
> 40,1,0,0,0,82,0,0,0,0,40,0,0,0,0,40,
> 0,0,0,0,116,23,0,0,0,47,104,111,109,101,47,118, /* This 
> line */
> 112,97,114,114,47,115,105,98,47,116,101,115,116,46,112,121,
> 116,4,0,0,0,109,97,105,110,5,0,0,0,115,4,0,
> 0,0,0,1,6,1,116,8,0,0,0,95,95,109,97,105,
> 110,95,95,40,4,0,0,0,116,3,0,0,0,115,121,115,
> 116,2,0,0,0,111,115,82,2,0,0,0,116,8,0,0,
> 0,95,95,110,97,109,101,95,95,40,3,0,0,0,82,4,
> 0,0,0,82,2,0,0,0,82,5,0,0,0,40,0,0,
> 0,0,40,0,0,0,0,82,1,0,0,0,116,1,0,0,
> 0,63,3,0,0,0,115,6,0,0,0,18,2,9,4,13,
> 1,
> };  x
>
>  And under SGI (python 2.4.2) it created :
>
>
> /*==*/
>/* Frozen main script for test 
>  */
>/* Generated from test.py  
>  */
>/* This is generated code; Do not modify it!   
>  */
>
> /*--*/
>unsigned char M___main__[] =
>{
>99,0,0,0,0,0,0,0,0,2,0,0,0,64,0,0,
>0,115,55,0,0,0,100,0,0,107,0,0,90,0,0,100,
>0,0,107,1,0,90,1,0,100,1,0,132,0,0,90,2,
>0,101,3,0,100,2,0,106,2,0,111,11,0,1,101,2,
>0,131,0,0,1,110,1,0,1,100,0,0,83,40,3,0,
>0,0,78,99,0,0,0,0,1,0,0,0,1,0,0,0,
>67,0,0,0,115,15,0,0,0,100,1,0,125,0,0,124,
>0,0,71,72,100,0,0,83,40,2,0,0,0,78,102,5,
>49,46,50,51,52,40,1,0,0,0,116,1,0,0,0,120,
>40,1,0,0,0,82,0,0,0,0,40,0,0,0,0,40,
>0,0,0,0,116,23,0,0,0,47,87,111,114,107,47,118,  /* This 
> line */
>112,97,114,114,47,115,105,98,47,116,101,115,116,46,112,121,
>116,4,0,0,0,109,97,105,110,5,0,0,0,115,4,0,
>0,0,0,1,6,1,116,8,0,0,0,95,95,109,97,105,
>110,95,95,40,4,0,0,0,116,3,0,0,0,115,121,115,
>116,2,0,0,0,111,115,82,2,0,0,0,116,8,0,0,
>0,95,95,110,97,109,101,95,95,40,3,0,0,0,82,4,
>0,0,0,82,2,0,0,0,82,5,0,0,0,40,0,0,
>0,0,40,0,0,0,0,82,1,0,0,0,116,1,0,0,
>0,63,3,0,0,0,115,6,0,0,0,18,2,9,4,13,
>1,
>};
>
>
> The difference between the two is very slight:
>
> 18c18
> < 0,0,0,0,116,23,0,0,0,47,104,111,109,101,47,118,
> ---
> > 0,0,0,0,116,23,0,0,0,47,87,111,114,107,47,118,

Stare at thi

Re: replace words

2005-10-28 Thread Scott David Daniels
Peter Otten wrote:
> [EMAIL PROTECTED] wrote:
> 
> 
>>What is the way for replacing in a string from . to . the sentence?
>>for example:
>>"been .taken.  it may be .left. there,
>>even if the .live coals were not. cleared"
>>I want to do this-> replace(\.(.*)\.,\.start (1) end\.)
>>result:
>>"been .start taken end.  it may be .start left end. there,
>>even if the .start live coals were not end. cleared"
> 
> 
> Use \1 to refer to the group in the substitution expression.
> You also need to change the regex to non-greedy match (the trailing ?).
> Otherwise you only get one big match from .taken ... not.
> 
> import re
> s = ("been .taken.  it may be .left. there, "
>  "even if the .live coals were not. cleared")
> 
> r = re.compile(r"\.(.*?)\.")
> print r.sub(r".start \1 end.", s)
> 
> Peter
> 
Perhaps you can use a variant of:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231347

 def wrap(source, pre, post):
 gen = iter(source)
 for portion in gen:
 yield portion
 try:
 bracketed = gen.next()
 except StopIteration:
 break
 yield pre
 yield bracketed
 yield post

 def mangledots(string):
 return ''.join(wrap(string.split('.'), '.start ', ' end.'))

print mangledots('been .taken.  it may be .left. there, '
  'even if the .live coals were not. cleared')

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


SNMP

2005-10-28 Thread py
>From what I have seen Python does not come with an snmp module built
in, can anyone suggest some other SNMP module (preferably one you have
used/experienced)..I have googled and seen yapsnmp and pysnmp (which
seem to be the two most active SNMP modules).

Thanks

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


Re: SNMP

2005-10-28 Thread py
...also I am looking to work with windows, as well as linux.

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


Re: xml-rpc - adodb - None type - DateTime type

2005-10-28 Thread infidel
> I can replace all None values with the string 'Null', there's no
> problem, but I can't detect the DateTime type object I retrieve from
> the database.
>
> I have something like this:
> def xmlrpc_function():
> conn = adodb.NewADOConnection('postgres')
> conn.Connect(host,user,password,database)
> rs = conn.Exec("select * from table")
> result = []
> i = 0
> while not rs.EOF:
> row = rs.GetRowAssoc(False)
> for key, value in row.items():
> if value==None:
> row[key]='Null'
> result.append(row)
> i = i + 1
> rs.MoveNext()
> rs.Close()
>
> print result
> return result
>
> The problem here is that if row[key] ==  etc...>, then I don't know what to do for detect it and make the
> appropriate change to string.
>
> Console output:
> [{'name': 'Null', 'date':  at 1515f60>}]
>
> If you consult the python manual, you'll see that there's no 'DateTime'
> type object, so I can't do something like:
>
> if value==DateTimeType:
> ...
>
> I only need to know which type of data is a field for make the change
> according to what can I pass through the xml-rpc.

Well, there is the possibility of passing null values through xml-rpc.
I believe there is an optional keyword argument in some of the
xmlrpclib functions to allow it.  Basically it translates None to
 in the xml.

The DateTime type must be defined somewhere.  Is it an adodb type?  If
so, you could do something like this:

if type(value) == adodb.DateTime:
...

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


Re: syntax question - if 1:print 'a';else:print 'b'

2005-10-28 Thread Christopher Subich
Steve Holden wrote:

>> On Thu, 2005-10-27 at 14:00, Gregory Piñero wrote:
>>
>>> Not quite because if something(3) fails, I still want something(4) to
>>> run.  
> Then the obvious extension:
> 
> for i in range(20):
>...
> 
> but I get the idea that Gregory was thinking of different statements 
> rather than calls to the same function with different arguments.


Sorry for the descendant-reply, but the original hasn't hit my news 
server yet (I think).

It sounds like Gregory wants a Python equivalent of "on error continue 
next," which is really a bad idea almost everywhere.
-- 
http://mail.python.org/mailman/listinfo/python-list


tkinter blues (greens, reds, ...)

2005-10-28 Thread Sean McIlroy
hi all

i recently wrote a script that implements a puzzle. the interface
mostly consists of a bunch of colored disks on a tkinter canvas. the
problem is that the disks change their colors in ways other than the
way they're supposed to. it certainly isn't just a bug in my script,
since i can sometimes change the color of certain disks just by taking
focus off of the window and then bringing it back again! does this
sound like some known bug in tkinter? and if so, is there a recommended
way of working around it? if it matters, i'm using python 2.3 under
windows 95. any advice will be much appreciated.

peace

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


popen2

2005-10-28 Thread g.franzkowiak
I start a process in my application with popen2.popen3('MyOtherProcess').
That's ok, but what can I do if the other process is running ?
Can I fetch some information and start with that ?

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


Re: How to translate python into C

2005-10-28 Thread Lawrence Oluyede
Il 2005-10-28, Johnny Lee <[EMAIL PROTECTED]> ha scritto:
> Thanks, Szabolcs. In fact, I want to reproduce a crush on cygwin. I
> used a session of python code to produce the crush, and want to
> translate it into C and reproduce it. Is the tools provided by you help
> with these issues? Of coz, I'll try them first. :)

Do you mean "crash" ?
Take a look at this: http://pycrash.sourceforge.net


-- 
Lawrence
http://www.oluyede.org/blog
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question: string replace

2005-10-28 Thread [EMAIL PROTECTED]
Now it works:
rex = re.compile(r'(^.*username *=[^"]*")([^"]*)(".*$)')
for line in fileinput.input(FILE, inplace=1):
 m = rex.match(line)
 if m is not None:
 line = "%s%s%s\n" % (m.group(1), new_name, m.group(3))
 print line

But there is an extra line break after each line in FILE. Why is that?
I tried to line = "%s%s%s" % (m.group(1), new_name, m.group(3)) but it
turns out there are two extra line breaks after each line...

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


Tkinter Frame Size

2005-10-28 Thread Tuvas
I'm tyring to set the size of the window that is opened when you open a
Tkinter window, without much sucess. I have tried changing the heigth
and width atributes, but it doesn't do anything. I tried using the
grid_propagate command that I saw to use, but made the window even
smaller... What can I do? Thanks!

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


Re: Tkinter Frame Size

2005-10-28 Thread James Stroud


On Friday 28 October 2005 10:38, Tuvas wrote:
> I'm tyring to set the size of the window that is opened when you open a
> Tkinter window, without much sucess. I have tried changing the heigth
> and width atributes, but it doesn't do anything. I tried using the
> grid_propagate command that I saw to use, but made the window even
> smaller... What can I do? Thanks!

Here is a very simple way:

from Tkinter import *
app = Tk()
app.geometry("%dx%d%+d%+d" % (600, 400, 0, 0))
f = Frame(app)
f.pack()
app.mainloop()


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning a file

2005-10-28 Thread James Stroud
On Friday 28 October 2005 06:29, Björn Lindström wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> > f = open("filename", "rb")
> > s = f.read()
> > sub = "\x00\x00\x01\x00"
> > count = s.count(sub)
> > print count
>
> That's a lot of lines. This is a bit off topic, but I just can't stand
> unnecessary local variables.
>
> print file("filename", "rb").read().count("\x00\x00\x01\x00")


The "f" is not terribly unnecessary, because the part of the code you didn't 
see was

f.close()

Which would be considered good practice.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Why doesn't this work? :)

2005-10-28 Thread Jeremy Moles
Jumping right into the code (which should speak for itself):

# ---

try:
# this will fail and be caught
# below, w
import foobar

except ImportError, error:
class foobar:
@staticmethod
def __getattr__(*args, **kargs):
return None

print foobar.bg

# ---

This doesn't work and I'm just curious as to why? I can, of course, make
__getattr__ non-static, instantiate a foolbar object, and everything
works; but, the "idea" above seems cleaner and whatnot. :)

Am I misunderstanding something fundamental about the builtin __*
functions? Can they not be "static?"

No rush on this, just curious. I'm using the following in a more general
way, and it works fine for now... :)

# ---

try:
import foobar

except ImportError, error:
class Foobar:
def __getattr__(*args, **kargs):
return None

foobar = Foobar()

print foobar.bg

# ---


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


Re: Tkinter Frame Size

2005-10-28 Thread Tuvas
Okay. I have alot of items that are put on the basic frame already,
using a grid method. Will this change anything?

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


Re: tkinter blues (greens, reds, ...)

2005-10-28 Thread Steve Holden
Sean McIlroy wrote:
> hi all
> 
> i recently wrote a script that implements a puzzle. the interface
> mostly consists of a bunch of colored disks on a tkinter canvas. the
> problem is that the disks change their colors in ways other than the
> way they're supposed to. it certainly isn't just a bug in my script,
> since i can sometimes change the color of certain disks just by taking
> focus off of the window and then bringing it back again! does this
> sound like some known bug in tkinter? and if so, is there a recommended
> way of working around it? if it matters, i'm using python 2.3 under
> windows 95. any advice will be much appreciated.
> 
It sounds to me much more like a bug in your script, to me at least. 
Change of focus generates windowing events in much the same way as 
clicking a button or hitting a key does, so I don't understand why you 
think that "just [by] taking the focus off the window and bringing it 
back again" shouldn't change anything.

For more specific insights we'd need to see some code, but sometimes 
just changing your own focus from "Tkinter has a bug" to "my code has a 
bug" is enough to help one find out what the problem really is. If you 
have a soft toy I'd recommend you sit it down somewhere and explain to 
it in great detail exactly why it can't be a bug in your program. You 
may find you discover the error with no further assistance.

If not, fire the toy and ask again :-)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Newbie question: string replace

2005-10-28 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Now it works:
> rex = re.compile(r'(^.*username *=[^"]*")([^"]*)(".*$)')
> for line in fileinput.input(FILE, inplace=1):
>  m = rex.match(line)
>  if m is not None:
>  line = "%s%s%s\n" % (m.group(1), new_name, m.group(3))
>  print line
> 
> But there is an extra line break after each line in FILE. Why is that?
> I tried to line = "%s%s%s" % (m.group(1), new_name, m.group(3)) but it
> turns out there are two extra line breaks after each line...
> 
 >>> for l in open('wshtest1.pys'):
... print repr(l)
...
'import sys\n'
'# WScript.Echo(str(sys.modules))\n'
'\n'
'from msg import Message\n'
'Message("Hello")\n'
'\n'
 >>>

As yoyu can see, iterating over a (text) file gives you lines with a 
line ending. Print adds a line ending as well. Instead use

import sys
 ...
 ...
 ...
 sys.stdout.write(l)

You will find you lose the blank lines.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Typing tutor help script needed, please

2005-10-28 Thread SPE - Stani's Python Editor
#---Input data

#List of words; every word or sentence on one line
#If from file: WORDS = open(fileName).readlines()
WORDS = """\
Afrikaans
Anna
Bread
red
word
bored
python""".split('\n')

#---Main program
import re

PATTERN = ['[^(%s)]+','[%s]+']
FILENAME= ['not_%s.txt','%s.txt']

def filter(letters='bdeor',words=WORDS,contain=True,ignoreCase=True):
pattern = PATTERN[contain]%'|'.join(list(letters))
if ignoreCase:
allowed = re.compile(pattern,re.IGNORECASE)
else:
allowed = re.compile(pattern)
result  = []
for word in words:
match   = allowed.match(word)
if match and match.group(0) == word: result.append(word)
print result
output  = open(FILENAME[contain]%letters,'w')
output.write('\n'.join(result))
output.close()



if __name__ == '__main__':
filter()

---
This should do it.

Stani
--
http://pythonide.stani.be
http://pythonide.stani.be/manual/html/manual.html

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


Re: popen2

2005-10-28 Thread David Wahler
g.franzkowiak wrote:
> I start a process in my application with popen2.popen3('MyOtherProcess').
> That's ok, but what can I do if the other process is running ?
> Can I fetch some information and start with that ?
>
> gerd

It's not clear what you're asking for. Could you please clarify?

-- David

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


Re: SNMP

2005-10-28 Thread Larry Bates


py wrote:
>>From what I have seen Python does not come with an snmp module built
> in, can anyone suggest some other SNMP module (preferably one you have
> used/experienced)..I have googled and seen yapsnmp and pysnmp (which
> seem to be the two most active SNMP modules).
> 
> Thanks
> 
Google turns up the following:

Yet Another Python SNMP module - http://yapsnmp.sourceforge.net/intro.html
Python SNMP framework  - http://pysnmp.sourceforge.net/

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


Re: Scanning a file

2005-10-28 Thread Mike Meyer
Andrew McCarthy <[EMAIL PROTECTED]> writes:

> On 2005-10-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> I'm now down to:
>>
>> f = open("filename", "rb")
>> s = f.read()
>> sub = "\x00\x00\x01\x00"
>> count = s.count(sub)
>> print count
>>
>> Which is quite fast. The only problems is that the file might be huge.
>> I really have no need for reading the entire file into a string as I am
>> doing here. All I want is to count occurences this substring. Can I
>> somehow count occurences in a file without reading it into a string
>> first?
>
> Yes - use memory mapping (the mmap module). An mmap object is like a
> cross between a file and a string, but the data is only read into RAM
> when, and for as long as, necessary. An mmap object doesn't have a
> count() method, but you can just use find() in a while loop instead.

Except if you can't read the file into memory because it's to large,
there's a pretty good chance you won't be able to mmap it either.  To
deal with huge files, the only option is to read the file in in
chunks, count the occurences in each chunk, and then do some fiddling
to deal with the pattern landing on a boundary.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I sort these?

2005-10-28 Thread KraftDiner
I have two lists.
I want to sort by a value in the first list and have the second list
sorted as well... Any suggestions on how I should/could do this?

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


Re: urllib2 problem

2005-10-28 Thread John J. Lee
"Jeremy Martin" <[EMAIL PROTECTED]> writes:
[...]
> website. I originally just used urllib.urlopen and everything worked 
> fine on my Windows PC at work. I tried the same script at home on my 
> Fedora COre 3 box using python 2.4, and whenever I try to connect to 
> the site I get the (110, Connection Timed Out) Error.  
> 
> At first I thought my firewall was causing problems with the script but 
> I noticed an odd patten. If the web site asked to accept cookies (like 
> the site I need) the script times out), if I point it to a site that 
> doesnt it works fine. Ive tried several attempts at using urllib2 and 
> the HTTPCookieProccessor and I still have no luck.

If this is just a single server you're talking to, this doesn't
necessarily implicate HTTPCookieProccessor -- it may be that that
server does different stuff depending on whether you return cookies or
not (not much point in having the cookies if not ;-), so the timeout
might be caused by all kinds of unrelated problems.


> Can anyone give me 
> any advice or pointers on what may be the problem here? I apologize if 
> this is kind of a rookie question but Ive been searching for about a 
> week with no luck. 

I'm the author of cookielib and HTTPCookieProccessor.  It's very hard
to guess what's wrong without being able to reproduce the problem.  If
you can send me your script ([EMAIL PROTECTED]), I may be able to help.

One point, though.  This doesn't seem to be the problem you are
having, but it's a good thing for this info to be more easily
Google-able for others: Are you using threads?  cookielib is
thread-broken, I suspect (poorly-tested thread support code was left
in when I contributed the module, which was a mistake: I'm almost
certain it's incorrect, and intend to request the thread
synchronisation code be removed in 2.5).  I suspect that could cause
deadlock if you are using threads.  It's probably possible to work
around this, but I reccommend just not using threads (and not only
because of my buggy synchronisation code!).  But as I say, I don't
think this is your problem.


John

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


Re: Why doesn't this work? :)

2005-10-28 Thread Chris Lambacher
I think what you really want is:

try:
# this will fail and be caught
# below, w
import foobar

except ImportError, error:
class foobarclass:
def __getattr__(*args, **kargs):
return None
foobar = foobarclass()

print foobar.bg


foobar in your version is a class.  By making it an instance, the __getattr__ 
method is properly called.


-Chris


On Fri, Oct 28, 2005 at 02:02:29PM -0400, Jeremy Moles wrote:
> Jumping right into the code (which should speak for itself):
> 
> # ---
> 
> try:
>   # this will fail and be caught
>   # below, w
>   import foobar
> 
> except ImportError, error:
>   class foobar:
>   @staticmethod
>   def __getattr__(*args, **kargs):
>   return None
> 
> print foobar.bg
> 
> # ---
> 
> This doesn't work and I'm just curious as to why? I can, of course, make
> __getattr__ non-static, instantiate a foolbar object, and everything
> works; but, the "idea" above seems cleaner and whatnot. :)
> 
> Am I misunderstanding something fundamental about the builtin __*
> functions? Can they not be "static?"
> 
> No rush on this, just curious. I'm using the following in a more general
> way, and it works fine for now... :)
> 
> # ---
> 
> try:
>   import foobar
> 
> except ImportError, error:
>   class Foobar:
>   def __getattr__(*args, **kargs):
>   return None
> 
>   foobar = Foobar()
> 
> print foobar.bg
> 
> # ---
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Typing tutor help script needed, please

2005-10-28 Thread Mike Meyer
"Throw" <[EMAIL PROTECTED]> writes:

> G'day everyone!
>
> I would like to design typing tutor exercises for Afrikaans (and other
> languages possibly).  This is for a GPL project.  For this, I need a
> script that can extract words from a long list of words, based on which
> letters those words contain, and write then write output to a file.
> Does anyone know of an existing script for this, or can anyone write me
> one, please?

This sounds nearly trivial in Python. More specifics would help.

> Preferably I must be able to extract words which contain only certain
> letters (they need not contain all of those letters, but they may not
> contain any other letters).  It would be nice if I can also extract
> words which do not contain certain letters.

Again, this sounds nearly trivial in Python.

For instance. to get a list of all words that don't contain 'a', you'd
do something  like:

f = open(textfile)
words = f.read().split()
f.close()
selected = [word for word in words if 'a' not in word]

and then selected has the list of words that don't have an 'a' in
them. Tweaking the test the other way - to select words with an 'a',
remove the 'not'. You can combine the tests with 'and' and 'or'.

But without a UI, that's pretty much useless - and you haven't said
what you want the UI to be.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter blues (greens, reds, ...)

2005-10-28 Thread Ron Adam


Steve Holden wrote:

> Sean McIlroy wrote:
> 
>> hi all
>>
>> i recently wrote a script that implements a puzzle. the interface
>> mostly consists of a bunch of colored disks on a tkinter canvas. the
>> problem is that the disks change their colors in ways other than the
>> way they're supposed to. it certainly isn't just a bug in my script,
>> since i can sometimes change the color of certain disks just by taking
>> focus off of the window and then bringing it back again! does this
>> sound like some known bug in tkinter? and if so, is there a recommended
>> way of working around it? if it matters, i'm using python 2.3 under
>> windows 95. any advice will be much appreciated.
>>
> It sounds to me much more like a bug in your script, to me at least. 
> Change of focus generates windowing events in much the same way as 
> clicking a button or hitting a key does, so I don't understand why you 
> think that "just [by] taking the focus off the window and bringing it 
> back again" shouldn't change anything.
> 
> For more specific insights we'd need to see some code, but sometimes 
> just changing your own focus from "Tkinter has a bug" to "my code has a 
> bug" is enough to help one find out what the problem really is. If you 
> have a soft toy I'd recommend you sit it down somewhere and explain to 
> it in great detail exactly why it can't be a bug in your program. You 
> may find you discover the error with no further assistance.
> 
> If not, fire the toy and ask again :-)
> 
> regards
>  Steve

To add to Steve's humorous perosonificatious techniques.  You should 
probably check that you aren't inadvertently using some sort of object 
id or window handle as a color value.  As long as the object you use 
returns an integer you won't get an error message, but instead get 
different colors when the canvas object is updated.  Like when changing 
the focus.

Another place to look is where you may be adding or converting rgb color 
values.

This function convert decimal rgb values to a hex rgb string that 
tkinter expects.

 def rgb(red, green, blue):
 """ Convert RGB value of 0 to 255 to
 hex Tkinter color string.
 """
 return '#%02x%02x%02x' % (red, green, blue)

Cheers,
Ron

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


Re: Scanning a file

2005-10-28 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> I want to scan a file byte for byte for occurences of the the four byte
> pattern 0x0100. 

data = sys.stdin.read()
print data.count('\x00\x00\x01\x00')

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


Re: OEM character set issue

2005-10-28 Thread Kent Johnson
Dennis Lee Bieber wrote:
> On Fri, 28 Oct 2005 15:55:56 +0200, "Ladvánszky Károly" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
>>On my hungarian Win2k, some of the accented characters of the file names
>>appear incorrectly when Python is driven from the command line. However,
>>they
> 
> 
>   The "MS-DOS" command window tends to use a different character
> encoding than full "Windows" widgets.

You can chaneg the encoding used by the command window with the chcp command.

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


Re: How do I sort these?

2005-10-28 Thread Steve Holden
KraftDiner wrote:
> I have two lists.
> I want to sort by a value in the first list and have the second list
> sorted as well... Any suggestions on how I should/could do this?
> 
 >>> first = [1, 3, 5, 7, 9, 2, 4, 6, 8]
 >>> second = ['one', 'three', 'five', 'seven', 'nine', 'two', 'four', 
'six', 'eight']
 >>> both = zip(first, second)
 >>> both.sort()
 >>> [b[0] for b in both]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> [b[1] for b in both]
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
 >>>

You mean like this?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: How do I sort these?

2005-10-28 Thread Diez B. Roggisch
KraftDiner wrote:
> I have two lists.
> I want to sort by a value in the first list and have the second list
> sorted as well... Any suggestions on how I should/could do this?

I guess you mean that you have two lists of same size where each index 
position pointing to corrsponding items - like two excel columns? Then 
this helps:

sl = zip(list_a, list_b)
sl.sort()
list_a, list_b = unzip(*sl)

Regards,

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


Re: Opaque documentation

2005-10-28 Thread Mike Meyer
"Ben Sizer" <[EMAIL PROTECTED]> writes:
> Documentation is often a problem with Python and its libraries, sadly.
> The same almost certainly goes for most open source projects.

You over-specified the last clause.  It should say "most software
projects."

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question: string replace

2005-10-28 Thread Mike Meyer
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Now it works:
> rex = re.compile(r'(^.*username *=[^"]*")([^"]*)(".*$)')
> for line in fileinput.input(FILE, inplace=1):
>  m = rex.match(line)
>  if m is not None:
>  line = "%s%s%s\n" % (m.group(1), new_name, m.group(3))
>  print line
>
> But there is an extra line break after each line in FILE. Why is that?

Because print prints a newline after all the values you pass it.

> I tried to line = "%s%s%s" % (m.group(1), new_name, m.group(3)) but it
> turns out there are two extra line breaks after each line...

It's not clear what you mean by this. I would have expected this
change to solve the problem. Where do you get two extra newlines?

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Typing tutor help script needed, please

2005-10-28 Thread Anno Siegel
Throw <[EMAIL PROTECTED]> wrote in comp.lang.perl.misc:
> 
> G'day everyone!
> 
> I would like to design typing tutor exercises for Afrikaans (and other
> languages possibly).  This is for a GPL project.  For this, I need a
> script that can extract words from a long list of words, based on which
> letters those words contain, and write then write output to a file.
> Does anyone know of an existing script for this, or can anyone write me
> one, please?

For the letters a, d, f and g:

perl -ne 'print if /^[adfg]+$/' < /list/of/words > words_with_adfg

For other combinations, change both occurrences of "adfg".

Anno
-- 
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article.  Click on 
"show options" at the top of the article, then click on the 
"Reply" at the bottom of the article headers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Typing tutor help script needed, please

2005-10-28 Thread RedGrittyBrick


 > Throw wrote:
 >> I must be able to extract words which contain only
 >> certain letters (they need not contain all of those letters,
 >> but they may not contain any other letters).

SPE - Stani's Python Editor wrote:
> #---Input data
> 
> #List of words; every word or sentence on one line
> #If from file: WORDS = open(fileName).readlines()
> WORDS = """\
> Afrikaans
> Anna
> Bread
> red
> word
> bored
> python""".split('\n')
> 
> #---Main program
> import re
> 
> PATTERN = ['[^(%s)]+','[%s]+']
> FILENAME= ['not_%s.txt','%s.txt']
> 
> def filter(letters='bdeor',words=WORDS,contain=True,ignoreCase=True):
> pattern = PATTERN[contain]%'|'.join(list(letters))
> if ignoreCase:
> allowed = re.compile(pattern,re.IGNORECASE)
> else:
> allowed = re.compile(pattern)
> result  = []
> for word in words:
> match   = allowed.match(word)
> if match and match.group(0) == word: result.append(word)
> print result
> output  = open(FILENAME[contain]%letters,'w')
> output.write('\n'.join(result))
> output.close()
> 
> 
> 
> if __name__ == '__main__':
> filter()
> 
> ---
> This should do it.
> 

Am I underestimating the task, it looks simple enough for the simplest grep?

# perl -n -e "print if /^[bdeor]+$/i" words.txt
red
bored
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't this work? :)

2005-10-28 Thread Jeremy Moles
On Fri, 2005-10-28 at 14:50 -0400, Chris Lambacher wrote:
> I think what you really want is:
> 
> try:
>   # this will fail and be caught
>   # below, w
>   import foobar
> 
> except ImportError, error:
>   class foobarclass:
>   def __getattr__(*args, **kargs):
>   return None
> foobar = foobarclass()
> 
> print foobar.bg
>
> foobar in your version is a class.  By making it an instance, the __getattr__ 
> method is properly called.
> 
> 
> -Chris

:)

Well, that's what I am using. :) What I'm wondering is if the other
method could work, of if it simply impossible in Python considering it's
underlying implementation.

> On Fri, Oct 28, 2005 at 02:02:29PM -0400, Jeremy Moles wrote:
> > Jumping right into the code (which should speak for itself):
> > 
> > # ---
> > 
> > try:
> > # this will fail and be caught
> > # below, w
> > import foobar
> > 
> > except ImportError, error:
> > class foobar:
> > @staticmethod
> > def __getattr__(*args, **kargs):
> > return None
> > 
> > print foobar.bg
> > 
> > # ---
> > 
> > This doesn't work and I'm just curious as to why? I can, of course, make
> > __getattr__ non-static, instantiate a foolbar object, and everything
> > works; but, the "idea" above seems cleaner and whatnot. :)
> > 
> > Am I misunderstanding something fundamental about the builtin __*
> > functions? Can they not be "static?"
> > 
> > No rush on this, just curious. I'm using the following in a more general
> > way, and it works fine for now... :)
> > 
> > # ---
> > 
> > try:
> > import foobar
> > 
> > except ImportError, error:
> > class Foobar:
> > def __getattr__(*args, **kargs):
> > return None
> > 
> > foobar = Foobar()
> > 
> > print foobar.bg
> > 
> > # ---
> > 
> > 
> > -- 
> > http://mail.python.org/mailman/listinfo/python-list

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


Re: Newbie question: string replace

2005-10-28 Thread [EMAIL PROTECTED]
hm...Is there a way to get rid of the newline in "print"?

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


Re: Newbie question: string replace

2005-10-28 Thread [EMAIL PROTECTED]
Got it, thanks all!

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


Print to printer

2005-10-28 Thread avnit
I can't seem to figure out how to print with my printer using python.
I'm using Mac OSX 10.4. I was thinking maybe something with
applescript. Does anyone know?

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


Re: Microsoft Hatred FAQ

2005-10-28 Thread David Schwartz

"Mike Meyer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> The quote about the mafia doesn't compare MS's actions to "actual use
> of force".

I'm sorry, that's just absurd. I won't speculate on what motivates you 
to engage in such crazy distortion. Of course the quote about the Mafia 
compares MS's actions to actual use of force.

> It compares MS to people who are willing to use force to
> get their ends. But there is no "actual use of force."

This is a gross distortion. What makes the Mafia the Mafia, and the only 
reason to invoke them, is because they actually do use and threaten force. 
They're not just willing to use force, they directly threaten it and use it 
to get their ends, and it's the only thing they do.

The type of threatening force that the Mafia uses it the type that is 
itself force. When you say to someone "give me all your money or I'll shoot 
you", it's force whether or not you actually have to shoot them.

DS


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


drag/move image from staticBitmap control?

2005-10-28 Thread James Hu








Hi, all gurus,

 

I have an application to show bitmap image
on one wx.staticBitmap control area, I can display part of the image, or the
whole image(detail is unclear),

But I would like to use mouse to drag/move
the image inside thewx.staticBitmap control when only part image on the screen,
just like maps.google does, 

is it possible to do that?

Any sample code or any idea or suggestion
are appreciated!

Have a nice weekend!

 

James






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

Re: Microsoft Hatred FAQ

2005-10-28 Thread David Schwartz

"Lasse Vågsæther Karlsen" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> Ok, let me just make my opinion very clear on this and then I'll just 
> leave this thread altogether.
>
> I think you are comparing apples and oranges so whatever conclusion you 
> manage to draw from that is in my eyes invalid. It doesn't matter, in my 
> opinion, if you managed to conclude that Microsoft was the saints 
> themselves because, in my opinion, your reasoning is not valid. I'm not 
> saying one way or the other, I'm just picking at your reasoning.
>
> To me it sounds like concluding that the prices of RAM will drop because 
> the swallows are flying high this fall.
>
> But enough, I'll just leave it.

There is no value whatsoever in simply saying "I don't agree with you" 
and including no argument or reasoning. Were you afraid someone might 
erroneously think you did agree with me and that this would harm your 
reputation? If you want to participate in discussion, you have to make 
claims and defend them.

MS imposed a restriction that was logically lesser than saying "if you 
want to buy Windows wholesale, you cannot sell products that compete with 
PCs with Windows pre-loaded on them". (Logically lesser because they allowed 
you sell them but charged a fee. You could avoid the fee by simply not 
selling them.) This is a perfectly ordinary type of franchise sales 
arrangement engaged in by companies of all kinds. For someone who does not 
already have a monopoly, it is even perfectly legal.

DS


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

? Pythoncard

2005-10-28 Thread LenS
I have created a small gui stub as follows using Pythoncard:

c:\myhome
 lmsgui.py
 lmsgui.rsrc.py

When I try to run I get the following error:

(Errno2) no such file or directory lmsqui.rsrc.py

I understand why I am getting the error the question is how do I fix
this so it looks in the proper directories.

Len Sumnler

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


  1   2   >