Re: Test for Pythonwin?

2009-07-31 Thread Roger Miller
On Jul 31, 2:09 am, steve st...@nospam.au wrote:
 Is there a good way to check if a script is running inside Pythonwin?
 Perhaps a property or method that is exposed by that environment?

I've used
  if sys.stdin.fileno()  0:
This is not precisely a test for pythonwin, but indicates whether
standard streams are available, which is usually what I really
want to know.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question about tuples and list comprehensions

2008-06-25 Thread Roger Miller
First, I second Matt's comment about using a boring old for loop when
it is the simplest way to express what you want to do.  Being Pythonic
is not about using exotic features to scrunch your code down to a cool
one-liner.  It is about expressing your intentions in a simple, direct
way.  Sometimes comprehensions, generators, etc. help.  Sometimes they
only obfuscate.

That said, the *most* Pythonic way to do something is to find the
existing library that already does it.  Check out the Image.point()
function in the PIL documentation.  You may not need to convert the
image to a list at all.

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


Re: Separators inside a var name

2008-06-09 Thread Roger Miller
On Jun 9, 7:29 am, Rainy [EMAIL PROTECTED] wrote:
 ... Another question I have is what
 other languages allow this naming scheme?

The most widely used such language would probably be COBOL,
where you write things like

   SUBTRACT DISCOUNT FROM LIST-PRICE GIVING AMOUNT-DUE

I doubt that syntax would catch on in Python :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an official way to add methods to an instance?

2008-04-03 Thread Roger Miller
On Apr 3, 2:57 pm, Brian Vanderburg II [EMAIL PROTECTED]
wrote:

 I've checked out some ways to get this to work.  I want to be able to
 add a new function to an instance of an object.  I've tested two
 different methods that cause problems with 'deleting'/garbage collection
 (__del__ may never get called), but implemented one sort of hackishly
 maybe that works find. I'm wondering if there is more of an official way
 than mine.


Maybe I'm missing something, but the boring old straightforward
approach works for me:

class A:
def __del__(self):
print Deleting

def f(x):
print x

a = A()
a.f = f
a.f(42)
del a

Output:
42
Deleting
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: License of Python

2008-03-31 Thread Roger Miller
Is there any legal problem with including licenses for languages you
don't use?  (But I agree with the other posters that any competitor
worthy of concern will figure it out in short order if they care.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Naive idiom questions

2008-01-31 Thread Roger Miller
On Jan 31, 11:48 am, Grant Edwards [EMAIL PROTECTED] wrote:

 I'm not sure what you're asking.  AFAIK, the main reason that
 strings are immutable is so they can be used as dict keys.


I think its more fundamental than that.  If strings were mutable
you would be constantly worrying about whether changing a string
here might affect something there, or whether to write x = y or
x = copy.copy(y).  Or condsider


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


Re: Ignore exceptions

2008-01-24 Thread Roger Miller
On Jan 24, 11:30 am, Jonathan Gardner [EMAIL PROTECTED]
wrote:
 

 A few sample good uses of try/except blocks:

 (1) Do something else if an expected exception occurs.
 ...
 (2) Show a friendly error message when an exception occurs over a
 significant chunk of the program. (Useful for websites and GUI apps.)
 ...

I'd add (3) Clean-up handlers.  These don't actually handle the
problem,
they just free resources, close files, etc. before re-raising the
exception
for someone else to worry about.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: index of min element of sequence

2008-01-21 Thread Roger Miller
On Jan 21, 8:48 am, Peter Otten [EMAIL PROTECTED] wrote:

 Neal Becker wrote:
  What's a good/fast way to find the index of the minimum element of a
  sequence?
...

  min(xrange(len(items)), key=items.__getitem__)
...

Or just
   items.index(min(items))
I found this to be significantly faster in a simple test (searching a
list of 1000 ints with the minimum in the middle), despite the fact
that it requires two passes.  I'm sure that one could find cased where
Peter's approach is faster, so you if you are concerned about speed
you should measure with your own data.



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


Re: Ping Implementation in Python

2007-12-20 Thread Roger Miller
On Dec 20, 5:41 am, Mrown [EMAIL PROTECTED] wrote:
 Hi,
   I was wondering if there was a ping implementation written in
 Python.

