Re: YOU MUST KNOW THIS MAN

2007-12-06 Thread Deltantor
Piet van Oostrum wrote:
 Deltantor [EMAIL PROTECTED] (D) wrote:
 
 D Does c.l.python get religious spam that much? Of all of the places to be
 D spammed the least likely I expected would be here.
 
 Is that the reason you find it necessary to repeat it?
Sorry, was busy and forgot to clean up the post. I sometimes forget that 
some people dont have an unlimited usenet account.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Timezones in python

2007-12-06 Thread lukasz . f24
On 5 Dec, 13:59, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Wed, 05 Dec 2007 06:43:49 -0300, [EMAIL PROTECTED] escribió:

  Thanks guys for your answers! I know those library's but I was
  wondering is there something build-in for this simple convert convert.
  I have to do it only from +4 to +0.

 Copying the example from the tzinfo docs:

  from datetime import tzinfo, timedelta, datetime

 ZERO = timedelta(0)
 HOUR = timedelta(hours=1)

 # A class building tzinfo objects for fixed-offset time zones.
 # Note that FixedOffset(0, UTC) is a different way to build a
 # UTC tzinfo object.

 class FixedOffset(tzinfo):
  Fixed offset in minutes east from UTC.
  def __init__(self, offset, name):
  self.__offset = timedelta(minutes = offset)
  self.__name = name
  def utcoffset(self, dt):
  return self.__offset
  def tzname(self, dt):
  return self.__name
  def dst(self, dt):
  return ZERO

 UTC = FixedOffset(0, 'UTC')
 Argentina = FixedOffset(-3*60, 'UTC-3')
 UTCPlus4 = FixedOffset(4*60, 'UTC+4')

 py now = datetime.now(Argentina)
 py print now.strftime('%c %Z')
 12/05/07 10:52:28 UTC-3
 py print now.astimezone(UTC).strftime('%c %Z')
 12/05/07 13:52:28 UTC
 py print now.astimezone(Argentina).strftime('%c %Z')
 12/05/07 10:52:28 UTC-3
 py print now.astimezone(UTCPlus4).strftime('%c %Z')
 12/05/07 17:52:28 UTC+4

 --
 Gabriel Genellina

Thank you that iwll help a lot
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is not a good name, should rename to Athon

2007-12-06 Thread Adrian Cherry
Piet van Oostrum [EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

 Adrian Cherry [EMAIL PROTECTED] (AC) wrote:
 
AC For that matter C# is no better, I thought that # was
pronounced AC hash, I still refer to C# as C-hash.
 
 Are you musically illiterate?

Yup! The limits of my musically ability is

Spam, spam, spam, spam.
Lovely spam! Wonderful spaaam!
Lovely spam! Wonderful spam.
Spa-a-a-a-a-a-a-am! Spa-a-a-a-a-a-a-am!

Is that a problem? It's still a hash sign to me.

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


RE: Timeout test hangs IDLE

2007-12-06 Thread Andreas Tawn
 I once made a small app that used threads on IDLE.
 
 There was a strange error when using 'print'  threads. When 
 what I printed filled the entire screen, instead of moving 
 all the text up, IDLE just hanged. Try running your code from 
 the shell instead, to see if the problem is in IDLE. 
 
 HTH,
 Sergio

It looks like there's two issues here, an IDLE problem and a me
problem ;o)

I changed the countTest function to time.sleep(10) rather than a big
loop. When I run the script from the command line, the timeout triggers
properly after 5 seconds but the countTest function (running in a
seperate thread now) continues for the whole 10 seconds. This is the
me problem. I though that the timeout function would kill the
countTest thread, but it seems like it doesn't do that. Rather, the
timout just returns after 5 seconds with the message that the countTest
thread is still alive. I guess I need to set event flags so the
countTest function can end itself rather than trying to kill it from the
main thread?

When I run it from IDLE, everything runs correctly, but after the
countTest thread ends after 10 seconds, IDLE hangs as before. IDLE bug,
maybe?

Thanks for the help everyone.

The code looks like this now.

def countTest():# Succeeds from the command line, hangs in IDLE
import time
time.sleep(10)
return True

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None

def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default

it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result

def runTest():
timeout(countTest, timeout_duration=5)
print finished

if __name__ == __main__:
runTest()
-- 
http://mail.python.org/mailman/listinfo/python-list


Surfing Script

2007-12-06 Thread [EMAIL PROTECTED]
AJ Surfing is a fully functional surfing website with full
administration controls. Users need no programming experience to
change any site features. It is a complete web application developed
using PHP with MYSQL as back-end. Full developer API allows for
endless possibilities and use in your own project!

Sources: http://www.ajsquare.com/ajsurfing/index.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reloading modules and isinstance()

2007-12-06 Thread Diez B. Roggisch
Tlis schrieb:
 On 5 Dec, 13:18, Steven D'Aprano [EMAIL PROTECTED]
 cybersource.com.au wrote:
 On Tue, 04 Dec 2007 15:41:48 +0100, Diez B. Roggisch wrote:
 You just discovered one reason why reload() is a bad idea and IMHO
 shouldn't be used at all - as tempting it might be.
 I disagree -- I find reload() extremely useful for interactively testing
 modules. But I would never dream of using it in production code!

 --
 Steven.
 
 Please note, that I was using the 'Reload modules' functionality of
 the software system in use, rather than the reload() function
 directly. I admit, though, that in the background it just may call
 reload() ...
 
 With all the problems of the reload() function, I still hope, that
 there should be possible to write a safe module 'reloader', that would
 fix the references, as required (e.g. by changing the
 variable.__class__ references). This should be provided by every
 serious Python development environment.

Wishful thinking. If I do

foo = {}
foo['some_key'] = somemodule.SomeClass

somewhere in my code, how do you suppose is reload(somemodule) to know 
where in all the world I keep references to that class? Thus it would 
essentially have to scan all references to anything, all list contents, 
all class-properties, all everything. Which is not feasible.

reload() can be convenient, if you know its limitiations. But it has 
some, and they are deeply rooted in the way python works. So you gonna 
have to live with it.


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


Re: An Object's Type

2007-12-06 Thread paul
Bruno Desthuilliers schrieb:
 [EMAIL PROTECTED] a écrit :
 Hi,

 Is it possible to find out if an object is of a certain type or of a
 type derived from this type?

 You have the answer, thanks to Diez and Christian. Now unless you have a 
 *very* compelling reason to check the type of an object, *just forget 
 about it*. 9 times out of 10, this is fighting against the language's 
 type system (hint: google for duck typing).
So I have to give up the concept that argument types are part of the 
interface or signature? Honestly, I don't like that. Granted; not having 
strict type checking makes for great flexibility but the price is you 
either write typchecking code or let the error propagate into the 
function or method. I hope type annotations in py3k will allow for 
something like constraints in C# where you can tell the caller right 
away she's doing something wrong.

greetings
  Paul

BTW: are type annotations to be backported to 2.x?

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


Re: Python surpasses Perl in TIOBE index

2007-12-06 Thread Carl Banks
On Dec 5, 4:18 pm, George Sakkis [EMAIL PROTECTED] wrote:
 On Dec 5, 7:34 am, BlueBird [EMAIL PROTECTED] wrote:

  On Dec 4, 4:08 pm, [EMAIL PROTECTED] wrote:

   This is *not* an attempt to start yet another Python-versus-
   AnyOtherProgrammingLanguage flame war, but I thought people might be
   interested in this:

  http://www.tiobe.com/tpci.htm

   Marc

  I find Ohloh comparisons also 
  useful:http://www.ohloh.net/languages/compare?commit=Updatel0=pythonl0_0=-...

  What it highlights is that the number of python programmer is growing
  quicker than the number of perl programmers.

 Not necessarily; it shows that the count of monthly commits by open
 source developers is growing, which might be mostly thanks to
 relatively few dedicated committers rather than an overall increase in
 the population.

I think it's probably more to do with the opinion of version control
is held in by the Python and Perl communities.

Less pejoratively, Perl's main strength is simple throwaway or single-
task scripts that (paraphrasing the perl man page) require a bit more
complexity than sed or awk; these sorts of things don't really need
version control.  Python is more geared to complex applications, so
version control comes into play a lot more.  It's not a surprise that
Python would have more commits then, even back as far as 2000 when
Perl was the shizzle.


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


Re: reloading modules and isinstance()

2007-12-06 Thread Jean-Paul Calderone
On Thu, 06 Dec 2007 12:21:01 +0100, Diez B. Roggisch [EMAIL PROTECTED] 
wrote:
Tlis schrieb:
 On 5 Dec, 13:18, Steven D'Aprano [EMAIL PROTECTED]
 cybersource.com.au wrote:
 On Tue, 04 Dec 2007 15:41:48 +0100, Diez B. Roggisch wrote:
 You just discovered one reason why reload() is a bad idea and IMHO
 shouldn't be used at all - as tempting it might be.
 I disagree -- I find reload() extremely useful for interactively testing
 modules. But I would never dream of using it in production code!

 --
 Steven.

 Please note, that I was using the 'Reload modules' functionality of
 the software system in use, rather than the reload() function
 directly. I admit, though, that in the background it just may call
 reload() ...

 With all the problems of the reload() function, I still hope, that
 there should be possible to write a safe module 'reloader', that would
 fix the references, as required (e.g. by changing the
 variable.__class__ references). This should be provided by every
 serious Python development environment.

Wishful thinking. If I do

foo = {}
foo['some_key'] = somemodule.SomeClass

somewhere in my code, how do you suppose is reload(somemodule) to know
where in all the world I keep references to that class? Thus it would
essentially have to scan all references to anything, all list contents,
all class-properties, all everything. Which is not feasible.

Who says it isn't feasible?

http://twistedmatrix.com/trac/browser/trunk/twisted/python/rebuild.py

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


Re: reloading modules and isinstance()

2007-12-06 Thread Diez B. Roggisch
Jean-Paul Calderone schrieb:
 On Thu, 06 Dec 2007 12:21:01 +0100, Diez B. Roggisch 
 [EMAIL PROTECTED] wrote:
 Tlis schrieb:
 On 5 Dec, 13:18, Steven D'Aprano [EMAIL PROTECTED]
 cybersource.com.au wrote:
 On Tue, 04 Dec 2007 15:41:48 +0100, Diez B. Roggisch wrote:
 You just discovered one reason why reload() is a bad idea and IMHO
 shouldn't be used at all - as tempting it might be.
 I disagree -- I find reload() extremely useful for interactively 
 testing
 modules. But I would never dream of using it in production code!

 -- 
 Steven.

 Please note, that I was using the 'Reload modules' functionality of
 the software system in use, rather than the reload() function
 directly. I admit, though, that in the background it just may call
 reload() ...

 With all the problems of the reload() function, I still hope, that
 there should be possible to write a safe module 'reloader', that would
 fix the references, as required (e.g. by changing the
 variable.__class__ references). This should be provided by every
 serious Python development environment.

 Wishful thinking. If I do

 foo = {}
 foo['some_key'] = somemodule.SomeClass

 somewhere in my code, how do you suppose is reload(somemodule) to know
 where in all the world I keep references to that class? Thus it would
 essentially have to scan all references to anything, all list contents,
 all class-properties, all everything. Which is not feasible.
 
 Who says it isn't feasible?
 
 http://twistedmatrix.com/trac/browser/trunk/twisted/python/rebuild.py

Nice try - for sure. But it seems to be geared towards special cases, 
not a general-purpose now reloading really works implementation.

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


Re: An Object's Type

2007-12-06 Thread Diez B. Roggisch
paul schrieb:
 Bruno Desthuilliers schrieb:
 [EMAIL PROTECTED] a écrit :
 Hi,

 Is it possible to find out if an object is of a certain type or of a
 type derived from this type?

 You have the answer, thanks to Diez and Christian. Now unless you have 
 a *very* compelling reason to check the type of an object, *just 
 forget about it*. 9 times out of 10, this is fighting against the 
 language's type system (hint: google for duck typing).
 So I have to give up the concept that argument types are part of the 
 interface or signature? Honestly, I don't like that. Granted; not having 
 strict type checking makes for great flexibility but the price is you 
 either write typchecking code or let the error propagate into the 
 function or method. I hope type annotations in py3k will allow for 
 something like constraints in C# where you can tell the caller right 
 away she's doing something wrong.


This is a dead horse beaten into the ground, full way through to china. 
If you want typechecking - use a statically checked language. After all, 
if you like to constrain yourself to certain types - why not benefit 
from a compiler then?

I for once prefer to be able to pass object that behaves like e.g. a 
file - think StringIO - to something taking a file, instead of 
introducing a interface-maze like the java.io-hierarchy to capture each 
possible thinkable aspect of file IO in a separate interface - and then 
hoping that the third party library was careful enough to only require 
what is really needed.

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


Re: SimpleXMLRPCServer interruptable?

2007-12-06 Thread Bret
On Dec 5, 10:00 pm, Edward Kozlowski [EMAIL PROTECTED] wrote:
 On Dec 5, 10:19 pm, Edward Kozlowski [EMAIL PROTECTED] wrote:



  On Dec 5, 6:22 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:

   En Wed, 05 Dec 2007 18:20:35 -0300, Bret [EMAIL PROTECTED] escribió:

I just tried changing this so that I now have a threading.Event()
called self.done, which is set within the body of the shutdown()
method.  The serverWrapper loop now looks like this:

def serverWrapper():
while True:
server.handle_request()
if self.done.isSet():
break

