Difference between 'function' and 'method'

2008-03-04 Thread 甜瓜
Howdy everyone,

 This is a big problem puzzles me for a long time. The core question is:
How to dynamically create methods on a class or an instance?

Let me state it step by step.
1.
def gunc(self):
pass
class A(object):
def func(self):
pass
a = A()
a.func   # gives "bound method", type is "instancemethod"
A.func  # gives "unbound method", type is "instancemethod"
gunc# gives "function", type if "function"

# ?? Does this line attach a method to instance?  ... I don't think so.
a.gunc = gunc

I found stardard library 'new' may help. Is that right?

2.
a = A()  # instance of old class A
# Do attach a new method to class A...
b = A()  # instance of new class A
Does "a" can get the new method automatically?
Does new method have the *same* concept level with old methods?
Especially, if there
are classes inherit from class A, how does name resolution work on this case?

3.
How do I write a decroator for a method? Eg:
class A(object):
@my_dec
def func(self):
pass
Here, my_dec should return a method rathar than a function/lambda. Am I right?
What does @property  @staticmethod... really do? I cannot step-into them for
source code.

4.
If most of above questions can be solved, then it would be easy to implement
the feature: "dynamic property attach".
Eg:
One class can read/store settings from/to some file based on
the file content.
# File: cfg.ini
x = 1
y = python
config = SettingClass('cfg.ini')  # dynamically build up properties x and y.
x = config.x  #  x will be set to 1   (str -> int convertion would be
done by 'property x')
y = config.y  #  y will be set to 'python'
config.x = 9   # 'x = 9' is written to cfg.ini.

How to implement
^_^ Maybe there are some library does the same thing. What is it? How
to implement ?


Thank you for your attention!

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


Re: Command line arguments in Windows

2008-03-04 Thread Chris
On Mar 4, 8:38 am, "Mike Walker" <[EMAIL PROTECTED]> wrote:
> > If you run a python file, ie. just double clicking it the only
> > argument you will have will be the filename of the script.  If you
> > create a shortcut to the script and in the target box add your
> > arguments (if you have quotation marks place them after not inside)
> > you will see your arguments.  fwiw you answered yourself in the third
> > paragraph.
>
> As I mentioned I am working from the command line, not clicking on the icon.
> The only difference between it working and not is the python prefix, which
> is why I was thinking this is some sort of file association problem.
>
> I probably wasn't as clear as I could have been in the third paragraph.
>
> argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0]
> python argtest.py arg1 arg2 arg3 - Works

That seems rather wierd, just running argtest.py arg1 arg2 arg3 I get
the correct output, Python 2.5.1 from python.org but running on XP
though.  Potentially an issue with Vista... ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Erik Max Francis
Mensanator wrote:

> On Mar 3, 11:58 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
>> Mensanator wrote:
>>> I'm not hard to please at all.
>> No, of course not, since logically you must think all software is useless.
> 
> Somehow, I expected better logic from people who call themselves
> programmers.

So you agree with me.  Lack of prefection = uselessness.  Thanks for 
being honest, whether your realized you defeated your own disclaimer or not.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   I wonder if heaven got a ghetto
-- Tupac Shakur
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: EasyExtend 3.0 - beta1 released

2008-03-04 Thread Kay Schluehr
After more than half a year of work I released the first beta of
EasyExtend 3.0 today. EasyExtend 3.0 is the second major redesign of
EasyExtend. To gain more power and simplicity I implemented a new
parser generator from the scratch called "Trail". Trail unifies
several aspects of EasyExtend. It is the fundament of both the EE 3.0
tokenizer and the parser. It is used to validate parse trees against
grammars and it is used for parse tree synthesis.

Besides Trail other new aspects of EE 3.0 are

* User defined file suffixes are recognized by the import
machinery
* Framework extension that supports facilitation of writing user
defined tokenizers
* Simplification of access to tokenizer and parser from individual
extension languages ( langlets ).
* Improved stability of the CST transformation process and
improved debugging facilities

Currently EasyExtend 3.0 does not support several extension languages
being described on the home page. Some of them like the macro langlet
will be reimplemented in EasyExtend 3.1 using Trail techniques and a
new persistence layer called exo.space. Others will be upgraded until
the final release of EasyExtend 3.0.

URLs:

http://www.fiber-space.de/EasyExtend/doc/EE.html
http://pypi.python.org/pypi/EasyExtend/3.0-beta1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble using XML Reader

2008-03-04 Thread Mike D
On 3/3/08, Mike D <[EMAIL PROTECTED]> wrote:
>
> Hello,
>
> I'm using XML Reader (xml.sax.xmlreader.XMLReader) to create an rss
> reader.
>
> I can parse the file but am unsure how to extract the elements I require.
> For example: For each  element I want the title and description.
>
> I have some stub code; I want to create a list of objects which include a
> title and description.
>
> I have the following code (a bit hacked up):
>
> import sys
> from xml.sax import make_parser
> from xml.sax import handler
>
> class rssObject(object):
> objectList=[]
> def addObject(self,object):
> rssObject.objectList.append(object)
>
> class rssObjectDetail(object):
> title = ""
> content = ""
>
>
> class SimpleHandler(handler.ContentHandler):
> def startElement(self,name,attrs):
> print name
>
> def endElement(self,name):
> print name
>
> def characters(self,data):
> print data
>
>
> class SimpleDTDHandler(handler.DTDHandler):
> def notationDecl(self,name,publicid,systemid):
> print "Notation: " , name, publicid, systemid
>
> def unparsedEntityDecl(self,name,publicid,systemid):
> print "UnparsedEntity: " , name, publicid, systemid, ndata
>
> p= make_parser()
> c = SimpleHandler()
> p.setContentHandler(c)
> p.setDTDHandler(SimpleDTDHandler())
> p.parse('topstories.xml')
>
> And am using this xml file:
>
> 
> 
>   
> Stuff.co.nz - Top Stories
> http://www.stuff.co.nz
> Top Stories from Stuff.co.nz. New Zealand, world, sport,
> business & entertainment news on Stuff.co.nz. 
> en-nz
> Fairfax New Zealand Ltd.
> 30
> 
>   /static/images/logo.gif
>   Stuff News
>   http://www.stuff.co.nz
> 
>
> 
> Prince Harry 'wants to live in Africa'
> http://www.stuff.co.nz/4423924a10.html?source=RSStopstories_20080303
> 
> For Prince Harry it must be the ultimate dark irony: to be in
> such a privileged position and have so much opportunity, and yet be unable
> to fulfil a dream of fighting for the motherland.
> EDMUND TADROS
> stuff.co.nz/4423924
> Mon, 03 Mar 2008 00:44:00 GMT
> 
>
>   
> 
>
> Is there something I'm missing? I can't figure out how to correctly
> interpret the document using the SAX parser. I'm sure I;'m missing something
> obvious :)
>
> Any tips or advice would be appreciated! Also advice on correctly
> implementing what I want to achieve would be appreciated as using
> objectList=[] in the ContentHandler seems like a hack.
>
> Thanks!
>

My mistake, The provided example is a SAX object, which can be parsed with
DOM manipulation. I'll be able to do it now :)

Oh, I also
posted a hacked up implementation, I understand my classes look awful!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: tools to install not in python tree?

2008-03-04 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hello,
> 
> I have some materials for a project that I am working on that I keep
> in a source code control system (svn now, but I'm experimenting with
> mercurial).  I want to install these things from the repository, but
> not into site-packages/ as Distutils wants to do.
> 
> For instance there are some administrative scripts I want to put in ~/
> admin/  and some programs that I want in ~/public_html/ .   I also
> want to run some post-install routines (for instance, reset the
> database tables on my development machine).  So I'm looking for a tool
> to take things from a repository and install them into place.
> Something like:
>   install_from_repository.py -version "1.2.7"
> if there is a bug in 1.2.7 that I need to work on.
> 
> Some of the things that I am looking for are like what setup.py does
> (for instance, changing the #! line on scripts or having a
> convenient .cfg file).  But as I understand it setup only targets
> installing below sys.prefix; is that right?

You can use setuptools. And it will install to any path available on
sys.path. So if you define PYTHONPATH pointing to some folder, you can use
setuptools to install the code (eggs) as well as create script
entry-points, so if the same path is part of PATH they will become
available on the command line.

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


Re: Difference between 'function' and 'method'

2008-03-04 Thread Paul Boddie
On 4 Mar, 09:22, "甜瓜" <[EMAIL PROTECTED]> wrote:
>
>  This is a big problem puzzles me for a long time. The core question is:
> How to dynamically create methods on a class or an instance?
>
> Let me state it step by step.
> 1.
> def gunc(self):
> pass
> class A(object):
> def func(self):
> pass
> a = A()
> a.func   # gives "bound method", type is "instancemethod"
> A.func  # gives "unbound method", type is "instancemethod"
> gunc# gives "function", type if "function"
>
> # ?? Does this line attach a method to instance?  ... I don't think so.
> a.gunc = gunc

No, unfortunately not. You might get the detailed explanation from
someone else, but generally, you have to assign functions to classes;
these are then exposed as methods via instances of such classes.

  A.gunc = gunc

> I found stardard library 'new' may help. Is that right?

Yes, it can help:

  import new
  a.gunc = new.instancemethod(gunc, a, A)

> 2.
> a = A()  # instance of old class A
> # Do attach a new method to class A...
> b = A()  # instance of new class A
> Does "a" can get the new method automatically?

Can "a" get the new method automatically? Apparently, yes:

  class A:
  pass

  a = A()

  def f(self, x):
  print x

  A.f = f
  a.f(123) # works, printing 123

> Does new method have the *same* concept level with old methods?
> Especially, if there
> are classes inherit from class A, how does name resolution work on this case?

As far as I'm aware, after you've added a method to a class, instances
will regard the method like all the previously existing methods, since
method lookup is a dynamic operation.

I'll not address your other questions in this message since I'm not a
heavy user of decorators and don't want to provide a quick answer
without fully testing it first. However, it is important to remember
that the "magic" occurs for class attributes, not instance attributes.
So, for example, it's quite possible that you'd want to assign a
function to an instance attribute, but you wouldn't want the instance
to suddenly "own" that function...

  def somefunc(x, y):
  # Do something with x and y...
  return x + y

  a = A()
  a.somefunc = somefunc # store the function somewhere

  # Later...

  adder = a.somefunc

  # Later still...

  result = adder(p, q) # wouldn't work if somefunc became a method

Python seems to do the most intuitive thing, I think, but it's quite
tricky to contemplate all the implications.

Paul

P.S. I can never really remember all the different situations and
outcomes with method assignment, but then it's something I hardly ever
do. I'd be interested to know whether my situation is unusual, however.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: tools to install not in python tree?

2008-03-04 Thread M.-A. Lemburg
On 2008-03-04 02:55, [EMAIL PROTECTED] wrote:
> Hello,
> 
> I have some materials for a project that I am working on that I keep
> in a source code control system (svn now, but I'm experimenting with
> mercurial).  I want to install these things from the repository, but
> not into site-packages/ as Distutils wants to do.
> 
> For instance there are some administrative scripts I want to put in ~/
> admin/  and some programs that I want in ~/public_html/ .   I also
> want to run some post-install routines (for instance, reset the
> database tables on my development machine).  So I'm looking for a tool
> to take things from a repository and install them into place.
> Something like:
>   install_from_repository.py -version "1.2.7"
> if there is a bug in 1.2.7 that I need to work on.
> 
> Some of the things that I am looking for are like what setup.py does
> (for instance, changing the #! line on scripts or having a
> convenient .cfg file).  But as I understand it setup only targets
> installing below sys.prefix; is that right?

The distutils "install" command provides a lot of what you're looking for,
in particular, it makes it easy to install the various parts of
a package in different directories:

$ python2.5 setup.py install --help
Common commands: (see '--help-commands' for more)

   setup.py build  will build the package underneath 'build/'
   setup.py installwill install the package

Global options:
   --verbose (-v)  run verbosely (default)
   --quiet (-q)run quietly (turns verbosity off)
   --dry-run (-n)  don't actually do anything
   --help (-h) show detailed help message
   --set-version   override the package version number

Options for 'mx_install' command:
   --prefixinstallation prefix
   --exec-prefix   (Unix only) prefix for platform-specific files
   --home  (Unix only) home directory to install under
   --install-base  base installation directory (instead of --prefix or --
   home)
   --install-platbase  base installation directory for platform-specific files
   (instead of --exec-prefix or --home)
   --root  install everything relative to this alternate root
   directory
   --install-purelib   installation directory for pure Python module
   distributions
   --install-platlib   installation directory for non-pure module distributions
   --install-lib   installation directory for all module distributions
   (overrides --install-purelib and --install-platlib)
   --install-headers   installation directory for C/C++ headers
   --install-scripts   installation directory for Python scripts
   --install-data  installation directory for data files
   --compile (-c)  compile .py to .pyc [default]
   --no-compiledon't compile .py files
   --optimize (-O) also compile with optimization: -O1 for "python -O", -O2
   for "python -OO", and -O0 to disable [default: -O0]
   --force (-f)force installation (overwrite any existing files)
   --skip-buildskip rebuilding everything (for testing/debugging)
   --recordfilename in which to record list of installed files

usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help

> I can write routines for myself but other people must need to do these
> things also and a tested solution is obviously better.  Is there such
> a tool?

Things that the stock distutils cannot do out of the box can
easily be added by subclassing commands or adding new ones
in your setup.py.

For some examples how this can be done, have a look at e.g.
the mxSetup.py module we ship with the eGenix mx Base Distribution:

http://www.egenix.com/products/python/mxBase/

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Mar 04 2008)
 >>> Python/Zope Consulting and Support ...http://www.egenix.com/
 >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python logging: Retrieving the last log record from a handler

2008-03-04 Thread Vinay Sajip
On Mar 3, 11:41 am, Frank Aune <[EMAIL PROTECTED]> wrote:
> I will be fairly surprised if this functionality is not already built-in for
> the defaultlogginghandlers, but so far I've been unable to figure out how
> to pull it of without the custom loghandler above.

Prepare to be surprised ;-)

Except for the MemoryHandler, which is designed specifically as a
buffer for logging events, the handlers in the logging package do not
store the last record they processed. (Neither do loggers, filters or
formatters, all of which get to see records as they are processed.)

Best regards,

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


Re: tools to install not in python tree?