http://www.gnist.org/~lars/code/ping/ping.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determine whether program was started by clicking icon or command line

2007-11-29 Thread Roger Miller
On Nov 28, 10:51 pm, Benjamin Hell [EMAIL PROTECTED] wrote:
 Hi!

 I wonder whether there might be a way to find out how a Python
 program was started (in my case in Windows): By double clicking the
 file or by calling it on the DOS command line prompt.

 Background: I would like to have the program run in an interactive
 mode if double clicked, and silently in a batch mode when started
 otherwise.

I'm not sure whether this applies to your situation, but often
programs
started by clicking an icon are run by pythonw, but when started from
the command line are run by python. If this is the case
sys.stdin.fileno()
will return -1 in the former case and 0 in the latter.

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


Re: Limits on search length

2007-10-01 Thread Roger Miller
Since you are getting the regular expression pattern via an argument I
would first check that searchPattern is what you expect. Shells can do
funny things with arguments containing special characters.  Also, is
it possible that the quoted strings in the files contain escapes?  For
example if a file contains the text hello\n would you consider that
6 characters or 7?

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


Re: A problem with Time

2007-08-16 Thread Roger Miller
On Aug 16, 9:46 am, MRAB [EMAIL PROTECTED] wrote:

 As well as the other replies, this also works (as far as I can tell!):

 import time
 today = time.localtime()
 yesterday = today[ : 2] + (today[2] - 1, ) + today[3 : ]
 yesterday = time.localtime(time.mktime(yesterday))

This is something I have wondered about.  The C library mktime
function is
documented to fix up out of range values,.  For example July 32
becomes
August 1 and August -1 becomes July 31.  Python presumably inherits
this
very useful (and seemingly not well known) behavior, but it is not
documented.  Is this just an oversight, or is it intentional on the
grounds
that it might be platform-dependent?  Any language lawyers out there
that
would care to comment?

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


Re: float to string with different precision

2007-08-10 Thread Roger Miller
On Aug 10, 8:37 am, Zentrader [EMAIL PROTECTED] wrote:

 If the above does not work
 [/code]test_list = [ 5.32, 10.35634, 289.234 ]
 for num in test_list :
str_num = %11.5f % (num)   ## expand to at least 5
print str_num, --, str_num.strip()[:5][/code]

This has the disadvantage that it doesn't round the last digit.  For
example 10.356634 yields 10.356 instead of 10.357.

You can use '*' in format strings to take a numeric field value from a
variable.  For example

   ndecimals = 2
   print %5.*f % (ndecimals, x)

formats x with 2 digits following the decimal point.  Or you can
simply
cobble up a format string at run time:

   format = %%5.%df % ndecimals
   print format % x

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


Re: idiom for RE matching

2007-07-19 Thread Roger Miller
On Jul 18, 6:52 pm, Gordon Airporte [EMAIL PROTECTED] wrote:

 ...
 I've also been assuming that using the re functions that create match
 objects is slower/heavier than dealing with the simple list returned by
 findall(). I've profiled it and these matches are the biggest part of
 the running time of the program, so I really would rather not use
 anything slower.

My guess would be that searching for more matches after finding the
first would be more expensive than creating a match object.  But that
would probably depend on the nature of your data and REs, so you need
to test it both ways if you are concerned about performance.

It would be nice if findall() had an optional parameter to limit the
number of matches, similar to the maxsplit parameter of string.split().

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


Re: Portable general timestamp format, not 2038-limited

2007-06-22 Thread Roger Miller
On Jun 22, 10:33 am, James Harris [EMAIL PROTECTED]
wrote:
 I have a requirement to store timestamps in a database. Simple enough
 you might think but finding a suitably general format is not easy.
 ...
 Any thoughts on a better way to do this? (Please reply-all. Thanks).

 --
 James


My rule of thumb in situations like this is When in doubt store it as
text.  The one format I am pretty sure we will still be able to deal
with in 2039.

- Roger

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


Re: how to do reading of binary files?

2007-06-08 Thread Roger Miller
On Jun 8, 2:07 am, Diez B. Roggisch [EMAIL PROTECTED] wrote:

 ...

 What has the searching to do with the reading? 10MB easily fit into the
 main memory of a decent PC, so just do

 contents = open(file).read() # yes I know I should close the file...

 print contents.find('\x0c')

 Diez