This works, but only if I follow the shutdown() rpc call a few seconds
later with ... something else to cause handle_request() to complete
again.  Obviously, not quite the right approach

   You could try setting a reasonable timeout on the listening socket; I
   would override the server_bind method, calling self.socket.settimeout(xxx)
   before calling the inherited method. I've never actually done it with a
   SimpleXMLRPCServer, but *should* work. Don't use a very small timeout,
   because it affects *all* subsequent operations.

   --
   Gabriel Genellina

  Try this:

  def __init__(self, host, port):
  self.done = False
  server = SimpleXMLRPCServer((host, port))
  :
  : Bunch of server.register_function calls
  :
  def serverWrapper():
  try:
  while not self.done:
  server.handle_request()
  except:
  pass

  Your shutdown method becomes:

  def shutdown(self):
  self.done = True

  HTH

  -Edward Kozlowski

 Sorry about the first post, I shot from the hip and had to make a few
 more modifications to make it 'working' code.  The example below works
 fine for me.

 import SimpleXMLRPCServer

 class myServer:
 def __init__(self, host, port):
 self.done = False
 self.server = SimpleXMLRPCServer.SimpleXMLRPCServer((host,
 port))

 def shutdown(self):
 self.done = True
 return 0

 def getName(self):
 return Hey, I'm Ed

 def serverWrapper(self):
 self.server.register_function(self.getName)
 self.server.register_function(self.shutdown)
 try:
 while not self.done:
 self.server.handle_request()
 except:
 pass

 if __name__ == __main__:
 myServer('localhost', 6058).serverWrapper()

  s.getName()
 Hey, I'm Ed
  s.shutdown()

 0

Thanks to all!  I'm now keeping a file of my own snippets in hardcopy
so I won't lose them next time I change jobs.  :-)


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


Re: Python is not a good name, should rename to Athon

2007-12-06 Thread Boris Borcic
Piet van Oostrum wrote:
 Adrian Cherry [EMAIL PROTECTED] (AC) wrote:
 
 AC For that matter C# is no better, I thought that # was pronounced 
 AC hash, I still refer to C# as C-hash.
 
 Are you musically illiterate?

Note that the notation for the note (!) isn't universal. French speakers for 
instance write that one do# and call it do dièze. C# reads as unpronounceable 
linenoise to them.







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


Re: An Object's Type

2007-12-06 Thread Bruno Desthuilliers
paul a écrit :
 Bruno Desthuilliers schrieb:
 [EMAIL PROTECTED] a écrit :
 Hi,

 Is it possible to find out if an object is of a certain type or of a
 type derived from this type?

 You have the answer, thanks to Diez and Christian. Now unless you have 
 a *very* compelling reason to check the type of an object, *just 
 forget about it*. 9 times out of 10, this is fighting against the 
 language's type system (hint: google for duck typing).

 So I have to give up the concept that argument types are part of the 
 interface or signature?

Nope - you have to give up the notion of type you learned from 
statically typed languages, and get used to the one used in dynamically 
typed languages. Same word, different concept, really.

 Honestly, I don't like that. Granted; not having 
 strict type checking makes for great flexibility but the price is you 
 either write typchecking code or let the error propagate into the 
 function or method.

Just tell me: what will happens if, *in Python*, you write typechecking 
code ? Surely, when you'll (possibly wrongly[1]) conclude you don't 
have the correct type (meaning: the one you expected when writing your 
code[1]), you'll raise an exception, won't you ? (I can't imagine what 
else...). So ask yourself: in which way will the final result be 
different from would very probably happens without the typecheking 
code ? In *both* cases, you end up with a runtime exception.

Granted, without typechecking, there can be a couple corner cases 
where you end up with incorrect results instead of an exception (like 
your user passed a string where you expected a sequence which is *not* a 
string). These corner cases might be worth the most minimal possible 
check. As far as I'm concerned, I've run into this kind of corner case 
perhaps half a dozen time in 7+ years. And usually because I (as a user 
of someone else's code) failed to read the doc - which is my 
responsability, the author's.


[1] dynamic typing means that two totally unrelated types may both 
implement the expected (implied) interface. You just can't hope to know 
by advance the exhaustive list of classes that will implement the 
interface your code expects.

 I hope type annotations in py3k will allow for 
 something like constraints in C# where you can tell the caller right 
 away she's doing something wrong.

Lord have mercy. As Diez mentions, if you want static type checking, 
then don't use a dynamically typed language. But trying to fight against 
the language is not going to buy you much.

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


Re: reloading modules and isinstance()

2007-12-06 Thread Jean-Paul Calderone
On Thu, 06 Dec 2007 13:59:00 +0100, Diez B. Roggisch [EMAIL PROTECTED] 
wrote:
 [snip]

 Who says it isn't feasible?

 http://twistedmatrix.com/trac/browser/trunk/twisted/python/rebuild.py

Nice try - for sure. But it seems to be geared towards special cases,
not a general-purpose now reloading really works implementation.


What special cases?  I won't argue that it works for every case, but the
failure modes are really defined by special cases in Python, not the
other way around.  Maybe that's what you meant, I'm not sure.

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


ANN: UliPad 3.8 released!

2007-12-06 Thread limodou
UliPad is a flexible editor, based on wxPython. It's has many features,just
like:class browser, code auto-complete, html viewer, directory browser, wizard,
etc. The main feature is the usage of mixin. This makes UliPad can be
extended easily. So you can write your own mixin or plugin, or simple script,
these can be easy and seamless integrated with UliPad.

What's new in 3.8
===

New Features and Changes:

#. Add mako template syntax highlight support
#. Add new option in preference, [Python]-Automatically save modified file
   when running python program, if it's checked, it'll automatically save
   the modified file.
#. Add Shift+Delete = Cut, Shift+Insert = Paste
#. Upgrade winpdb to lastest version
#. Now you can set pythonpath option in config.ini/[default],
   and ulipad will insert it into the sys.path. pythonpath can
   be a string or a string list of directory.
#. Svn support, you should install pysvn first, and also support proxy.
#. Change long line indicator default is true.
#. Add doctest support, you can run the doctest of current document in UliPad
#. Add time stamp info in debug and error file
#. Replace the shell window popup menu, and add Copy Without Prompts
   and Paste and Run menu items. And if the result cann't be convert to
   unicode, then display the result as repr().
#. Script Manager can find menu name from the script content, you
   can define it as a comment line, format is: #\s*name:(.*)$
#. Add Run in Shell menu item in Editor context menu
#. Add script and shell key binding. Change Shell to External Tool
#. Change Find in Files dialog to panel
#. Using meide module to create Preference dialog
#. Add an option to control if show the docstring in class browser window.
#. Don't create a tmp file again, directly save the file
#. Improve Find in Files process with thread
#. Add some config.ini options support in Preference Dialog
#. Refactor Find  Replace with pane, but not dialog
#. Made Open Command Here work in Linux
#. Add dropfile plugin. thanks Tyberius Prime. Now you can drop files on
   toolbar, then UliPad will open it. Just like drop files on Directory
   Browser window.
#. Add new custom lexer class and refactor related lexer process
#. Upgrade FlatNotebook.py to lastest version, thanks to swordsp
#. Improve default identifiers process, add type judgement
#. Add pylint plugin

Bug fix:

#. Fix print bug, add print line number functionality
#. Fix snippet template indent bug(when using tab mode, the '\t'
   in template will be replaced with spaces). And you can press
   Alt+Q to cancel current snippet.
#. Fix press Ctrl+B jump position is not correct bug.
#. Fix that when you change the file type, the icon in directory
   and dynamic menu don't change bug
#. Fix line number margin width, and find back End-of-line Marker menu
#. Fix adding empty directory error
#. Fix open un-exists file will popup two message dialog bug
#. Fix line end mix checking bug also including twice prompt dialog bug
#. Fix webbrowser bug. Thanks Tom Eubank
#. Fix message console postion bug, thanks for swordsp

UliPad has been ported to code.google.com, so you can visit the new
project site at: http://code.google.com/p/ulipad, and also visit the
new svn address. Recommends using source version.

Source Code: http://ulipad.googlecode.com/files/ulipad.3.8.zip
Win Execute Code: http://ulipad.googlecode.com/files/ulipad.3.8.exe

If you have any suggestion or question, please subscribe the ulipad
mailling list: http://groups.google.com/group/UliPad

-- 
I like python!
UliPad The Python Editor: http://code.google.com/p/ulipad/
meide wxPython UI module: http://code.google.com/p/meide/
My Blog: http://www.donews.net/limodou
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is not a good name, should rename to Athon

2007-12-06 Thread Piet van Oostrum
 Adrian Cherry [EMAIL PROTECTED] (AC) wrote:

AC Piet van Oostrum [EMAIL PROTECTED] wrote in
AC news:[EMAIL PROTECTED]: 

 Adrian Cherry [EMAIL PROTECTED] (AC) wrote:
 
AC For that matter C# is no better, I thought that # was
 pronounced AC hash, I still refer to C# as C-hash.
 
 Are you musically illiterate?

AC Yup! The limits of my musically ability is

AC Spam, spam, spam, spam.
AC Lovely spam! Wonderful spaaam!
AC Lovely spam! Wonderful spam.
AC Spa-a-a-a-a-a-a-am! Spa-a-a-a-a-a-a-am!

AC Is that a problem? It's still a hash sign to me.

No problem, but if you know music notation, C# will ring a bell.
-- 
Piet van Oostrum [EMAIL PROTECTED]
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


splitting a words of a line

2007-12-06 Thread Sumit
Hi ,
   I am trying to splitt  a Line whihc is below of format ,

AzAccept PLYSSTM01 [23/Sep/2005:16:14:28 -0500] 162.44.245.32 CN=
cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk
Secure,DC=customer,DC=rxcorp,DC=com plysmhc03zp GET /mci/performance/
SelectProducts.aspx?
p=0V=Ca=29menu=adhoc [d4b62ca2-09a0-4334622b-0e1c-03c42ba5] [0]

Here all the string whihc i want to split is
-
AzAccept
PLYSSTM01
[23/Sep/2005:16:14:28 -0500]
162.44.245.32
CN= cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk
Secure,DC=customer,DC=rxcorp,DC=com
GET
/mci/performance/SelectProducts.aspx?p=0V=Ca=29menu=adhoc
d4b62ca2-09a0-4334622b-0e1c-03c42ba5
0


i am trying to use re.split() method to split them , But unable to get
the exact result .

Any help on this is highly appriciated .

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


which configparse?

2007-12-06 Thread Neal Becker
I have all my options setup with optparse.  Now, I'd like to be able to
parse an ini file to set defaults (that could be overridden by command line
switches).

I'd like to make minimal change to my working optparse setup (there are lots
of options - I don't want to duplicate all the cmdline parsing with ini
file parsing code)

I've looked at configparse, cfgparse, iniparse.

configparse looks like what I want, but it seems last commit was 2years
ago.

What is the best choice?

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


multidimensional arrays

2007-12-06 Thread Horacius ReX
in python, when I want to use arrays, I follow this way;

DATA = [0] * nint

and when I want to use I do;



DATA[i] = 

do you know how to do similar but in two dimensions ?

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


Re: multidimensional arrays

2007-12-06 Thread bearophileHUGS
Horacius ReX:
 do you know how to do similar but in two dimensions ?

 nr = 3
 nc = 4
 [[None] * nc for _ in xrange(nr)]
[[None, None, None, None], [None, None, None, None], [None, None,
None, None]]

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleXMLRPCServer interruptable?

2007-12-06 Thread Bret
On Dec 6, 7:04 am, Bret [EMAIL PROTECTED] wrote:
 On Dec 5, 10:00 pm, Edward Kozlowski [EMAIL PROTECTED] wrote:



  On Dec 5, 10:19 pm, Edward Kozlowski [EMAIL PROTECTED] wrote:

   On Dec 5, 6:22 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:

En Wed, 05 Dec 2007 18:20:35 -0300, Bret [EMAIL PROTECTED] escribió:

 I just tried changing this so that I now have a threading.Event()
 called self.done, which is set within the body of the shutdown()
 method.  The serverWrapper loop now looks like this:

 def serverWrapper():
 while True:
 server.handle_request()
 if self.done.isSet():
 break

 This works, but only if I follow the shutdown() rpc call a few seconds
 later with ... something else to cause handle_request() to complete
 again.  Obviously, not quite the right approach

You could try setting a reasonable timeout on the listening socket; I
would override the server_bind method, calling 
self.socket.settimeout(xxx)
before calling the inherited method. I've never actually done it with a
SimpleXMLRPCServer, but *should* work. Don't use a very small timeout,
because it affects *all* subsequent operations.

--
Gabriel Genellina

   Try this:

   def __init__(self, host, port):
   self.done = False
   server = SimpleXMLRPCServer((host, port))
   :
   : Bunch of server.register_function calls
   :
   def serverWrapper():
   try:
   while not self.done:
   server.handle_request()
   except:
   pass

   Your shutdown method becomes:

   def shutdown(self):
   self.done = True

   HTH

   -Edward Kozlowski

  Sorry about the first post, I shot from the hip and had to make a few
  more modifications to make it 'working' code.  The example below works
  fine for me.

  import SimpleXMLRPCServer

  class myServer:
  def __init__(self, host, port):
  self.done = False
  self.server = SimpleXMLRPCServer.SimpleXMLRPCServer((host,
  port))

  def shutdown(self):
  self.done = True
  return 0

  def getName(self):
  return Hey, I'm Ed

  def serverWrapper(self):
  self.server.register_function(self.getName)
  self.server.register_function(self.shutdown)
  try:
  while not self.done:
  self.server.handle_request()
  except:
  pass

  if __name__ == __main__:
  myServer('localhost', 6058).serverWrapper()

   s.getName()
  Hey, I'm Ed
   s.shutdown()

  0

 Thanks to all!  I'm now keeping a file of my own snippets in hardcopy
 so I won't lose them next time I change jobs.  :-)

 Bret