2008-03-04 Thread commander_coder
Thank you for the helpful replies.  I shall check out the links.  (I
looked at some setup.py's but mxBase was not among them.)

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


Re: Difference between 'function' and 'method'

2008-03-04 Thread Bruno Desthuilliers
?? a écrit :
> Howdy everyone,
> 
>  This is a big problem puzzles me for a long time. The core question is:
> How to dynamically create methods on a class or an instance?

class Foo(object):
pass

def bar(self, arg):
print "in bar : self == % - arg == %s" % (self, str(arg))

def baaz(self, arg):
print "in baaz : self == % - arg == %s" % (self, str(arg))


f = Foo()

# adding bar as a method to class Foo
Foo.bar = bar

# f now can use bar:
f.bar(42)

# as well as new instances of Foo, of course
g = Foo()
g.bar()

# adding baaz as a method to f, the old way:
import new
f.baaz = new.instancemethod(baaz, f, type(f))

f.baaz()

# adding baaz as a method to g, the other way:
g.baaz = baaz.__get__(g, type(g))

g.baaz()


> Let me state it step by step.
> 1.
> def gunc(self):
> pass
> class A(object):
> def func(self):
> pass
> a = A()
> a.func   # gives "bound method", type is "instancemethod"
> A.func  # gives "unbound method", type is "instancemethod"
> gunc# gives "function", type if "function"
> 
> # ?? Does this line attach a method to instance?  ... I don't think so.
> a.gunc = gunc

It doesn't.


> I found stardard library 'new' may help. Is that right?

cf above. If you work with old-style classes, you'll need 
new.instancemethod.

> 2.
> a = A()  # instance of old class A
> # Do attach a new method to class A...
> b = A()  # instance of new class A
> Does "a" can get the new method automatically?

Yes. In Python, a class is itself an object, and is an attribute of it's 
instances (instance.__class__). Names are resolved at runtime, and 
attributes not found in the instance's __dict__ are looked up in the 
class (and then in the superclasses etc).

> Does new method have the *same* concept level with old methods?

The newly added method works exactly the same way as already existing 
ones. Not a single difference. The class statement is just syntactic 
sugar anyway. The following snippets are equivalent:

# sugar-coated:
class Boo(object):
 faaz = 0

 def far(self):
 type(self).faaz += 1
 print self

 def frob(self):
 print "yadda"

# raw:
def far(self):
 type(self).faaz += 1
 print self

Boo = type('Boo', (object,), dict(faaz=0, far=far))

def frob(self):
print "yadda"

Boo.frob = frob

> Especially, if there
> are classes inherit from class A, how does name resolution work on this case?

As usual.

> 3.
> How do I write a decroator for a method?

Mostly the same way you'd write a decorator for a function

> Eg:
> class A(object):
> @my_dec
> def func(self):
> pass
> Here, my_dec should return a method rathar than a function/lambda. Am I right?

Nope. Functions defined within a class statement are plain ordinary 
functions. It's the lookup mechanism that "turns them into methods" when 
they are looked up as attribute of a class. In fact, Python "methods" 
are thin callable wrappers around a function, a class and (most of the 
time) an instance, wrappers which are created - usually at lookup time - 
by the __get__ method of the function type (you may want to read about 
the descriptor protocol on python.org - in the section about new style 
classes IIRC).

Anyway, you can explore this by yourself:

 >>> Boo.far

 >>> b.far
>
 >>> Boo.__dict__['far']

 >>> Boo.__dict__['far'] is far
True
 >>> f1 = b.far
 >>> f2 = b.far
 >>> f1 is f2
False
 >>> f1()
<__main__.Boo object at 0xb787f96c>
 >>> f2()
<__main__.Boo object at 0xb787f96c>
 >>> dir(f1)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', 
'__get__', '__getattribute__', '__hash__', '__init__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 
'im_class', 'im_func', 'im_self']
 >>> f1.im_class

 >>> f1.im_func

 >>> f1.im_func is far
True
 >>> f1.im_self
<__main__.Boo object at 0xb787f96c>
 >>> f1.im_self is b
True
 >>> bf = Boo.far
 >>> bf.im_func

 >>> bf.im_func is far
True
 >>> bf.im_class

 >>> bf.im_self
 >>> bf.im_self is None
True
 >>> far.__get__(b, Boo)
>
 >>> far.__get__(b, Boo).im_func is far
True
 >>>


So, to answer your question: what you are decorating are functions, not 
methods.

> What does @property  @staticmethod... really do? I cannot step-into them for
> source code.

staticmethod wraps the function into an object that, when looked up as 
an attribute, will return the raw function instead of returning a method.

property is a type that provides a simple generic implementation for 
computed attributes. You'll find more detailed explanations in the doc 
(but perhaps not in the most obvious place - it's somewhere in the peps 
or in the 'nws style classes' stuff IIRC). Anyway, using it as a 
decorator is a somewhat special case (well... to me at least), that will 
defined a property with only a getter (the decorated function).

> 4.
> If most of above questions can be solved, then it would be easy to implement
> the feature: "dynamic property attach".
> Eg:
> One class can read/store settings 

Re: Command line arguments in Windows

2008-03-04 Thread Steve Holden
Chris wrote:
> On Mar 4, 8:38 am, "Mike Walker" <[EMAIL PROTECTED]> wrote:
>>> If you run a python file, ie. just double clicking it the only
>>> argument you will have will be the filename of the script.  If you
>>> create a shortcut to the script and in the target box add your
>>> arguments (if you have quotation marks place them after not inside)
>>> you will see your arguments.  fwiw you answered yourself in the third
>>> paragraph.
>> As I mentioned I am working from the command line, not clicking on the icon.
>> The only difference between it working and not is the python prefix, which
>> is why I was thinking this is some sort of file association problem.
>>
>> I probably wasn't as clear as I could have been in the third paragraph.
>>
>> argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0]
>> python argtest.py arg1 arg2 arg3 - Works
> 
> That seems rather wierd, just running argtest.py arg1 arg2 arg3 I get
> the correct output, Python 2.5.1 from python.org but running on XP
> though.  Potentially an issue with Vista... ?

Strange as it may seem, there have been issues with other Windows 
command processors, and one in particular (I can never remember which 
one) messes up IO redirection when the pathext mechanism is used to 
select the executable that processes the Python file.

So I would tend to suspect yet another variation on this familiar theme 
given your testing results. But I don't intend to tangle with Vaster any 
sooner than I must.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Embedding a literal "\u" in a unicode raw string.

2008-03-04 Thread NickC
On Feb 26, 8:45 am, rmano <[EMAIL PROTECTED]> wrote:
> BTW, 2to3.py should warn when a raw string (not unicode) with \u in
> it, I think.
> I tried it and it seems to ignore the problem...

Python 3.0a3+ (py3k:61229, Mar  4 2008, 21:38:15)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> r"\u"
'\\u'
>>> r"\uparrow"
'\\uparrow'
>>> r"\u005c"
'\\u005c'
>>> r"\N{REVERSE SOLIDUS}"
'\\N{REVERSE SOLIDUS}'
>>> "\u005c"
'\\'
>>> "\N{REVERSE SOLIDUS}"
'\\'

2to3.py may be ignoring a problem, but existing raw 8-bit string
literals containing a '\u' aren't going to be it. If anything is going
to have a problem with conversion to Py3k at this point, it is raw
Unicode literals that contain a Unicode escape.
-- 
http://mail.python.org/mailman/listinfo/python-list


Eurosymbol in xml document

2008-03-04 Thread Hellmut Weber
Hi,
i'm new here in this list.

i'm developing a little program using an xml document. So far it's easy 
going, but when parsing an xml document which contains the EURO symbol 
('€') then I get an error:

UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in 
position 11834: character maps to 

the relevant piece of code is:

from xml.dom.minidom import Document, parse, parseString
...
doc = parse(inFIleName)


[EMAIL PROTECTED] usexml $ locale
[EMAIL PROTECTED]
LC_CTYPE="[EMAIL PROTECTED]"
LC_NUMERIC="[EMAIL PROTECTED]"
LC_TIME="[EMAIL PROTECTED]"
LC_COLLATE="[EMAIL PROTECTED]"
LC_MONETARY="[EMAIL PROTECTED]"
LC_MESSAGES="[EMAIL PROTECTED]"
LC_PAPER="[EMAIL PROTECTED]"
LC_NAME="[EMAIL PROTECTED]"
LC_ADDRESS="[EMAIL PROTECTED]"
LC_TELEPHONE="[EMAIL PROTECTED]"
LC_MEASUREMENT="[EMAIL PROTECTED]"
LC_IDENTIFICATION="[EMAIL PROTECTED]"
[EMAIL PROTECTED]


any help appreciated

Hellmut

-- 
Dr. Hellmut Weber [EMAIL PROTECTED]
Degenfeldstraße 2 tel   +49-89-3081172
D-80803 München-Schwabing mobil +49-172-8450321
please: No DOCs, no PPTs. why: tinyurl.com/cbgq

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


Re: Eurosymbol in xml document

2008-03-04 Thread Diez B. Roggisch
Hellmut Weber wrote:

> Hi,
> i'm new here in this list.
> 
> i'm developing a little program using an xml document. So far it's easy
> going, but when parsing an xml document which contains the EURO symbol
> ('€') then I get an error:
> 
> UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in
> position 11834: character maps to 
> 
> the relevant piece of code is:
> 
> from xml.dom.minidom import Document, parse, parseString
> ...
> doc = parse(inFIleName)

The contents of the file must be encoded with the proper encoding which is
given in the XML-header, or has to be utf-8 if no header is given.

From the above I think you have a latin1-based document. Does the encoding
header match?


> 
> [EMAIL PROTECTED] usexml $ locale
> [EMAIL PROTECTED]
> LC_CTYPE="[EMAIL PROTECTED]"
> LC_NUMERIC="[EMAIL PROTECTED]"
> LC_TIME="[EMAIL PROTECTED]"
> LC_COLLATE="[EMAIL PROTECTED]"
> LC_MONETARY="[EMAIL PROTECTED]"
> LC_MESSAGES="[EMAIL PROTECTED]"
> LC_PAPER="[EMAIL PROTECTED]"
> LC_NAME="[EMAIL PROTECTED]"
> LC_ADDRESS="[EMAIL PROTECTED]"
> LC_TELEPHONE="[EMAIL PROTECTED]"
> LC_MEASUREMENT="[EMAIL PROTECTED]"
> LC_IDENTIFICATION="[EMAIL PROTECTED]"
> [EMAIL PROTECTED]

This is irrelevant.

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

Removing default logging handler (causes duplicate logging)

2008-03-04 Thread Gal Aviel
Hello All,

I want to add a logger to my application, then addHandler to it to log to a
special destination.

Unfortunately when I use logging.getLogger("my_logger") to create the new
logger, it apparently comes with a default handler that logs to STDOUT (or
STDERR?). When I add my special handler it works Ok, but still logs to terminal,
which I do not want.

The only way I found to remove the default handler is by using
'logger.removeHandler(logger.handlers[0])'.

Is there a more elegant solution that uses the logging API?

my setup: Python 2.5.1 on Linux Suse 9. 

P.S.I am not using Basic config, just 'import logging' and then regular
logging.* calls.

Thanks in advance, 
Gal Aviel.

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


Re: Eurosymbol in xml document

2008-03-04 Thread Stephan Diehl
Hallo Helmut,

> Hi,
> i'm new here in this list.
> 
> i'm developing a little program using an xml document. So far it's easy
> going, but when parsing an xml document which contains the EURO symbol
> ('€') then I get an error:
> 
> UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in
> position 11834: character maps to 

first of all, unicode handling is a little bit difficult, when encountered
the first time, but in the end, it really makes a lot of sense :-)
Please read some python unicode tutorial like
http://www.amk.ca/python/howto/unicode

If you open up a python interactive prompt, you can do the following:
>>> print u'\u20ac'
€
>>> u'\u20ac'.encode('utf-8')
'\xe2\x82\xac'
>>> u'\u20ac'.encode('iso-8859-15')
'\xa4'
>>> u'\u20ac'.encode('iso-8859-1')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'latin-1' codec can't encode character u'\u20ac' in
position 0: 

\u20ac is the unicode code point for the Euro sign, so u'\u20ac' is the
unicode euro sign in python. The different encode calls translate the
unicode into actual encodings.
What you are seeing in your xml document is the iso-8859-15 encoded euro
sign. As Diez already noted, you must make shure, that 
1. the whole xml document is encoded in latin-15 and the encoding header
reflects that
or
2. make sure that the utf-8 encoded euro sign is in your xml document.

Hope that makes sense

Stephan

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

Re: News from Jython world

2008-03-04 Thread Ant
On Mar 3, 6:40 pm, Sébastien Boisgérault
<[EMAIL PROTECTED]> wrote:
> Frank Wierzbicki and Ted Leung have been hired by Sun. Frank is a
> key Jython developer and is specifically hired to work full time on
> Jython, a version of the Python interpreter that runs on top of the
> JVM and provides full access to Java libraries. After a period where
> the development had slowed, Jython was recently getting seriously
> back on track. Now it's getting even better !

Development on Jython over the last year or so has been superb, and
it's good to see that Sun are getting really focused on dynamic
languages on the JVM. It may be that they are trying to play keep-up
with Microsoft and their support of IronPython - but regardless of the
reasons it is good news for Jython and Frank W, and for the Python
community in general.

A Sun endorsement of Jython means the possibility of more Python jobs
out there for us all in the future given the ubiquity of the JVM in
the enterprise and willingness of corporations to accept such
endorsements!

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


Re: Eurosymbol in xml document

2008-03-04 Thread Robert Bossy
Diez B. Roggisch wrote:
> Hellmut Weber wrote:
>
>   
>> Hi,
>> i'm new here in this list.
>>
>> i'm developing a little program using an xml document. So far it's easy
>> going, but when parsing an xml document which contains the EURO symbol
>> ('€') then I get an error:
>>
>> UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in
>> position 11834: character maps to 
>>
>> the relevant piece of code is:
>>
>> from xml.dom.minidom import Document, parse, parseString
>> ...
>> doc = parse(inFIleName)
>> 
>
> The contents of the file must be encoded with the proper encoding which is
> given in the XML-header, or has to be utf-8 if no header is given.
>
> From the above I think you have a latin1-based document. Does the encoding
> header match?
If the file is declared as latin-1 and contains an euro symbol, then the 
file is actually invalid since euro is not defined of in iso-8859-1. If 
there is no encoding declaration, as Diez already said, the file should 
be encoded as utf-8.

Try replacing or adding the encoding with latin-15 (or iso-8859-15) 
which is the same as latin-1 with a few changes, including the euro symbol:




If your file has lot of strange diacritics, you might take a look on the 
little differences between latin-1 and latin-15 in order to make sure 
that your file won't be broken:
http://en.wikipedia.org/wiki/ISO_8859-15

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

Re: pySQLite Insert speed

2008-03-04 Thread mmm

Steve,  I think you were right the first time is saying

> it should really be this:
> sqlxb= 'INSERT INTO DTABLE2 VALUES (?, ?, ?, ?)'

my copy.copy() has the equivalent effect.

Running this test code produces the output below

import copy

print 'Test 1'
pf= '?,?,?,?'
sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf
print sqlx1

print
print 'Test 2'
sqlx2= copy.copy(sqlx1)
sqlx3= sqlx1
pf= '?,?,?, '
sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf
print 'sqlx1= ', sqlx1
print 'sqlx2= ', sqlx2
print 'sqlx3= ', sqlx2

== output
Test group 1
INSERT INTO DTABLE2 VALUES ( ?,?,?,? )

Test group 2
sqlx1=  INSERT INTO DTABLE2 VALUES ( ?,?,?,  )
sqlx2=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
sqlx3=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )

I interpret this to mean that sqlx1 is not a simple string
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pySQLite Insert speed

2008-03-04 Thread Steve Holden
mmm wrote:
> Steve,  I think you were right the first time is saying
> 
>> it should really be this:
>> sqlxb= 'INSERT INTO DTABLE2 VALUES (?, ?, ?, ?)'
> 
> my copy.copy() has the equivalent effect.
> 
> Running this test code produces the output below
> 
> import copy
> 
> print 'Test 1'
> pf= '?,?,?,?'
> sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf
> print sqlx1
> 
> print
> print 'Test 2'
> sqlx2= copy.copy(sqlx1)
> sqlx3= sqlx1
> pf= '?,?,?, '
> sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf
> print 'sqlx1= ', sqlx1
> print 'sqlx2= ', sqlx2
> print 'sqlx3= ', sqlx2
> 
> == output
> Test group 1
> INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
> 
> Test group 2
> sqlx1=  INSERT INTO DTABLE2 VALUES ( ?,?,?,  )
> sqlx2=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
> sqlx3=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
> 
> I interpret this to mean that sqlx1 is not a simple string

Sorry, since you didn't copy and paste the actual code you ran I don't 
regard those results as reliable.

What I will repeat, however, is that while there is a *slight* 
difference is semantics between

s = "some string"
s1 = s

and

s = "some string"
s1 = copy.copy(s)

that difference is only to ensure that s and s1 point to different 
copies of the same string in the latter case, whereas in the former case 
  s and s1 point to the same string.

Since strings are immutable in Python this really doesn't make any 
difference. In either case changing the value of s will leave the value 
of s1 unchanged, since it will still point to the string it was 
originally bound to and s will point to some other string.

I suspect some superstition is at play here, or possibly you are cargo 
cult programming :)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


for-else

2008-03-04 Thread bearophileHUGS
So far in Python I've almost hated the 'else' of the 'for' loops:
- I have problems to remember its meaning;
- It gives me little problems when I later want to translate Python
code to other languages (and you always have to translate long-lived
code).
- I have used it only once, so far.

So so far I'd liked to see it removed from Python 3.0.

But then this article:
http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel_language_features
has shown me that my problems with the 'else' of the 'for' mostly come
from just its bad naming. The converge language is yet another very
Python-like language, and it uses a better naming (the word
"exhausted" is long and has a complex spelling for non-English
speakers, so it's not perfect):

for ...:
...
exhausted:
...
broken:
...

The meaning is explicit. While "else" seems to mean little there.
So I may like something similar for Python 3.x (or the removal of the
"else").

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


Re: Eurosymbol in xml document

2008-03-04 Thread Diez B. Roggisch
> If the file is declared as latin-1 and contains an euro symbol, then the
> file is actually invalid since euro is not defined of in iso-8859-1. If
> there is no encoding declaration, as Diez already said, the file should
> be encoded as utf-8.
> 

You are right of course - latin1 doesn't contain the euro-symbol.
ISO-8859-15 it is. Dumb me.

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


Re: How about adding rational fraction to Python?

2008-03-04 Thread NickC
On Mar 4, 7:11 am, Lie <[EMAIL PROTECTED]> wrote:
> On Mar 2, 11:36 pm, Paul Rubin  wrote:
> > > > Try with a=7, b=25
>
> > > They should still compare true, but they don't. The reason why they
> > > don't is because of float's finite precision, which is not exactly
> > > what we're talking here since it doesn't change the fact that
> > > multiplication and division are inverse of each other.
>
> > What?  Obviously they are not exact inverses for floats, as that test
> > shows.  They would be inverses for mathematical reals or rationals,
> > but Python does not have those.
>
> When I said multiplication and division are inverse, I was pointing
> out the fact that even though float's inexactness make them imperfect
> inverse, mult & div are still inverse of each other. In-practice, the
> inversing behavior is impossible unless we have a way to represent
> real number (which we don't), and the *workaround* to make them work
> is to do epsilon comparison.

A mildly interesting Py3k experiment:

Python 3.0a3+ (py3k:61229, Mar  4 2008, 21:38:15)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> def check_accuracy(num_type, max_val=1000):
... wrong = 0
... for x in range(1, max_val):
... for y in range(1, max_val):
... wrong += (x / num_type(y)) * y != x
... return wrong
...
>>> check_accuracy(float)
101502
>>> check_accuracy(Decimal)
310013
>>> check_accuracy(Fraction)
0


The conclusions I came to based on running that experiment are:
- Decimal actually appears to suffer more rounding problems than float
for rational arithmetic
- Decimal appears to be significantly slower than Fraction for small
denominator rational arithmetic
- both Decimal and Fraction are significantly slower than builtin
floats

The increased number of inaccurate answers with Decimal (31% vs 10%)
is probably due to the fact that it is actually more precise than
float - for the builtin floats, the rounding error in the division
step may be cancelled out by a further rounding error in the
multiplication step (this can be seen happening in the case of ((1 /
3.0) * 3) == 1.0, where the result of the multiplication ends up being
1.0 despite the rounding error on division, due to the next smallest
floating value being 0.99989).

The speed difference between Decimal and Fraction is likely due to the
fact that Fraction can avoid actually doing any division most of the
time - it does addition and multiplication instead. The main reason
behind the overall speed advantage of builtin floats should hopefully
be obvious ;)

Regardless, the result of integer division is going to be a binary
floating point value in Py3k. For cases where that isn't adequate or
acceptable, the application should really be tightly controlling its
numeric types anyway and probably using a high performance math
library like numpy or gmpy instead of the standard numeric types (as
others have already noted in this thread).


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


Re: 'normal' shell with curses

2008-03-04 Thread Thynnus
On 3/3/2008 9:57 PM, Michael Goerz wrote:
> Hi,
> 
> I'm trying to print out text in color. As far as I know, curses is the 
> only way to do that (or not?). So, what I ultimately want is a curses 
> terminal that behaves as closely as possible as a normal terminal, i.e. 
> it breaks lines and scrolls automatically, so that I can implement a 
> function myprint(color, text) that does what print() does, only in color.

You might find the below helpful. Let us know how you make out?



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

Title:
  Using terminfo for portable color output & cursor control

Description:
The curses module defines several functions (based on terminfo) that can be 
used to perform lightweight cursor control & output formatting (color, bold, 
etc). These can be used without invoking curses mode (curses.initwin) or using 
any of the more heavy-weight curses functionality. This recipe defines a 
TerminalController class, which can make portable output formatting very 
simple. Formatting modes that are not supported by the terminal are simply 
omitted.



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


Re: Eurosymbol in xml document

2008-03-04 Thread Richard Brodie

"Robert Bossy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> If the file is declared as latin-1 and contains an euro symbol, then the file 
> is 
> actually invalid since euro is not defined of in iso-8859-1.

Paradoxical would be a better description than invalid, if it contains
things that it can't contain. If you decoded iso-8859-15 as if it were
iso-8859-1, you would get u'\xa4' (Currency Sign) instead of the
Euro. From the original error:

"UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in
position 11834: character maps to "

that seems to be what happened, as you said. 


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


Re: pySQLite Insert speed

2008-03-04 Thread Peter Otten
Steve Holden wrote:

> What I will repeat, however, is that while there is a *slight*
> difference is semantics between
> 
> s = "some string"
> s1 = s
> 
> and
> 
> s = "some string"
> s1 = copy.copy(s)
> 
> that difference is only to ensure that s and s1 point to different
> copies of the same string in the latter case, whereas in the former case
> s and s1 point to the same string.

No, both "point" to the same string:

>>> import copy
>>> s = "some string"
>>> s1 = s
>>> s1 is s
True
>>> s2 = copy.copy(s)
>>> s2 is s
True

copy.copy() is just an expensive no-op here.

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


Re: How about adding rational fraction to Python?

2008-03-04 Thread Mark Dickinson
On Mar 4, 8:46 am, NickC <[EMAIL PROTECTED]> wrote:
> The increased number of inaccurate answers with Decimal (31% vs 10%)
> is probably due to the fact that it is actually more precise than
> float

I suspect it has more to do with the fact that 10 is bigger than 2,
though I'm not sure I could precisely articulate the reasons why
this matters.  (A bigger base means a bigger 'wobble', the wobble
being the variation in the relationship between an error of 1ulp and
a relative error of base**-precision.)

Rerunning your example after a

getcontext().prec = 16

(i.e. with precision comparable to that of float) gives

>>> check_accuracy(Decimal)
310176

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


http server performance

2008-03-04 Thread bharath venkatesh
hi,
   my project involves lot of  I/O  over the network.. one part of my
project involves a server(http) which is listening on the port for many
client . this sever fetches an image from the web and  and send it to
clients   and many clients will request the server concurrently .. to
implement concurrent serving to clients i used threaded http server
like this

class HTTPServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer):
 pass

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def do_GET(self):
 print "received connection from: ",self.client_address
 image=image_retreive()   #where image retreive is a function that
retrieves image from the web and works fine
 self.send_response(200)
 self.send_header("Content-type",format)
 self.send_header("Content-Length",len(image_data))
 self.end_headers()
 self.request.sendall(image_data)

httpd = HTTPServer(('',port_number), RequestHandler)
httpd.serve_forever()


this code worked fine but this performance was very bad ... it workes fine
if the clients requested for small n medium size images as the server sends
the response immediately and also workes fine if one client is requesting a
large image (obviously server takes time to send response  as  it takes time
to fetch the image from the web ) and other clients concurrently request for
small and medium images  these  clients will  be served immediately even if
the other client is waiting but problem crops up when 2 clients concurrently
request for an large image .. while these  two clients are waiting for the
response fromthe server . The server doesn't accept any other client request
... i can see this as i am printing the  address of the client that connects
with server   in the 1st line of get method  of the request handler if two
clients concurrently request for an large image and only two clients address
gets printed  that means only 2 clients receives connection to the server
even if  other clients  are requesting  the server at the same time and
other servers are served only after the  those 2 server releases the
connection or get the response . that means server servers only 2 clients at
a time .this is very undesirable as even if 3rd client is requesting for
very small image and 2 clients are waiting for large image .. 3rd client
won't receive the response until those 2 clients are  served . to make thing
worst my server should serve 10 to 15 clients concurrently

to solve this i did some searching and found about cherrypy and twisted also
implemented my server in cherrypy
like this

from cherrypy import wsgiserver
def image_httpserver_app(environ, start_response):
print >>sys.stdout,"received connection from: (%s : %s ) \nthe image url
is: %s " %
(environ["REMOTE_ADDR"],environ["REMOTE_PORT"],environ["QUERY_STRING"])
status = '200 OK'
response_headers = [('Content-type',format)]
 image=image_retreive()
 response_headers = [("Content-Length",`len(image_data)`)]
 start_response(status, response_headers)
 return [image_data]

mappings=[('/', image_httpserver_app)]
wsgi_apps = mappings
server = wsgiserver.CherryPyWSGIServer(('localhost', ), wsgi_apps,

server_name='localhost',numthreads=20)

if __name__ == '__main__':
  try:
  server.start()
  except KeyboardInterrupt:
  server.stop()

this didn't solve the problem at all .. same thing is happening only 2
clients is served at a time ..even if no of threads is assigned  to 20 ..
i have did lot of searching and reading .. and hoping to find a solution
..can anyone make it easier for me
i have heard of twisted deffered object .. will it solved the problem ? if
not pls suggest me alternative..
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Talking to a usb device (serial terminal)

2008-03-04 Thread blaine
>
> It looks like the fastest speed supported by python termios on
> Linux is B460800 (uses a constant of 0x1004).  If you look in
> /usr/include/..., baud rates do go up to 921600 (which uses a
> constant of 0x1007).
>
> Try using the appropriate constant from /usr/include/... (for
> the target platform, of course).
>
> --
> Grant Edwards   grante Yow! Please come home with
>   at   me ... I have Tylenol!!
>visi.com
Thank you for your response.  I can't seem to find what you're
referencing in /usr/include.  I found termios.h - but it does not
define any constants (I can include it if you wish).  I did find
termios.c in the Python module file, which only defines constants up
to :
[...]
{"B2400", B2400},
{"B4800", B4800},
{"B9600", B9600},
{"B19200", B19200},
{"B38400", B38400},
#ifdef B57600
{"B57600", B57600},
#endif
#ifdef B115200
{"B115200", B115200},
#endif
#ifdef B230400
{"B230400", B230400},

I could recompile python, I imagine, with additional constants but
this wouldn't be ideal - although it is a possible solution.

the only reference to a baud rate in termios.h is here:
/* Return the output baud rate stored in *TERMIOS_P.  */
extern speed_t cfgetospeed (__const struct termios *__termios_p)
__THROW;

/* Return the input baud rate stored in *TERMIOS_P.  */
extern speed_t cfgetispeed (__const struct termios *__termios_p)
__THROW;

/* Set the output baud rate stored in *TERMIOS_P to SPEED.  */
extern int cfsetospeed (struct termios *__termios_p, speed_t __speed)
__THROW;

/* Set the input baud rate stored in *TERMIOS_P to SPEED.  */
extern int cfsetispeed (struct termios *__termios_p, speed_t __speed)
__THROW;

the termios.h and const.h in the linux/ folder aren't much help.  I'm
sure I'm just looking at the wrong file.

Thank you again for all your help!
Blaine
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pySQLite Insert speed

2008-03-04 Thread Steve Holden
Peter Otten wrote:
> Steve Holden wrote:
> 
>> What I will repeat, however, is that while there is a *slight*
>> difference is semantics between
>>
>> s = "some string"
>> s1 = s
>>
>> and
>>
>> s = "some string"
>> s1 = copy.copy(s)
>>
>> that difference is only to ensure that s and s1 point to different
>> copies of the same string in the latter case, whereas in the former case
>> s and s1 point to the same string.
> 
> No, both "point" to the same string:
> 
 import copy
 s = "some string"
 s1 = s
 s1 is s
> True
 s2 = copy.copy(s)
 s2 is s
> True
> 
> copy.copy() is just an expensive no-op here.
> 
I suppose wiht strings being immutable there is no need for copy.copy() 
to actually return anything other than its argument for a string. Thanks 
for pointing that out.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-04 Thread Gabriel Genellina
En Tue, 04 Mar 2008 11:46:48 -0200, NickC <[EMAIL PROTECTED]> escribi�:

> A mildly interesting Py3k experiment:
>
> Python 3.0a3+ (py3k:61229, Mar  4 2008, 21:38:15)
> [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 from fractions import Fraction
 from decimal import Decimal
 def check_accuracy(num_type, max_val=1000):
> ... wrong = 0
> ... for x in range(1, max_val):
> ... for y in range(1, max_val):
> ... wrong += (x / num_type(y)) * y != x
> ... return wrong
> ...
 check_accuracy(float)
> 101502
 check_accuracy(Decimal)
> 310013
 check_accuracy(Fraction)
> 0
>
>
> The conclusions I came to based on running that experiment are:
> - Decimal actually appears to suffer more rounding problems than float
> for rational arithmetic

Mmm, but I doubt that counting how many times the results are equal, is  
the right way to evaluate "accuracy".
A stopped clock shows the right time twice a day; a clock that loses one  
minute per day shows the right time once every two years. Clearly the  
stopped clock is much better!
http://mybanyantree.wordpress.com/category/lewis-carrol/

-- 
Gabriel Genellina

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

Re: Altering imported modules

2008-03-04 Thread Tro
On Monday 03 March 2008, [EMAIL PROTECTED] wrote:
> On Mar 3, 5:09 pm, Tro <[EMAIL PROTECTED]> wrote:
> > On Sunday 02 March 2008, Paul McGuire wrote:
> > > On Mar 2, 3:48 pm, Tro <[EMAIL PROTECTED]> wrote:
> > > > On Sunday 02 March 2008, Terry Reedy wrote:
> > > > > "Tro" <[EMAIL PROTECTED]> wrote in message
> > > > >news:[EMAIL PROTECTED]
> > > > >
> > > > > | Hi, list.
> > > > > |
> > > > > | I've got a simple asyncore-based server. However, I've modified
> > > > > | the
> > > > >
> > > > > asyncore
> > > > >
> > > > > | module to allow me to watch functions as well as sockets. The
> > > > > | modified asyncore module is in a specific location in my project
> > > > > | and is imported
> > > > >
> > > > > as
> > > > >
> > > > > | usual from my classes.
> > > > > |
> > > > > | Now I'd like to use the tlslite library, which includes an
> > > > > | asyncore mixin class. However, tlslite imports "asyncore", which
> > > > > | doesn't include my own modifications.
> > > > > |
> > > > > | I'd like to know if it's possible to make tlslite load *my*
> > > > > | asyncore
> > > > >
> > > > > module
> > > > >
> > > > > | without changing any of the tlslite code.
> > > > >
> > > > > If your module is also 'asyncore' and comes earlier in the search
> > > > > path, I would expect the import to get yours.
> > > >
> > > > It's not. It has a package prefix like my.package.asyncore. I think I
> > > > can either move my version of asyncore up a couple of levels or add
> > > > the my.package directory to sys.path.
> > > >
> > > > My version of asyncore imports several functions from the built-in
> > > > asyncore. Now that my version of it is imported as asyncore, how
> > > > would it import the built-in version from python2.5/site-packages?
> > > >
> > > > Thanks,
> > > > Tro
> > >
> > > What happens if you do "import my.package.asyncore as asyncore"?
> > >
> > > If that doesn't work (trying the simplest hack first), I know that
> > > there are various hooks in the import mechanism that should help.
> >
> > In the classes that use my version of asyncore currently, that is how I
> > do it. I import my version as "import my.package.asyncore as asyncore".
> > In my asyncore module I do "import asyncore", because I override a few
> > functions from the asyncore module included with python. However, if I
> > were to add "my.package" to sys.path, then I wouldn't be able to "import
> > asyncore" from my own asyncore module. I'd have to do some trickery with
> > sys.path to take the "my.package" component out, import standard
> > asyncore, readd the "my.package" component, so that other modules can
> > "import asyncore" and get my version.
> >
> > Is there a way to import the standard python asyncore module in this
> > scenario?
> >
> > Thanks,
> > Tro
> >
> > 
>
> Are you trying to interfere with the default module on only your
> machine?  Just rename it.  If something in the std. lib. imports
> asyncore, they get yours too that way.

No, I'd like it to be a generalized solution and only for this one project. 
I'm trying to get it to work on any recent python installation out of the 
box, so I can't rename built-in modules. What I'm trying to do is allow a 3rd 
party module (tlslite) to import *my* version of asyncore without me going 
into tlslite's code and changing its import statement explicitly, but only 
for the scope of this one project.

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


Re: pySQLite Insert speed

2008-03-04 Thread mmm
Oops  I did make a mistake. The code I wanted to test should have been

import copy
print 'Test 1'
pf= '?,?,?,?'
sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf
print sqlx1

print
print 'Test 2'
sqlx2= copy.copy(sqlx1)
sqlx3= sqlx1
pf= '?,?,?, '
print 'sqlx1= ', sqlx1
print 'sqlx2= ', sqlx2
print 'sqlx3= ', sqlx2

and the results would
 == output
 Test group 1
 INSERT INTO DTABLE2 VALUES ( ?,?,?,? )

 Test group 2
 sqlx1=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
 sqlx2=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
 sqlx3=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )

Such that sqlx1 does to change with the re-assignment of 'pf'
And of course immutables such as strings are immutable.  Got it now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why not bisect options?

2008-03-04 Thread rbossy
Quoting Raymond Hettinger <[EMAIL PROTECTED]>:

> [Robert Bossy]
> > I thought it would be useful if insort and consorts* could accept the
> > same options than list.sort, especially key and cmp.
>
> If you're going to do many insertions or searches, wouldn't it be
> *much* more efficient to store your keys in a separate array?
>
> The sort() function guarantees that it calls the key function exactly
> once for each member of the list.  With and bisect/insort, successive
> searches can call the key function over and over again with the same
> value.

I factored your remark into the code. I actually don't have any particular
question about it, that's just an acknowledgment. Though I feel that if one
uses the default key, then an awkward list of twins is stored...



from operator import itemgetter


def identity(x): return x


class Bisect:
def __init__(self, it, key=identity, cmp=cmp):
self.lst = [ (key(x),x,) for x in it ]
self.lst.sort(cmp=cmp, key=itemgetter(0))
self.key = key
self.cmp = cmp

def insort_right(self, x, lo = 0, hi = None):
if hi is None:
hi = len(self.lst)
xk = self.key(x)
while lo < hi:
mid = (lo + hi) // 2
if self.cmp(xk, self.lst[mid][0]) < 0:
hi = mid
else:
lo = mid + 1
self.lst.insert(lo, (kx,x,))

# skipped insort_left, bisect_right, bisect_left
# also skipped the container methods __len__, __getitem__, __iter__


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


tab completion?