Better make that 'open(file, rb).

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


Re: Random selection

2007-05-18 Thread Roger Miller
On May 17, 10:39 pm, Tartifola [EMAIL PROTECTED] wrote:
 Hi,
 I have a list with probabilities as elements

 [p1,p2,p3]

 with of course p1+p2+p3=1. I'd like to draw a
 random element from this list, based on the probabilities contained in
 the list itself, and return its index.

 Any help on the best way to do that?
 Thanks

This of course depends on your definition of best.  There is a fast
and simple technique if all probabilities are multiples of 1/n for a
reasonably small n, or if you are willing to round them to such.
Suppose for example that the probabilities are [0.42, 0.23, 0.35].
Create a list of 100 items with 42 0's, 23 1's, and 35 2's, then
select a random element using random.choice() or
equivalent.

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


Re: behavior difference for mutable and immutable variable in function definition

2007-05-04 Thread Roger Miller
On May 4, 12:39 pm, 7stud [EMAIL PROTECTED] wrote:
 On May 4, 3:30 pm, [EMAIL PROTECTED] wrote:



  Hi,

  Can anyone explain the following:

  Python 2.5 (r25:51908, Apr  9 2007, 11:27:23)
  [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2
  Type help, copyright, credits or license for more information. 
  def foo():

  ... x = 2
  ... foo()
   def bar():

  ... x[2] = 2
  ...

   bar()

  Traceback (most recent call last):
File stdin, line 1, in module
File stdin, line 2, in bar
  NameError: global name 'x' is not defined

  Thanks,
  Jianbing

 The first function is completely irrelevant unless you expect this to
 work:

 x = 2
 x[2] = 2

 Traceback (most recent call last):
   File test1.py, line 2, in ?
 x[2] = 2
 TypeError: object does not support item assignment

 So that leaves you with:

   def bar():

  ... x[2] = 2
  ...

   bar()

 Would you expect this to work:

 x[2] = 2
 print x

I will sympathize with the OP to the extent that the message global
name 'x' is not defined is a bit misleading. All that the interpreter
really knows is that 'x' is not defined, locally or globally, and it
should probably not presume to guess the coder's intention.


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


Re: Weird gcc behaviour with function pointer types

2007-03-29 Thread Roger Miller
On Mar 29, 3:05 am, greg [EMAIL PROTECTED] wrote:
 In my quest to eliminate C compiler warnings from
 Pyrex output, I've discovered some utterly bizarre
 behaviour from gcc 3.3.

 The following code:

void g(struct foo *x) {
}

void f(void) {
  void (*h)(struct foo *);
  h = g;
}

 produces the following warning:

blarg.c: In function `f':
blarg.c:6: warning: assignment from incompatible pointer type

 However, adding the following line at the top:

typedef struct foo Foo;

 makes the warning go away. The mere *presence* of
 the typedef is all that's needed -- it doesn't even
 have to be used.

 This looks like a bug in gcc to me -- what do people
 think?

 --
 Greg

If there is no outer declaration of struct foo visible to both
functions
gcc is right (it usually is when it comes to C technicalities).  The
scope
of a struct declared inside a parameter list is limited to the
parameter
list itself, so the two struct foos are technically different types.
Adding the typedef provides a common declaration of struct foo that is
shared by both functions.  You don't really even need a typedef; a
global
declaration of just struct foo; should make the problem go away.

I would have expected gcc to also warn you about declaring a struct
inside
a parameter list.  Did you get any warnings like that?

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


Re: eval('000052') = 42?

2007-02-21 Thread Roger Miller
On Feb 20, 7:37 pm, John Machin [EMAIL PROTECTED] wrote:
 On Feb 21, 3:09 pm, Astan Chee [EMAIL PROTECTED] wrote:

  Hi,
  I just tried to do
  eval('00052') and it returned 42.
  Is this a known bug in the eval function? Or have I missed the way eval
  function works?
  Thanks

 Eight fives are forty. Forty plus two is forty two. I see no bug here,
 only a language design strangeness which can be blamed on the then-
 pervasive influence of all things from Bell Labs :-)

So is this anachronism slated for removal in Python 3?


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


Re: why I don't like range/xrange

2007-02-16 Thread Roger Miller
On Feb 16, 7:01 am, Bart Ogryczak [EMAIL PROTECTED] wrote:
 On Feb 16, 4:30 pm, stdazi [EMAIL PROTECTED] wrote:

  for (i = 0; some_function() /* or other condition */ ; i++)

 C's for(pre,cond,post) code is nothing more, then shorthand form of
 pre; while(cond) {code; post;}

I don't disagree with your basic point, but technically this is not
quite true.
Try it with
   for (i = 0; i  n; i++) {
  if (x[i] == 0) continue;

  printf(%d\n, x[i]);
   }




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


wx.Font.GetPointSize returning bogus value?

2006-12-08 Thread Roger Miller
The following program gets a TextCtrl's text attributes and sets them
back unchanged. However it reports that the font size is 124, and after
resetting the attributes the text becomes that size. That is, the
window displays a normal-size foo and a gigantic bar. Anyone know
what's going on?

This is WxPython 2.6 on Python 2.5 on Windows XP.

--

import sys
import wx

class MyApp (wx.App):

   def __init__ (self):
  wx.App.__init__(self, redirect=0)

   def OnInit (self):
  top = wx.Frame(None, size=(500, 300))
  txt = wx.TextCtrl(top, -1, foo\n, (-1, -1), (400, 200),
wx.TE_RICH|wx.TE_READONLY|wx.TE_MULTILINE)
  top.Show()

  attrs = wx.TextAttr()
  txt.GetStyle(0, attrs)
  font = attrs.GetFont()
  print font face, font.GetFaceName()  # prints MS Shell Dlg 2
  print font family, font.GetFamily()  # prints 74
  print font size, font.GetPointSize() # prints 124!
  txt.SetDefaultStyle(attrs)
  txt.AppendText(bar\n)
  return True

app = MyApp()
app.MainLoop()

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


uninstall and Windows file associations

2006-11-01 Thread Roger Miller
When I installed Python 2.5 (on Windows XP) I left 2.4 in place just
in case. Today I decided to remove it. However after doing so (from
the control panel) I found that Windows no longer knows about the
Python file types and associations. Is this behavior expected, or was
there something wrong with my installation? Is there a way to restore
the file associations, short of reinstalling 2.5 or manually editing
them?

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


pythonw documentation?

2006-10-09 Thread Roger Miller
I was going to ask how to a program can tell whether it was started by
python.exe or pythonw.exe, but after some experimentation I noticed
that sys.stdin.fileno() is -1 in the latter case.

However on a more general note, the only references to pythonw that I
could find in the Python 2.5 documentation are in the Macintosh
section. Have I overlooked something, or is this a deficiency that
should be addressed?

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


wxPython: wxStaticBitmap and large images

2006-07-19 Thread Roger Miller
I have a WxPython app that displays images that are typically around
600x600 pixels. I use a wxStaticBitmap, which appears to work fine on
Windows XP. However the documentation states that a StaticBitmap ...
is meant for display of the small icons in the dialog boxes and is not
meant to be a general purpose image display control. In particular,
under Windows 9x the size of bitmap is limited to 64*64 pixels and thus
you should use your own control if you want to display larger images
portably.

Assuming that I don't care about Windows 9X, should I be worried? Is
there a better way to display images, hopefully without diving down
into the device context level?

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


Re: Coding style

2006-07-17 Thread Roger Miller
Peter Otten wrote:
 Steve Holden wrote:

  I'll bet you still write
 
  if a3 == True:
 
  don't you ;-)

 I'll second that.

 if (a3) == True:

 is the correct way :-)

 Peter

No, to be consistent you'll have to write

   if ((a3) == True) == True:

Oops, I mean,

   if (((a3) == True) == True) == True:

Umm, never mind.

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


Re: zipfile module doesn't allow append

2006-06-29 Thread Roger Miller
Ritesh Raj Sarraf wrote:

 The line
 filename = zipfile.ZipFile(zip_file_name, a)
 throws an exception if the given filename is not present already.
 Shouldn't it create a file (in case one is not there) since it is
 append mode ??

Perhaps it would be nicer that way, but it is working as documented.
Catch the exception and open in 'w' mode.

To anticipate your next possible problem, note that in append mode if
you write a file that already exists in the archive it will not replace
the existing file, but will add another one with the same name. As far
as I can tell, there is no way to read the newer version because
zipfile.read(name) always finds the first version. So if you are trying
to update a zipfile you will probably have to read the old archive and
write a new one, copying the files you want to keep and replacing the
ones you want to update. (At this point you might want to consider
invoking an external zip utility instead.)

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


Re: source reduction using Python

2006-06-22 Thread Roger Miller
[EMAIL PROTECTED] wrote:
 Intel has introduced something called CESR, written in Python, to aid
 C, C++, and Fortran programmers in reducing the sizes of programs
 included in bug reports. Here is a brief description from
 http://cache-www.intel.com/cd/00/00/21/93/219320_relnotes_10.pdf :
 ...
 I think one needs to qualify for Intel Premier Support to get CESR. I
 wonder if a similar open-source Python program exists.

I can't answer your question, but if you are searching it may be
helpful to know that the relevant phrase is probably program slicing.

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


Re: Sampling a population

2006-06-02 Thread Roger Miller
For your example, since the probabilities are all multiples of 0.01 you
could make a list of 100 elements.  Set one of them to a, 5 of them to
b, 50 of them to c, etc. Then just randomly sample from the table
(which is O(1)). Of course if the probabilities can be arbitrary
floating point values then this won't work. But if you can live with
rounding to 3 or 4 digits this is probably the fastest and easiest
approach.

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


Re: shuffling elements of a list

2006-05-31 Thread Roger Miller
Sybren Stuvel wrote:
 David C  Ullrich enlightened us with:
  I thought that the fact that you could use the same trick for
  _shuffling_ a list was my idea, gonna make me rich and famous. I
  guess I'm not the only one who thought of it. Anyway, you can use
  DSU to _shuffle_ a list by decorating the list with random numbers.

 This is often done in database queries that need to randomize the data
 ;-)

 Sybren
 --
 The problem with the world is stupidity. Not saying there should be a
 capital punishment for stupidity, but why don't we just take the
 safety labels off of everything and let the problem solve itself?
  Frank Zappa

DSU seems like a lot of trouble to go through in order to use an O(n
log n) sorting algorithm to do what can be done in O(N) with a few
lines of code.  The core code of random.shuffle() shows how easy it is
to do it right:

for i in reversed(xrange(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]

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


Re: Looking for help with Regular Expression

2006-05-24 Thread Roger Miller
Seem to be a lot of regular expression questions lately. There is a
neat little RE demonstrator buried down in
Python24/Tools/Scripts/redemo.py, which makes it easy to experiment
with regular expressions and immediately see the effect of changes. It
would be helpful if it were mentioned in the RE documentation, although
I can understand why one might not want a language reference to deal
with informally-supported tools.

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


Re: memory error with zipfile module

2006-05-19 Thread Roger Miller
The basic problem is that the zipfile interface only reads and writes
whole files, so it may perform poorly or fail on huge files. At one
time I implemented a patch to allow reading files in chunks. However I
believe that the current interface has too many problems to solve by
incremental patching, and that a zipfile2 module is probably warranted.
(Is anyone working on this?)

In the meantime I think the best solution is often to just run an
external zip/unzip utility to do the heavy lifting.

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


Re: Python trig precision problem

2006-05-18 Thread Roger Miller
If I were you I would see if I could get the Perl script referred to on
the ERIN web page. You might find that the discrepancy is something as
simple as a slightly different value for the Earth's radius. And by the
way, math.radians() might be a bit clearer than the pi/180 business.

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


Re: Add file to zip, or replace file in zip

2006-04-28 Thread Roger Miller
First note that zipfile is a plain Python module, so reading
Python.../Lib/zipfile.py will reveal all its secrets.

I don't think it is possible to replace archive members using the
module. You could copy all the files into a new zip file, replacing the
ones you want to change as you go. But it might be easier just to use
os.system() or something similar to run an external zip program.

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


SEEK_SET defined?

2006-03-28 Thread Roger Miller
I see that the posixfile module is deprecated.  Have the SEEK_SET, etc.
constants moved somewhere else, or do I need to define them myself?

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