Oops, this actually misses part of the problem -- I need to construct
this server programmatically, so imbedding the call to start the
server in the if __name__ construct doesn't work.  If I start it
within the __init__, then the object that's creating it gets stuck
waiting for it to finish, which it never will.  I need this to be
autonomous, which is why I was trying to do the start of the server in
a separate thread, but that doesn't seem to work either (that's what's
causing my process to need the second call; the thread completes the
loop and enters the next handle_request() call before the event or
boolean gets set).

Basically, I need a way for one server to start other autonomous
servers without waiting on them, and still retain the ability to shut
them down when their work is done.

Back to the keyboard.  ;-)


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


Re: which configparse?

2007-12-06 Thread Shane Geiger
Best, is naturally, a somewhat subjective evaluation.  That being said,
configparser is well regarded.  I have also seen these two options that
you might want to check out:

http://wiki.woodpecker.org.cn/moin/Dict4Ini
http://www.voidspace.org.uk/python/configobj.html


 I have all my options setup with optparse.  Now, I'd like to be able to
 parse an ini file to set defaults (that could be overridden by command line
 switches).

 I'd like to make minimal change to my working optparse setup (there are lots
 of options - I don't want to duplicate all the cmdline parsing with ini
 file parsing code)

 I've looked at configparse, cfgparse, iniparse.

 configparse looks like what I want, but it seems last commit was 2years
 ago.

 What is the best choice?

   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: An Object's Type

2007-12-06 Thread Hrvoje Niksic
Bruno Desthuilliers [EMAIL PROTECTED]
writes:

 So ask yourself: in which way will the final result be different
 from would very probably happens without the typecheking code ? In
 *both* cases, you end up with a runtime exception.

The idea behind such type checks is to make sure type errors are
caught as early as possible.  Exceptions caught later, the philosophy
goes, are harder to debug because by then the cause of the problem can
be obscured.  Consider an object of the wrong type passed to a method:
the method can store the object in its own instance attribute, and
keep working on something else.  Then, much later, the faulty object
gets actually used and the error is raised.  By the time the exception
is thrown, you have no idea where the offending object came from.

Personally, I consider the loss in flexibility to outweigh any
benefits of overeager type checks.  Besides, type checks are only one
of the many possible constraints you could check in your objects, yet
proponents of type checks tend to treat them as somehow much more
important or fundamental.

Hopefully Python 3's support for abstract base classes will provide a
standard way to have our cake and eat it by allowing declarative
subtypes.  That way type checks will be possible to prevent accidents,
but without compromising flexibility.  Pure duck typing will be made
a bit more verbose, but not impossibly so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multidimensional arrays

2007-12-06 Thread Jeremy Sanders
Horacius ReX wrote:

 do you know how to do similar but in two dimensions ?

Investigate the numpy module if you are dealing with numbers.

Jeremy

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


Re: multidimensional arrays

2007-12-06 Thread Remco Gerlich
Hi,

DATA = [ [ 0 for i in range(ncolumns) ] for i in range(nrows) ]

Is one way.

DON'T do it like this:

row = [0] * ncolumns
data = [ row ] * nrows # WRONG!

Since after that, every row is the exact same object; if you set data[0][0]
= 1, the first element of _every_ row is 1.

But I guess you already found out about that :-)

That said, are you sure a list of lists is the best data structure for what
you're trying to do? I keep being surprised by Python code that uses other
data structures in clever ways; lists of lists seem to be pretty rare!

Remco Gerlich

On Dec 6, 2007 4:29 PM, Horacius ReX [EMAIL PROTECTED] wrote:

 in python, when I want to use arrays, I follow this way;

 DATA = [0] * nint

 and when I want to use I do;

 

 DATA[i] = 

 do you know how to do similar but in two dimensions ?

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

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

Re: SimpleXMLRPCServer interruptable?

2007-12-06 Thread Bret
On Dec 6, 7:04 am, Bret [EMAIL PROTECTED] wrote:
 On Dec 5, 10:00 pm, Edward Kozlowski [EMAIL PROTECTED] wrote:



  On Dec 5, 10:19 pm, Edward Kozlowski [EMAIL PROTECTED] wrote:

   On Dec 5, 6:22 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:

En Wed, 05 Dec 2007 18:20:35 -0300, Bret [EMAIL PROTECTED] escribió:

 I just tried changing this so that I now have a threading.Event()
 called self.done, which is set within the body of the shutdown()
 method.  The serverWrapper loop now looks like this:

 def serverWrapper():
 while True:
 server.handle_request()
 if self.done.isSet():
 break

 This works, but only if I follow the shutdown() rpc call a few seconds
 later with ... something else to cause handle_request() to complete
 again.  Obviously, not quite the right approach

You could try setting a reasonable timeout on the listening socket; I
would override the server_bind method, calling 
self.socket.settimeout(xxx)
before calling the inherited method. I've never actually done it with a
SimpleXMLRPCServer, but *should* work. Don't use a very small timeout,
because it affects *all* subsequent operations.

--
Gabriel Genellina

   Try this:

   def __init__(self, host, port):
   self.done = False
   server = SimpleXMLRPCServer((host, port))
   :
   : Bunch of server.register_function calls
   :
   def serverWrapper():
   try:
   while not self.done:
   server.handle_request()
   except:
   pass

   Your shutdown method becomes:

   def shutdown(self):
   self.done = True

   HTH

   -Edward Kozlowski

  Sorry about the first post, I shot from the hip and had to make a few
  more modifications to make it 'working' code.  The example below works
  fine for me.

  import SimpleXMLRPCServer

  class myServer:
  def __init__(self, host, port):
  self.done = False
  self.server = SimpleXMLRPCServer.SimpleXMLRPCServer((host,
  port))

  def shutdown(self):
  self.done = True
  return 0

  def getName(self):
  return Hey, I'm Ed

  def serverWrapper(self):
  self.server.register_function(self.getName)
  self.server.register_function(self.shutdown)
  try:
  while not self.done:
  self.server.handle_request()
  except:
  pass

  if __name__ == __main__:
  myServer('localhost', 6058).serverWrapper()

   s.getName()
  Hey, I'm Ed
   s.shutdown()

  0

 Thanks to all!  I'm now keeping a file of my own snippets in hardcopy
 so I won't lose them next time I change jobs.  :-)

 Bret

For completeness, what I ended up doing is this:

server = SimpleXMLRPCServer((host, port))
server.socket.settimeout(0.1)

ServerWrapper became:

def ServerWrapper():
while True:
try:
server.handle_request()
if self.done.isSet():
break
except timeout:
pass

And that seems to do the trick!  Giving the socket a timeout allows me
to check the Event more frequently and catch the change within a
reasonable time.

Thanks again, Ed and Gabriel.


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


Re: Python is not a good name, should rename to Athon

2007-12-06 Thread Hertha Steck
Boris Borcic wrote:

 Piet van Oostrum wrote:
 Adrian Cherry [EMAIL PROTECTED] (AC) wrote:
 
 AC For that matter C# is no better, I thought that # was pronounced
 AC hash, I still refer to C# as C-hash.
 
 Are you musically illiterate?
 
 Note that the notation for the note (!) isn't universal. French speakers
 for instance write that one do# and call it do dièze. C# reads as
 unpronounceable linenoise to them.

In a german text it would be Cis. And in real musical notation
the sharpener doesn't look like '#', only similar. 

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

JSON

2007-12-06 Thread belred
i tried a couple python json libraries. i used simplejson on the
server and was using cjson on the client, but i ran into this issue.
i'm now using simplejson on both sides, but i'm still interested in
this issue.  did i do something wrong? is there a bug in one of the
libraries? or something i don't understand about the json spec?


i problem is the line where i call cjson.decode() below:

 import simplejson
 import cjson

 sj = simplejson.dumps('http://server.com')
 sj
'http:\\/\\/server.com'
 cj = cjson.encode('http://server.com')
 cj
'http://server.com;'
 simplejson.loads(cj)
u'http://server.com'
 cjson.decode(cj)
'http://server.com'
 simplejson.loads(sj)
u'http://server.com'
 cjson.decode(sj)
'http:\\/\\/server.com' # is this correct


is that last statement really correct?

thanks,

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


New subclass vs option in __init__

2007-12-06 Thread Kurt Smith
Hi List:

Class inheritance noob here.

For context, I have the following base class and subclass:

class Base(object):
def __init__(self, val):
self.val = val

class Derived1(Base):
def __init__(self, val):
super(Derived1, self).__init__(val)

I'm curious as to other's thoughts on the following: when
incorporating optional behavior differences for a subclass, do you a)
make a new subclass (e.g., 'Derived2') and override (and add new)
methods that would encapsulate the new behavior, or b) keep the same
subclass around (i.e., 'Derived1'), but add an initialization option
that would specify the different behavior, and check for the value of
this option in the different methods?

It would seem that there are cases where one would be preferable over
the other: a) when the new behavior would modify a large portion of
the existing subclass, making a new subclass would be ideal; b) when
the new behavior changes only slightly the existing subclass, perhaps
a simple default option in the subclass's __init__ method would be
best.  Where is the tipping point?  Since one cannot predict what
direction the new behavior might take things, should one usually err
on the side of a new subclass?  Is option b) just being lazy?  Is a)
too verbose in many situations?

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


pipeline encoding

2007-12-06 Thread Tomasz Toczyski
My locale is set to UTF-8. The command:
python -c print u'\u03A9'
gives me the desired result and doesn't produce any error.

But when I want to redirect the output to a file I invoke:
python -c print u'\u03A9'  file.txt
I get an error:

File string, line 1, in module
UnicodeEncodeError: 'ascii' codec can't encode character u'\u03a9' in 
position 0: ordinal not in range(128)

How to cope with it?

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


Best way to merge/sort two sorted lists?...

2007-12-06 Thread Aaron Watters
...is to forget they are sorted???

While trying to optimize some NUCULAR libraries I discovered
that the best way to merge 2 sorted lists together
into a new sorted list is to just append
them and re-sort.  The following test case demonstrates this.
It can be criticized in many ways: it only tests lists of the same
size,
it only uses hashed data, etcetera...
Still, my testing shows resort everything is consistently
two times faster than an explicit python merge even for fairly large
data.

I'm beginning to think
a sorted list merger might make a nice tiny extension module
(at least for my purposes).

See timing demonstration code below.  Let me know if there
is a better way or if the test is fatally flawed, please.

  --- Aaron Watters

http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=greedy+bastard

==snip: test code below
test different ways to merge two sorted lists

def ObviousMerge(L1, L2):
obvious way
len1 = len(L1)
len2 = len(L2)
resultlen = len1+len2
result = [None] * resultlen
count = 0
index1 = 0
index2 = 0
while countresultlen:
if index1len1:
elt1 = L1[index1]
if index2len2:
elt2 = L2[index2]
if elt1elt2:
result[count] = elt1
index1+=1
else:
result[count] = elt2
index2+=1
else:
result[count] = elt1
index1+=1
else:
result[count] = L2[index2]
index2+=1
count+=1
return result

def AggregateTailMerge(L1, L2):
obvious way, aggregating the tail
len1 = len(L1)
len2 = len(L2)
resultlen = len1+len2
result = [None] * resultlen
count = 0
index1 = 0
index2 = 0
while index1len1 and index2len2:
elt1 = L1[index1]
elt2 = L2[index2]
if elt1elt2:
result[count] = elt1
index1+=1
else:
result[count] = elt2
index2+=1
count+=1
if index1len1:
result[count:] = L1[index1:]
if index2len2:
result[count:] = L2[index2:]
return result

# could aggregate head and tail using bisect: skipped

def ResortEverythingMerge(L1, L2):
aggregate everything using list append and sort
result = L1+L2
result.sort()
return result

mergeFunctions = [ResortEverythingMerge, ObviousMerge,
AggregateTailMerge, ]


# make some test data
def makeAListOfHashes(length, data):
import md5
return [md5.md5(str(i)+data).hexdigest() for i in xrange(length)]

print constructing global test data

SIZES = [10, 100, 1000, 1, 10, 100]

LISTS = [ (L, makeAListOfHashes(L,A), makeAListOfHashes(L, B) )
for L in SIZES ]

for (length, L1, L2) in LISTS:
L1.sort()
L2.sort()

print done with making global test data
print

def timings(mergerFunction):
from time import time
fname = mergerFunction.__name__
print
print now timing, mergerFunction
print
for (length, L1, L2) in LISTS:
now = time()
result = f(L1, L2)
elapsed = time() - now
printfor, length, elapsed %3.5f%elapsed, for, fname

if __name__==__main__:
print
print running timings
for f in mergeFunctions:
timings(f)

 snip run output below:
constructing global test data
done with making global test data

running timings

now timing function ResortEverythingMerge at 0x204f4de8

   for 10 elapsed 0.3 for ResortEverythingMerge
   for 100 elapsed 0.6 for ResortEverythingMerge
   for 1000 elapsed 0.00057 for ResortEverythingMerge
   for 1 elapsed 0.00626 for ResortEverythingMerge
   for 10 elapsed 0.12484 for ResortEverythingMerge
   for 100 elapsed 1.60117 for ResortEverythingMerge