2008-03-04 Thread Siddhant
Hi people.
I was just wondering if a tab-completion feature in python command
line interface would be helpful?
If yes, then how can I implement it?
Thanks,
Siddhant
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread Carl Banks
On Mar 4, 8:27 am, [EMAIL PROTECTED] wrote:
> So far in Python I've almost hated the 'else' of the 'for' loops:
> - I have problems to remember its meaning;
> - It gives me little problems when I later want to translate Python
> code to other languages (and you always have to translate long-lived
> code).
> - I have used it only once, so far.
>
> So so far I'd liked to see it removed from Python 3.0.
>
> But then this 
> article:http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel...
> has shown me that my problems with the 'else' of the 'for' mostly come
> from just its bad naming. The converge language is yet another very
> Python-like language, and it uses a better naming (the word
> "exhausted" is long and has a complex spelling for non-English
> speakers, so it's not perfect):
>
> for ...:
> ...
> exhausted:
> ...
> broken:
> ...
>
> The meaning is explicit. While "else" seems to mean little there.
> So I may like something similar for Python 3.x (or the removal of the
> "else").


I would not be opposed to this on its own merits, but there is a
rationale behind the name "else".  If you consider a for loop to be a
rolled-up if...elif...else statement (situations where this is
reasonable tend to be the same ones were else would be useful), then
the "else" clause would remain unchanged on the for loop.

For instance, if you have a (trivial) if...elif...else like this:

if a == 0:
do_task_0()
elif a == 1:
do_task_1()
elif a == 2:
do_task_2()
else:
do_default_task()

You could roll it up into a for...else statement like this:

for i in range(3):
if a == i:
do_task[a]()
else:
do_default_task()

(Please never mind the trivialness of this example; I know you can
eliminate the for loop altogether; this is JUST an example.)

I keep this analogy in mind when using for...else to keep the
semantics straight.


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


Re: tab completion?

2008-03-04 Thread james . pye
On Mar 4, 8:13 am, Siddhant <[EMAIL PROTECTED]> wrote:
> Hi people.
> I was just wondering if a tab-completion feature in python command
> line interface would be helpful?
> If yes, then how can I implement it?
> Thanks,
> Siddhant

Is this what you are looking for?

   http://docs.python.org/lib/module-rlcompleter.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing default logging handler (causes duplicate logging)

2008-03-04 Thread Gerard Flanagan
On Mar 4, 1:29 pm, Gal Aviel <[EMAIL PROTECTED]> wrote:
> Hello All,
>
> I want to add a logger to my application, then addHandler to it to log to a
> special destination.
>
> Unfortunately when I use logging.getLogger("my_logger") to create the new
> logger, it apparently comes with a default handler that logs to STDOUT (or
> STDERR?). When I add my special handler it works Ok, but still logs to 
> terminal,
> which I do not want.
>

from docs:
--
getLogger( [name])

Return a logger with the specified name or, if no name is specified,
return a logger which is the root logger of the hierarchy.
--

so you should do 'root = getlogger()', then append your own logger to
the root.

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


Re: tab completion?

2008-03-04 Thread Ron DuPlain
On Mar 4, 10:13 am, Siddhant <[EMAIL PROTECTED]> wrote:
> Hi people.
> I was just wondering if a tab-completion feature in python command
> line interface would be helpful?
> If yes, then how can I implement it?
> Thanks,
> Siddhant

ipython provides auto tab completion.
http://ipython.scipy.org/

You can also get it by:
$ easy_install ipython

Run it using the command:
$ ipython

Is this what you want?

Ron


--
Ron DuPlain <[EMAIL PROTECTED]>
http://www.linkedin.com/in/rduplain
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread BJörn Lindqvist
On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks <[EMAIL PROTECTED]> wrote:
>  > for ...:
>  > ...
>  > exhausted:
>  > ...
>  > broken:
>  > ...
>  >
>  > The meaning is explicit. While "else" seems to mean little there.
>  > So I may like something similar for Python 3.x (or the removal of the
>  > "else").
>
>
>  I would not be opposed to this on its own merits, but there is a
>  rationale behind the name "else".  If you consider a for loop to be a
>  rolled-up if...elif...else statement (situations where this is
>  reasonable tend to be the same ones were else would be useful), then
>  the "else" clause would remain unchanged on the for loop.
>
>  For instance, if you have a (trivial) if...elif...else like this:
>
>  if a == 0:
> do_task_0()
>  elif a == 1:
> do_task_1()
>  elif a == 2:
> do_task_2()
>  else:
> do_default_task()
>
>  You could roll it up into a for...else statement like this:
>
>  for i in range(3):
> if a == i:
> do_task[a]()
>  else:
> do_default_task()

You forgot the break statement. The else suite will always be executed
in this loop. Kind of proves bearophiles point, for-else is really
tricky.


-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread Tim Chase
> For instance, if you have a (trivial) if...elif...else like this:
> 
> if a == 0:
> do_task_0()
> elif a == 1:
> do_task_1()
> elif a == 2:
> do_task_2()
> else:
> do_default_task()
> 
> You could roll it up into a for...else statement like this:
> 
> for i in range(3):
> if a == i:
> do_task[a]()

important "break" missing here...

> else:
> do_default_task()


or otherwise this code will do_task_i *and* do_default_task()...

-tkc


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


HTTP keep-alive performance

2008-03-04 Thread Manuel Metz
Hi all,
I tried to use the HTTP keep-alive (HTTP/1.1) mechanism for an xmlrpc 
server/client session. This worked fine, after I found out how to fix 
the client, see:
http://mail.python.org/pipermail/python-list/2004-April/256360.html
   and also
http://mail.python.org/pipermail/python-list/2007-May/442541.html


Now, as I said, everything seems to work fine -- except: performance got 
very bad :-(

So, I captured the TCP traffic with wireshark (both, server and client 
are running on the same machine, 'http://localhost', so its not the 
network). What I found out is the following:

The first remote-call is executed very fast. Then the connection is kept 
open (I verified that it is closed for HTTP/1.0). But when it comes to 
the second call, the performance gets bad. The TCP ACK package is sent 
after ~40ms only, which took ~ < 1ms before for the first call, even for 
HTTP/1.1. Why is that?

So this is a sketch of what's going on:

client  server
--  --
HEADER   -->
  <-- ACK   ~1ms
CONTENT  -->
  <-- ACK   ~1ms
  <-- HEADER
ACK  -->   ~1ms
[...] response is submitted; connection is NOT closed [...]
HEADER   -->
  <-- ACK   ~40ms
CONTENT  -->
  <-- ACK   ~1ms
  <-- HEADER
ACK  -->   ~40ms
[...] response data is submitted

It's just a rought timeline to show where the bottleneck is. Has anyone 
any idea why the acknowledgement messages take so long to be sent???

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


Re: Altering imported modules

2008-03-04 Thread Steve Holden
Tro wrote:
> On Monday 03 March 2008, [EMAIL PROTECTED] wrote:
>> On Mar 3, 5:09 pm, Tro <[EMAIL PROTECTED]> wrote:
>>> On Sunday 02 March 2008, Paul McGuire wrote:
 On Mar 2, 3:48 pm, Tro <[EMAIL PROTECTED]> wrote:
> On Sunday 02 March 2008, Terry Reedy wrote:
>> "Tro" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>>
>> | Hi, list.
>> |
>> | I've got a simple asyncore-based server. However, I've modified
>> | the
>>
>> asyncore
>>
>> | module to allow me to watch functions as well as sockets. The
>> | modified asyncore module is in a specific location in my project
>> | and is imported
>>
>> as
>>
>> | usual from my classes.
>> |
>> | Now I'd like to use the tlslite library, which includes an
>> | asyncore mixin class. However, tlslite imports "asyncore", which
>> | doesn't include my own modifications.
>> |
>> | I'd like to know if it's possible to make tlslite load *my*
>> | asyncore
>>
>> module
>>
>> | without changing any of the tlslite code.
>>
>> If your module is also 'asyncore' and comes earlier in the search
>> path, I would expect the import to get yours.
> It's not. It has a package prefix like my.package.asyncore. I think I
> can either move my version of asyncore up a couple of levels or add
> the my.package directory to sys.path.
>
> My version of asyncore imports several functions from the built-in
> asyncore. Now that my version of it is imported as asyncore, how
> would it import the built-in version from python2.5/site-packages?
>
> Thanks,
> Tro
 What happens if you do "import my.package.asyncore as asyncore"?

 If that doesn't work (trying the simplest hack first), I know that
 there are various hooks in the import mechanism that should help.
>>> In the classes that use my version of asyncore currently, that is how I
>>> do it. I import my version as "import my.package.asyncore as asyncore".
>>> In my asyncore module I do "import asyncore", because I override a few
>>> functions from the asyncore module included with python. However, if I
>>> were to add "my.package" to sys.path, then I wouldn't be able to "import
>>> asyncore" from my own asyncore module. I'd have to do some trickery with
>>> sys.path to take the "my.package" component out, import standard
>>> asyncore, readd the "my.package" component, so that other modules can
>>> "import asyncore" and get my version.
>>>
>>> Is there a way to import the standard python asyncore module in this
>>> scenario?
>>>
>>> Thanks,
>>> Tro
>>>
>>>
>> Are you trying to interfere with the default module on only your
>> machine?  Just rename it.  If something in the std. lib. imports
>> asyncore, they get yours too that way.
> 
> No, I'd like it to be a generalized solution and only for this one project. 
> I'm trying to get it to work on any recent python installation out of the 
> box, so I can't rename built-in modules. What I'm trying to do is allow a 3rd 
> party module (tlslite) to import *my* version of asyncore without me going 
> into tlslite's code and changing its import statement explicitly, but only 
> for the scope of this one project.
> 

In that case try something like

import myasyncore as asnycore
sys.modules['asyncore'] = asyncore
import tlslite

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: pySQLite Insert speed

2008-03-04 Thread Steve Holden
mmm wrote:
> Oops  I did make a mistake. The code I wanted to test should have been
> 
> import copy
> print 'Test 1'
> pf= '?,?,?,?'
> sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf
> print sqlx1
> 
> print
> print 'Test 2'
> sqlx2= copy.copy(sqlx1)
> sqlx3= sqlx1
> pf= '?,?,?, '
> print 'sqlx1= ', sqlx1
> print 'sqlx2= ', sqlx2
> print 'sqlx3= ', sqlx2
> 
> and the results would
>  == output
>  Test group 1
>  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
> 
>  Test group 2
>  sqlx1=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
>  sqlx2=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
>  sqlx3=  INSERT INTO DTABLE2 VALUES ( ?,?,?,? )
> 
> Such that sqlx1 does to change with the re-assignment of 'pf'
> And of course immutables such as strings are immutable.  Got it now.

You still aren't showing us the code you are actually running. Why can't 
you just paste it into your message?

But anyway, you appear to have got the drift now.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Altering imported modules

2008-03-04 Thread Floris Bruynooghe
On Mar 1, 11:56 pm, Tro <[EMAIL PROTECTED]> wrote:
> I'd like to know if it's possible to make tlslite load *my* asyncore module
> without changing any of the tlslite code.

the pkgutil module might be helpful, not sure though as I've never
used it myself.

http://blog.doughellmann.com/2008/02/pymotw-pkgutil.html is a fairly
detailed look at what pkgutil can do.

Regards
Floris

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


Re: tab completion?

2008-03-04 Thread [EMAIL PROTECTED]
On Mar 4, 10:44 am, Ron DuPlain <[EMAIL PROTECTED]> wrote:
> On Mar 4, 10:13 am, Siddhant <[EMAIL PROTECTED]> wrote:
>
> > Hi people.
> > I was just wondering if a tab-completion feature in python command
> > line interface would be helpful?
> > If yes, then how can I implement it?
> > Thanks,
> > Siddhant
>
> ipython provides auto tab completion.http://ipython.scipy.org/
>
> You can also get it by:
> $ easy_install ipython
>
> Run it using the command:
> $ ipython
>
> Is this what you want?

ipython also makes stack traces nearly unreadable by default (setting
"xmode Plain" in the ipythonrc fixed that) and tends to take up too
much vertical screen space, wants to colorize a lot of stuff, and has
a few other things that I was't fond of.  There's some nice stuff in
ipython (saving the return values of every line in the shell), but I
found trying to configure off all of the "magically helpful" stuff
that wound up being more annoying than useful was a fairly long job.

I found it easier just to turn on completion in the regular python
shell.  From my .pythonrc:

try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
del readline, rlcompleter

With that and persistent history I'm pretty happy:

import readline
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
readline.read_history_file(histfile)
except IOError:
pass
import atexit
atexit.register(readline.write_history_file, histfile)
del os, histfile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Lie
On Mar 4, 1:12 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Mar 3, 11:58 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
>
> > Mensanator wrote:
> > > While we're on the subject of English, the word "worthless"
> > > means "has no value". So, a program that doesn't work would
> > > generally be "worthless". One that not only doesn't work but
> > > creates side effects that cause other programs to not work
> > > (which don't have bugs) would be "worse than worthless".
>
> > All programs have bugs, which means that in some circumstances, they
> > won't work.  
>
> And in such circumstances, would be worthless.
>
> > Therefore, by your reasoning, all programs are worse than
> > useless.
>
> That doesn't follow from my reasoning.
>
> Suppose you downloaded a new calculator program that
> couldn't add properly. That would be useless to you, right?
>
> But suppose the program contained a virus that erased
> your hard drive. That would be "worse than useless", wouldn't it?
>
>
>
> > > I'm not hard to please at all.
>
> > No, of course not, since logically you must think all software is useless.
>
> Somehow, I expected better logic from people who call themselves
> programmers.

Mensanator, for alls sake, you've done right by pointing out the bug
instead of muttering silently in your room, but there is a thing
called tolerance that you really should learn, it's about tolerating
and understanding the possibility that other people are humans too and
humans create mistakes, lots of them in fact and that includes you (if
you're humans). Along with tolerance should come a better choice of
wordings, instead of saying "it sucks because it does something
unexpected and unwanted" and telling everyone not to use it, you could
just say "it does something unexpected and unwanted" and say that you
wanted it fixed. It's not that you've done anything wrong, but it's
about your attitude.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'normal' shell with curses

2008-03-04 Thread Michael Goerz
Thynnus wrote, on 03/04/2008 08:48 AM:
> On 3/3/2008 9:57 PM, Michael Goerz wrote:
>> Hi,
>>
>> I'm trying to print out text in color. As far as I know, curses is the 
>> only way to do that (or not?). So, what I ultimately want is a curses 
>> terminal that behaves as closely as possible as a normal terminal, 
>> i.e. it breaks lines and scrolls automatically, so that I can 
>> implement a function myprint(color, text) that does what print() does, 
>> only in color.
> 
> You might find the below helpful. Let us know how you make out?
> 
> 
> 
> Python Cookbook
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116
> 
> Title:
>  Using terminfo for portable color output & cursor control
> 
> Description:
> The curses module defines several functions (based on terminfo) that can 
> be used to perform lightweight cursor control & output formatting 
> (color, bold, etc). These can be used without invoking curses mode 
> (curses.initwin) or using any of the more heavy-weight curses 
> functionality. This recipe defines a TerminalController class, which can 
> make portable output formatting very simple. Formatting modes that are 
> not supported by the terminal are simply omitted.
> 
> 
> 

That looks *extremely* interesting. From a very brief test, it seems to 
do exactly what I want!

Now, Windows seems very problematic for color output. I was using the 
following as a test, based on the above recipe:

term = TerminalController()
while True:
 print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled'
 print term.render('${RED}Error:${NORMAL}'), 'paper is ripped'

On Linux, it works fine, on Windows, it just prints white on black 
(which is of course what it should do if the terminal doesn't support 
color). Can anyone get the Windows cmd.exe terminal to do color? I 
already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, 
but that doesn't seem to do anything (neither in what I tried yesterday 
with the ANSI escape codes, nor with the recipe code now). I also very 
briefly tried running it on the winbash shell 
(http://win-bash.sourceforge.net/), it didn't have any color either... 
So, any way to get color in Windows?

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


Re: tab completion?

2008-03-04 Thread Siddhant
Yes. Almost what I wanted. Thanks. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why not bisect options?

2008-03-04 Thread Aaron Watters
On Feb 29, 9:31 am, Robert Bossy <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I thought it would be useful if insort and consorts* could accept the
> same options than list.sort, especially key and cmp.

Wouldn't this make them slower and less space efficient?  It would
be fine to add something like this as an additional elaboration, but
I want bisect to scream as fast as possible in the default streamlined
usage.
   -- Aaron Watters
===
dueling bumper stickers:
  use java/get rich
  use perl/get laid  -- both equally sensible

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


Re: for-else

2008-03-04 Thread Carl Banks
On Mar 4, 10:55 am, "BJörn Lindqvist" <[EMAIL PROTECTED]> wrote:
> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks <[EMAIL PROTECTED]> wrote:
> >  > for ...:
> >  > ...
> >  > exhausted:
> >  > ...
> >  > broken:
> >  > ...
>
> >  > The meaning is explicit. While "else" seems to mean little there.
> >  > So I may like something similar for Python 3.x (or the removal of the
> >  > "else").
>
> >  I would not be opposed to this on its own merits, but there is a
> >  rationale behind the name "else".  If you consider a for loop to be a
> >  rolled-up if...elif...else statement (situations where this is
> >  reasonable tend to be the same ones were else would be useful), then
> >  the "else" clause would remain unchanged on the for loop.
>
> >  For instance, if you have a (trivial) if...elif...else like this:
>
> >  if a == 0:
> > do_task_0()
> >  elif a == 1:
> > do_task_1()
> >  elif a == 2:
> > do_task_2()
> >  else:
> > do_default_task()
>
> >  You could roll it up into a for...else statement like this:
>
> >  for i in range(3):
> > if a == i:
> > do_task[a]()
> >  else:
> > do_default_task()
>
> You forgot the break statement. The else suite will always be executed
> in this loop. Kind of proves bearophiles point, for-else is really
> tricky.

Ah ha, but that would have been a mistake with or without the else
clause


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


Re: why not bisect options?

2008-03-04 Thread Robert Bossy
Aaron Watters wrote:
> On Feb 29, 9:31 am, Robert Bossy <[EMAIL PROTECTED]> wrote:
>   
>> Hi all,
>>
>> I thought it would be useful if insort and consorts* could accept the
>> same options than list.sort, especially key and cmp.
>> 
>
> Wouldn't this make them slower and less space efficient?  It would
> be fine to add something like this as an additional elaboration, but
> I want bisect to scream as fast as possible in the default streamlined
> usage.
Yes it is slower and bigger, so I agree that the canonical 
implementation for default values should be kept. Also because the 
original bisect functions are actually written in C, the speed 
difference is even more noticeable.

Though, I needed custom ordering bisects since I was implementing 
interval trees (storing intervals by startpoint/endpoint).

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


Re: Talking to a usb device (serial terminal)

2008-03-04 Thread Grant Edwards
On 2008-03-04, blaine <[EMAIL PROTECTED]> wrote:

>> Try using the appropriate constant from /usr/include/... (for
>> the target platform, of course).
>>
>> --
>> Grant Edwards   grante Yow! Please come home with
>>   at   me ... I have Tylenol!!
>>visi.com
> Thank you for your response.  I can't seem to find what you're
> referencing in /usr/include.  I found termios.h - but it does not
> define any constants (I can include it if you wish).

$ grep -r  B921600 /usr/include
/usr/include/asm/termbits.h:#define   B921600 0010007
/usr/include/bits/termios.h:#define  B921600  0010007

> I could recompile python, I imagine, with additional constants but
> this wouldn't be ideal - although it is a possible solution.

termios.c in Python definitely needs to be updated.

> the only reference to a baud rate in termios.h is here:

It's in a file that's included in termios.h.  See above.

-- 
Grant Edwards   grante Yow! Here I am at the flea
  at   market but nobody is buying
   visi.commy urine sample bottles ...
-- 
http://mail.python.org/mailman/listinfo/python-list


unicode box drawing

2008-03-04 Thread jefm
How can I print the unicode box drawing characters in python:


print u'\u2500'
print u'\u2501'
print u'\u2502'
print u'\u2503'
print u'\u2504'

Traceback (most recent call last):
  File "\test.py", line 3, in ?
print u'\u2500'
  File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500'
in position 0: character maps to 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread Shane Geiger

>  if a == 0:
> do_task_0()
>  elif a == 1:
> do_task_1()
>  elif a == 2:
> do_task_2()
>  else:
> do_default_task()

The if-elif-else structure that calls functions (like that above) can be
avoided with the code below:


def foo0(): print 'foo0'
def bar0(): print 'bar0'
def foo1(): print 'foo1'
def bar1(): print 'bar1'
def do_default_task(): print 'do_default_task'

do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, }

a = 1

# example of normal usage
if a in do_task.keys(): do_task[a]()
else: do_default_task()

# example of testing all functions in the dict as well as the default
function
for a in do_task.keys() + [8]:  # 8 is a non-existent key in the do_task
dict
print "a is ",a,"and it gives this output:",
if a in do_task.keys(): do_task[a]()
else: do_default_task()





Carl Banks wrote:
> On Mar 4, 10:55 am, "BJörn Lindqvist" <[EMAIL PROTECTED]> wrote:
>   
>> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks <[EMAIL PROTECTED]> wrote:
>> 
>>>  > for ...:
>>>  > ...
>>>  > exhausted:
>>>  > ...
>>>  > broken:
>>>  > ...
>>>   
>>>  > The meaning is explicit. While "else" seems to mean little there.
>>>  > So I may like something similar for Python 3.x (or the removal of the
>>>  > "else").
>>>   
>>>  I would not be opposed to this on its own merits, but there is a
>>>  rationale behind the name "else".  If you consider a for loop to be a
>>>  rolled-up if...elif...else statement (situations where this is
>>>  reasonable tend to be the same ones were else would be useful), then
>>>  the "else" clause would remain unchanged on the for loop.
>>>   
>>>  For instance, if you have a (trivial) if...elif...else like this:
>>>   
>>>  if a == 0:
>>> do_task_0()
>>>  elif a == 1:
>>> do_task_1()
>>>  elif a == 2:
>>> do_task_2()
>>>  else:
>>> do_default_task()
>>>   
>>>  You could roll it up into a for...else statement like this:
>>>   
>>>  for i in range(3):
>>> if a == i:
>>> do_task[a]()
>>>  else:
>>> do_default_task()
>>>   
>> You forgot the break statement. The else suite will always be executed
>> in this loop. Kind of proves bearophiles point, for-else is really
>> tricky.
>> 
>
> Ah ha, but that would have been a mistake with or without the else
> clause
>
>
> Carl Banks
>   

This approach works well for me:



def foo0(): print 'foo0'
def bar0(): print 'bar0'
def foo1(): print 'foo1'
def bar1(): print 'bar1'

def do_default_task(): print 'do_default_task'

do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, }

a = 1 

# example of normal usage
if a in do_task.keys(): do_task[a]()
else: do_default_task()


# example of testing
for i in range(len(do_task.keys)):
 if a in do_task.keys(): do_task[a]()
 else: do_default_task()



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

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


Re: sympy: what's wrong with this picture?

2008-03-04 Thread castironpi
On Mar 4, 10:50 am, Lie <[EMAIL PROTECTED]> wrote:
> On Mar 4, 1:12 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Mar 3, 11:58 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
>
> > > Mensanator wrote:
> > > > While we're on the subject of English, the word "worthless"
> > > > means "has no value". So, a program that doesn't work would
> > > > generally be "worthless". One that not only doesn't work but
> > > > creates side effects that cause other programs to not work
> > > > (which don't have bugs) would be "worse than worthless".
>
> > > All programs have bugs, which means that in some circumstances, they
> > > won't work.  
>
> > And in such circumstances, would be worthless.
>
> > > Therefore, by your reasoning, all programs are worse than
> > > useless.
>
> > That doesn't follow from my reasoning.
>
> > Suppose you downloaded a new calculator program that
> > couldn't add properly. That would be useless to you, right?
>
> > But suppose the program contained a virus that erased
> > your hard drive. That would be "worse than useless", wouldn't it?
>
> > > > I'm not hard to please at all.
>
> > > No, of course not, since logically you must think all software is useless.
>
> > Somehow, I expected better logic from people who call themselves
> > programmers.
>
> Mensanator, for alls sake, you've done right by pointing out the bug
> instead of muttering silently in your room, but there is a thing
> called tolerance that you really should learn, it's about tolerating
> and understanding the possibility that other people are humans too and
> humans create mistakes, lots of them in fact and that includes you (if
> you're humans). Along with tolerance should come a better choice of
> wordings, instead of saying "it sucks because it does something
> unexpected and unwanted" and telling everyone not to use it, you could
> just say "it does something unexpected and unwanted" and say that you
> wanted it fixed. It's not that you've done anything wrong, but it's
> about your attitude.- Hide quoted text -
>
> - Show quoted text -

All of your statements were true.
You expressed your emotions, your observations, and desire.
You corrected statements incorrect that others made earlier.
Others gave you orders, their observations of your character, and
expressed their emotions.
Now keep your noses in the keyboard and simmer down.  I won't stand
for this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: metaclasses

2008-03-04 Thread castironpi
On Mar 4, 12:51 am, Gerard Flanagan <[EMAIL PROTECTED]> wrote:
> On Mar 4, 6:31 am, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > On Mar 3, 10:01 pm, Benjamin <[EMAIL PROTECTED]> wrote:
>
> > > On Mar 3, 7:12 pm, [EMAIL PROTECTED] wrote:
>
> > > > What are metaclasses?
>
> > > Depends on whether you want to be confused or not. If you do, look at
> > > this old but still head bursting 
> > > essay:http://www.python.org/doc/essays/metaclasses/.
>
> > > Basically, the metaclass of a (new-style) class is responsible for
> > > creating the class. This means when Python sees
> > > class Foo(object):
> > >     __metaclass__ = FooMeta
> > > class FooMeta(type):
> > >     def __new__(cls, name, bases, dct):
> > >        #do something cool to the class
> > >        pass
> > > It asks FooMeta to create the class Foo. Metaclasses always extend
> > > type because type is the default metaclass.
>
> > But you can stack class decorations, but not class metas.
>
> > @somethingcool1
> > @somethingcool2
> > class Foo:
> >    pass
>
> > * class Foo:
> >    __metaclass__= MetaCool1, MetaCool
>
> > * denotes malformed
>
> ---
> class Meta1(type):
>
>     def foo1(cls):
>         print 'hello'
>
> class Meta2(type):
>
>     def foo2(cls):
>         print 'castiron'
>
> class Meta(Meta1, Meta2):
>     pass
>
> class Base(object):
>     __metaclass__ = Meta
>
> Base.foo1()
> Base.foo2()

class Base(object):
   __metaclass__= type( 'Meta', ( Meta1, Meta2 ), {} )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between 'function' and 'method'

2008-03-04 Thread castironpi
On Mar 4, 5:27 am, Bruno Desthuilliers  wrote:
> ?? a écrit :
>
> > Howdy everyone,
>
> >      This is a big problem puzzles me for a long time. The core question is:
> > How to dynamically create methods on a class or an instance?
>
> class Foo(object):
>     pass
>
> def bar(self, arg):
>     print "in bar : self == % - arg == %s" % (self, str(arg))
>
> def baaz(self, arg):
>     print "in baaz : self == % - arg == %s" % (self, str(arg))
>
> f = Foo()
>
> # adding bar as a method to class Foo
> Foo.bar = bar
>
> # f now can use bar:
> f.bar(42)
>
> # as well as new instances of Foo, of course
> g = Foo()
> g.bar()
>
> # adding baaz as a method to f, the old way:
> import new
> f.baaz = new.instancemethod(baaz, f, type(f))
>
> f.baaz()
>
> # adding baaz as a method to g, the other way:
> g.baaz = baaz.__get__(g, type(g))
>
> g.baaz()
>
> > Let me state it step by step.
> > 1.
> > def gunc(self):
> >     pass
> > class A(object):
> >     def func(self):
> >         pass
> > a = A()
> > a.func   # gives "bound method", type is "instancemethod"
> > A.func  # gives "unbound method", type is "instancemethod"
> > gunc    # gives "function", type if "function"
>
> > # ?? Does this line attach a method to instance?  ... I don't think so.
> > a.gunc = gunc
>
> It doesn't.
>
> > I found stardard library 'new' may help. Is that right?
>
> cf above. If you work with old-style classes, you'll need
> new.instancemethod.
>
> > 2.
> > a = A()  # instance of old class A
> > # Do attach a new method to class A...
> > b = A()  # instance of new class A
> > Does "a" can get the new method automatically?
>
> Yes. In Python, a class is itself an object, and is an attribute of it's
> instances (instance.__class__). Names are resolved at runtime, and
> attributes not found in the instance's __dict__ are looked up in the
> class (and then in the superclasses etc).
>
> > Does new method have the *same* concept level with old methods?
>
> The newly added method works exactly the same way as already existing
> ones. Not a single difference. The class statement is just syntactic
> sugar anyway. The following snippets are equivalent:
>
> # sugar-coated:
> class Boo(object):
>      faaz = 0
>
>      def far(self):
>          type(self).faaz += 1
>          print self
>
>      def frob(self):
>          print "yadda"
>
> # raw:
> def far(self):
>      type(self).faaz += 1
>      print self
>
> Boo = type('Boo', (object,), dict(faaz=0, far=far))
>
> def frob(self):
>     print "yadda"
>
> Boo.frob = frob
>
> > Especially, if there
> > are classes inherit from class A, how does name resolution work on this 
> > case?
>
> As usual.
>
> > 3.
> > How do I write a decroator for a method?
>
> Mostly the same way you'd write a decorator for a function
>
> > Eg:
> > class A(object):
> >     @my_dec
> >     def func(self):
> >         pass
> > Here, my_dec should return a method rathar than a function/lambda. Am I 
> > right?
>
> Nope. Functions defined within a class statement are plain ordinary
> functions. It's the lookup mechanism that "turns them into methods" when
> they are looked up as attribute of a class. In fact, Python "methods"
> are thin callable wrappers around a function, a class and (most of the
> time) an instance, wrappers which are created - usually at lookup time -
> by the __get__ method of the function type (you may want to read about
> the descriptor protocol on python.org - in the section about new style
> classes IIRC).
>
> Anyway, you can explore this by yourself:
>
>  >>> Boo.far
> 
>  >>> b.far
> >
>  >>> Boo.__dict__['far']
> 
>  >>> Boo.__dict__['far'] is far
> True
>  >>> f1 = b.far
>  >>> f2 = b.far
>  >>> f1 is f2
> False
>  >>> f1()
> <__main__.Boo object at 0xb787f96c>
>  >>> f2()
> <__main__.Boo object at 0xb787f96c>
>  >>> dir(f1)
> ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__',
> '__get__', '__getattribute__', '__hash__', '__init__', '__new__',
> '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
> 'im_class', 'im_func', 'im_self']
>  >>> f1.im_class
> 
>  >>> f1.im_func
> 
>  >>> f1.im_func is far
> True
>  >>> f1.im_self
> <__main__.Boo object at 0xb787f96c>
>  >>> f1.im_self is b
> True
>  >>> bf = Boo.far
>  >>> bf.im_func
> 
>  >>> bf.im_func is far
> True
>  >>> bf.im_class
> 
>  >>> bf.im_self
>  >>> bf.im_self is None
> True
>  >>> far.__get__(b, Boo)
> >
>  >>> far.__get__(b, Boo).im_func is far
> True
>  >>>
>
> So, to answer your question: what you are decorating are functions, not
> methods.

Can you overload -type-'s decision of what to 'bind'?... whenever it
is it makes it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there enough information?

2008-03-04 Thread castironpi
On Mar 3, 10:34 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Mon, 3 Mar 2008 07:00:55 -0800 (PST), [EMAIL PROTECTED] declaimed
> the following in comp.lang.python:
>
> > What's the API call for it?
>
>         I'd suspect one of the win32event.WaitFor..., when combined with
> win32file.CreateFile(), win32file.ReadFile() with the Overlapped flag
> set, win32file.WriteFile() with Overlapped flag set...
> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         [EMAIL PROTECTED]             [EMAIL PROTECTED]
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               [EMAIL PROTECTED])
>                 HTTP://www.bestiaria.com/

select maps to two different calls on Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Resolver One 1.0.1

2008-03-04 Thread Giles Thomas
Hi!

We're delighted to announce version 1.0.1 of Resolver One, a Windows
spreadsheet/IDE mashup that can be programmed in IronPython.

As you enter formulae on the grid, it writes the equivalent IronPython
program for you.  As you add your own 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 tasks, so we think any Python developer
will be able to do fun stuff with it :-)

This is primarily a performance enhancement and bugfix release, but
has a couple of features correcting the more egregious missing
features in version 1.0. We've put up a full change list, but the
highlights are:

* Many memory usage and performance fixes, in particular while
importing Excel-format spreadsheets.
* Updated to IronPython 1.1.1 (fixes socket bugs)
* Added UI to set the background color.
* Fixed defect 367 - Looking up cells by header row/col is slow
* Fixed defect 370 - Cut and Copy part of the text in a cell is
not handled correctly

If you want to download the non-commercial version of the software, or
to buy the commercial version, you can download it from our website
(free registration required):




Regards,

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

Try out Resolver One! 
(Free registration required)

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: sympy: what's wrong with this picture?

2008-03-04 Thread Nanjundi
On Mar 3, 3:40 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> Notice anything funny about the "random" choices?
>
> import sympy
> import time
> import random
>
> f = [i for i in sympy.primerange(1000,1)]
>
> for i in xrange(10):
>   f1 = random.choice(f)
>   print f1,
>   f2 = random.choice(f)
>   print f2,
>   C = f1*f2
>   ff = None
>   ff = sympy.factorint(C)
>   print ff
>
> ##  7307 7243 [(7243, 1), (7307, 1)]
> ##  4091 6829 [(4091, 1), (6829, 1)]
> ##  8563 2677 [(2677, 1), (8563, 1)]
> ##  4091 6829 [(4091, 1), (6829, 1)]
> ##  8563 2677 [(2677, 1), (8563, 1)]
> ##  4091 6829 [(4091, 1), (6829, 1)]
> ##  8563 2677 [(2677, 1), (8563, 1)]
> ##  4091 6829 [(4091, 1), (6829, 1)]
> ##  8563 2677 [(2677, 1), (8563, 1)]
> ##  4091 6829 [(4091, 1), (6829, 1)]
>
> As in, "they're NOT random".
>
> The random number generator is broken by the sympy.factorint()
> function.
>
> Random.choice() works ok if the factorint() function commented out.
>
> ##  6089 1811 None
> ##  6449 1759 None
> ##  9923 4639 None
> ##  4013 4889 None
> ##  4349 2029 None
> ##  6703 8677 None
> ##  1879 1867 None
> ##  5153 5279 None
> ##  2011 4937 None
> ##  7253 5507 None
>
> This makes sympy worse than worthless, as it fucks up other modules.

Does seeding ( random.seed ) random with time fix this? It should.
-N
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run Python app at startup

2008-03-04 Thread SMALLp
Gabriel Genellina wrote:
> En Sun, 02 Mar 2008 19:37:35 -0200, SMALLp <[EMAIL PROTECTED]> escribi�:
> 
>> Hy.
>> I create simple application. Yust an windows and "compile" it with
>> py2exe. I add registry  value
>> reg add 
>> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v
>> MyApp /t REG_SZ /d C:\myapp.exe /f'
>>
>> And it wont start. When i use console instead od window in py2exe i get
>> console opend but it closes.
> 
> I'd check in this order:
> 
> python prog.py
> Then, use console=... in setup.py, generate prog.exe
> Open a cmd window and execute prog.exe (from the dist directory)
> Repeat using window=... in setup.py
> 
> That whole sequence works fine using on my WinXP SP2 + Python 2.5.1 + 
> wxPython 2.8.7.1
> 
Program works fine. When i run it it works. Problem is how to make this 
aplication start at windows startup. It opens and it closes in my case.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for-else

2008-03-04 Thread castironpi
Would you like it to be removed or its name changed?

You can do it with a special iteration:

for a in B:
   if behavior
  break
else:
   2behavior

>

class KeepResult:...
kr= KeepResult( B )
for a in kr:
   if behavior
  break
if kr.diditbreak?:
   2behavior
(if not:
   3behavior)

It just can't do automatic continues; you'd need a
kr.i'mcontinuingonthisone().  Would that be useful in addition?
-- 
http://mail.python.org/mailman/listinfo/python-list


Edit MP4 and/or WMV file metadata?

2008-03-04 Thread allen.fowler
Hello,

I have many WMV files with bad embedded author/title/date information.

However, the correct information is correctly encoded in the file
name.. i.e. "title-author-date.wmv"

I am about to conver these fiiles to MP$ for use on an iPod. The video
software I am using will, I think, transfer the metadata from the WMV
to MP4 files.

So, two questions:

1) Is there a python module I can use to edit the metadata in MP4
files?

2) Failing that, is there a python module I can use to edit the
metadata in the WMV files, and hope the data makes it through the
conversion?

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


Re: XML Schema validation in Python

2008-03-04 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
> I tested and tried a few XML validators but none of them is able to
> successfully validate a string of xml (not a file just a string) to
> programatically be able to validate messages of xml that flow in and
> out of the different systems.

http://codespeak.net/lxml/tutorial.html#parsing-from-strings-and-files
http://codespeak.net/lxml/validation.html#validation-at-parse-time
http://codespeak.net/lxml/validation.html#xmlschema

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


Re: Difference between 'function' and 'method'

2008-03-04 Thread castironpi
> > So, to answer your question: what you are decorating are functions, not
> > methods.
>
> Can you overload -type-'s decision of what to 'bind'?... whenever it
> is it makes it.

>>> from types import FunctionType, MethodType
>>> class A( FunctionType ): pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: type 'function' is not an acceptable base type
>>> class A( MethodType ): pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: type 'method' is not an acceptable base type

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


Re: unicode box drawing

2008-03-04 Thread Nanjundi
On Mar 4, 12:51 pm, jefm <[EMAIL PROTECTED]> wrote:
> How can I print the unicode box drawing characters in python:
>
> print u'\u2500'
> print u'\u2501'
> print u'\u2502'
> print u'\u2503'
> print u'\u2504'
>
> Traceback (most recent call last):
>   File "\test.py", line 3, in ?
> print u'\u2500'
>   File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode
> return codecs.charmap_encode(input,errors,encoding_map)
> UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500'
> in position 0: character maps to 

Just FYI, not an answer.

It works like a charm on linux (ubuntu, fc3, python 2.4.1 & 2.5.2)

Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'\u2500'
─
>>> print u'\u2501'
━
>>> print u'\u2502'
│
>>> print u'\u2503'
┃
>>>
>>> print u'\u2504'
┄

on windows using python 2.4. ???
-N
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How about adding rational fraction to Python?