now timing function ObviousMerge at 0x204f47d0

   for 10 elapsed 0.8 for ObviousMerge
   for 100 elapsed 0.00027 for ObviousMerge
   for 1000 elapsed 0.00259 for ObviousMerge
   for 1 elapsed 0.02587 for ObviousMerge
   for 10 elapsed 0.27862 for ObviousMerge
   for 100 elapsed 2.89965 for ObviousMerge

now timing function AggregateTailMerge at 0x204f4cf8

   for 10 elapsed 0.8 for AggregateTailMerge
   for 100 elapsed 0.00025 for AggregateTailMerge
   for 1000 elapsed 0.00246 for AggregateTailMerge
   for 1 elapsed 0.02366 for AggregateTailMerge
   for 10 elapsed 0.26594 for AggregateTailMerge
   for 100 elapsed 2.77103 for AggregateTailMerge
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is not a good name, should rename to Athon

2007-12-06 Thread Bruno Desthuilliers
Boris Borcic a écrit :
 Piet van Oostrum wrote:
 
 Adrian Cherry [EMAIL PROTECTED] (AC) wrote:


 AC For that matter C# is no better, I thought that # was pronounced 
 AC hash, I still refer to C# as C-hash.


 Are you musically illiterate?
 
 
 Note that the notation for the note (!) isn't universal. French speakers 
 for instance write that one do# and call it do dièze. C# reads as 
 unpronounceable linenoise to them.

Strange as it might be, some french speakers also know the english 
notation...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New subclass vs option in __init__

2007-12-06 Thread Bruno Desthuilliers
Kurt Smith a écrit :
 Hi List:
 
 Class inheritance noob here.
 
 For context, I have the following base class and subclass:
 
 class Base(object):
 def __init__(self, val):
 self.val = val
 
 class Derived1(Base):
 def __init__(self, val):
 super(Derived1, self).__init__(val)
 
 I'm curious as to other's thoughts on the following: when
 incorporating optional behavior differences for a subclass, do you a)
 make a new subclass (e.g., 'Derived2') and override (and add new)
 methods that would encapsulate the new behavior, or b) keep the same
 subclass around (i.e., 'Derived1'), but add an initialization option
 that would specify the different behavior, and check for the value of
 this option in the different methods?

You forgot the strategy pattern : extract the different behaviours into 
other objects (in Python, usually callback functions or custom 
callables) that are passed to the initializer and called when 
appropriate. This keeps a clean encapsulation of variations (ie you 
don't have to add new conditions and tests in your class) while avoiding 
class proliferation.

Inheritance - while useful - is a bit oversold IMHO, specially in the 
context of a dynamic language. FWIW, inheritance is just a special case 
of composition/delegation...
-- 
http://mail.python.org/mailman/listinfo/python-list


ANNOUNCE: Resolver One public Beta now live

2007-12-06 Thread giles . thomas
We're proud to announce that today Resolver One, our flagship
application, entered its public Beta phase.  It can be downloaded from
http://www.resolversystems.com/download/ (free registration
required), and we would very much welcome feedback from the Python
community.

Resolver One is a Rapid Application Development tool for analysing and
presenting business data using a familiar spreadsheet interface - or,
to put it another way, it is a mash-up of a spreadsheet and an IDE.
As you enter formulae on the grid, it writes the equivalent IronPython
code for you.  As you add your own IronPython code, the grid is
updated.   This allows you to build applications that are much more
complex but better-structured than a traditional spreadsheet, much
more quickly than you could if you were using a regular programming
language.  You can then export the code and re-use it elsewhere in
your own programs.

It's primarily targetted at heavy users of number-crunching software,
such as financial firms and the biotech industry, but we use it
internally for all kinds of scripts, so we think any Python programmer
will be able to do fun stuff with it.

If you're interested in taking a look, please do download it or drop
us a line!


Best regards,

Giles
--
Giles Thomas
MD  CTO, Resolver Systems Ltd.
[EMAIL PROTECTED]
+44 (0) 20 7253 6372

17a Clerkenwell Road, London EC1M 5RD, UK
VAT No.: GB 893 5643 79 Registered in England and Wales as company
number 5467329.
Registered address: 843 Finchley Road, London NW11 8NA, UK
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pipeline encoding

2007-12-06 Thread Tomek Toczyski
Diez B. Roggisch:


 Python tries and guesses the stdout-encoding based on the terminal 
 settings. So the first print works.

 However, piping to a file means that it can't do so, because it doesn't 
 (and shouldn't) make any assumptions on the output encoding desired - 
 after all, it might be appending to a XML-file with e.g. latin1 
 encoding.

 So you need to explictely encode the unicode-object with the desired 
 encoding:


 python -c print u'\u03A9'.encode('utf-8')  file.txt

Thanks. It is a solutiona to my problem but:

Are there any command line option for telling python what encoding to use 
for stdout?

To be honest I have a more complicated program than the example that I 
have presented - there are many print commands inside and it is not very 
feasible for me to put .encode('utf-8') inside every print occurence.

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


Re: An Object's Type

2007-12-06 Thread Bruno Desthuilliers
Hrvoje Niksic a écrit :
 Bruno Desthuilliers [EMAIL PROTECTED]
 writes:
 
 
So ask yourself: in which way will the final result be different
from would very probably happens without the typecheking code ? In
*both* cases, you end up with a runtime exception.
  
 The idea behind such type checks is to make sure type errors are
 caught as early as possible.  Exceptions caught later, the philosophy
 goes, are harder to debug because by then the cause of the problem can
 be obscured.  Consider an object of the wrong type passed to a method:
 the method can store the object in its own instance attribute, and
 keep working on something else.  Then, much later, the faulty object
 gets actually used and the error is raised.  By the time the exception
 is thrown, you have no idea where the offending object came from.

That's the theory, yes. In practice, when such a situation occurs, it's 
usually easy to track down the problem: just add a temporary check in 
the method (or around it - using a decorator), rerun the program and 
you'll be done. Once the faulty code is corrected, remove the check.
-- 
http://mail.python.org/mailman/listinfo/python-list


logging.py: mutiple system users writing to same file getting permission errors.

2007-12-06 Thread evenrik
An a redhat box I have root, apache and other normal users run code
that uses the logging module to write to the same log file.  Since
umasks are set to 2 or 022 this gets permission errors.

I have fixed my issue by patching the logging code everywhere there is
an open for write with:
try:
old_umask = os.umask(0)
# open for write here
finally:
os.umask(old_umask)

Is there a better way to solve this issue?
Are there any security problems with this solution other than the log
file not being protected?
-- 
http://mail.python.org/mailman/listinfo/python-list


Capture DOS error???

2007-12-06 Thread Tangen, Erik
Did you ever get a solution to this?
I am also in need of this solution.
Thanks,
Erik

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

Re: pipeline encoding

2007-12-06 Thread Rob Wolfe
Tomasz Toczyski [EMAIL PROTECTED] writes:

 My locale is set to UTF-8. The command:
 python -c print u'\u03A9'
 gives me the desired result and doesn't produce any error.

 But when I want to redirect the output to a file I invoke:
 python -c print u'\u03A9'  file.txt
 I get an error:

 File string, line 1, in module
 UnicodeEncodeError: 'ascii' codec can't encode character u'\u03a9' in
 position 0: ordinal not in range(128)

 How to cope with it?

If you print to a terminal Python can use terminal encoding,
but if you redirect to a file Python doesn't know
what encoding to use (e.g. how was encoded existing file) 
and refuses to guess.
You have to specify that encoding explicit:
python -c print u'\u03A9'.encode('utf-8')  file.txt

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


Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Robin Becker
Aaron Watters wrote:
 ...is to forget they are sorted???
code snipped

Aaron I just flung your python merge code into pyrex and the results show that 
the iteration overhead can be brought down without much effort. The real deal 
would presumably be to start using pointers into the result list rather than 
the 
generic python type code which I have used. I haven't done much of that with 
pyrex yet, but I believe others do that all the time with these predetermined 
list lengths. The pyrex code doesn't look too different from python that it 
puts 
them off (I guess). I'm guessing a lot of the pyrex time is spent incrementing 
and decrementing refcounts etc etc and that can clearly be made more efficient. 
Also since None is being used as a place holder we could eliminate that by 
using 
null or undefined initial contents for the result lists thus saving time 
decrementing None's refcount since each result list element is only accessed 
once.


start obvmerge.pyx
def PyxObviousMerge(L1, L2):
obvious way
cdef int len1, len2, resultlen, index1, index2
len1 = len(L1)
len2 = len(L2)
resultlen = len1+len2
result = [None] * resultlen
count = 0
index1 = 0
index2 = 0
while countresultlen:
if index1len1:
elt1 = L1[index1]
if index2len2:
elt2 = L2[index2]
if elt1elt2:
result[count] = elt1
index1 = index1+1
else:
result[count] = elt2
index2 = index2 + 1
else:
result[count] = elt1
index1 = index1+1
else:
result[count] = L2[index2]
index2=index2+1
count = count + 1
return result

def PyxAggregateTailMerge(L1, L2):
obvious way, aggregating the tail
cdef int len1, len2, resultlen, index1, index2
len1 = len(L1)
len2 = len(L2)
resultlen = len1+len2
result = [None] * resultlen
count = 0
index1 = 0
index2 = 0
while index1len1 and index2len2:
elt1 = L1[index1]
elt2 = L2[index2]
if elt1elt2:
result[count] = elt1
index1= index1+1
else:
result[count] = elt2
index2 = index2+1
count=count+1
if index1len1:
result[count:] = L1[index1:]
if index2len2:
result[count:] = L2[index2:]
return result
end  obvmerge.pyx


==test results
C:\code\users\robintmerge.py
constructing global test data
done with making global test data


running timings

now timing function ResortEverythingMerge at 0x00C150F0

for 10 elapsed 0.0 for ResortEverythingMerge
for 100 elapsed 0.0 for ResortEverythingMerge
for 1000 elapsed 0.0 for ResortEverythingMerge
for 1 elapsed 0.0 for ResortEverythingMerge
for 10 elapsed 0.06200 for ResortEverythingMerge
for 100 elapsed 0.78100 for ResortEverythingMerge

now timing function ObviousMerge at 0x00C15070

for 10 elapsed 0.0 for ObviousMerge
for 100 elapsed 0.0 for ObviousMerge
for 1000 elapsed 0.0 for ObviousMerge
for 1 elapsed 0.0 for ObviousMerge
for 10 elapsed 0.12500 for ObviousMerge
for 100 elapsed 1.32800 for ObviousMerge

now timing built-in function PyxObviousMerge

for 10 elapsed 0.0 for PyxObviousMerge
for 100 elapsed 0.0 for PyxObviousMerge
for 1000 elapsed 0.0 for PyxObviousMerge
for 1 elapsed 0.01600 for PyxObviousMerge
for 10 elapsed 0.09300 for PyxObviousMerge
for 100 elapsed 1.09400 for PyxObviousMerge

now timing function AggregateTailMerge at 0x00C150B0

for 10 elapsed 0.0 for AggregateTailMerge
for 100 elapsed 0.0 for AggregateTailMerge
for 1000 elapsed 0.0 for AggregateTailMerge
for 1 elapsed 0.0 for AggregateTailMerge
for 10 elapsed 0.12500 for AggregateTailMerge
for 100 elapsed 1.20300 for AggregateTailMerge

now timing built-in function PyxAggregateTailMerge

for 10 elapsed 0.0 for PyxAggregateTailMerge
for 100 elapsed 0.0 for PyxAggregateTailMerge
for 1000 elapsed 0.0 for PyxAggregateTailMerge
for 1 elapsed 0.0 for PyxAggregateTailMerge
for 10 elapsed 0.09400 for PyxAggregateTailMerge
for 100 elapsed 1.03100 for PyxAggregateTailMerge

C:\code\users\robin
-- 
Robin Becker

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


Re: pipeline encoding

2007-12-06 Thread Diez B. Roggisch
Tomasz Toczyski schrieb:
 My locale is set to UTF-8. The command:
 python -c print u'\u03A9'
 gives me the desired result and doesn't produce any error.
 
 But when I want to redirect the output to a file I invoke:
 python -c print u'\u03A9'  file.txt
 I get an error:
 
 File string, line 1, in module
 UnicodeEncodeError: 'ascii' codec can't encode character u'\u03a9' in 
 position 0: ordinal not in range(128)
 
 How to cope with it?

Python tries and guesses the stdout-encoding based on the terminal 
settings. So the first print works.

However, piping to a file means that it can't do so, because it doesn't 
  (and shouldn't) make any assumptions on the output encoding desired - 
after all, it might be appending to a XML-file with e.g. latin1 encoding.

So you need to explictely encode the unicode-object with the desired 
encoding:


python -c print u'\u03A9'.encode('utf-8')  file.txt


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


Re: An Object's Type

2007-12-06 Thread Chris Mellon
On Dec 6, 2007 5:52 AM, paul [EMAIL PROTECTED] wrote:
 Bruno Desthuilliers schrieb:
  [EMAIL PROTECTED] a écrit :
  Hi,
 
  Is it possible to find out if an object is of a certain type or of a
  type derived from this type?
 
  You have the answer, thanks to Diez and Christian. Now unless you have a
  *very* compelling reason to check the type of an object, *just forget
  about it*. 9 times out of 10, this is fighting against the language's
  type system (hint: google for duck typing).
 So I have to give up the concept that argument types are part of the
 interface or signature? Honestly, I don't like that. Granted; not having
 strict type checking makes for great flexibility but the price is you
 either write typchecking code or let the error propagate into the
 function or method. I hope type annotations in py3k will allow for
 something like constraints in C# where you can tell the caller right
 away she's doing something wrong.


You're Stockholmed to the gills by the crappy and nearly useless type
systems that you've been exposed to. If you're going to expound on the
merits of statically checked type systems, you should first gain some
experience with the ML family of languages, that actually have real
type systems without casts (like Python!), no escape hatches, and
guarantee the static type correctness of all programs.

Once you've done that, you'll hate the limited, verbose and cumbersome
C# type system and you'll be in a better situation to appreciate both
static and dynamic typing.

On a more pragmatic basis, there are only 2 kinds of type errors in Python:
1: The object passed doesn't implement the correct interface, and will
raise an error when called. This will be caught by a unit test.
2: The object passed implements something that looks like the right
interface, but implements it incorrectly. This will be caught by a
unit tests.

Note that both these errors will be caught by behavior exercising unit
tests and do not rely on any sort of typechecking code to be
written. Explicit typechecking in Python is done only when you need to
dispatch on type, not because you feel like generating spurious
errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Neil Cerutti
On 2007-12-06, Aaron Watters [EMAIL PROTECTED] wrote:
 ...is to forget they are sorted???

 While trying to optimize some NUCULAR libraries I discovered
 that the best way to merge 2 sorted lists together
 into a new sorted list is to just append
 them and re-sort.  The following test case demonstrates this.
 It can be criticized in many ways: it only tests lists of the same
 size,
 it only uses hashed data, etcetera...
 Still, my testing shows resort everything is consistently
 two times faster than an explicit python merge even for fairly large
 data.

 I'm beginning to think
 a sorted list merger might make a nice tiny extension module
 (at least for my purposes).

 See timing demonstration code below.  Let me know if there
 is a better way or if the test is fatally flawed, please.

   --- Aaron Watters

 http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=greedy+bastard

==snip: test code below
 test different ways to merge two sorted lists

 def ObviousMerge(L1, L2):
SNIP
 def AggregateTailMerge(L1, L2):
SNIP

Your merge functions are pretty complex; here's a simpler,
obvious solution:

def merge_sorted(a, b):
Merge two sorted lists into a new sorted list.

 merge_sorted(range(10), range(5))
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]

 merge_sorted(range(5), range(10))
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]

 merge_sorted(range(3), [])