2008-03-04 Thread Mark Dickinson
On Mar 4, 9:39 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Mar 4, 8:46 am, NickC <[EMAIL PROTECTED]> wrote:
>
> > The increased number of inaccurate answers with Decimal (31% vs 10%)
> > is probably due to the fact that it is actually more precise than
> > float
>
> I suspect it has more to do with the fact that 10 is bigger than 2,
> though I'm not sure I could precisely articulate the reasons why
> this matters.

Indeed, a quick lunchtime back-of-the-envelope calculation suggests
that precision is largely irrelevant:  it's the base that matters.
For randomly chosen(*) base B floats x and y, the probability that
(x/y)*y == x is approximately given by

1/2 + 1/log(B) - 1/log(B)**2 + 1/B/log(B)**2

For Decimal, this gives a probability of:

>>> 0.5 + 1/log(10) - 1/log(10)**2 + 1/10/log(10)**2
0.76454395459279922

while for randomly chosen floats it's the same thing with all 10s
replaced by 2s:

>>> 0.5 + 1/log(2) - 1/log(2)**2 + 1/2/log(2)**2
0.90201055038615952

(*) Here, randomly chosen means I'm assuming that log(x) and log(y)
are independent and uniformly distributed over some largish
interval.  Maybe not the most obvious definition of random, but
not unreasonable. (And it makes the analysis easier!)

A quick check, for floats:

#
from __future__ import division
from random import random
from math import exp

def random_float():
return exp(random()*400.-200.)

def test():
x = random_float()
y = random_float()
return (x/y)*y == x

print sum(test() for i in xrange(10**8))/10**8
#

produces (eventually):

0.90199129

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


ANN: GOZERBOT 0.8 released

2008-03-04 Thread Bart Thate
so 0.8 is there and can be downloaded from http://gozerbot.org

new features:

* third party addons for plugins. (needs setup.py  to work)
* reboots without disconnects (irc only for now)
* ipv6 udp support
* queues used all over the place to reduce thread usage
* normal irc log format is now supported (simplelog plugin)
* irc can now be disabled for jabber only usage
* owneruserhost is now a list so multiple userhosts can be used
* jabber reconnect code is improved
* rss error reporting is improved
* udp code is improved especially in the jabber case
* lots of other bug fixes

problems with this release can be reported on http://dev.gozerbot.org
or contact us on #dunkbots on IRCnet or freenode. email is at
[EMAIL PROTECTED]

the gozerbot development team

ABOUT GOZERBOT:

Requirements

* a shell
* python 2.4 or higher
* if you want to remotely install plugins: the gnupg module
* if you want mysql support: the py-MySQLdb module
* if you want jabber support: the xmpppy module

Why gozerbot?

* provide both IRC and Jabber support
* user management by userhost .. bot will not respond if it
doesn't know you (see /docs/USER/)
* fleet .. use more than one bot in a program (list of bots)
(see /
docs/FLEET/)
* use the bot through dcc chat
* fetch rss feeds (see /docs/RSS/)
* remember items
* relaying between bots (see /docs/RELAY/)
* program your own plugins (see /docs/PROGRAMPLUGIN/)
* run the builtin webserver (see /docs/WEBSERVER/)
* query other bots webserver via irc (see /docs/COLLECTIVE/)
* serve as a udp <-> irc or jabber gateway (see /docs/UDP)
* mysql and sqlite support
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-04 Thread Paul Rubin
Mark Dickinson <[EMAIL PROTECTED]> writes:
> For randomly chosen(*) base B floats x and y, the probability that
> (x/y)*y == x is approximately given by

I remember hearing that IEEE 754 was carefully designed to make this
identity hold as often as possible when y is a small integer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread Jeffrey Froman
Carl Banks wrote:

> there is a
> rationale behind the name "else".  If you consider a for loop to be a
> rolled-up if...elif...else statement

This is an interesting angle. I've always considered "for/else" to be
unintuitive, not because of "else", but because of the coupling with "for".
Instead, I think of this as a "break/else" statement, and everything gels
for me. The same applies to my comprehension of "while/else".

I wonder how this came to be called "for/else" or "for-else". I haven't
spotted that expression in the python docs yet.

With whatever name, I find the construct quite elegant and regularly useful.


Jeffrey


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

Python an Exchange Server

2008-03-04 Thread Yusniel
Hi friends.  Someone know how to work with python and exchange
server?.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Mensanator
On Mar 4, 2:44 am, Erik Max Francis <[EMAIL PROTECTED]> wrote:
> Mensanator wrote:
> > On Mar 3, 11:58 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
> >> Mensanator wrote:
> >>> I'm not hard to please at all.
> >> No, of course not, since logically you must think all software is useless.
>
> > Somehow, I expected better logic from people who call themselves
> > programmers.
>
> So you agree with me.  

Are you deliberately misconstruing what I write?

> Lack of prefection = uselessness.  

_I_ never said that.

What I said was a zero change in net functionality is "worthless".

A negative change in net functionality is "less than worthless".

Haven't negative numbers been well understood since the Middle Ages?

Why is this concept so difficult to grasp?

> Thanks for being honest,

I wish I could say the same.

> whether your realized you defeated your own disclaimer or not.

Conclusion based on false premise.

>
> --
> Erik Max Francis && [EMAIL PROTECTED] &&http://www.alcyone.com/max/
>   San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
>    I wonder if heaven got a ghetto
>     -- Tupac Shakur

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


Re: Python an Exchange Server

2008-03-04 Thread Tim Chase
> Hi friends.  Someone know how to work with python and exchange
> server?.

I've used both imaplib[1] and smtplib[2] (in the standard 
library) for talking successfully with an Exchange server.  I 
don't do much with POP3, but there's also a poplib module[3] in 
the standard library.  I just wrote some imaplib code this 
morning to work with an existing Exchange mailbox and some 
smtplib code last week for sending email through an Exchange box.

Exchange offers other proprietary functionality, exposed through 
the MAPI.  You might be able to use some of the Win32 
functionality in one of the add-on modules for talking with COM 
objects.

-tkc


[1] http://docs.python.org/lib/module-imaplib.html
[2] http://docs.python.org/lib/module-smtplib.html
[3] http://docs.python.org/lib/module-poplib.html



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


Re: unicode box drawing

2008-03-04 Thread Marc Christiansen
jefm <[EMAIL PROTECTED]> wrote:
> How can I print the unicode box drawing characters in python:
> 
> 
> print u'\u2500'
> print u'\u2501'
> print u'\u2502'
> print u'\u2503'
> print u'\u2504'
> 
> Traceback (most recent call last):
>  File "\test.py", line 3, in ?
>print u'\u2500'
>  File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode
>return codecs.charmap_encode(input,errors,encoding_map)
> UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500'
> in position 0: character maps to 

On linux in an utf8 console, it works with 2ython 2.4.4 and 2.5.1. It
looks like your python is using cp 1252 for output. Which does not
contain the box drawing characters. I don't think using a different
encoding would work (e.g. print u'\u2500'.encode('cp437'), or print
u'\u2500'.encode('utf8'))

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


SV: Polymorphism using constructors

2008-03-04 Thread K Viltersten
"Carl Banks" <[EMAIL PROTECTED]> skrev i meddelandet 
news:[EMAIL PROTECTED]
> On Mar 3, 4:17 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>> Since Python doesn't support having two methods with the same name,
>> the usual solution is to provide alternative constructors using
>> classmethod():
>>
>>   @classmethod
>>   def from_decimal(cls, d)
>> sign, digits, exp = d.as_tuple()
>> digits = int(''.join(map(str, digits)))
>> if sign:
>> digits = -digits
>> if exp >= 0:
>> return cls(digits * 10 ** exp)
>> return cls(digits, 10 ** -exp)
>
>
> Note that even some of Python's built in types (dict *cough*)
> implement homemade function overloading.
>
> The OP wanted to write a constructor that could accept either a pair
> of integers or a rational, there would be a good precedent for it.
>
> However, I would advise the OP to use the constructor only for the
> most common arguments, and use classmethods for more obscure, less
> common arguments (such as decimal or even float).


OP understands and thanfully accepts
the suggestion.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


SV: Polymorphism using constructors

2008-03-04 Thread K Viltersten
"Diez B. Roggisch" <[EMAIL PROTECTED]> skrev i meddelandet 
news:[EMAIL PROTECTED]
>K Viltersten schrieb:
>> I'm writing a class for rational numbers
>> and besides the most obvious constructor
>>
>>  def __init__ (self, nomin, denom):
>>
>> i also wish to have two supporting ones
>>
>>  def __init__ (self, integ):
>>self.__init__ (integ, 1)
>>  def __init__ (self):
>>self.__init__ (0, 1)
>>
>> but for some reason (not known to me at
>> this point) i get errors. My suspicion is that it's a syntax issue.
>
> "errors" is not much of an error-description. That's what stacktraces are 
> for.

I assumed that the error was so obvious to a
seasoned Pytonist (Pythoner?) that a trace
didn't matter. Your help below proves it. :)

Nevertheless, i'll be careful in the future
and make sure to post the traces too. Sorry.

> Apart from that, you won't succeed with the above. Python has no 
> signature-based polymorphism. Instead, you use default arguments, like 
> this:
>
> def __init__(nomin=0, denom=1):
> ...

Thank you.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Mensanator
On Mar 4, 10:50 am, Lie <[EMAIL PROTECTED]> wrote:
> On Mar 4, 1:12 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Mar 3, 11:58 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
>
> > > Mensanator wrote:
> > > > While we're on the subject of English, the word "worthless"
> > > > means "has no value". So, a program that doesn't work would
> > > > generally be "worthless". One that not only doesn't work but
> > > > creates side effects that cause other programs to not work
> > > > (which don't have bugs) would be "worse than worthless".
>
> > > All programs have bugs, which means that in some circumstances, they
> > > won't work.  
>
> > And in such circumstances, would be worthless.
>
> > > Therefore, by your reasoning, all programs are worse than
> > > useless.
>
> > That doesn't follow from my reasoning.
>
> > Suppose you downloaded a new calculator program that
> > couldn't add properly. That would be useless to you, right?
>
> > But suppose the program contained a virus that erased
> > your hard drive. That would be "worse than useless", wouldn't it?
>
> > > > I'm not hard to please at all.
>
> > > No, of course not, since logically you must think all software is useless.
>
> > Somehow, I expected better logic from people who call themselves
> > programmers.
>
> Mensanator, for alls sake, you've done right by pointing out the bug
> instead of muttering silently in your room,

I thought that was what's important. Who am I that anyone
cares about my opinions?

> but there is a thing
> called tolerance that you really should learn, it's about tolerating
> and understanding the possibility that other people are humans too and
> humans create mistakes, lots of them in fact and that includes you (if
> you're humans).

Actually, I had resolved to do that and I thought my original
post reflected that. Guess I still have to work at it.

> Along with tolerance should come a better choice of
> wordings,

Apparently.

> instead of saying "it sucks "

I didn't say that.

> "because it does something unexpected and unwanted"

I didn't say that either. "Unexpected and unwanted" is not
necessarily a problem, provided those symptoms are confined
to the program. When they reach out and damage things outside
the program, it's a lot more serious.

> and telling everyone not to use it,

It was intended as a warning not to use it. When I saw the
random number generator wasn't working, guess what the last
cause was that I considered? Do you realize how subtle that
error is, how many times I had to stare at it before realizing
the problem? You can't see it looking at the trees (factorint()
reurns exactly the factors of the composite it was given).

It isn't until you step back and look at the forest you suddenly
realize that the sequence coming from the "randomly" selected
factors is repeating. I was trying to prevent a lot of head
scratching by other end users who may be playing with it.

> you could
> just say "it does something unexpected and unwanted" and say that you
> wanted it fixed.

I don't think that conveys the proper seriousness.

> It's not that you've done anything wrong, but it's
> about your attitude.

As I said, I thought I had toned done the attitude.

OTOH, I'm not sure certain others aren't deliberately
misconstuing what I wrote.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread Raymond Hettinger
[BearOphile]
> So far in Python I've almost hated the 'else' of the 'for' loops

FWIW, I'm very happy with for-else.  Most of the time, you don't need
it, but when you do, it beats the heck out of doing silly tricks with
flags.

The primary use case is searching a container:

   prep_tasks()
   for item in container:
   if predicate(item):
   found_tasks()
   break
   else:
   not_found_tasks()
   follow_up_tasks

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


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Mensanator
On Mar 4, 12:32 pm, Nanjundi <[EMAIL PROTECTED]> wrote:
> On Mar 3, 3:40 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > Notice anything funny about the "random" choices?
>
> > import sympy
> > import time
> > import random
>
> > f = [i for i in sympy.primerange(1000,1)]
>
> > for i in xrange(10):
> >   f1 = random.choice(f)
> >   print f1,
> >   f2 = random.choice(f)
> >   print f2,
> >   C = f1*f2
> >   ff = None
> >   ff = sympy.factorint(C)
> >   print ff
>
> > ##  7307 7243 [(7243, 1), (7307, 1)]
> > ##  4091 6829 [(4091, 1), (6829, 1)]
> > ##  8563 2677 [(2677, 1), (8563, 1)]
> > ##  4091 6829 [(4091, 1), (6829, 1)]
> > ##  8563 2677 [(2677, 1), (8563, 1)]
> > ##  4091 6829 [(4091, 1), (6829, 1)]
> > ##  8563 2677 [(2677, 1), (8563, 1)]
> > ##  4091 6829 [(4091, 1), (6829, 1)]
> > ##  8563 2677 [(2677, 1), (8563, 1)]
> > ##  4091 6829 [(4091, 1), (6829, 1)]
>
> > As in, "they're NOT random".
>
> > The random number generator is broken by the sympy.factorint()
> > function.
>
> > Random.choice() works ok if the factorint() function commented out.
>
> > ##  6089 1811 None
> > ##  6449 1759 None
> > ##  9923 4639 None
> > ##  4013 4889 None
> > ##  4349 2029 None
> > ##  6703 8677 None
> > ##  1879 1867 None
> > ##  5153 5279 None
> > ##  2011 4937 None
> > ##  7253 5507 None
>
> > This makes sympy worse than worthless, as it fucks up other modules.
>
> Does seeding ( random.seed ) random with time fix this? It should.

I suppose that depends on how long it takes factorint() to
process a number. If the seed is reset before the next clock
tick, you will get the same random numbers as the previous
iteration.

Frankly, I don't understand why factorint() reseeds at all.
Doesn't Random automatically initialize the seed?
Doesn't constantly reseeding degrade the performance of the
random number generator? With Robert Kern's patch, the reseeding
is no longer a constant, fixing the immediate symptom.

But what if _I_ wanted to make a repeatable sequence for test
purposes? Wouldn't factorint() destroy my attempt by reseeding
on every call?

> -N

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


Re: for-else

2008-03-04 Thread bearophileHUGS
Raymond HettInger:
> FWIW, I'm very happy with for-else.  Most of the time, you don't need
> it, but when you do, it beats the heck out of doing silly tricks with
> flags.

I'd like it to be renamed to something more natural :-)

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


Re: 'normal' shell with curses

2008-03-04 Thread Thynnus
On 3/4/2008 12:05 PM, Michael Goerz wrote:
> Thynnus wrote, on 03/04/2008 08:48 AM:
>> On 3/3/2008 9:57 PM, Michael Goerz wrote:
>>> Hi,
>>>
>>> I'm trying to print out text in color. As far as I know, curses is the 
>>> only way to do that (or not?). So, what I ultimately want is a curses 
>>> terminal that behaves as closely as possible as a normal terminal, 
>>> i.e. it breaks lines and scrolls automatically, so that I can 
>>> implement a function myprint(color, text) that does what print() does, 
>>> only in color.
>> 
>> You might find the below helpful. Let us know how you make out?
>> 
>> 
>> 
>> Python Cookbook
>>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116
>> 
>> Title:
>>  Using terminfo for portable color output & cursor control
>> 
>> Description:
>> The curses module defines several functions (based on terminfo) that can 
>> be used to perform lightweight cursor control & output formatting 
>> (color, bold, etc). These can be used without invoking curses mode 
>> (curses.initwin) or using any of the more heavy-weight curses 
>> functionality. This recipe defines a TerminalController class, which can 
>> make portable output formatting very simple. Formatting modes that are 
>> not supported by the terminal are simply omitted.
>> 
>> 
>> 
> 
> That looks *extremely* interesting. From a very brief test, it seems to 
> do exactly what I want!
> 
> Now, Windows seems very problematic for color output. I was using the 
> following as a test, based on the above recipe:
> 
> term = TerminalController()
> while True:
>  print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled'
>  print term.render('${RED}Error:${NORMAL}'), 'paper is ripped'
> 
> On Linux, it works fine, on Windows, it just prints white on black 
> (which is of course what it should do if the terminal doesn't support 
> color). Can anyone get the Windows cmd.exe terminal to do color? I 
> already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, 
> but that doesn't seem to do anything (neither in what I tried yesterday 
> with the ANSI escape codes, nor with the recipe code now). I also very 
> briefly tried running it on the winbash shell 
> (http://win-bash.sourceforge.net/), it didn't have any color either... 
> So, any way to get color in Windows?
> 
> Michael

ipython - http://ipython.scipy.org/ - does a colored Windows interpreter, clue 
there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python an Exchange Server

2008-03-04 Thread Grant Edwards
On 2008-03-04, Tim Chase <[EMAIL PROTECTED]> wrote:

> Exchange offers other proprietary functionality, exposed
> through the MAPI.  You might be able to use some of the Win32 
> functionality in one of the add-on modules for talking with
> COM objects.

I spent a while looking into this a few years ago, and there
was no way to use MAPI other than via the COM interface to
Outlook.  There are examples of using Outlook via its COM
interface floating around somewhere.

-- 
Grant Edwards   grante Yow! Go on, EMOTE!
  at   I was RAISED on thought
   visi.comballoons!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python an Exchange Server

2008-03-04 Thread Mike Driscoll
On Mar 4, 1:20 pm, Yusniel <[EMAIL PROTECTED]> wrote:
> Hi friends.  Someone know how to work with python and exchange
> server?.

If you do go the COM route, you'll probably want to ask questions of
the PyWin32 user's group, which can be found here:
http://mail.python.org/mailman/listinfo/python-win32

They talk about this sort of thing quite a bit.

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


Re: Eurosymbol in xml document

2008-03-04 Thread Hellmut Weber
Hi,
thanks to all of you who have sent me helpful information.

I'm diving into the secrets of unicode.

It seems the crucial point was, that seemingly during the installation 
of the programming environment eric the file
*** /usr/lib/python2.4/site-packages/sitecustomize.py ***
has been modified.
I found that file mentioned in the excellent online book 'Diving into 
python'

Thanks again + happy pythoning

Hellmut

-- 
Dr. Hellmut Weber [EMAIL PROTECTED]
Degenfeldstraße 2 tel   +49-89-3081172
D-80803 München-Schwabing mobil +49-172-8450321
please: No DOCs, no PPTs. why: tinyurl.com/cbgq

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


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Istvan Albert
On Mar 4, 3:13 pm, Mensanator <[EMAIL PROTECTED]> wrote:

> But what if _I_ wanted to make a repeatable sequence for test
> purposes? Wouldn't factorint() destroy my attempt by reseeding
> on every call?

Would it?

It may just be that you are now itching to see a problem even where
there isn't one.

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


Re: sympy: what's wrong with this picture?

2008-03-04 Thread bearophileHUGS
apatheticagnostic:
> I swear, this is one of the most polite-oriented groups I've ever
> seen.
> Not that that's a bad thing or anything, it's nice to be nice.

Yep, and with lot more work it may even become a bit fit for women/
females too.

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


sqlite3 permission issue

2008-03-04 Thread chris
I am trying to execute an update to a sqlite3 db via a python cgi
script.  I can execute a select via a cgi script, but when I attempt
an update, I get an "unable to open database file" error.  But the
error comes on the update statement, not on the connect.

So the script has:

conn = sqlite3.connect('db')
c = conn.cursor()
--we get here ok--
c.execute("insert into contact ...") <-- this statement produces the
error

I can run the exact same python code from the command line and it
works, so it has something to do with the user that runs the cgi
(apache I assume).  I chmodded the db file to 666, but it did not
help.

Any ideas?

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


Re: unicode box drawing

2008-03-04 Thread jefm
> on windows using python 2.4. ???

yes, as a matter of fact I am.
Did not feel the need to switch to 2.5 yet.
I'm gonna give this a try, but it requires me to dig up 2.5 versions
of the libraries i am using.
(one of them didn't at the time and that is why I stuck to 2.4)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode box drawing

2008-03-04 Thread jefm
> on windows using python 2.4. ???


I was on Python 2.4.3 and it gave me that problem.
I upgraded to 2.4.4 and it works.
thanks for the tip.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| So far in Python I've almost hated the 'else' of the 'for' loops:
| - I have problems to remember its meaning;

Consider the following pseudoPython which you should understand:

label: loop
if cond:
   do_something()
   goto loop
else:
  do_else()

We actually write the above as

while cond:
  do_something()
else:
  do_else()

Same meaning; do_else is executed when condition is false.

A for-loop is equivalent to a while loop with the condition 'iterator is 
not exhausted'.  So do_else when that condition is false -- the iterator is 
exhausted.

Terry Jan Reedy



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


Re: sqlite3 permission issue

2008-03-04 Thread chris
On Mar 4, 3:10 pm, chris <[EMAIL PROTECTED]> wrote:
> I am trying to execute an update to a sqlite3 db via a python cgi
> script.  I can execute a select via a cgi script, but when I attempt
> an update, I get an "unable to open database file" error.  But the
> error comes on the update statement, not on the connect.
>
> So the script has:
>
> conn = sqlite3.connect('db')
> c = conn.cursor()
> --we get here ok--
> c.execute("insert into contact ...") <-- this statement produces the
> error
>
> I can run the exact same python code from the command line and it
> works, so it has something to do with the user that runs the cgi
> (apache I assume).  I chmodded the db file to 666, but it did not
> help.
>
> Any ideas?
>
> Thanks,
> Chris

Nevermind, it was the directory permissions causing the issue.  Works
now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SV: Polymorphism using constructors

2008-03-04 Thread Jeff Schwab
What does "SV" in the subject mean?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3 permission issue

2008-03-04 Thread Tim Chase
> I am trying to execute an update to a sqlite3 db via a python cgi

If you're running as a CGI, your script (as you guess below) will 
usually run with the effective permissions of the web-server. 
Frequently, this is some user such as "wwwdata" or "www".

> conn = sqlite3.connect('db')

Make sure that this is fully qualified:

   dbname = '/path/to/where/www/can/write/db'
   conn = sqlite3.connect(dbname)

In addition, if your local user ("cstromberger" for example) owns 
that DB file, you'll need to make sure that www can access that file:

   bash> chown :wwwdata db

(assuming the webserver runs with GID "wwwdata")  and then make 
sure you've got 660 permissions on it (rw-rw).  Issuing a 
chown as non-root may be disallowed.

> I can run the exact same python code from the command line and it
> works, so it has something to do with the user that runs the cgi
> (apache I assume).  I chmodded the db file to 666, but it did not
> help.

If the DB file is truly read/write as you describe, I'm guessing 
that the path has not been properly resolved.  It might be lazily 
opening the file, failing on first access rather than on the 
connect() call.

You might also check to see if your Apache is running in a chroot 
jail which may prevent it from seeing files in particular paths 
outside that jail.

Just a few ideas to test.  If you know you can open the file and 
read from it (the path is fully-qualified and you have permission 
to open the file), then make sure your permitted to.  It may help 
to make some stat() calls on the file to ensure that it's really 
where you think it is, and has the permissions you think it has.

Hope they help,

-tkc




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


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Mensanator
On Mar 4, 3:00 pm, Istvan Albert <[EMAIL PROTECTED]> wrote:
> On Mar 4, 3:13 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > But what if _I_ wanted to make a repeatable sequence for test
> > purposes? Wouldn't factorint() destroy my attempt by reseeding
> > on every call?
>
> Would it?

I don't know, haven't tried it yet, merely extrapolating
from how I _THINK_ it works. I used to be a System Test Engineer
and had a gift for being able to walk up to hardware/software
and break it. Spooky? No, because I could extrapolate from
the design, I could often anticipate just where to nudge it to
cause it to crash. I wasn't very popular with the programmers.

>
> It may just be that you are now itching to see a problem even where
> there isn't one.

No, no, no. That would be an oh-what-a-giveaway, wouldn't it?

>
> i.

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


Re: Edit MP4 and/or WMV file metadata?

2008-03-04 Thread Matej Cepl
On 2008-03-04, 18:53 GMT, allen.fowler wrote:
> 1) Is there a python module I can use to edit the metadata in 
> MP4
> files?

I am not sure whether taglib supports MP4, but take a look at 
http://developer.kde.org/~wheeler/taglib.html and 
http://developer.berlios.de/project/showfiles.php?group_id=2066 
or http://news.tiker.net/software/tagpy

> 2) Failing that, is there a python module I can use to edit the
> metadata in the WMV files, and hope the data makes it through the
> conversion?

You may also be able to do something with gst-launch (on Linux).

Matěj
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: 'normal' shell with curses

2008-03-04 Thread Michael Goerz
Michael Goerz wrote, on 03/04/2008 12:05 PM:
> Thynnus wrote, on 03/04/2008 08:48 AM:
>> On 3/3/2008 9:57 PM, Michael Goerz wrote:
>>> Hi,
>>>
>>> I'm trying to print out text in color. As far as I know, curses is 
>>> the only way to do that (or not?). So, what I ultimately want is a 
>>> curses terminal that behaves as closely as possible as a normal 
>>> terminal, i.e. it breaks lines and scrolls automatically, so that I 
>>> can implement a function myprint(color, text) that does what print() 
>>> does, only in color.
>>
>> You might find the below helpful. Let us know how you make out?
>>
>> 
>>
>> Python Cookbook
>>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116
>>
>> Title:
>>  Using terminfo for portable color output & cursor control
>>
>> Description:
>> The curses module defines several functions (based on terminfo) that 
>> can be used to perform lightweight cursor control & output formatting 
>> (color, bold, etc). These can be used without invoking curses mode 
>> (curses.initwin) or using any of the more heavy-weight curses 
>> functionality. This recipe defines a TerminalController class, which 
>> can make portable output formatting very simple. Formatting modes that 
>> are not supported by the terminal are simply omitted.
>>
>> 
>>
> 
> That looks *extremely* interesting. From a very brief test, it seems to 
> do exactly what I want!
> 
> Now, Windows seems very problematic for color output. I was using the 
> following as a test, based on the above recipe:
> 
> term = TerminalController()
> while True:
> print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled'
> print term.render('${RED}Error:${NORMAL}'), 'paper is ripped'
> 
> On Linux, it works fine, on Windows, it just prints white on black 
> (which is of course what it should do if the terminal doesn't support 
> color). Can anyone get the Windows cmd.exe terminal to do color? I 
> already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, 
> but that doesn't seem to do anything (neither in what I tried yesterday 
> with the ANSI escape codes, nor with the recipe code now). I also very 
> briefly tried running it on the winbash shell 
> (http://win-bash.sourceforge.net/), it didn't have any color either... 
> So, any way to get color in Windows?
> 
> Michael

This recipe seems to work very well on WinXP:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496901

So now, I'll just have to combine the two methods, which shouldn't be 
too hard.

Michael

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


Re: Talking to a usb device (serial terminal)

2008-03-04 Thread blaine

> It looks like the fastest speed supported by python termios on
> Linux is B460800 (uses a constant of 0x1004).  If you look in
> /usr/include/..., baud rates do go up to 921600 (which uses a
> constant of 0x1007).
>
> Try using the appropriate constant from /usr/include/... (for
> the target platform, of course).
>
> --
> Grant Edwards   grante Yow! Please come home with
>   at   me ... I have Tylenol!!
>visi.com

I want to thank you SO MUCH for all your help.  Here are my issues
that I overcame (sanity check):
1.  Why did we have to use 0x1007, instead of 0x10007 that our grep
command returns?
2.  PySerial works beautifully.  Thank you for the suggestion.  What I
had to do was add this to the PySerial source root in serialpostix.py,
after the import termios:

termios.B921600 = 0x1007

because PySerial looks for the actual baud rate in termios (via
getattr()) which does not exist.  PySerial actually defines the
following baud rates, but termios does not handle it:
#default values, may be overriden in subclasses that do not
support all values
BAUDRATES =
(50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
 
19200,38400,57600,115200,230400,460800,50,576000,921600,
 
100,1152000,150,200,250,300,350,400)
... so now I can pass 921600 as a parameter to PySerial! :)

So my next question is - I would like to contribute to the python
source tree by updating termios.h to handle the higher baud rates by
default.  Is this a good opportunity for me to submit a patch? I've
never done this before but have always been interested in doing so.

Thanks again!
Blaine
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Mensanator
On Mar 4, 4:40 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Mar 4, 3:00 pm, Istvan Albert <[EMAIL PROTECTED]> wrote:
>
> > On Mar 4, 3:13 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > > But what if _I_ wanted to make a repeatable sequence for test
> > > purposes? Wouldn't factorint() destroy my attempt by reseeding
> > > on every call?
>
> > Would it?
>
> I don't know, haven't tried it yet,

Now I have and there is no problem.

> merely extrapolating from how I _THINK_ it works.

And my thinking was mistaken, the patch doesn't reset the seed,
so nevermind.

> I used to be a System Test Engineer
> and had a gift for being able to walk up to hardware/software
> and break it. Spooky? No, because I could extrapolate from
> the design, I could often anticipate just where to nudge it to
> cause it to crash. I wasn't very popular with the programmers.
>
>
>
> > It may just be that you are now itching to see a problem even where
> > there isn't one.
>
> No, no, no. That would be an oh-what-a-giveaway, wouldn't it?
>
>
>
>
>
> > i.- Hide quoted text -
>
> - Show quoted text -

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


  1   2   >