[0, 1, 2]

 merge_sorted([], range(3))
[0, 1, 2]

 merge_sorted([], [])
[]

rval = []
aix, bix = 0, 0
astop, bstop = len(a), len(b)
while aix  astop and bix  bstop:
if a[aix]  b[bix]:
rval.append(a[aix])
aix += 1
else:
rval.append(b[bix])
bix += 1
while aix  astop:
rval.append(a[aix])
aix += 1
while bix  bstop:
rval.append(b[bix])
bix += 1
return rval

It should beat ResortEverything consistently once the lists
become larger than a certain size. Do you get better results at
all with the above function?

-- 
Neil Cerutti
The audience is asked to remain seated until the end of the recession.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Raymond Hettinger
On Dec 6, 9:30 am, Aaron Watters [EMAIL PROTECTED] wrote:

 While trying to optimize some NUCULAR libraries I discovered
 that the best way to merge 2 sorted lists together
 into a new sorted list is to just append
 them and re-sort.
 . . .
 I'm beginning to think
 a sorted list merger might make a nice tiny extension module
 (at least for my purposes).


See recipes:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491285
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305269

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


__iadd__ useless in sub-classed int

2007-12-06 Thread samwyse
For whatever reason, I need an inproved integer.  Sounds easy, let's
just subclass int:

 class test(int):
pass

Now let's test it:

 zed=test(0)
 zed.__class__
class '__main__.test'
 zed
0

So far, so good.  Now let's try incrementing:

 zed+=1
 zed
1
 zed.__class__
type 'int'

WTF??!
Is this a bug or is it the inevitable result of optimizing for the
case where all integers are indistinguishable?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pipeline encoding

2007-12-06 Thread Diez B. Roggisch
Tomek Toczyski schrieb:
 Diez B. Roggisch:
 

 Python tries and guesses the stdout-encoding based on the terminal 
 settings. So the first print works.

 However, piping to a file means that it can't do so, because it 
 doesn't (and shouldn't) make any assumptions on the output encoding 
 desired - after all, it might be appending to a XML-file with e.g. 
 latin1 encoding.

 So you need to explictely encode the unicode-object with the desired 
 encoding:


 python -c print u'\u03A9'.encode('utf-8')  file.txt
 
 Thanks. It is a solutiona to my problem but:
 
 Are there any command line option for telling python what encoding to 
 use for stdout?
 
 To be honest I have a more complicated program than the example that I 
 have presented - there are many print commands inside and it is not very 
 feasible for me to put .encode('utf-8') inside every print occurence.

No it hasn't, and it's easy enough remedied by doing


def eprint(msg):
 print msg.encode('utf-8')

and then doing

eprint('whatever')

instead of

print 'whatever'

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


Re: __iadd__ useless in sub-classed int

2007-12-06 Thread Diez B. Roggisch
samwyse schrieb:
 For whatever reason, I need an inproved integer.  Sounds easy, let's
 just subclass int:
 
 class test(int):
   pass
 
 Now let's test it:
 
 zed=test(0)
 zed.__class__
 class '__main__.test'
 zed
 0
 
 So far, so good.  Now let's try incrementing:
 
 zed+=1
 zed
 1
 zed.__class__
 type 'int'
 
 WTF??!
 Is this a bug or is it the inevitable result of optimizing for the
 case where all integers are indistinguishable?

There has been a lengthe thread over the semantics of __iadd__ a few 
weeks ago. It _can_ modify the object in question in-place (something 
not possible for ints anyway), but it will ALWAYS return a reference 
which will be set to the left-hand-side.

zed = zed.__iadd__(1)

So - you need to overload the __iadd__-method to return a test-instance.

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


Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Neil Cerutti
On 2007-12-06, Raymond Hettinger [EMAIL PROTECTED] wrote:
 On Dec 6, 9:30 am, Aaron Watters [EMAIL PROTECTED] wrote:

 While trying to optimize some NUCULAR libraries I discovered
 that the best way to merge 2 sorted lists together
 into a new sorted list is to just append
 them and re-sort.
  . . .
 I'm beginning to think
 a sorted list merger might make a nice tiny extension module
 (at least for my purposes).


 See recipes:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491285
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305269

That's fairly awesome.

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


Re: pipeline encoding

2007-12-06 Thread Martin v. Löwis
 Are there any command line option for telling python what encoding to
 use for stdout?

Not a command line option. However, you can wrap sys.stdout with a
stream that automatically performs an encoding. If all your print
statements output Unicode strings, you can do

sys.stdout = codecs.getwriter(utf-8)(sys.stdout)

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


Re: pipeline encoding

2007-12-06 Thread Rob Wolfe
Tomek Toczyski [EMAIL PROTECTED] writes:

 Are there any command line option for telling python what encoding to
 use for stdout?

 To be honest I have a more complicated program than the example that I
 have presented - there are many print commands inside and it is not
 very feasible for me to put .encode('utf-8') inside every print
 occurence.

You can use sitecustomize.py [1]_ for that purpose, e.g.
create this file in your current directory:

# sitecustomize.py
import sys
sys.setdefaultencoding('utf-8')

and run Python like that:

PYTHONPATH=. python -c print u'\u03A9'  file.txt

But remember that when you copy this file to the global
PYTHONPATH on your system it will affect all Python
programs.

.. [1] http://docs.python.org/lib/module-site.html

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


Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Neil Cerutti
On 2007-12-06, Neil Cerutti [EMAIL PROTECTED] wrote:
 It should beat ResortEverything consistently once the lists
 become larger than a certain size. Do you get better results at
 all with the above function?

With psyco, my merge_sorted becamse faster than relying on
timsort at roughly 80 elements total. Without psyco it was always
slowest.

Both were much faster than the ASPN imerge recipe--if you built a
list with the result. imerge is wicked fast if you never extract
any values, though. ;-)

Or perhaps I'm just misprofiling. I used:

a = range(2)  # e.g
b = range(17000)

t = timeit.Timer('merge_sorted(a, b)', 'from __main__ import '
   'merge_sorted, a, b')
t2 = timeit.Timer('merge_sorted2(a, b)', 'from __main__ import '
 'merge_sorted2, a, b')
t3 = timeit.Timer('list(imerge(a, b))', 'from __main__ import imerge, a, b')
print t.timeit(100)
print t2.timeit(100)
print t3.timeit(100)

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


Re: pipeline encoding

2007-12-06 Thread Peter Otten
Tomek Toczyski wrote:

 Diez B. Roggisch:
 

 Python tries and guesses the stdout-encoding based on the terminal 
 settings. So the first print works.

 However, piping to a file means that it can't do so, because it doesn't 
 (and shouldn't) make any assumptions on the output encoding desired - 
 after all, it might be appending to a XML-file with e.g. latin1 
 encoding.

 So you need to explictely encode the unicode-object with the desired 
 encoding:


 python -c print u'\u03A9'.encode('utf-8')  file.txt
 
 Thanks. It is a solutiona to my problem but:
 
 Are there any command line option for telling python what encoding to use 
 for stdout?
 
 To be honest I have a more complicated program than the example that I 
 have presented - there are many print commands inside and it is not very 
 feasible for me to put .encode('utf-8') inside every print occurence.

Alternatively you can wrap stdout:

# -*- coding: utf-8 -*-
import sys

if sys.stdout.encoding is None:
import locale
import codecs

encoding = locale.getpreferredencoding() # or just utf-8
streamwriter = codecs.lookup(encoding).streamwriter
sys.stdout = streamwriter(sys.stdout)

print uähnlich üblich möglich
-- 
http://mail.python.org/mailman/listinfo/python-list

Determining Dependencies

2007-12-06 Thread Greg Lindstrom
Hello All-

I have a Python routine consisting of 75 or more files (most files house 1
object) and would like to know if there is an automated way to search though
the files and determine all of the (non-standard lib) modules required to
run the routine.  For example, looking in my base class I can see that I
need cx_Oracle and odbc, but there are many files to go through which
increases the chance for errors.

The flip side of this is that the code has gone through many revisions and I
would like to know if all of the modules being brought in are actually being
used in a given file.  If I'm not using it I don't want to bring it in.

Worst case is we go though each file manually.  I was just curious if there
is a better way.

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

Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Neil Cerutti
On 2007-12-06, Aaron Watters [EMAIL PROTECTED] wrote:
 On Dec 6, 2:14 pm, Neil Cerutti [EMAIL PROTECTED] wrote:
 On 2007-12-06, Raymond Hettinger [EMAIL PROTECTED] wrote:
  See recipes:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491285
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305269

 That's fairly awesome.

 The second one is!  That's why it works so fast.
 Tim Peters optimized this case!
 Gotta hand it to Tim Peters.  The first one should
 win some sort of obfuscated code contest, imho.
 It also seems to be 5 times slower than any of the others.

 btw: Neil's merge_sorted is a bit slower than any of mine due
 to the use of list.append, I think instead of preallocating a
 list of the right size.

I was hoping that, as it was slightly simpler that way, it would
be slightly faster. But sadly, it wasn't. I ultimately added that
optimization, too.

-- 
Neil Cerutti
I make love to pressure. --Stephen Jackson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which configparse?

2007-12-06 Thread Joshua Kugler
Shane Geiger wrote:

 Best, is naturally, a somewhat subjective evaluation.  That being said,
 configparser is well regarded.  I have also seen these two options that
 you might want to check out:
 
 http://wiki.woodpecker.org.cn/moin/Dict4Ini
 http://www.voidspace.org.uk/python/configobj.html

+1 on configobj.  The ability to have mutli-level config files is wonderful,
and it's all dict and/or array access methods.  Wonderful.

 I'd like to make minimal change to my working optparse setup (there are
 lots of options - I don't want to duplicate all the cmdline parsing with
 ini file parsing code)

I found (at least) two areas where lots of code is unavoidable:
configuration handling and error handling.  That said, you could use
configparse (or configobj) to set the defaults of all your command line
options, like so:

cfg = configobj.ConfigObj('file.ini', file_error=True)
parser.add_option('--opt', dest='opt',  default=cfg.get('opt', None)

Hmm...now why didn't I do that in my code?  Thanks for the idea! :)

j


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


Re: JSON

2007-12-06 Thread Joshua Kugler
[EMAIL PROTECTED] wrote:

 i tried a couple python json libraries. i used simplejson on the
 server and was using cjson on the client, but i ran into this issue.
 i'm now using simplejson on both sides, but i'm still interested in
 this issue.  did i do something wrong? is there a bug in one of the
 libraries? or something i don't understand about the json spec?
 
 
 i problem is the line where i call cjson.decode() below:
 
 import simplejson
 import cjson

 sj = simplejson.dumps('http://server.com')
 sj
 'http:\\/\\/server.com'
 cj = cjson.encode('http://server.com')
 cj
 'http://server.com;'
 simplejson.loads(cj)
 u'http://server.com'
 cjson.decode(cj)
 'http://server.com'
 simplejson.loads(sj)
 u'http://server.com'
 cjson.decode(sj)
 'http:\\/\\/server.com' # is this correct

Known issue.  See:
http://blog.extracheese.org/2007/07/when-json-isnt-json.html

Neither project has fixed it it seems.  Not sure which is actually
the correct way to do it, but it would be nice if they would agree.

j


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


Re: Capture DOS error???

2007-12-06 Thread Joshua Kugler
Tangen, Erik wrote:

 Did you ever get a solution to this?
 I am also in need of this solution.
 Thanks,
 Erik

Can you clarify?  What is a DOS error?  You mean an error in reading or
writing a file?  That would be an IOError exception.  If a file is not
found, or you can't read it, that's an OSError exception.  Beyond that, I'm
not sure what you're asking for.

j

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


Re: which configparse?

2007-12-06 Thread Neal Becker
Martin Marcher wrote:

 Hi,
 
 On 12/6/07, Neal Becker [EMAIL PROTECTED] wrote:
 configparse looks like what I want, but it seems last commit was 2years
 ago.

 What is the best choice?
 
 that seems like configparse is the best choice. 

Thanks.  I see something right off that should be improved in configparse.

In OptionParser.__init__, a hard-coded list of arguments is passed to the
base _OptionParser.  This (predictably) is no longer current - OptionParser
now has one more optional argument.

I suspect the correct thing to do here is to allow configparse.OptionParser
to accept error_handler only as a keyword arg, and then strip it out,
passing all other args to _OptionParser.__init__.

   

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


Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Aaron Watters
On Dec 6, 2:14 pm, Neil Cerutti [EMAIL PROTECTED] wrote:
 On 2007-12-06, Raymond Hettinger [EMAIL PROTECTED] wrote:
  See recipes:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491285
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305269

 That's fairly awesome.

The second one is!  That's why it works so fast.
Tim Peters optimized this case!
Gotta hand it to Tim Peters.  The first one should
win some sort of obfuscated code contest, imho.
It also seems to be 5 times slower than any of the others.

btw: Neil's merge_sorted is a bit slower than any of
mine due to the use of list.append, I think instead
of preallocating a list of the right size.

 -- Aaron
===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=inherently+hosed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which configparse?

2007-12-06 Thread Martin Marcher
Hi,

On 12/6/07, Neal Becker [EMAIL PROTECTED] wrote:
 configparse looks like what I want, but it seems last commit was 2years
 ago.

 What is the best choice?

that seems like configparse is the best choice. I use it quite often
and no commit in 2years to me means Boy that's stable software. A
search on bugs.python.org mentions 1 enhancement to use for line in
f: instead of while 1:

Why do we always need a ton of commits? For me that means that
developement is still in progress and changes have to be expected
because it's not yet stable.

(Actually not that hard rules, but I hope you get what I meant)

martin

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list


sqlite or xml

2007-12-06 Thread Kelie
Hello group,

If I need store and use a couple thousand of people's contact info:
first name, last name, phone, fax, email, address, etc. I'm thinking
of using either sqlite or xml. Which one is better? My understanding
is if there is large amount of data, sqlite would be better as far as
speed is concerned. But how much data is considered to be large
amount?

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


Charging range

2007-12-06 Thread Miguel Galves
I was recently approached with a offer to work on a web related
project where I'd use Python as my main tool. I am using Python for
the past year, and this would be first project. Also, this is a remote
position. The company is located in the US, South Atlantic Region.

Considering it is contract work and it would be a 3-5 man-months
project, how much would you guys think to be the appropriate range to
charge for such project? Any type of figures would help me, to give me
at least an idea.

Thanks,

-- 
Miguel Galves - Engenheiro de Computação
Já leu meus blogs hoje?
Para geeks http://log4dev.com
Pra pessoas normais
http://miguelcomenta.wordpress.com

Não sabendo que era impossível, ele foi lá e fez...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How can I create customized classes that have similar properties as 'str'?

2007-12-06 Thread samwyse
On Nov 24, 6:38 pm, Hrvoje Niksic [EMAIL PROTECTED] wrote:
 samwyse [EMAIL PROTECTED] writes:
  create a hash that maps your keys to themselves, then use the values
  of that hash as your keys.

 The atom function you describe already exists under the name
 intern.

D'oh!  That's what I get for not memorizing Non-essential Built-in
Functions.

In my defense, however, my function will work with anything that can
be used as a dictionary key (strings, tuples, frozen sets, etc), not
just character strings; thus we return to the original:

 a=(1,2,3)
 b=(1,1+1,1+1+1)
 a == b
True
 a is b
False
 atom(a) is atom(b)
True
 intern(a) is intern(b)
Traceback (most recent call last):
  File pyshell#33, line 1, in ?
intern(a) is intern(b)
TypeError: intern() argument 1 must be string, not tuple
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distutils help for sub-packages

2007-12-06 Thread Rick Muller
On Dec 5, 7:20 am, [EMAIL PROTECTED] wrote:


 I recommend asking the distutils guys at their list:

 http://mail.python.org/mailman/listinfo/distutils-sig

 Mike

I did, and no one replied there either. Probably because everyone,
there and here, were too polite to say that I was nutso. Which, it
turns out, I was. After not hearing from two normally helpful forums
(fora?) I went back a little more carefully and found the bug. Sorry
for the false alarm.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite or xml

2007-12-06 Thread Chris
On Dec 6, 10:21 pm, Kelie [EMAIL PROTECTED] wrote:
 Hello group,

 If I need store and use a couple thousand of people's contact info:
 first name, last name, phone, fax, email, address, etc. I'm thinking
 of using either sqlite or xml. Which one is better? My understanding
 is if there is large amount of data, sqlite would be better as far as
 speed is concerned. But how much data is considered to be large
 amount?

 Thank you!

I'm personally partial to databases myself and at a thousand records a
database is good idea, or an indexed file.  Depends on what you want
to do with it in the end which should resolve the problem.  Do you
need it to accessed (read  write) by multiple people ? Or would it
just be a single transaction process (ie. just you locally)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distutils help for sub-packages

2007-12-06 Thread kyosohma
On Dec 6, 2:37 pm, Rick Muller [EMAIL PROTECTED] wrote:
 On Dec 5, 7:20 am, [EMAIL PROTECTED] wrote:



  I recommend asking the distutils guys at their list:

 http://mail.python.org/mailman/listinfo/distutils-sig

  Mike

 I did, and no one replied there either. Probably because everyone,
 there and here, were too polite to say that I was nutso. Which, it
 turns out, I was. After not hearing from two normally helpful forums
 (fora?) I went back a little more carefully and found the bug. Sorry
 for the false alarm.

Sorry to hear that...they are both pretty helpful in most cases.
C.l.py doesn't usually mind telling OP's that they're nutso either. I
personally didn't think you were, but I didn't know how to answer your
question either.

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


Re: sqlite or xml

2007-12-06 Thread Tim Chase
 how much data is considered to be large amount?

one record

Unless you really need XML to communicate with some other app via 
a predetermined schema, use a database to store and retrieve 
data.  If you only need to send data to another app via a 
predetermined schema, use a database and then offer an export to 
XML functionality.

for s in ['regular expressions', 'XML', 'perl', 'WS-*']:
   print 
 Some people, when confronted by a problem,
 think I know, I'll use %s!
 Now they have two problems. % s

-tkc


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


Re: splitting a words of a line

2007-12-06 Thread John Machin
On Dec 7, 2:21 am, Sumit [EMAIL PROTECTED] wrote:
 Hi ,
I am trying to splitt  a Line whihc is below of format ,

 AzAccept PLYSSTM01 [23/Sep/2005:16:14:28 -0500] 162.44.245.32 CN=
 cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk
 Secure,DC=customer,DC=rxcorp,DC=com plysmhc03zp GET /mci/performance/
 SelectProducts.aspx?
 p=0V=Ca=29menu=adhoc [d4b62ca2-09a0-4334622b-0e1c-03c42ba5] [0]

Because lines are mangled in transmission, it is rather difficult to
guess exactly what you have in your input and what your expected
results are.

Also you don't show exactly what you have tried.

At the end is a small script that contains my guess as to your input
and expected results, shows an example of what the re.VERBOSE flag is
intended for, and how you might debug your results.

So that you don't get your homework done 100% for free, I haven't
corrected the last mistake I made.

As usual, re may not be the best way of doing this exercise. Your
*single* piece of evidence may not be enough. It appears to be a
horrid conglomeration of instances of different things, each with its
own grammar. You may find that something like PyParsing would be more
legible and more robust.


 Here all the string whihc i want to split is
 -
 AzAccept
 PLYSSTM01
 [23/Sep/2005:16:14:28 -0500]
 162.44.245.32
 CN= cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk
 Secure,DC=customer,DC=rxcorp,DC=com
 GET
 /mci/performance/SelectProducts.aspx?p=0V=Ca=29menu=adhoc
 d4b62ca2-09a0-4334622b-0e1c-03c42ba5
 0
 

 i am trying to use re.split() method to split them , But unable to get
 the exact result .


C:\junktype sumit.py
import re

textin = \
AzAccept PLYSSTM01 [23/Sep/2005:16:14:28 -0500] 162.44.245.32
CN=  \
cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk  \
Secure,DC=customer,DC=rxcorp,DC=com plysmhc03zp GET /mci/
performance/ \
SelectProducts.aspx? \
p=0V=Ca=29menu=adhoc [d4b62ca2-09a0-4334622b-0e1c-03c42ba5]
[0]

expected = [
AzAccept,
PLYSSTM01,
23/Sep/2005:16:14:28 -0500,
162.44.245.32,
CN= cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk
Secure,DC=custom
er,DC=rxcorp,DC=com,
plysmhc03zp,
GET,
/mci/performance/SelectProducts.aspx?p=0V=Ca=29menu=adhoc,
d4b62ca2-09a0-4334622b-0e1c-03c42ba5,
0,
]

pattern = r
(\S+)   # AzAccept
\s+
(\S+)   # PLYSSTM01
\s+\[
([^]]+) # 23/Sep/2005:16:14:28 -0500
]\s+
(\S+)   # 162.44.245.32
\s+
([^]+) # CN= cojack (890),OU=1, etc etc,DC=rxcorp,DC=com
\s+
(\S+)   # plysmhc03zp
\s+
(\S+)   # GET
\s+
(\S+)   # /mci/performance/ ... menu=adhoc
\s+\[
([^]]+) # d4b62ca2-09a0-4334622b-0e1c-03c42ba5
]\s+\[
([^]]+) # 0
]$


mobj = re.match(pattern, textin, re.VERBOSE)
if not mobj:
print Bzzzt!
else:
result = mobj.groups()
print len check, len(result) == len(expected), len(result),
len(expected)
for a, b in zip(result, expected):
print a == b, repr(a), repr(b)



C:\junkpython sumit.py
len check True 10 10
True 'AzAccept' 'AzAccept'
True 'PLYSSTM01' 'PLYSSTM01'
True '23/Sep/2005:16:14:28 -0500' '23/Sep/2005:16:14:28 -0500'
True '162.44.245.32' '162.44.245.32'
True 'CN= cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk
Secure,DC=custo
mer,DC=rxcorp,DC=com' 'CN= cojack (890),OU=1,OU=Customers,OU=ISM-
Users,OU=kk
k Secure,DC=customer,DC=rxcorp,DC=com'
True 'plysmhc03zp' 'plysmhc03zp'
True 'GET' 'GET'
False '/mci/performance/SelectProducts.aspx?p=0V=Ca=29menu=adhoc'
'/mci/perf
ormance/SelectProducts.aspx?p=0V=Ca=29menu=adhoc'
True 'd4b62ca2-09a0-4334622b-0e1c-03c42ba5'
'd4b62ca2-09a0-4334622b-0e1c-03c42ba
5'
True '0' '0'

C:\junk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __iadd__ useless in sub-classed int

2007-12-06 Thread samwyse
On Dec 6, 1:12 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 samwyse schrieb:

  For whatever reason, I need an inproved integer.  Sounds easy, let's
  just subclass int:

  class test(int):
 pass

  Now let's test it:

  zed=test(0)
  zed.__class__
  class '__main__.test'
  zed
  0

  So far, so good.  Now let's try incrementing:

  zed+=1
  zed
  1
  zed.__class__
  type 'int'

  WTF??!
  Is this a bug or is it the inevitable result of optimizing for the
  case where all integers are indistinguishable?

 There has been a lengthe thread over the semantics of __iadd__ a few
 weeks ago. It _can_ modify the object in question in-place (something
 not possible for ints anyway), but it will ALWAYS return a reference
 which will be set to the left-hand-side.

Thanks!  I'd missed that thread, googling found it but it didn't look
noteworthy at first glance.  I've not yet read the entire thread, but
I did see a reference to PEP 203.

)So, given the expression:
)
)  x += y
)
)The object `x' is loaded, then `y' is added to it, and the
)resulting object is stored back in the original place.

That agrees with what I'm seeing, all right.  The problem is, the
resulting object has a different type, which seems to violate the
spirit of a later paragraph:

)Writing the above expression as
)
)x operator= y
)
)is both more readable and less error prone, because it is
)instantly obvious to the reader that it is x that is being
)changed, and not x that is being replaced by something almost,
)but not quite, entirely unlike x.

And that's my complaint.  The value in zed is being replaced by
something almost, but not quite, identical to the original value.
Python's internal implementation of __iadd__ for int isn't returning
self, it's returning a new value belonging to the super-class.  My
whole point is overloading int was that I'd hoped to avoid having to
write a bunch of methods to perform in-place modifications.  Looks
like I stuck, however.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __iadd__ useless in sub-classed int

2007-12-06 Thread Chris Mellon
On Dec 6, 2007 3:02 PM, samwyse [EMAIL PROTECTED] wrote:

 On Dec 6, 1:12 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
  samwyse schrieb:
 
   For whatever reason, I need an inproved integer.  Sounds easy, let's
   just subclass int:
 
   class test(int):
  pass
 
   Now let's test it:
 
   zed=test(0)
   zed.__class__
   class '__main__.test'
   zed
   0
 
   So far, so good.  Now let's try incrementing:
 
   zed+=1
   zed
   1
   zed.__class__
   type 'int'
 
   WTF??!
   Is this a bug or is it the inevitable result of optimizing for the
   case where all integers are indistinguishable?
 
  There has been a lengthe thread over the semantics of __iadd__ a few
  weeks ago. It _can_ modify the object in question in-place (something
  not possible for ints anyway), but it will ALWAYS return a reference
  which will be set to the left-hand-side.

 Thanks!  I'd missed that thread, googling found it but it didn't look
 noteworthy at first glance.  I've not yet read the entire thread, but
 I did see a reference to PEP 203.

 )So, given the expression:
 )
 )  x += y
 )
 )The object `x' is loaded, then `y' is added to it, and the
 )resulting object is stored back in the original place.

 That agrees with what I'm seeing, all right.  The problem is, the
 resulting object has a different type, which seems to violate the
 spirit of a later paragraph:


The phrasing is a little awkward. Instead of store say bound to the
same name as

 )Writing the above expression as
 )
 )x operator= y
 )
 )is both more readable and less error prone, because it is
 )instantly obvious to the reader that it is x that is being
 )changed, and not x that is being replaced by something almost,
 )but not quite, entirely unlike x.

 And that's my complaint.  The value in zed is being replaced by
 something almost, but not quite, identical to the original value.
 Python's internal implementation of __iadd__ for int isn't returning
 self, it's returning a new value belonging to the super-class.  My
 whole point is overloading int was that I'd hoped to avoid having to
 write a bunch of methods to perform in-place modifications.  Looks
 like I stuck, however.


Remember that in Python, name binding (which is to say, pure
assignment) is never a mutating operation. It's purely internal to the
namespace it occurs in. So even when augmented assignment returns
self, it still results in a normal Python assignment.

You're going to be struggling against the grain trying to implement a
mutable int anyway, you won't be able to make foo = 10 mutate the
int, and even if you do create one you probably don't want it to
return true for isinstance(foo, int).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __iadd__ useless in sub-classed int

2007-12-06 Thread Neil Cerutti
On 2007-12-06, samwyse [EMAIL PROTECTED] wrote:
 And that's my complaint.  The value in zed is being replaced
 by something almost, but not quite, identical to the original
 value. Python's internal implementation of __iadd__ for int
 isn't returning self, it's returning a new value belonging to
 the super-class.

int.__iadd__ cannot return self because int instances are
immutable. In order to return self it would first have to change
what's unchangeable.

 My whole point is overloading int was that
 I'd hoped to avoid having to write a bunch of methods to
 perform in-place modifications.  Looks like I stuck, however.

You have to implement only the operations you actually use. So to
save yourself drudge-work, use fewer operations. ;-)

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


Calculate an age

2007-12-06 Thread Pierre Quentel
Hi all,

I have searched in the standard distribution if there was a function
to return the difference between 2 dates expressed like an age :
number of years, of months and days. The difference between datetime
instances returns a timedelta object that gives a number of days, but
not an age

So is there such a function somewhere ? If not, for what reason, since
it's a rather usual task

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


Capturing global input?

2007-12-06 Thread nomihn0
I'd like to accept mouse gestures and keyboard shortcuts as input to a
program. The nature of this program requires that these commands be
issued regardless of the currently active window. Here's the rub: I
need a platform-independent solution.

Java supports with its MouseInfo class, but I'd like a Python
equivalent without turning to Jython.  Is this possible?

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


Class destructor -- strange behaviour

2007-12-06 Thread Spes
Hi,

I have this simple code:
| #!/usr/bin/python
| import codecs
| import re
| from copy import deepcopy
|
| class MyClass(object):
|   def __del__(self):
| deepcopy(1)
|
| x=MyClass()

but I get an error:
| Exception exceptions.TypeError: 'NoneType' object is not callable
in bound method MyClass.__del__ of __main__.MyClass object at
0x6fcf0 ignored

The problem disappears if I do anything of this:
1. change
 - from copy import deepcopy
 + import copy
and call directly copy.deepcopy(1)

or
2. don't store object to variable `x'

or
3. don't import module `re'

The first solution is OK, but I would like to know why it behaves so
strange. We have tested on:

- Mac OS X Tiger for PPC
Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

- Linux 64bit and 32bit
Python 2.4.4 (#1, Oct 30 2007, 14:31:50)
[GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2
Python 2.5 (r25:51908, Jan 12 2007, 13:57:15)
[GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2

Thanks for the explanation,
Vlasta
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite or xml

2007-12-06 Thread Yu-Xi Lim
Tim Chase wrote:
 how much data is considered to be large amount?
 
 one record
 
 Unless you really need XML to communicate with some other app via a 
 predetermined schema, use a database to store and retrieve data.  If you 
 only need to send data to another app via a predetermined schema, use a 
 database and then offer an export to XML functionality.

I agree. IMO, XML should be used as a data exchange format, not as 
database format for databases of *any* length. Though some 
products/projects may tell you otherwise.

I won't limit data exchange to only other apps/programs. One benefit of 
XML is that it's relatively human readable, so exchanging data directly 
with humans using XML is probably acceptable, but shouldn't be encouraged.
-- 
http://mail.python.org/mailman/listinfo/python-list


I'm missing something here with range vs. xrange

2007-12-06 Thread Joe Goldthwaite
I've been playing with Python a bit. Doing little performance benchmarks and
working with Psyco.  It's been fun and I've been learning a lot.  For
example, in a previous post, I was looking for a way to dynamically add new
runtime function to a class.  Martin told me to use a class instance
variable instead.  It turns out that's faster than hard coding a list of
functions.  Thanks Martin.

I read that the range function builds a list and that xrange returns an
iterator and is therefore more efficient.  In my testing, they both come out
to almost exactly the same performance wise.  Did something get changed in
Python 2.4 to make them identical?  I searched the web but couldn't find
anything that would account for the similarities.


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


Re: Calculate an age

2007-12-06 Thread John Machin
On Dec 7, 8:34 am, Pierre Quentel [EMAIL PROTECTED] wrote:
 Hi all,

 I have searched in the standard distribution if there was a function
 to return the difference between 2 dates expressed like an age :
 number of years, of months and days. The difference between datetime
 instances returns a timedelta object that gives a number of days, but
 not an age

 So is there such a function somewhere ? If not, for what reason, since
 it's a rather usual task

and a rather usually imprecisely specified task [what do you mean by
number of months?] with multiple interpretations/implementations/
doctrines the publication of any one of which attracts a truckload of
rotten tomatoes and derision from adherents of other sects :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I'm missing something here with range vs. xrange

2007-12-06 Thread Bjoern Schliessmann
Joe Goldthwaite wrote:
 I read that the range function builds a list and that xrange
 returns an iterator and is therefore more efficient.  

This is generally not true.

 In my testing, they both come out to almost exactly the same
 performance wise.  Did something get changed in Python 2.4 to make
 them identical? 

No. Try again with a list of length 1000.

Regards,


Björn

-- 
BOFH excuse #359:

YOU HAVE AN I/O ERROR - Incompetent Operator error

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


Re: sqlite or xml

2007-12-06 Thread Yu-Xi Lim
Tim Chase wrote:
 how much data is considered to be large amount?
 
 one record
 
 Unless you really need XML to communicate with some other app via a 
 predetermined schema, use a database to store and retrieve data.  If you 
 only need to send data to another app via a predetermined schema, use a 
 database and then offer an export to XML functionality.

I agree. IMO, XML should be used as a data exchange format, not as 
database format for databases of *any* length. Though some 
products/projects may tell you otherwise.

I won't limit data exchange to only other apps/programs. One benefit of 
XML is that it's relatively human readable, so exchanging data directly 
with humans using XML is probably acceptable, but shouldn't be encouraged.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite or xml

2007-12-06 Thread Kelie
Thanks Chris, Tim and Yu-Xi. I'll follow your advice and use database.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of Nested Functions Lambda Expressions

2007-12-06 Thread Terry Jones
[Referring to the thread at
 http://mail.python.org/pipermail/python-list/2007-October/463348.html
 with apologies for top posting (I don't have the original mail)]

Duncan Booth wrote:

 You can use Python's bytecode disassembler to see what actually gets 
 executed here:
 
  def fn_outer(v):
 a=v*2
 def fn_inner():
 print V:%d,%d % (v,a)
 
 fn_inner()
 
  import dis
  dis.dis(fn_outer)
   2   0 LOAD_DEREF   1 (v)
[snip]


 When you execute the 'def' statement, the two scoped variables a and v 
 are built into a tuple on the stack, the compiled code object for the 
 inner function is also pushed onto the stack and then the function is 
 created by the 'MAKE_CLOSURE' instruction. This is then stored in a 
 local variable (STORE_FAST) which is then loaded and called.
 
 So the function definition is pretty fast, BUT notice how fn_inner is 
 referenced by STORE_FAST/LOAD_FAST whereas a and v are referenced by 
 LOAD_DEREF/STORE_DEREF and LOAD_CLOSURE.
 
 The code for fn_inner also uses LOAD_DEREF to get at the scoped 
 variables:

I'd like to understand what it is that triggers the use of LOAD/STORE_DEREF
versus LOAD/STORE_FAST. This seems dependent on how fn_inner above uses the
a and v variables. If I change the print V:%d,%d % (v,a) line to be
something like (a, v) = (v, a) or do other simple uses and assignments to a
and v, LOAD/STORE_FAST is used. It seems that it's the use of print (in
this case) that triggers the use of LOAD/STORE_DEREF in the bytecode.

Can anyone shed more light on what in general causes the switch to
LOAD/STORE_DEREF?

I find it a bit disconcerting that the simple presence of a nested function
(even if never used) may trigger significant slowdown in variable access
for the rest of the code in the containing function. I'd be happy to know
how/when this happens. I know I probably shouldn't care, but I do.

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


Re: Calculate an age

2007-12-06 Thread Paul McGuire
On Dec 6, 4:19 pm, John Machin [EMAIL PROTECTED] wrote:
 On Dec 7, 8:34 am, Pierre Quentel [EMAIL PROTECTED] wrote:

  Hi all,

  I have searched in the standard distribution if there was a function
  to return the difference between 2 dates expressed like an age :
  number of years, of months and days. The difference between datetime
  instances returns a timedelta object that gives a number of days, but
  not an age

  So is there such a function somewhere ? If not, for what reason, since
  it's a rather usual task

 and a rather usually imprecisely specified task [what do you mean by
 number of months?] with multiple interpretations/implementations/
 doctrines the publication of any one of which attracts a truckload of
 rotten tomatoes and derision from adherents of other sects :-)

I think metric months are all the same length, 10**1.4834089785587095
days.

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


Re: using pdb and catching exception

2007-12-06 Thread R. Bernstein
Just checked to see how Ruby deals with this. Both languages allow one
to register a trace functon to catch events like call, line, return,
exception, etc. Ruby however register an event before the raise takes
place.

It might be cool for some good person to go through the process of
making a formal suggestion this get added, etc.  (unless a change like
this is already in the works).

Diez B. Roggisch [EMAIL PROTECTED] writes:

 raise is a statement, not a function. So it won't work.
 
 I do know that e.g. nose allows for dropping into pdb when a test
 fails. Maybe that works by catching the exception top-level, examining
 the stack-trace, setting a break-point, and restarting it.
 
 Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calculate an age

2007-12-06 Thread thebjorn
On Dec 6, 11:19 pm, John Machin [EMAIL PROTECTED] wrote:
 On Dec 7, 8:34 am, Pierre Quentel [EMAIL PROTECTED] wrote:

  Hi all,

  I have searched in the standard distribution if there was a function
  to return the difference between 2 dates expressed like an age :
  number of years, of months and days. The difference between datetime
  instances returns a timedelta object that gives a number of days, but
  not an age

  So is there such a function somewhere ? If not, for what reason, since
  it's a rather usual task

 and a rather usually imprecisely specified task [what do you mean by
 number of months?] with multiple interpretations/implementations/
 doctrines the publication of any one of which attracts a truckload of
 rotten tomatoes and derision from adherents of other sects :-)

It may be imprecisely specified, yet it's quite useful anyway. I've
got an implementation at http://blog.tkbe.org/archive/python-how-old-are-you/
if anyone's interested..

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


Re: Best ways of managing text encodings in source/regexes?

2007-12-06 Thread tinkerbarbet
OK, for those interested in this sort of thing, this is what I now
think is necessary to work with Unicode in python.  Thanks to those
who gave feedback, and to Cliff in particular (but any remaining
misconceptions are my own!)  Here are the results of my attempts to
come to grips with this. Comments/corrections welcome...

(Note this is not about which characters one expects to match with \w
etc. when compiling regexes with python's re.UNICODE flag. It's about
the encoding of one's source strings when building regexes, in order
to match against strings read from files of various encodings.)

I/O: READ TO/WRITE FROM UNICODE STRING OBJECTS. Always use codecs to
read from a specific encoding to a python Unicode string, and use
codecs to encode to a specific encoding when writing the processed
data.  codecs.read() delivers a Unicode string from a specific
encoding, and codecs.write() will put the Unicode string into a
specific encoding (be that an encoding of Unicode such as UTF-8).

SOURCE: Save the source as UTF-8 in your editor, tell python with # -
*- coding: utf-8 -*-, and construct all strings with u'' (or ur''
instead of r'').  Then, when you're concatenating strings constructed
in your source with strings read with codecs, you needn't worry about
conversion issues. (When concatenating byte strings from your source
with Unicode strings, python will, without an explicit decode, assume
the byte string is ASCII which is a subset of Unicode (IS0-8859-1
isn't).)

Even if you save the source as UTF-8, tell python with # -*- coding:
utf-8 -*-, and say myString = blah, myString is a byte string.  To
construct a
Unicode string you must say myString = ublah or myString =
unicode(blah), even if your source is UTF-8.

Typing 'u' when constructing all strings isn't too arduous, and less
effort than passing selected non-ASCII source strings to unicode() and
needing to remember where to do it.  (You could easily slip a non-
ASCII char into a byte string in your code because most editors and
default system encodings will allow this.) Doing everything in Unicode
simplifies life.

Since the source is now UTF-8, and given Unicode support in the
editor, it
doesn't matter whether you use Unicode escape sequences or literal
Unicode
characters when constructing strings, since

 uá == u\u00E1
True

REGEXES: I'm a bit less certain about regexes, but this is how I think
it's going to work: Now that my regexes are constructed from Unicode
strings, and those regexes will be compiled to match against Unicode
strings read with codecs, any potential problems with encoding
conversion disappears.  If I put an
en-dash into a regex built using u'', and I happen to have read the
file in
the ASCII encoding which doesn't support en-dashes, the regex simply
won't
match because the pattern doesn't exist in the /Unicode/ string served
up by
codecs.  There's no actual problem with my string encoding handling,
it just means I'm looking for the wrong chars in a Unicode string read
from a file not saved in a Unicode encoding.

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


Re: sqlite or xml

2007-12-06 Thread tinkerbarbet
On Dec 7, 12:34 am, Kelie [EMAIL PROTECTED] wrote:
 Thanks Chris, Tim and Yu-Xi. I'll follow your advice and use database.

Hi Kelie

If you're happy going with sqlite then stick with it.  If on the other
hand you were considering XML because you're more comfortable with
that (e.g. you find XML easy to work with and you're more familiar
with XPath/XQuery than SQL) then you could use XML if you wanted.  The
choice is not between XML and databases, it's between XML and
relational. There are -- shock-horror! -- full-featured XML databases
too (e.g. Berkeley DB XML, which is lightweight, fast, embeddable and
open source like sqlite, with indexing, transactions etc. if you need
that).  XML is very widely used in publishing and not only as a data
transfer format which happens to be human-readable.  The main reason
for going for a database over a file in your case is I'd guess to
support searching, since performance wouldn't be an issue these days
with a few thousand records.

Developers tend to have strong feelings in favour of relational (=
tabular storage) over xml database (= hierarchical storage) but
this will change.  If you are asking what would work for your
relatively simple use-case, the answer is both, since the storage
model isn't that important for a contacts address list.  What would
work best for you in this case is whichever you would prefer...

TimvN

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


Re: which configparse?

2007-12-06 Thread limodou
On Dec 6, 2007 11:49 PM, Shane Geiger [EMAIL PROTECTED] wrote:
 Best, is naturally, a somewhat subjective evaluation.  That being said,
 configparser is well regarded.  I have also seen these two options that
 you might want to check out:

 http://wiki.woodpecker.org.cn/moin/Dict4Ini
 http://www.voidspace.org.uk/python/configobj.html

Thanks for you mentioned Dict4ini, but the new project site is in
http://code.google.com/p/dict4ini

-- 
I like python!
UliPad The Python Editor: http://code.google.com/p/ulipad/
meide wxPython UI module: http://code.google.com/p/meide/
My Blog: http://www.donews.net/limodou
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Profiler GUI like Matlab?

2007-12-06 Thread Davy
Hi all,

Is there any Python Profiler GUI like Matlab? I found the Matlab
Profiler is very intuitive and easy to use.

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


Can I embed Windows Python in C# or VC++?

2007-12-06 Thread grbgooglefan
I want to use Python's Windows (python25.dll) version to embed in my
C# (or atleast VC++) program for performing syntax checks on the
Python expressions which are later supposed to be evaluated at runtime
by another C++ program

For this, I would like to use CPython API functions such as
Py_Initialize, PyModule_New, PyModule_GetDict, PyRun_String,
PyObject_GetAttrString, PyObject_CallObject, PyTuple_SetItem  other
similar functions from my C#/ VC++ program on Windows.

I have installed Python251.msi on my Desktop.
Can I start doing the development using the include, lib  the
python25.dll files availale after installing this MSI?
-- 
http://mail.python.org/mailman/listinfo/python-list


PyImport_ImportModule(foo.bar)

2007-12-06 Thread sndive
I'm trying to import foo.bar in order not to add every single
directory with python files to the search path.
i immediately follow the import with the PyModule_AddObject call to
put the imported module
to __main__ module
but later on  PyEval_EvalCode on Py_CompileString compiled code
foo.bar.baz() and dictionary of __main__
used for global and local context does not work (I get NameError).

is there an equivalent of import foo.bar as Bar; in c api
or should i call into submodules differently?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JSON

2007-12-06 Thread Marc Christiansen
Joshua Kugler [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
 
 i tried a couple python json libraries. i used simplejson on the
 server and was using cjson on the client, but i ran into this issue.
 i'm now using simplejson on both sides, but i'm still interested in
 this issue.  did i do something wrong? is there a bug in one of the
 libraries? or something i don't understand about the json spec?
 
 
 i problem is the line where i call cjson.decode() below:
 
 import simplejson
 import cjson

 sj = simplejson.dumps('http://server.com')
 sj
 'http:\\/\\/server.com'
 cj = cjson.encode('http://server.com')
 cj
 'http://server.com;'
 simplejson.loads(cj)
 u'http://server.com'
 cjson.decode(cj)
 'http://server.com'
 simplejson.loads(sj)
 u'http://server.com'
 cjson.decode(sj)
 'http:\\/\\/server.com' # is this correct
 
 Known issue.  See:
 http://blog.extracheese.org/2007/07/when-json-isnt-json.html
 
 Neither project has fixed it it seems.  Not sure which is actually
 the correct way to do it, but it would be nice if they would agree.

Since both Opera and SpiderMonkey give http://server.com as result for
eval('http:\\/\\/server.com'), I'd say cjson gets it wrong (If by
nothing else than majority rule ;). That is unless I'm wrong that in
javascript something like eval(JSON_repr_of_s) == s should be true.

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


Re: Best way to merge/sort two sorted lists?...

2007-12-06 Thread Terry Reedy

Aaron Watters [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| While trying to optimize some NUCULAR libraries I discovered
| that the best way to merge 2 sorted lists together
| into a new sorted list is to just append
| them and re-sort.

The current version of list.sort (timsort) was designed to take advantage 
of pre-existing order.  It should discover the 2 sorted sublists and merge 
them together.  It will not really re-sort the way it would with random 
data.

A psyco/Python version can be faster only because it avoids the comparisons 
need to discover the existing sorted sublists.

tjr



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


Thought you would enjoy some funny math cartoons!!!

2007-12-06 Thread craig . snodgrass
I just wanted to share some math cartoons (mathtoons) I put together
at http://notsohumblepi.com.  I thought you guys might enjoy.  I tried
to figure out how to make a mathtoon involving Pi in place of Python
(like Pi in the middle of a snake) but couldn't get it to work.
Anyways, I hope you enjoy.  Thanks, Craig
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleXMLRPCServer interruptable?

2007-12-06 Thread Gabriel Genellina
En Thu, 06 Dec 2007 13:11:09 -0300, Bret [EMAIL PROTECTED] escribió:

 For completeness, what I ended up doing is this:

 server = SimpleXMLRPCServer((host, port))
 server.socket.settimeout(0.1)

 ServerWrapper became:

 def ServerWrapper():
 while True:
 try:
 server.handle_request()
 if self.done.isSet():
 break
 except timeout:
 pass

 And that seems to do the trick!  Giving the socket a timeout allows me
 to check the Event more frequently and catch the change within a
 reasonable time.

Remember that the timeout applies to *all* socket operations; what if the  
XML request requires more than 0.1s to read?
If handling large requests is more important than the delay at shutdown  
time, consider raising that value.

-- 
Gabriel Genellina

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


Re: Python Profiler GUI like Matlab?

2007-12-06 Thread sturlamolden
On 7 Des, 02:58, Davy [EMAIL PROTECTED] wrote:

 Is there any Python Profiler GUI like Matlab? I found the Matlab
 Profiler is very intuitive and easy to use.

There is a Python profiler. But is does not have a GUI.



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


Re: Capturing global input?

2007-12-06 Thread sturlamolden
On 6 Des, 22:51, nomihn0 [EMAIL PROTECTED] wrote:

 I'd like to accept mouse gestures and keyboard shortcuts as input to a
 program.

It depends on which GUI toolkit you use. Look in the wxPython, PyGTK,
tkinter or pygame documentation.


 The nature of this program requires that these commands be
 issued regardless of the currently active window.

As in keylogger?





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


Re: Timeout test hangs IDLE

2007-12-06 Thread Gabriel Genellina
En Thu, 06 Dec 2007 08:03:49 -0300, Andreas Tawn  
[EMAIL PROTECTED] escribió:

 There was a strange error when using 'print'  threads. When
 what I printed filled the entire screen, instead of moving
 all the text up, IDLE just hanged. Try running your code from
 the shell instead, to see if the problem is in IDLE.

 It looks like there's two issues here, an IDLE problem and a me
 problem ;o)

 I changed the countTest function to time.sleep(10) rather than a big
 loop. When I run the script from the command line, the timeout triggers
 properly after 5 seconds but the countTest function (running in a
 seperate thread now) continues for the whole 10 seconds. This is the
 me problem. I though that the timeout function would kill the
 countTest thread, but it seems like it doesn't do that. Rather, the
 timout just returns after 5 seconds with the message that the countTest
 thread is still alive. I guess I need to set event flags so the
 countTest function can end itself rather than trying to kill it from the
 main thread?

It's not your problem, the cookbook recipe your code is based on should  
make it clear: it does *not* kill the thread, it just returns to the  
caller earlier (at most when the timeout elapses). The thread continues to  
run (and consuming resources, of course).
If you actually want to stop a background task, the safest way would be  
for the thread to test some condition periodically and gracefully stop  
when requested. If that's not possible, and you have to forcibly kill a  
running thread, there is a different recipe at  
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 (follow the  
link at the end for an updated version).

 When I run it from IDLE, everything runs correctly, but after the
 countTest thread ends after 10 seconds, IDLE hangs as before. IDLE bug,
 maybe?

Not exactly; doing background tasks with a GUI is tricky and requires some  
kind of cooperation, else the interfase usually becomes unresponsive.
How to run background tasks depends on the GUI toolkit used. IDLE uses  
Tkinter, do you use that toolkit for your final program?

-- 
Gabriel Genellina

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


Re: Class destructor -- strange behaviour

2007-12-06 Thread MonkeeSage
On Dec 6, 3:51 pm, Spes [EMAIL PROTECTED] wrote:
 Hi,

 I have this simple code:
 | #!/usr/bin/python
 | import codecs
 | import re
 | from copy import deepcopy
 |
 | class MyClass(object):
 |   def __del__(self):
 | deepcopy(1)
 |
 | x=MyClass()

 but I get an error:
 | Exception exceptions.TypeError: 'NoneType' object is not callable
 in bound method MyClass.__del__ of __main__.MyClass object at
 0x6fcf0 ignored

 The problem disappears if I do anything of this:
 1. change
  - from copy import deepcopy
  + import copy
 and call directly copy.deepcopy(1)

 or
 2. don't store object to variable `x'

 or
 3. don't import module `re'

 The first solution is OK, but I would like to know why it behaves so
 strange. We have tested on:

 - Mac OS X Tiger for PPC
 Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
 [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

 - Linux 64bit and 32bit
 Python 2.4.4 (#1, Oct 30 2007, 14:31:50)
 [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2
 Python 2.5 (r25:51908, Jan 12 2007, 13:57:15)
 [GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2

 Thanks for the explanation,
 Vlasta

I can't explain why, but it also works if you call del x manually
before the script exits.

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


Re: Capturing global input?

2007-12-06 Thread MonkeeSage
On Dec 6, 9:16 pm, MonkeeSage [EMAIL PROTECTED] wrote:
 On Dec 6, 3:51 pm, nomihn0 [EMAIL PROTECTED] wrote:

  I'd like to accept mouse gestures and keyboard shortcuts as input to a
  program. The nature of this program requires that these commands be
  issued regardless of the currently active window. Here's the rub: I
  need a platform-independent solution.

  Java supports with its MouseInfo class, but I'd like a Python
  equivalent without turning to Jython.  Is this possible?

  Thanks in advance.

 There is no cross-platform way to do that. You have to use whatever
 interface the OS provides for that (e.g., Xlib events for X11). You
 could probably write a platform independent way by testing the OS and
 using the appropriate apis for that OS (assuming that there are python
 modules like python-xlib for other OS). I wonder why you'd want to
 though, if Java already provides a solution? If you don't want to muck
 with Java syntax, what about Jython?

 Regards,
 Jordan

Ps. I saw you said you didn't want Jython, but I can't see why.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >