Announcing IronPython 2.6 CTP for .NET 4.0 Beta 2

2009-10-22 Thread Dino Viehland
Hello Python Community,

We're quite pleased to announce the release of IronPython 2.6 CTP for .NET 4.0 
Beta 2.  This is our third preview of IronPython running under the Dynamic 
Language Runtime that is built directly into a .NET 4.0 release!  As before, 
this release allows you to use IronPython objects and types as .NET 4.0 dynamic 
objects from within C# and Visual Basic code.  This release is extremely 
similar to IronPython 2.6 RC 1.  Please also note that IronPython 2.6 CTP for 
.NET 4.0 Beta 2 will run only under .NET 4.0 Beta 2.

Here's a small example showing just how powerful the new dynamic feature is for 
taking advantage of dynamic language functionality in statically typed 
languages:
    mock.py
    import random, math
    
    class Mock(object): 
    def __getattr__(self, key):
    Mock objects of this type will dynamically implement any 
requested member
    return random.choice([hello world, math.pi])
     /mock.py

    dynamic_demo.cs
    using System;
    using IronPython.Hosting;
    using Microsoft.Scripting.Hosting;
    
    public class dynamic_demo {
    static void Main() {  
   var ipy = Python.CreateRuntime();
       dynamic mock = ipy.UseFile(mock.py);
       dynamic m = mock.Mock();
   //The Python Mock type dynamically implements any member that is 
requested of it
   
System.Console.WriteLine(m.the_csharp_compiler_cannot_possbily_know_this_member_exists_at_compile_time);
    }
    }
    dynamic_demo.cs


To try out this preview release:
1. Install some variant of .NET 4.0 Beta 2 or Visual Studio 2010 Beta 2.  E.g., 
http://www.microsoft.com/downloads/details.aspx?FamilyID=9f5e8774-c8dc-4ff6-8285-03a4c387c0dbdisplaylang=en
 
2. Install  IronPython 2.6 CTP for .NET 4.0 Beta 2.msi from 
http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28125 
3. Follow any of the many dynamic walkthroughs online.  
http://blogs.msdn.com/vbteam/archive/2008/12/17/walkthrough-dynamic-programming-in-visual-basic-10-0-and-c-4-0-lisa-feigenbaum.aspx
 would be a good start

Have fun!

The IronPython Team



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

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: a splitting headache

2009-10-22 Thread rurpy
On 10/21/2009 11:47 PM, Carl Banks wrote:
 On Oct 21, 12:46 pm, David C Ullrich dullr...@sprynet.com wrote:
 On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
  On Oct 20, 1:51 pm, David C Ullrich dullr...@sprynet.com wrote:
  I'm not saying either behaviour is wrong, it's just not obvious that the
  one behaviour doesn't follow from the other and the documentation could
  be
  a little clearer on this matter. It might make a bit more sense to
  actually
  mention the slpit(sep) behavior that split() doesn't do.

 Have you _read_ the docs? They're quite clear on the difference
 between no sep (or sep=None) and sep=something:

 Even if the docs do describe the behavior adequately, he has a point
 that the documents should emphasize the counterintutive split
 personality of the method better.

 s.split() and s.split(sep) do different things, and there is no string
 sep that can make s.split(sep) behave like s.split().  That's not
 unheard of but it does go against our typical expectations.  It would
 have been a better library design if s.split() and s.split(sep) were
 different methods.

 That they are the same method isn't the end of the world but the
 documentation really ought to emphasize its dual nature.

I would also offer that the example

  '1,,2'.split(',') returns ['1', '', '2'])

could be improved by including a sep instance at the
beginning or end of the string, like

  '1,,2,'.split(',') returns ['1', '', '2', ''])

since that illustrates another difference between the
sep and non-sep cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: equivalent to globals(), locals() for nonlocal variables?

2009-10-22 Thread Gabriel Genellina
En Wed, 21 Oct 2009 16:06:31 -0300, geremy condra debat...@gmail.com  
escribió:



I decided to play around with nonlocal declarations today, and was
somewhat surprised when a call to nonlocals() resulted in 'nonlocals
is not defined'. Is there an a standard equivalent to globals() or
locals() for variables in outer nested scopes?


Not that I know of - and as someone pointed out recently, vars() should  
include those variables instead of simply returning locals().


--
Gabriel Genellina

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


Re: Cpython optimization

2009-10-22 Thread Olof Bjarnason
2009/10/22 John Yeung gallium.arsen...@gmail.com

 On Oct 22, 12:28 am, John Nagle na...@animats.com wrote:

 The Shed Skin people would welcome some help.
 
 http://shed-skin.blogspot.com/

 People?  It's one guy.  It apparently started out as a Master's thesis
 as well. ;)

 I am a great admirer of the Shed Skin project, and I would be as happy
 as anyone to see it progress.  However, it seems to me that Shed Skin
 is at a stage where what it really needs is plain old more work.  (I
 don't want to call it grunt work, but it's things like more testing,
 implementing more library support, maintaining the Windows build,
 etc.  Very worthy and worthwhile work, but tough to pass off as
 academic graduate work.)

 To the original poster:  I am not sure if this is too ambitious for
 your time frame, but one thing many real-world Python users would LOVE
 is for some way to get rid of the GIL (while still retaining thread
 safety, single-core performance, etc.).  If you could patch CPython to
 make it GIL-less, I think you would have academically publishable
 material as well as being a hero in the Python community. :D


A short question after having read through most of this thread, on the same
subject (time-optimizing CPython):

http://mail.python.org/pipermail/python-list/2007-September/098964.html

We are experiencing multi-core processor kernels more and more these days.
But they are all still connected to the main memory, right?

To me that means, even though some algorithm can be split up into several
threads that run on different cores of the processor, that any algorithm
will be memory-speed limited. And memory access is a quite common operation
for most algorithms.

Then one could ask oneself: what is the point of multiple cores, if memory
bandwidth is the bottleneck? Specifically, what makes one expect any speed
gain from parallelizing a sequential algorithm into four threads, say, when
the memory shuffling is the same speed in both scenarios? (Assuming memory
access is much slower than ADDs, JMPs and such instructions - a quite safe
assumption I presume)

[ If every core had it's own primary memory, the situation would be
different. It would be more like the situation in a distributed/internet
based system, spread over several computers. One could view each core as a
separate computer actually ]


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




-- 
twitter.com/olofb
olofb.wordpress.com
olofb.wordpress.com/tag/english
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a splitting headache

2009-10-22 Thread Mensanator
On Oct 21, 11:21�pm, John Yeung gallium.arsen...@gmail.com wrote:
 On Oct 21, 5:43�pm, Mensanator mensana...@aol.com wrote:

   '01110'.split('0')

  ['', '1', '', '', '', '11', '']

  is a perfect example. It shows the empty strings
  generated from the leading and trailing delimiters,
  and also that you get 3 empty strings between the
  '1's, not 4. When creating documentation, it is
  always a good idea to document such cases.

 It's documented. �

What does 'it' refer to? A leading or trailing
delimiter? That's what _I_ was refering to.

 It's even in the example

No, it is not.

 (that you cited yourself):

 � '1,,2'.split(',') returns ['1', '', '2']

 There are two commas between the '1' and the '2', but only one empty
 string between them. �To me, it's obvious that

 � '1,,2'.split(',')

 is equivalent to

 � '1002'.split('0')

That wasn't what I was complaining about.


  And you'll then want to compare this to the
  equivalent whitespace case:

   ' 1 � �11 '.split()
  ['1', '11']

 The documentation could not be more explicit that when the separator
 is not specified or is None, it behaves very differently.

I am not complaining that it behaves differently, but
the description of said difference could be better
explained.


 Have you tried to see what happens with

 � ' 1 � �11 '.split(' ')

Yes, I actually did that test.


 (Hint: �The separator is (a kind of) white space... yet IS specified.

And yet doesn't behave like .split(). In other words,
when specified, whitespace does not behave like
whitespace. Is it any wonder I have a headache?

)

  I was looking for some feedback here.
  And it seems that no one else considers the
  documentation wanting.

 This particular section of documentation, no. �I have issues with some
 of the documentation here and there; this is not one of those areas.

 You kept using phrases in your arguments like Yes, if you
 think it through and An example would at least force me to think
 about it. �Um... are we not supposed to think?

No, you are not. Documentation isn't supposed to give
you hints so that you can work out the way things
behave. It should provide adequete explantion along
with unambiguous, complete examples. The thinking part
comes into play as you try to figure out how to apply
what you have just learned.


 John

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


Re: md5 strange error

2009-10-22 Thread Steven D'Aprano
On Wed, 21 Oct 2009 01:11:29 -0700, catalinf...@gmail.com wrote:

 I have this error , what happen ?
 
 Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) [GCC 4.3.2 20080917
 (Red Hat 4.3.2-4)] on linux2 Type help, copyright, credits or
 license for more information.
 import md5
 pass = md5.new()
   File stdin, line 1
 pass = md5.new()
  ^
 SyntaxError: invalid syntax
 m = md5.new()
 n = md5.new()



What makes you think it's an error with md5? As you can see, md5 works 
fine. The error message tells you the problem occurs *before* the call to 
md5.new().


 pass = 45
  File stdin, line 1
pass = 45
 ^
SyntaxError: invalid syntax


As others have told you, it's a problem with pass, which is a statement 
and reserved word.


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


Re: Optimal Character recognition using python

2009-10-22 Thread Steven D'Aprano
On Wed, 21 Oct 2009 07:07:54 -0700, pytart wrote:

 Hello ,
I have a project to develop a basic character recognition
 module in python using backpropagation and artificial neural networks. I
 would be very helpful if u cud give me some helpful links for the
 project.

Oh that's hilarious. Sophisticated tech speak (basic character 
recognition module in python using backpropagation and artificial neural 
networks) immediately followed by the most egregious sms-drooling (u 
cud).

pytart, do you code like you write English?



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


Re: a splitting headache

2009-10-22 Thread Mensanator
On Oct 22, 1:13�am, ru...@yahoo.com wrote:
 On 10/21/2009 11:47 PM, Carl Banks wrote:





  On Oct 21, 12:46 pm, David C Ullrich dullr...@sprynet.com wrote:
  On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
   On Oct 20, 1:51 pm, David C Ullrich dullr...@sprynet.com wrote:
   I'm not saying either behaviour is wrong, it's just not obvious that the
   one behaviour doesn't follow from the other and the documentation could
   be
   a little clearer on this matter. It might make a bit more sense to
   actually
   mention the slpit(sep) behavior that split() doesn't do.

  Have you _read_ the docs? They're quite clear on the difference
  between no sep (or sep=None) and sep=something:

  Even if the docs do describe the behavior adequately, he has a point
  that the documents should emphasize the counterintutive split
  personality of the method better.

  s.split() and s.split(sep) do different things, and there is no string
  sep that can make s.split(sep) behave like s.split(). �That's not
  unheard of but it does go against our typical expectations. �It would
  have been a better library design if s.split() and s.split(sep) were
  different methods.

  That they are the same method isn't the end of the world but the
  documentation really ought to emphasize its dual nature.

 I would also offer that the example

 � '1,,2'.split(',') returns ['1', '', '2'])

 could be improved by including a sep instance at the
 beginning or end of the string, like

 � '1,,2,'.split(',') returns ['1', '', '2', ''])

 since that illustrates another difference between the
 sep and non-sep cases.

But if '1,,2'.split(',') returned ['1', '', '2', ''],
then ','.join(['1', '', '2', '']) would return
'1,,2,' which is not what you started with, so I would
hardly call that an improvement.

The split function works fine, either version, I just
think it could be explained better.

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


Re: Optimal Character recognition using python

2009-10-22 Thread Murtaza Gheewala
That was harsh, Steven.
Well, to answer your question pytart, do a quick search here:
http://groups.google.com/group/comp.lang.python/topics?pli=1
and/or here:
http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-list
as I'm pretty sure someone has already asked this question that has got
answered before.

On Thu, Oct 22, 2009 at 12:05 PM, Steven D'Aprano 
ste...@remove.this.cybersource.com.au wrote:

 On Wed, 21 Oct 2009 07:07:54 -0700, pytart wrote:

  Hello ,
 I have a project to develop a basic character recognition
  module in python using backpropagation and artificial neural networks. I
  would be very helpful if u cud give me some helpful links for the
  project.

 Oh that's hilarious. Sophisticated tech speak (basic character
 recognition module in python using backpropagation and artificial neural
 networks) immediately followed by the most egregious sms-drooling (u
 cud).

 pytart, do you code like you write English?



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

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


Mixing different interpreters in the same program

2009-10-22 Thread Jaime Buelta
Hello:

  I keep thinking from some time ago in how to conect two or more
Python interpreters. This began as interest in calling Java code from
C program, which was solved (at the time) using an intermediate file.

  But having CPython and Jython, I think it would be great to call a
function from, let's say, a CPython interpreter and execute java code.

  I been reading about the multiprocessing module, but doesn't been
able to call the Jython interpreter from CPython. Also, Jython is
still at version 2.5 and doesn't have the multiprocessing, so it won't
probably work either.

  Any way, thinking like a wish list, I think it will be very
interesting a module with the following behaviour to make python even
more powerful in gluing things up.
  Could make from MyModule import java or from MyModule import
jython, so the module will start a jython interpreter. Then call code
to be executed on the jython interpreter like 'jython.javafunction'

  Of course, it could be also an import ironpython to start an
IronPython or any other Python interpreter configured. Or import
cpython from jython.

  Regarding performance, which I think won't be never great at it has
some overhead setting interpreters up, sending data, etc, it will be
great to add a MyModule.exec(function) to execute completely a funtion
on the remote interpreter

  Well, just thinking about some ideas and sharing with you ;-)

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


Re: How to write a facebook client?

2009-10-22 Thread holmes86
On Oct 22, 10:42 am, geremy condra debat...@gmail.com wrote:
 On Wed, Oct 21, 2009 at 9:45 PM, holmes86 holme...@gmail.com wrote:
  Hi,everyone

  I'm a python newbie,and I want to write a facebook client.But I don't
  know how to do it.Meanwhile I have any write web experience,so I also
  don't know how to analyse web page.Any help will be appreciate.
  --
 http://mail.python.org/mailman/listinfo/python-list

 Obligatory warning: any project, of any size, in computer science or
 any related field, will require you to learn a *lot*, and most of the time
 other people aren't going to be able or willing to help you- you just have
 to do it yourself. If that doesn't sound like something you want to do
 or are able to do, then you should probably save yourself some trouble
 and stop now. Otherwise, the links below may be helpful.

 1) google.com, it's your friend
 2) htmlgoodies.com, for the basics of the web side
 3) w3schools.com, for a bit more of the web stuff
 4) docs.python.org, for the python stuff
 5)http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial,
     for getting python and facebook to play nicely together.

 Good luck.

 Geremy Condra

OK,thanks very much
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unittest wart/bug for assertNotEqual

2009-10-22 Thread Gabriel Genellina
En Tue, 20 Oct 2009 19:57:19 -0300, Ethan Furman et...@stoneleaf.us  
escribió:

Steven D'Aprano wrote:

On Tue, 20 Oct 2009 14:45:49 -0700, Zac Burns wrote:



My preference would be that failIfEqual checks both != and ==. This is
practical, and would benefit almost all use cases. If != isn't not
== (IEEE NaNs I hear is the only known use case)



  numpy uses == and != as element-wise operators:


Two issues:  1) Sounds like we should have two more Asserts --  
failIfNotEqual, and assertNotNotEqual to handle the dichotomy in Python;  
and 2) Does this mean (looking at Mark Dickinson's post) that 2.7 and  
3.1 are now broken?


1) assertEqual and assertNotEqual test for == and != respectively. The  
failXXX methods are being deprecated. Why do you think we need more  
asserts?
2) Not exactly, but there are still inconsistencies (e.g. assertDictEqual  
and assertMultiLineEqual use != instead of ==, and some assertion messages  
use the wrong terminology)


--
Gabriel Genellina

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


Re: which dictionary with attribute-style access?

2009-10-22 Thread baloan
On Oct 22, 6:34 am, Gabriel Genellina gagsl-...@yahoo.com.ar
wrote:
  class AttrDict(dict):
       A dict whose items can also be accessed as member variables.
       def __init__(self, *args, **kwargs):
           dict.__init__(self, *args, **kwargs)
           self.__dict__ = self

       def copy(self):
           return AttrDict(self)

       def __repr__(self):
           return 'AttrDict(' + dict.__repr__(self) + ')'

      �...@classmethod
       def fromkeys(self, seq, value = None):
           return AttrDict(dict.fromkeys(seq, value))

 Looks fine as long as nobody uses an existing method name as adictionary 
 key:

 py d = AttrDict({'name':'value'})
 py d.items()
 [('name', 'value')]
 py d = AttrDict({'items': [1,2,3]})
 py d.items()
 Traceback (most recent call last):
    File stdin, line 1, in module
 TypeError: 'list' object is not callable

 (I should have included a test case for this issue too).
 Of course, if this doesn't matter in your application, go ahead and use  
 it. Just be aware of the problem.

 --
 Gabriel Genellina

I see two ways to avoid collisions with existing method names:

1. (easy, reduced functionality) override __setattr__ and __init__,
test for keys matching existing method names, throw an exception if
exists (KeyError).
2. (complex, emulates dict) override __setattr__ and __init__, test
for keys matching existing method names, and store those keys in a
shadow dict. More problems arise when thinking about how to choose
access between dict method names and item keys.

--
Andreas Balogh
baloand at gmail dot com
-- 
http://mail.python.org/mailman/listinfo/python-list


form have 2 iframe.problem to input text in other iframe

2009-10-22 Thread elca

hello,
i have some form which split by  iframe.
subject field is no probelm ,but content field was come from another iframe
source..
so i can't input text in content's field..
im using PAMIE and win32com module..
i have to put text in 'contents.contentsValue' here.
but i have no luck..anyone can help me? if so really appreciate 
follow is some of html source code. thanks in advance
Paul.

IFRAME style=WIDTH: 100%; DISPLAY: block; HEIGHT: 400px height=100%
src=/npost/default.jsp frameBorder=0 width=100%
allowTransparency/IFRAMETEXTAREA style=BORDER-BOTTOM: 0px; BORDER-LEFT:
0px; WIDTH: 100%; DISPLAY: none; HEIGHT: 400px; BORDER-TOP: 0px;
BORDER-RIGHT: 0px id=textbox name=contents.contentsValue  



/TEXTAREA
DIV position=relativeINPUT style=POSITION: absolute; WIDTH: 0px
id=focusHolderForIE11248 type=buttonINPUT style=POSITION: absolute;
WIDTH: 0px id=focusHolderForIE26051
type=button/DIV/TD/TR/TBODY/TABLE/TD
TD class=attach width=75


-- 
View this message in context: 
http://www.nabble.com/form-have-2-iframe.problem-to-input-text-in-other-iframe-tp25989646p25989646.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


[OT] Supporting homework (was: Re: Checking a Number for Palindromic Behavior)

2009-10-22 Thread Dieter Maurer
Steven D'Aprano ste...@remove.this.cybersource.com.au writes on 20 Oct 2009 
05:35:18 GMT:
 As far as I'm concerned, asking for help on homework without being honest 
 up-front about it and making an effort first, is cheating by breaking the 
 social contract. Anyone who rewards cheaters by giving them the answer 
 they want is part of the problem. Whether cheaters prosper in the long 
 run or not, they make life more difficult for the rest of us, and should 
 be discouraged.

A few days ago, I have read an impressive book: Albert Jacquard: Mon utopie.
The author has been a university professor (among others for
population genectics, a discipline between mathematics and biologie).
One of the corner therories in his book: mankind has reached the current
level of development not mainly due to exceptional work by individuals
but by the high level of cooperation between individuals.

In this view, asking for help (i.e. seeking communication/cooperation)
with individual tasks should probably be highly encouraged not discouraged.
At least, it is highly doubtful that the paradigm each for himself,
the most ruthless wins will be adequate for the huge problems mankind
will face in the near future (defeating hunger, preventing drastic
climate changes, natural resources exhaustion, ); intensive
cooperation seems to be necessary.

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


Cpython optimization

2009-10-22 Thread Qrees
Hello

As my Master's dissertation I chose Cpython optimization. That's why
i'd like to ask what are your suggestions what can be optimized. Well,
I know that quite a lot. I've downloaded the source code (I plan to
work on Cpython 2.6 and I've downloaded 2.6.3 release). By looking at
the code I've found comment's like this can be optimized by... etc.
but maybe you guide me what should I concentrate on in my work?

I've 6-7 month  for this and If I create something decent I can
publish it.

Thank you in advance for any help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking a Number for Palindromic Behavior

2009-10-22 Thread Steven D'Aprano
On Wed, 21 Oct 2009 22:53:29 -0700, rurpy wrote:

 On 10/21/2009 03:13 PM, Lie Ryan wrote:
  ru...@yahoo.com wrote:
  On 10/21/2009 01:40 AM, Lie Ryan wrote:
 [...]
  As a metaphor, which one do you think is better in the long term:
  charities or microcredits?
 
  Both of course.  Why on earth would anyone think there is a simple,
  single, best answer for complex problems?
 
  Nope, read again. On the *long term* (as I have stated in the
  question), microcredits is proven to be much more effective to
  solving poverty. In the short term, charities will have much quicker
  effect but not one that is lasting and in fact too much charities
  makes a lot more problems.
 
 Uh, let's see, charity is no longer needed since micro- credits have
 been *proven* to eliminate their need.

Lie did not say that. Rurpy, how stupid do you take us for, leaving Lie's 
direct quote there in your email and then outrageously misrepresenting 
him like that?

What Lie actually said, rather than your fantasy interpretation, is not 
only intuitively obvious, but also supported by the evidence:

* charities can have a good effect very quickly;
* but reliance on charity in the long-term breeds dependency and 
encourages corruption;
* long term solutions for solving poverty require empowering individuals;
* micro-credits are often a good way to empower individuals with little 
risk to the lender.

The motto about giving a man a fish to feed him for a day, versus 
teaching him to fish to feed him for life, applies here. Why you think 
any of this is controversial is beyond me.

Of course, micro-credits aren't a panacea -- the Wikipedia article 
discusses some of the limits and problems with them:

http://en.wikipedia.org/wiki/Microcredit



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


Re: Checking a Number for Palindromic Behavior

2009-10-22 Thread rurpy
On 10/21/2009 03:13 PM, Lie Ryan wrote:
  ru...@yahoo.com wrote:
  On 10/21/2009 01:40 AM, Lie Ryan wrote:
[...]
  As a metaphor, which one do you think is better in the long term:
  charities or microcredits?
 
  Both of course.  Why on earth would anyone think there
  is a simple, single, best answer for complex problems?
 
  Nope, read again. On the *long term* (as I have stated in the question),
  microcredits is proven to be much more effective to solving poverty. In
  the short term, charities will have much quicker effect but not one that
  is lasting and in fact too much charities makes a lot more problems.

Uh, let's see, charity is no longer needed since micro-
credits have been *proven* to eliminate their need.

OK.  Since we have now entered la-la land, I think
I'll let myself out quietly by the back door... :-)

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


Re: Checking a Number for Palindromic Behavior

2009-10-22 Thread rurpy
On 10/22/2009 12:35 AM, Steven D'Aprano wrote:
 On Wed, 21 Oct 2009 22:53:29 -0700, rurpy wrote:

 On 10/21/2009 03:13 PM, Lie Ryan wrote:
  ru...@yahoo.com wrote:
  On 10/21/2009 01:40 AM, Lie Ryan wrote:
 [...]
  As a metaphor, which one do you think is better in the long term:
  charities or microcredits?
 
  Both of course.  Why on earth would anyone think there is a simple,
  single, best answer for complex problems?
 
  Nope, read again. On the *long term* (as I have stated in the
  question), microcredits is proven to be much more effective to
  solving poverty. In the short term, charities will have much quicker
  effect but not one that is lasting and in fact too much charities
  makes a lot more problems.

 Uh, let's see, charity is no longer needed since micro- credits have
 been *proven* to eliminate their need.

 Lie did not say that. Rurpy, how stupid do you take us for, leaving Lie's
 direct quote there in your email and then outrageously misrepresenting
 him like that?

What he said was, which one do you think is better
in the long term: charities or microcredits?
I said, both (thinking in the sense that both are
necessary.)
He said, Nope.
I concluded that means one or the other is better
followed by the unjustified conclusion (influenced
by his incorrect claim that microcredits were
*proven* and *much* more effective than charity)
that if one was better then the other was unnecessary.

My apologies Lie, for misrepresenting you.

However I don't agree that micro credits are
better (whatever that means) than charity but
am not interested in arguing the point here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Supporting homework (was: Re: Checking a Number for Palindromic Behavior)

2009-10-22 Thread Stephen Hansen
On Wed, Oct 21, 2009 at 10:04 PM, Dieter Maurer die...@handshake.de wrote:

 Steven D'Aprano ste...@remove.this.cybersource.com.au writes on 20 Oct
 2009 05:35:18 GMT:
  As far as I'm concerned, asking for help on homework without being honest
  up-front about it and making an effort first, is cheating by breaking the
  social contract. Anyone who rewards cheaters by giving them the answer
  they want is part of the problem. Whether cheaters prosper in the long
  run or not, they make life more difficult for the rest of us, and should
  be discouraged.

 A few days ago, I have read an impressive book: Albert Jacquard: Mon
 utopie.
 The author has been a university professor (among others for
 population genectics, a discipline between mathematics and biologie).
 One of the corner therories in his book: mankind has reached the current
 level of development not mainly due to exceptional work by individuals
 but by the high level of cooperation between individuals.

 In this view, asking for help (i.e. seeking communication/cooperation)
 with individual tasks should probably be highly encouraged not discouraged.
 At least, it is highly doubtful that the paradigm each for himself,
 the most ruthless wins will be adequate for the huge problems mankind
 will face in the near future (defeating hunger, preventing drastic
 climate changes, natural resources exhaustion, ); intensive
 cooperation seems to be necessary.


It's not that people aren't willing to assist others in questions that are
homework, but when those with homework come to the community to seek the
answers without showing that they are trying to achieve that answer on their
own.

The student must learn to think through a problem and find a solution.
There's a distinct difference between one student coming to the community
and saying, How do I do X?, and another coming and saying, I am trying to
do X, and I have attempted Y and Z. This is not working, can you explain
why?

In the former, the student is simply asking for an answer to the question
they have been tasked with answering. This is unethical. The student is not
seeking help to find a solution to a problem, but seeking the solution
itself. In the latter, the student clearly articulates they have a problem
and shows their attempt at discovering a solution-- and they are asking
questions which are not simply 'Tell me the answer' but 'Tell me what I do
not understand'.

The former is an example of a lazy mind seeking solution; the latter is an
example of a curious mind seeking understanding. IMHO and in my experience,
the community is more then willing to support the curious-- be they student,
hobbyist, or professional. But the lazy student who tries to use the
community to get an answer without ever really understanding the problem...
that's something else entirely.

In my experience, the Python community is very willing to support and
encourage those questioning and seeking the advice of others to find good
and workable solutions. Every once in awhile, someone comes to the community
with a question which doesn't really seek to expand their understanding but
instead seeks to bypass the need to understand-- they seek simple answers to
questions posed to them without any need of them learning the necessary
lessons. That's cheating.

The community isn't here to do the work for anyone. Its here to share its
collective expertise, wisdom and knowledge in order to enrich  everyone's
experience.

We aren't here to do anyone elses work for them. We're here to share and
grow together. Anyone who shows an interest in putting effort into a task
tends to get helped-- but if someone wants to just sit around and be handed
the solution, why should we bother? IMHO, the community doesn't object to
those asking for help. It objects to those asking for others to do their
work for them.

IMHO.

Did I mention IMHO? :)

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


Re: [OT] Supporting homework (was: Re: Checking a Number for Palindromic Behavior)

2009-10-22 Thread Andre Engels
On Thu, Oct 22, 2009 at 7:04 AM, Dieter Maurer die...@handshake.de wrote:
 Steven D'Aprano ste...@remove.this.cybersource.com.au writes on 20 Oct 2009 
 05:35:18 GMT:
 As far as I'm concerned, asking for help on homework without being honest
 up-front about it and making an effort first, is cheating by breaking the
 social contract. Anyone who rewards cheaters by giving them the answer
 they want is part of the problem. Whether cheaters prosper in the long
 run or not, they make life more difficult for the rest of us, and should
 be discouraged.

 A few days ago, I have read an impressive book: Albert Jacquard: Mon utopie.
 The author has been a university professor (among others for
 population genectics, a discipline between mathematics and biologie).
 One of the corner therories in his book: mankind has reached the current
 level of development not mainly due to exceptional work by individuals
 but by the high level of cooperation between individuals.

 In this view, asking for help (i.e. seeking communication/cooperation)
 with individual tasks should probably be highly encouraged not discouraged.
 At least, it is highly doubtful that the paradigm each for himself,
 the most ruthless wins will be adequate for the huge problems mankind
 will face in the near future (defeating hunger, preventing drastic
 climate changes, natural resources exhaustion, ); intensive
 cooperation seems to be necessary.

I think you are much mis-interpreting the quoted text here. Steven is
arguing against asking for help on homework **without being honest
up-front about it and making an effort first**. We are all willing to
help people who say For such-and-such homework assignment I created
this-and-that program but I still cannot work out how to do so-and-so
part. The problems come when someone shoves a simple problem at us,
and basically says I must write this simple program, please do it for
me. The canned response for that is What have you tried and where
did you get problems? - look for a way to cooperate with people, to
help them where that is necessary. What is being argued against is to
just give the people the code in such a case. Steven and others are
*looking for* cooperation, not shying away from it. Cooperation in the
form of try to do it yourself, and if that fails, we will help you.
What we don't want is 'cooperation' in the form just shove your
problem on our plate and consider yourself done.

-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode again ... default codec ...

2009-10-22 Thread Lele Gaifax
Gabriel Genellina gagsl-...@yahoo.com.ar writes:

 En Wed, 21 Oct 2009 06:24:55 -0300, Lele Gaifax l...@metapensiero.it
 escribió:

 Gabriel Genellina gagsl-...@yahoo.com.ar writes:

 nosetest should do nothing special. You should configure the environment
 so Python *knows* that your console understands utf-8. Once Python is
 aware of the *real* encoding your console is using, sys.stdout.encoding
 will be utf-8 automatically and your problem is solved. I don't know how
 to do that within virtualenv, but the answer certainly does NOT involve
 sys.setdefaultencoding()

 On Windows, a normal console window on my system uses cp850:


 D:\USERDATA\Gabrielchcp
 Tabla de códigos activa: 850

 D:\USERDATA\Gabrielpython
 Python 2.6.3 (r263rc1:75186, Oct  2 2009, 20:40:30) [MSC v.1500 32 bit
 (Intel)]
 on win32
 Type help, copyright, credits or license for more information.
 py import sys
 py sys.getdefaultencoding()
 'ascii'
 py sys.stdout.encoding
 'cp850'
 py u = uáñç
 py print u
 áñç

This is the same on my virtualenv:

$ python -c import sys; print sys.getdefaultencoding(), 
sys.stdout.encoding
ascii UTF-8
$ python -c print u'\xe1\xf1\xe7'
áñç

But look at this:

$ cat test.py
# -*- coding: utf-8 -*-

class TestAccents(object):
u'\xe1\xf1\xe7'

def test_simple(self):
u'cioè'

pass


$ nosetests  test.py
.
--
Ran 1 test in 0.002s

OK

$ nosetests -v test.py
ERROR

==
Traceback (most recent call last):
  File /tmp/env/bin/nosetests, line 8, in module
load_entry_point('nose==0.11.1', 'console_scripts', 'nosetests')()
  File 
/tmp/env/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/core.py, line 
113, in __init__
argv=argv, testRunner=testRunner, testLoader=testLoader)
  File /usr/lib/python2.6/unittest.py, line 817, in __init__
self.runTests()
  File 
/tmp/env/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/core.py, line 
192, in runTests
result = self.testRunner.run(self.test)
  File 
/tmp/env/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/core.py, line 
63, in run
result.printErrors()
  File 
/tmp/env/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/result.py, 
line 81, in printErrors
_TextTestResult.printErrors(self)
  File /usr/lib/python2.6/unittest.py, line 724, in printErrors
self.printErrorList('ERROR', self.errors)
  File /usr/lib/python2.6/unittest.py, line 730, in printErrorList
self.stream.writeln(%s: %s % (flavour,self.getDescription(test)))
  File /usr/lib/python2.6/unittest.py, line 665, in writeln
if arg: self.write(arg)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in 
position 10: ordinal not in range(128)

Who is the culprit here?

The fact is, encodings are the real Y2k problem, and they are here to
stay for a while!

thank you,
ciao, lele.
-- 
nickname: Lele Gaifax| Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas| comincerò ad aver paura di chi mi copia.
l...@nautilus.homeip.net | -- Fortunato Depero, 1929.

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


Passing values from html to python

2009-10-22 Thread Ahmed Barakat
Hi guys,

I am new to python and wed-development, I managed to have some nice example
running up till now.
I am playing with google app engine, I have this situation:

I have a text box in an html page, I want to get the value in it and pass it
to the python script to process it
I can pass values from python to html, but the other way I don't know how to
do that.

appreciate your help.

-- 

Regards,
Ahmed Barakat

http://ahmedbarakat83.blogspot.com/
Even a small step counts
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt4 - remember widget positions

2009-10-22 Thread nusch
On Oct 22, 4:05 am, TerryP bigboss1...@gmail.com wrote:
 On Oct 21, 9:04 pm, nusch nusc...@gmail.com wrote:

  Is there any simple command which allows me to save position of all
  windows:  QMainWindow, QDialogs and qdockwidgets with their sizes,
  dock state and positions ? Or do I need to store those values
  manually, how can I do it fast?

 Both fast and simple have relative meanings, there may be some common
 persistence mumbo jumbo added to Qt since I last looked but, in
 generally read this:

    http://doc.trolltech.com/4.5/geometry.html

 I don't know off the top of my head if PyQt's documentation has code
 examples on it, but it should be fairly easy for you to comprehend how
 to do it in Python.
 .
 --
 TerryP

Yes, but I meant how to store all QApplication windows size and pos at
once, I don't want to introduce lot of additional strings describing
keys in QSettings. I migrated my app from PyKDE to pure PyQt4 and
there was 1 command for whole app to remember those settings.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Frameworks

2009-10-22 Thread Bruno Desthuilliers

Emmanuel Surleau a écrit :

It still manages to retain flexibility, but you're basically stuck with
Django's ORM

You're by no way stuck with Django's ORM - you are perfectly free not
to use it. But then you'll obviously loose quite a lot of useful
features and 3rd part apps...

You lose most of what makes it worth using Django,

Mmmm... I beg to disagree. You still have the core framework (request /
response handling, sessions etc), the templating system, the form API
etc. As far as I'm concerned, it's quite enough to make it worth.


The form API is pretty good, but I don't think the rest makes it stand out 
that much, compared to other frameworks.


I don't care if it stand out that much - it works fine and is well 
documented. Given that for most web apps, Django's ORM is a good enough 
tool, I don't see the point in using 3 or more different frameworks 
that basically do the same things in slightly different ways, each with 
it's own strong and weak points.


To me, the notion of reusable apps 
and the application ecosystem it allows is Django's most compelling feature.


+1.


You are, of course, welcome to disagree.


I'm not saying that Django is better than Pylons or web.py or (insert 
yur favorite framework here) - and to be true, I think Pylons is 
globally smarter than Django -, I'm saying that it do the job, and do it 
well enough to be worth using. Sorry for being so pragmatic.



Having to implement a mini-parser for
each single tag

Most of the mini-parser stuff is so very easily factored out I'm
afraid I won't buy your argument.


You'll at least agree that in terms of line of codes necessary to implement a 
custom tag, it's very far from optimal, I hope?


I also agree that in terms of LOCs necessary to implement a log file 
parser, Python is also very far from optimal, at least compared to Perl !-)


How many Django custom tags did you write, exactly ? And of which level 
of complexity ? Once again, I'm not pretending Django is the best thing 
ever, but most of your remarks remind me of what I once could have say - 
that is, before having enough experience writing and maintaining Django 
apps. One of the greatest features of Django - and possibly what finally 
makes it so pythonic - is that it doesn't try to be *too* smart - just 
smart enough.


My 2 cents.
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess executing shell

2009-10-22 Thread Gabriel Genellina
En Wed, 21 Oct 2009 12:24:37 -0300, Tim Arnold tim.arn...@sas.com  
escribió:


Hi, I'm writing a script to capture a command on the commandline and run  
it

on a remote server.
I guess I don't understand subprocess because the code below exec's the
user's .cshrc file even though by default shell=False in the Popen call.


Do you mean it execs the .cshrc file in your *local* system or the  
*remote* one?

Popen controls what happens on the local system only.


action.insert(0,'rsh my_remotehost')
p = subprocess.Popen(shlex.split(' '.join(action)))
p.wait()

Since the shell is executing in the child process anyway, is the only
difference when using shell=True is that environment variables can be
expanded in the command to be executed?


Note that in this case, the child process is rsh on the local system.  
Popen has no control over what happens once rsh starts.


--
Gabriel Genellina

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


Re: a simple unicode question

2009-10-22 Thread Gabriel Genellina

En Wed, 21 Oct 2009 15:14:32 -0300, ru...@yahoo.com escribió:


On Oct 21, 4:59 am, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:

beSTEfar a écrit :
(snip)
  When parsing strings, use Regular Expressions.

And now you have _two_ problems g

For some simple parsing problems, Python's string methods are powerful
enough to make REs overkill. And for any complex enough parsing (any
recursive construct for example - think XML, HTML, any programming
language etc), REs are just NOT enough by themselves - you need a full
blown parser.


But keep in mind that many XML, HTML, etc parsing problems
are restricted to a subset where you know the nesting depth
is limited (often to 0 or 1), and for that large set of
problems, RE's *are* enough.


I don't think so. Nesting isn't the only problem. RE's cannot handle  
comments, by example. And you must support unquoted attributes, single and  
double quotes, any attribute ordering, empty tags, arbitrary whitespace...  
If you don't, you are not reading XML (or HTML), only a specific file  
format that resembles XML but actually isn't.


--
Gabriel Genellina

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


Re: PyQt4 - remember widget positions

2009-10-22 Thread Jeremy Sanders
nusch wrote:

 Is there any simple command which allows me to save position of all
 windows:  QMainWindow, QDialogs and qdockwidgets with their sizes,
 dock state and positions ? Or do I need to store those values
 manually, how can I do it fast?

You can use saveState() from QMainWindow to save the dockwidget geometries. 
I save the size and position of the main window separately and restore it 
with resize() and move().

You need to make sure all your toolbars and dockwidgets have unique object 
names for saveState to work.

Jeremy

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


A new way to configure Python logging

2009-10-22 Thread Vinay Sajip
If you use the logging package but don't like using the ConfigParser-based
configuration files which it currently supports, keep reading. I'm proposing to
provide a new way to configure logging, using a Python dictionary to hold
configuration information. It means that you can convert a text file such as

# logconf.yml: example logging configuration
formatters:
  brief:
format: '%(levelname)-8s: %(name)-15s: %(message)s'
  precise:
format: '%(asctime)s %(name)-15s %(levelname)-8s %(message)s'
handlers:
  console:
class : logging.StreamHandler
formatter : brief
level : INFO
stream : ext://sys.stdout
  file:
class : logging.handlers.RotatingFileHandler
formatter : precise
filename : logconfig.log
maxBytes : 100
backupCount : 3
  email:
class: logging.handlers.SMTPHandler
mailhost: localhost
fromaddr: my_...@domain.tld
toaddrs:
  - support_t...@domain.tld
  - dev_t...@domain.tld
subject: Houston, we have a problem.
loggers:
  foo:
level : ERROR
handlers: [email]
  bar.baz:
level: WARNING
root:
  level : DEBUG
  handlers  : [console, file]
# -- EOF --

into a working configuration for logging. The above text is in YAML format, and
can easily be read into a Python dict using PyYAML and the code

import yaml; config = yaml.load(open('logconf.yml', 'r'))

but if you're not using YAML, don't worry. You can use JSON, Python source code
or any other method to construct a Python dict with the configuration
information, then call the proposed new configuration API using code like

import logging.config

logging.config.dictConfig(config)

to put the configuration into effect.

For full details of the proposed change to logging, see PEP 391 at

http://www.python.org/dev/peps/pep-0391/

I need your feedback to make this feature as useful and as easy to use as
possible. I'm particularly interested in your comments about the dictionary
layout and how incremental logging configuration should work, but all feedback
will be gratefully received. Once implemented, the configuration format will
become subject to backward compatibility constraints and therefore hard to
change, so get your comments and ideas in now!

Thanks in advance,


Vinay Sajip


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


Re: a simple unicode question

2009-10-22 Thread Chris Jones
On Wed, Oct 21, 2009 at 12:35:11PM EDT, Nobody wrote:

[..]

 Characters outside the 16-bit range aren't supported on all builds.
 They won't be supported on most Windows builds, as Windows uses 16-bit
 Unicode extensively:

I knew nothing about UTF-16  friends before this thread.

Best part of Unicode is that there are multiple encodings, right? ;-)

Moot point on xterm anyway, since you'd be hard put to it to find a
decent terminal font that covers anything outside the BMP.

   Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
   (Intel)] on win32

unichr(0x1)
   Traceback (most recent call last):
 File stdin, line 1, in module
   ValueError: unichr() arg not in range(0x1) (narrow Python build)
 
 Note that narrow builds do understand names outside of the BMP, and
 generate surrogate pairs for them:
 
u'\N{LINEAR B SYLLABLE B008 A}'
   u'\U0001'
len(_)
   2
 
 Whether or not using surrogates in this context is a good idea is open to
 debate. What's the advantage of a multi-wchar string over a multi-byte
 string?

I don't understand this last remark, but since I'm only a GNU/Linux
hobbyist, I guess it doesn't make much difference.

Thanks for the code snippet and comments.

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


Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread baboucarr sanneh


Hi all

I want to output the date of the with this format strftime('%d%m%y') but the 
date ie '%d' should be the date of yesterday
eg

import time
strftime('%d%m%y') # something like minus a day..
Thank you..am a newbie to python




  
_
Keep your friends updated—even when you’re not signed in.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_5:092010-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread Tim Golden

baboucarr sanneh wrote:


Hi all

I want to output the date of the with this format strftime('%d%m%y') but the 
date ie '%d' should be the date of yesterday
eg

import time
strftime('%d%m%y') # something like minus a day..
Thank you..am a newbie to python



code
import datetime
yesterday = datetime.date.today () - datetime.timedelta (days=1)
print yesterday.strftime (%d%m%y)
/code

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


buggy popup

2009-10-22 Thread Vinay Sagar Prakash
Hi All,
Need some idea here:
On my windows machine, there is a Java based program that runs all the time.
Every now and then, a popup appears out of this program.

To close this popup, it requires user to Check the Do-not-show-this-popup
check box and then, click on OKAY button.

Is there a python way of automating the above procedure?

Say, I run a python script on my windows machine which waits all the time
and then if the popup appears, the python guy checks the check box and then
hits the OKAY button?

Any modules/ packages that I can refer to? A small hint would be of a big
help.

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


Re: Unicode again ... default codec ...

2009-10-22 Thread Gabriel Genellina
En Thu, 22 Oct 2009 05:25:16 -0300, Lele Gaifax l...@metapensiero.it  
escribió:

Gabriel Genellina gagsl-...@yahoo.com.ar writes:


En Wed, 21 Oct 2009 06:24:55 -0300, Lele Gaifax l...@metapensiero.it
escribió:


Gabriel Genellina gagsl-...@yahoo.com.ar writes:


nosetest should do nothing special. You should configure the environment
so Python *knows* that your console understands utf-8.



This is the same on my virtualenv:

$ python -c import sys; print sys.getdefaultencoding(),  
sys.stdout.encoding

ascii UTF-8
$ python -c print u'\xe1\xf1\xe7'
áñç


Good, so stdout's encoding isn't really the problem.


But look at this:

  File /usr/lib/python2.6/unittest.py, line 730, in printErrorList
self.stream.writeln(%s: %s %  
(flavour,self.getDescription(test)))

  File /usr/lib/python2.6/unittest.py, line 665, in writeln
if arg: self.write(arg)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in  
position 10: ordinal not in range(128)


Who is the culprit here?


unittest, or ultimately, this bug: http://bugs.python.org/issue4947

This is not specific to nosetest; unittest in verbose mode fails in the  
same way.


fix: add this method to the _WritelnDecorator class in unittest.py (near  
line 664):


def write(self, arg):
if isinstance(arg, unicode):
arg = arg.encode(self.stream.encoding, replace)
self.stream.write(arg)


The fact is, encodings are the real Y2k problem, and they are here to
stay for a while!


Ok, but the idea is to solve the problem (or not let it happen in the  
first place!), not hide it under the rug :)


--
Gabriel Genellina

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


Re: buggy popup

2009-10-22 Thread Gabriel Genellina
En Thu, 22 Oct 2009 07:14:31 -0300, Vinay Sagar Prakash  
vinya@gmail.com escribió:


On my windows machine, there is a Java based program that runs all the  
time.

Every now and then, a popup appears out of this program.

To close this popup, it requires user to Check the Do-not-show-this-popup
check box and then, click on OKAY button.

Is there a python way of automating the above procedure?


I'm very happy using pywinauto for those tasks.

--
Gabriel Genellina

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


RE: Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread baboucarr sanneh


Hi tim,

well i tried what your script but i do have an error
 import datetime
 yesterday = datetime.date.today () - datetime.timedelta (days=1)
 print yesterday.strftime (%d%m%y)
SyntaxError: invalid syntax (pyshell#2, line 1)

when i jus check the variable i.e yesterday i do get the out put but its in a 
different format
datetime.date(2009, 10, 21)
it seems like the conversion that is where the error is coming form 

I want it to be like 211009 

Thank you

$LIM $...@dy



 Date: Thu, 22 Oct 2009 11:14:46 +0100
 From: m...@timgolden.me.uk
 CC: python-list@python.org
 Subject: Re: Date strftime('%d%m%y') date to be of yesterday
 
 baboucarr sanneh wrote:
  
  Hi all
  
  I want to output the date of the with this format strftime('%d%m%y') but 
  the date ie '%d' should be the date of yesterday
  eg
  
  import time
  strftime('%d%m%y') # something like minus a day..
  Thank you..am a newbie to python
 
 
 code
 import datetime
 yesterday = datetime.date.today () - datetime.timedelta (days=1)
 print yesterday.strftime (%d%m%y)
 /code
 
 TJG
 -- 
 http://mail.python.org/mailman/listinfo/python-list
  
_
Windows Live: Keep your friends up to date with what you do online.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_1:092010-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread Tim Golden

baboucarr sanneh wrote:


Hi tim,

well i tried what your script but i do have an error

import datetime
yesterday = datetime.date.today () - datetime.timedelta (days=1)
print yesterday.strftime (%d%m%y)

SyntaxError: invalid syntax (pyshell#2, line 1)

when i jus check the variable i.e yesterday i do get the out put but its in a 
different format
datetime.date(2009, 10, 21)
it seems like the conversion that is where the error is coming form 

I want it to be like 211009 


Thank you



I assume you're running Python 3.1? Try this:

print (yesterday.strftime (%d%m%y))

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


Re: Passing values from html to python

2009-10-22 Thread Albert Hopkins
On Thu, 2009-10-22 at 10:44 +0200, Ahmed Barakat wrote:
 Hi guys,
 
 I am new to python and wed-development, I managed to have some nice
 example running up till now.
 I am playing with google app engine, I have this situation:
 
 I have a text box in an html page, I want to get the value in it and
 pass it to the python script to process it
 I can pass values from python to html, but the other way I don't know
 how to do that.
 

You need a web server: something that speaks the HTTP protocol.


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


RE: Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread baboucarr sanneh


Hi tim 

Thank you very much ...I have got it now..now i can continue with the backup 
script i want to make

$LIM $...@dy



 Date: Thu, 22 Oct 2009 11:36:50 +0100
 From: m...@timgolden.me.uk
 CC: python-list@python.org
 Subject: Re: Date strftime('%d%m%y') date to be of yesterday
 
 baboucarr sanneh wrote:
  
  Hi tim,
  
  well i tried what your script but i do have an error
  import datetime
  yesterday = datetime.date.today () - datetime.timedelta (days=1)
  print yesterday.strftime (%d%m%y)
  SyntaxError: invalid syntax (pyshell#2, line 1)
  
  when i jus check the variable i.e yesterday i do get the out put but its in 
  a different format
  datetime.date(2009, 10, 21)
  it seems like the conversion that is where the error is coming form 
  
  I want it to be like 211009 
  
  Thank you
 
 
 I assume you're running Python 3.1? Try this:
 
 print (yesterday.strftime (%d%m%y))
 
 TJG
 -- 
 http://mail.python.org/mailman/listinfo/python-list
  
_
Windows Live: Friends get your Flickr, Yelp, and Digg updates when they e-mail 
you.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_3:092010-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread Tim Golden

baboucarr sanneh wrote:


Hi tim 


Thank you very much ...I have got it now..now i can continue with the backup 
script i want to make



By the way, the convention on this list is to bottom-post,
that is to add your comments / reply to the bottom of the
post you're replying to. These things vary from one place
to another, but it's only courteous to follow the local
customs :)

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


RE: Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread baboucarr sanneh




$LIM $...@dy



 Date: Thu, 22 Oct 2009 11:51:08 +0100
 From: m...@timgolden.me.uk
 CC: python-list@python.org
 Subject: Re: Date strftime('%d%m%y') date to be of yesterday
 
 baboucarr sanneh wrote:
  
  Hi tim 
  
  Thank you very much ...I have got it now..now i can continue with the 
  backup script i want to make
 
 
 By the way, the convention on this list is to bottom-post,
 that is to add your comments / reply to the bottom of the
 post you're replying to. These things vary from one place
 to another, but it's only courteous to follow the local
 customs :)
 
 TJG
 -- 
 http://mail.python.org/mailman/listinfo/python-list


okay i got that will be doing so from now on :)thnx

  
_
Windows Live Hotmail: Your friends can get your Facebook updates, right from 
Hotmail®.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_4:092009-- 
http://mail.python.org/mailman/listinfo/python-list


Re-enabling a logger

2009-10-22 Thread jorma kala
Hi,
I'm using the logging module.
At one point in my code I disable logging like this:

logging.disable(logging.INFO)

But how can I enable the logging again further on?

I've tried the following, which doesn't work for re-enabling the logger:

my_logger.setLevel(logging.INFO)

I've also tried to disable the logger by doin this:

 my_logger.setLevel(logging.NOTSET)

and then re-enabling like this:

my_logger.setLevel(logging.INFO)

But that doesnt work either.

Can you tell me how to re-enable the logging?
Many thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-enabling a logger

2009-10-22 Thread Jean-Michel Pichavant

jorma kala wrote:

Hi,
I'm using the logging module.
At one point in my code I disable logging like this:
 
logging.disable(logging.INFO)
 
But how can I enable the logging again further on?
 
I've tried the following, which doesn't work for re-enabling the logger:
 
my_logger.setLevel(logging.INFO)
 
I've also tried to disable the logger by doin this:
 
 my_logger.setLevel(logging.NOTSET)
 
and then re-enabling like this:
 
my_logger.setLevel(logging.INFO)
 
But that doesnt work either.
 
Can you tell me how to re-enable the logging?

Many thanks.

logging.disable(0)


JM


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


Python socket won't connect on Windows

2009-10-22 Thread Florian Berger
Hi,

I have an annoying problem connecting to a remote host via the
socket module from Python 2.5 / 2.6 on WinXP.  :-(

Short description
-

socket.connect((host, port)) times out with socket.error
10060, while other applications on the same box can connect
to the remote site without any problems.

Long description


On the remote host in a LAN there is a server listening on port 2020.
I want to connect to that port via TCP, so what I do is:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((192.168.178.12, 2020))

After a while this returns a socket.error hinting at WinSock error
10060 which basically says the remote host does not respond.

The expected behaviour would be that connect() just returns with the
socket ready to send.


Software involved
-

Python 2.6.2 on Linux 2.6.31-rc3 on the server side

Python 2.6 and 2.5 on Win XP 64 on the client side


Things I already tried
--

[x] Basic network checks - ping etc. Network is up and running.

[x] Using netcat -l -p 2020 as a server replacement. No success.

[x] Using alternative software on the client side. A browser and telnet
pointed to 192.168.178.12:2020 can connect at once without any
problems.

[x] Turned off any firewall and filtering. No success.

[x] Using different ports. No success.

[x] Using Python on Linux on the very same client hardware. Connects
without problems.

[x] Python docs.

[x] WWW search.


Help! :-)
-

I think I narrowed it down to the fact that Python 2.x on WinXP won't
connect in this setup.

Does anyone have a hint what to do?

Are there known pitfalls with the socket module on Windows?


Any help will be greatly appreciated.

Regards,
Florian

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


[no subject]

2009-10-22 Thread baboucarr sanneh


Hi guys

I want to make a script that can copy files and folders from one location and 
paste it to another location..

e.g  from c:\test to d:\test
thanks regrads

$LIM $...@dy

  
_
Windows Live Hotmail: Your friends can get your Facebook updates, right from 
Hotmail®.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_4:092009-- 
http://mail.python.org/mailman/listinfo/python-list


Re:

2009-10-22 Thread Tim Golden

baboucarr sanneh wrote:

I want to make a script that can copy files and folders from one location and 
paste it to another location..

e.g  from c:\test to d:\test


Have a look at the shutil module

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


Re: Fallen Sword

2009-10-22 Thread Richard Riley
Ben Finney ben+pyt...@benfinney.id.au writes:

 Richard Riley rileyrg...@gmail.com writes:

 Ben Finney ben+pyt...@benfinney.id.au writes:
  Reported to service provider as spam.

 Please don't reply to SPAM. You just make it visible to those of us
 with better filters. Hint : spammers do not read your reply.

 I didn't quote the spam except to be clear which message I'm responding
 to. None of the substantive content was quoted, and the spammer's
 message is thwarted.

Immaterial. You are opening a thread which has no place here or in any
other technical newsgroup.


 And no one else is really interested in your reports either.

 Others who might want the message reported can know that it has already
 happened. I also see it as visibly advocating, by example, the practice
 of reporting each and every spam message to the service provider that
 was used to send it.

That's nice. But please don't do it. You wake up threads and pollute the
thread pool. It's common knowledge never to respond to SPAM
publicly.

The reports fall on deaf ears and real spammers change their access
route more often than a monkey scratches his bits.


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


Re: Unicode again ... default codec ...

2009-10-22 Thread Lele Gaifax
Gabriel Genellina gagsl-...@yahoo.com.ar writes:

 En Thu, 22 Oct 2009 05:25:16 -0300, Lele Gaifax l...@metapensiero.it
 escribió:
 Who is the culprit here?

 unittest, or ultimately, this bug: http://bugs.python.org/issue4947

Thank you. In particular I found
http://bugs.python.org/issue4947#msg87637 as the best fit, I think
that may be what's happening here.

 fix: add this method to the _WritelnDecorator class in unittest.py
 (near line 664):

 def write(self, arg):
 if isinstance(arg, unicode):
 arg = arg.encode(self.stream.encoding, replace)
 self.stream.write(arg)

Uhm, that's almost as dirty as my reload(), you must admit! :-)

bye, lele.
-- 
nickname: Lele Gaifax| Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas| comincerò ad aver paura di chi mi copia.
l...@nautilus.homeip.net | -- Fortunato Depero, 1929.

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


Re: Passing values from html to python

2009-10-22 Thread Richard Brodie

Albert Hopkins mar...@letterboxes.org wrote in message 
news:mailman.1851.1256208328.2807.python-l...@python.org...
 On Thu, 2009-10-22 at 10:44 +0200, Ahmed Barakat wrote:
 Hi guys,

 I am playing with google app engine, I have this situation:

 I have a text box in an html page, I want to get the value in it and
 pass it to the python script to process it

 You need a web server: something that speaks the HTTP protocol.

Google's servers will probably be able to handle his requirements for
the time being ;)

It's going in at the deep end a bit, going straight to App Engine but
webapp or cgi is what you need. Or we could discuss what the best
Python web framework is again...

http://code.google.com/appengine/docs/python/runtime.html#Requests_and_CGI


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


Re: a splitting headache

2009-10-22 Thread David C . Ullrich
On Wed, 21 Oct 2009 22:47:24 -0700 (PDT), Carl Banks
pavlovevide...@gmail.com wrote:

On Oct 21, 12:46 pm, David C Ullrich dullr...@sprynet.com wrote:
 On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
  On Oct 20, 1:51 pm, David C Ullrich dullr...@sprynet.com wrote:
  I'm not saying either behaviour is wrong, it's just not obvious that the
  one behaviour doesn't follow from the other and the documentation could
  be
  a little clearer on this matter. It might make a bit more sense to
  actually
  mention the slpit(sep) behavior that split() doesn't do.

 Have you _read_ the docs? They're quite clear on the difference
 between no sep (or sep=None) and sep=something:

Even if the docs do describe the behavior adequately, he has a point
that the documents should emphasize the counterintutive split
personality of the method better.

s.split() and s.split(sep) do different things,

And they _state_ quite clearly that they do different things!
I don't see what your complaint could possibly be.

 and there is no string
sep that can make s.split(sep) behave like s.split().  That's not
unheard of but it does go against our typical expectations.  It would
have been a better library design if s.split() and s.split(sep) were
different methods.

_That_ may be so. But claiming that there's a problem with the
docs here seems silly, since the docs say exactly what happens.

That they are the same method isn't the end of the world but the
documentation really ought to emphasize its dual nature.


Carl Banks

David C. Ullrich

Understanding Godel isn't about following his formal proof. 
That would make a mockery of everything Godel was up to.
(John Jones, My talk about Godel to the post-grads.
in sci.logic.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Terminating python script easily

2009-10-22 Thread Balban
Hi,

I have a python build script that calls various commands, some using
os.system().

Often, if I want to terminate the script prematurely, I press ctrl-c,
but I have to do this many times before I can kill the script for
good. I was wondering is there a way that I define a signal handler
and kill the whole thing at once with a single ctrl-c? Perhaps I
should  also call my other scripts with a method other than os.system
() as well?

Thank you,

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


Re: a splitting headache

2009-10-22 Thread David C . Ullrich
On Wed, 21 Oct 2009 14:43:48 -0700 (PDT), Mensanator
mensana...@aol.com wrote:

On Oct 21, 2:46 pm, David C Ullrich dullr...@sprynet.com wrote:
 On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
  On Oct 20, 1:51 pm, David C Ullrich dullr...@sprynet.com wrote:
  On Thu, 15 Oct 2009 18:18:09 -0700, Mensanator wrote:
   All I wanted to do is split a binary number into two lists, a list of
   blocks of consecutive ones and another list of blocks of consecutive
   zeroes.

   But no, you can't do that.

   c = '001110'
   c.split('0')
   ['', '', '1', '', '', '', '11', '']

   Ok, the consecutive delimiters appear as empty strings for reasons
   unknown (except for the first one). Except when they start or end the
   string in which case the first one is included.

   Maybe there's a reason for this inconsistent behaviour but you won't
   find it in the documentation.

  Wanna bet? I'm not sure whether you're claiming that the behavior is
  not specified in the docs or the reason for it. The behavior certainly
  is specified. I conjecture you think the behavior itself is not
  specified,

  The problem is that the docs give a single example

  '1,,2'.split(',')
  ['1','','2']

  ignoring the special case of leading/trailing delimiters. Yes, if you
  think it through, ',1,,2,'.split(',') should return ['','1','','2','']
  for exactly the reasons you give.

  Trouble is, we often find ourselves doing ' 1  2  '.split() which
  returns
  ['1','2'].

  I'm not saying either behaviour is wrong, it's just not obvious that the
  one behaviour doesn't follow from the other and the documentation could
  be
  a little clearer on this matter. It might make a bit more sense to
  actually
  mention the slpit(sep) behavior that split() doesn't do.

 Have you _read_ the docs?

Yes.

 They're quite clear on the difference
 between no sep (or sep=None) and sep=something:

I disagree that they are quite clear. The first paragraph makes no
mention of leading or trailing delimiters and they show no example
of such usage. An example would at least force me to think about it
if it isn't specifically mentioned in the paragraph.

One could infer from the second paragraph that, as it doesn't return
empty stings from leading and trailing whitespace, slpit(sep) does
for leading/trailing delimiters. Of course, why would I even be
reading
this paragraph when I'm trying to understand split(sep)?

Now there you have an excellent point.

At the start of the documentation for every function and method
they should include the following: 

Note: If you want to understand completely how this
function works you may need to read the entire documentation.

And of course they should precede that in every instance with

Note: Read the next sentence.

The splitting of real strings is just as important, if not more so,
than the behaviour of splitting empty strings. Especially when the
behaviour is radically different.

 '01110'.split('0')
['', '1', '', '', '', '11', '']

is a perfect example. It shows the empty strings generated from the
leading and trailing delimiters, and also that you get 3 empty
strings
between the '1's, not 4. When creating documentation, it is always a
good idea to document such cases.

And you'll then want to compare this to the equivalent whitespace
case:
 ' 111 '.split()
['1', '11']

And it wouldn't hurt to point this out:
 c = '01110'.split('0')
 '0'.join(c)
'01110'

and note that it won't work with the whitespace version.

No, I have not submitted a request to change the documentation, I was
looking for some feedback here. And it seems that no one else
considers
the documentation wanting.


 If sep is given, consecutive delimiters are not grouped together and are
 deemed to delimit empty strings (for example, '1,,2'.split(',') returns
 ['1', '', '2']). The sep argument may consist of multiple characters (for
 example, '123'.split('') returns ['1', '2', '3']). Splitting an
 empty string with a specified separator returns [''].

 If sep is not specified or is None, a different splitting algorithm is
 applied: runs of consecutive whitespace are regarded as a single
 separator, and the result will contain no empty strings at the start or
 end if the string has leading or trailing whitespace. Consequently,
 splitting an empty string or a string consisting of just whitespace with
 a None separator returns [].





  because your description of what's happening,

  consecutive delimiters appear as empty strings for reasons

   unknown (except for the first one). Except when they start or end the
   string in which case the first one is included

  is at best an awkward way to look at it. The delimiters are not
  appearing as empty strings.

  You're asking to split  '001110' on '0'. So you're asking for
  strings a, b, c, etc such that

  (*) '001110' = a + '0' + b + '0' + c + '0' + etc

  The sequence of strings you're getting as output satisfies (*) exactly;
  the first '' is what appears before 

Re: Terminating python script easily

2009-10-22 Thread Benjamin Kaplan
On Thu, Oct 22, 2009 at 8:46 AM, Balban bilgehan.bal...@gmail.com wrote:
 Hi,

 I have a python build script that calls various commands, some using
 os.system().

 Often, if I want to terminate the script prematurely, I press ctrl-c,
 but I have to do this many times before I can kill the script for
 good. I was wondering is there a way that I define a signal handler
 and kill the whole thing at once with a single ctrl-c? Perhaps I
 should  also call my other scripts with a method other than os.system
 () as well?

 Thank you,

 Bahadir
 --
In Python, ctrl-C raises a KeyboarInterrupt. You can just catch that
and terminate everything in the except clause. If you're using 2.6,
subprocess.Popen has a terminate method you can use to quit the other
scripts if you use that instead of os.system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Terminating python script easily

2009-10-22 Thread Jean-Michel Pichavant

Balban wrote:

Hi,

I have a python build script that calls various commands, some using
os.system().

Often, if I want to terminate the script prematurely, I press ctrl-c,
but I have to do this many times before I can kill the script for
good. I was wondering is there a way that I define a signal handler
and kill the whole thing at once with a single ctrl-c? Perhaps I
should  also call my other scripts with a method other than os.system
() as well?

Thank you,

Bahadir
  

you may want to use subprocess instead of os.system.
On catching CTRL+C, you kill all the pid started with subprocess and 
exit the script smoothly.


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


Re: Terminating python script easily

2009-10-22 Thread Bahadir Balban
On Thu, Oct 22, 2009 at 4:01 PM, Jean-Michel Pichavant
jeanmic...@sequans.com wrote:
 Balban wrote:

 Hi,

 I have a python build script that calls various commands, some using
 os.system().

 Often, if I want to terminate the script prematurely, I press ctrl-c,
 but I have to do this many times before I can kill the script for
 good. I was wondering is there a way that I define a signal handler
 and kill the whole thing at once with a single ctrl-c? Perhaps I
 should  also call my other scripts with a method other than os.system
 () as well?

 Thank you,

 Bahadir


 you may want to use subprocess instead of os.system.
 On catching CTRL+C, you kill all the pid started with subprocess and exit
 the script smoothly.

 JM


Hmm. OK, this is what I suspected I needed. So no explicit signal
catching is required I guess.

I will look into it, thanks.


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


Re: a splitting headache

2009-10-22 Thread Mensanator
On Oct 22, 7:47�am, David C. Ullrich dullr...@sprynet.com wrote:
 On Wed, 21 Oct 2009 14:43:48 -0700 (PDT), Mensanator





 mensana...@aol.com wrote:
 On Oct 21, 2:46�pm, David C Ullrich dullr...@sprynet.com wrote:
  On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
   On Oct 20, 1:51�pm, David C Ullrich dullr...@sprynet.com wrote:
   On Thu, 15 Oct 2009 18:18:09 -0700, Mensanator wrote:
All I wanted to do is split a binary number into two lists, a list of
blocks of consecutive ones and another list of blocks of consecutive
zeroes.

But no, you can't do that.

c = '001110'
c.split('0')
['', '', '1', '', '', '', '11', '']

Ok, the consecutive delimiters appear as empty strings for reasons
unknown (except for the first one). Except when they start or end the
string in which case the first one is included.

Maybe there's a reason for this inconsistent behaviour but you won't
find it in the documentation.

   Wanna bet? I'm not sure whether you're claiming that the behavior is
   not specified in the docs or the reason for it. The behavior certainly
   is specified. I conjecture you think the behavior itself is not
   specified,

   The problem is that the docs give a single example

   '1,,2'.split(',')
   ['1','','2']

   ignoring the special case of leading/trailing delimiters. Yes, if you
   think it through, ',1,,2,'.split(',') should return ['','1','','2','']
   for exactly the reasons you give.

   Trouble is, we often find ourselves doing ' 1 �2 �'.split() which
   returns
   ['1','2'].

   I'm not saying either behaviour is wrong, it's just not obvious that the
   one behaviour doesn't follow from the other and the documentation could
   be
   a little clearer on this matter. It might make a bit more sense to
   actually
   mention the slpit(sep) behavior that split() doesn't do.

  Have you _read_ the docs?

 Yes.

  They're quite clear on the difference
  between no sep (or sep=None) and sep=something:

 I disagree that they are quite clear. The first paragraph makes no
 mention of leading or trailing delimiters and they show no example
 of such usage. An example would at least force me to think about it
 if it isn't specifically mentioned in the paragraph.

 One could infer from the second paragraph that, as it doesn't return
 empty stings from leading and trailing whitespace, slpit(sep) does
 for leading/trailing delimiters. Of course, why would I even be
 reading
 this paragraph when I'm trying to understand split(sep)?

 Now there you have an excellent point.

 At the start of the documentation for every function and method
 they should include the following:

 Note: If you want to understand completely how this
 function works you may need to read the entire documentation.

When I took Calculus, I wasn't required to read the
entire book before doing the chapter 1 homework.
Has teaching changed since I was ib school?


 And of course they should precede that in every instance with

 Note: Read the next sentence.

And don't forget to add:

We can't be bothered to show any examples of how
this actually works, work out all the special
cases for yourself.






 The splitting of real strings is just as important, if not more so,
 than the behaviour of splitting empty strings. Especially when the
 behaviour is radically different.

  '01110'.split('0')
 ['', '1', '', '', '', '11', '']

 is a perfect example. It shows the empty strings generated from the
 leading and trailing delimiters, and also that you get 3 empty
 strings
 between the '1's, not 4. When creating documentation, it is always a
 good idea to document such cases.

 And you'll then want to compare this to the equivalent whitespace
 case:
  ' 1 � �11 '.split()
 ['1', '11']

 And it wouldn't hurt to point this out:
  c = '01110'.split('0')
  '0'.join(c)
 '01110'

 and note that it won't work with the whitespace version.

 No, I have not submitted a request to change the documentation, I was
 looking for some feedback here. And it seems that no one else
 considers
 the documentation wanting.

  If sep is given, consecutive delimiters are not grouped together and are
  deemed to delimit empty strings (for example, '1,,2'.split(',') returns
  ['1', '', '2']). The sep argument may consist of multiple characters (for
  example, '123'.split('') returns ['1', '2', '3']). Splitting an
  empty string with a specified separator returns [''].

  If sep is not specified or is None, a different splitting algorithm is
  applied: runs of consecutive whitespace are regarded as a single
  separator, and the result will contain no empty strings at the start or
  end if the string has leading or trailing whitespace. Consequently,
  splitting an empty string or a string consisting of just whitespace with
  a None separator returns [].

   because your description of what's happening,

   consecutive delimiters appear as empty strings for reasons

unknown (except for the first one). 

bad operand type for unary +: tuple

2009-10-22 Thread Frank Millman
Hi all

This is just out of curiosity.

I have a tuple, and I want to create a new tuple with a new value in the 
first position, and everything else unchanged.

I figured out that this would work -

 t = ('a', 'b', 'c')
 t2 = ('x',) + t[1:]
 t2
('x', 'b', 'c')

Then I thought I would neaten it a bit by replacing ('x',) with 'x', on 
the assumption that it is not necessary to surround a tuple with brackets.

This is the result -

 t = ('a', 'b', 'c')
 t2 = 'x', + t[1:]
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: bad operand type for unary +: 'tuple'


It is not a problem - I will just stick to using the brackets. However, I 
would be interested to find out the reason for the error.

Version is 2.6.2.

Thanks

Frank Millman



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


Re: a splitting headache

2009-10-22 Thread David C . Ullrich
On Wed, 21 Oct 2009 14:43:48 -0700 (PDT), Mensanator
mensana...@aol.com wrote:

On Oct 21, 2:46 pm, David C Ullrich dullr...@sprynet.com wrote:
 On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
  On Oct 20, 1:51 pm, David C Ullrich dullr...@sprynet.com wrote:
  On Thu, 15 Oct 2009 18:18:09 -0700, Mensanator wrote:
   All I wanted to do is split a binary number into two lists, a list of
   blocks of consecutive ones and another list of blocks of consecutive
   zeroes.

   But no, you can't do that.

   c = '001110'
   c.split('0')
   ['', '', '1', '', '', '', '11', '']

   Ok, the consecutive delimiters appear as empty strings for reasons
   unknown (except for the first one). Except when they start or end the
   string in which case the first one is included.

   Maybe there's a reason for this inconsistent behaviour but you won't
   find it in the documentation.

  Wanna bet? I'm not sure whether you're claiming that the behavior is
  not specified in the docs or the reason for it. The behavior certainly
  is specified. I conjecture you think the behavior itself is not
  specified,

  The problem is that the docs give a single example

  '1,,2'.split(',')
  ['1','','2']

  ignoring the special case of leading/trailing delimiters. Yes, if you
  think it through, ',1,,2,'.split(',') should return ['','1','','2','']
  for exactly the reasons you give.

  Trouble is, we often find ourselves doing ' 1  2  '.split() which
  returns
  ['1','2'].

  I'm not saying either behaviour is wrong, it's just not obvious that the
  one behaviour doesn't follow from the other and the documentation could
  be
  a little clearer on this matter. It might make a bit more sense to
  actually
  mention the slpit(sep) behavior that split() doesn't do.

 Have you _read_ the docs?

Yes.

 They're quite clear on the difference
 between no sep (or sep=None) and sep=something:

I disagree that they are quite clear. The first paragraph makes no
mention of leading or trailing delimiters and they show no example
of such usage. An example would at least force me to think about it
if it isn't specifically mentioned in the paragraph.

One could infer from the second paragraph that, as it doesn't return
empty stings from leading and trailing whitespace, slpit(sep) does
for leading/trailing delimiters. Of course, why would I even be
reading
this paragraph when I'm trying to understand split(sep)?

A skightly less sarcastic answer than what I just posted:

I don't see why you _should_ need to read the second paragraph
to infer that leading delimiters will return empty strings when
you do split(sep). That's exactly what one would expect!
As I pointed out the other day, if you're splitting ',,p' with
sep = ',' that means you're looking for strings _separated by_
commas. That means you're asking for [s1, s2, ...] where
s1 is the part of the string preceding the first comma,
s2 is the part of the string after the first comma but
before the second comma, etc. And that means s1 = ''
here.

That's what split on commas _means_. It's also exactly
what you want in typical applications, for example
parsing comma-separated data. The fact that s.split()
does _not_ include an empty string at the start if s
begins with whitespace is that counterintuitive part;
that's why it's specified in the second paragraph
(whether you believe it or not, _that's_ what
confused _me_ once. At which point I read the docs...)
I suppose it makes sense given a typical use case of
s.split(), where s is text and we want to find a list of
the words in s.

Really. I can't understand why you would _expect_
s.split(sep) to do anything other than

def split(s, sep):
  res = []
  acc = ''
  for c in s:
if c in sep:
  res.append(acc)
  acc = ''
else:
  acc = acc + c
  res.append(acc)
  return res

Really. You're used to the idea that sum_{j=1}^0 c_j
should be 0, right? That's for exactly the same reason -
the obvious thing for sum_{j=a}^b c_j to return is 
given by

def sum(c, lower, upper):
  res = 0
  j = lower
  while j = upper:
res = res + c[j]
j = j + 1
  return res


The splitting of real strings is just as important, if not more so,
than the behaviour of splitting empty strings. Especially when the
behaviour is radically different.

 '01110'.split('0')
['', '1', '', '', '', '11', '']

is a perfect example. It shows the empty strings generated from the
leading and trailing delimiters, and also that you get 3 empty
strings
between the '1's, not 4. When creating documentation, it is always a
good idea to document such cases.

And you'll then want to compare this to the equivalent whitespace
case:
 ' 111 '.split()
['1', '11']

And it wouldn't hurt to point this out:
 c = '01110'.split('0')
 '0'.join(c)
'01110'

and note that it won't work with the whitespace version.

No, I have not submitted a request to change the documentation, I was
looking for some feedback here. And it seems that no one else
considers
the documentation 

Re: bad operand type for unary +: tuple

2009-10-22 Thread Diez B. Roggisch
Frank Millman wrote:

 Hi all
 
 This is just out of curiosity.
 
 I have a tuple, and I want to create a new tuple with a new value in the
 first position, and everything else unchanged.
 
 I figured out that this would work -
 
 t = ('a', 'b', 'c')
 t2 = ('x',) + t[1:]
 t2
 ('x', 'b', 'c')
 
 Then I thought I would neaten it a bit by replacing ('x',) with 'x',
 on the assumption that it is not necessary to surround a tuple with
 brackets.
 
 This is the result -
 
 t = ('a', 'b', 'c')
 t2 = 'x', + t[1:]
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: bad operand type for unary +: 'tuple'

 
 It is not a problem - I will just stick to using the brackets. However, I
 would be interested to find out the reason for the error.
 
 Version is 2.6.2.
 
 Thanks

the operator precedence. Sure you want to write

 (a, -b, c)

to form a tuple with a negated (or actually all other kinds of expressions)
value in it. So python made -/+ and more or less all other operators
precede the comma, which is the actual tuple-operator. And consequently, 

a, +(c, d)

tries to *first* apply + to the tuple (c, d) - which isn't defined.

Diez


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


Re: unittest wart/bug for assertNotEqual

2009-10-22 Thread Ethan Furman

Gabriel Genellina wrote:
En Tue, 20 Oct 2009 19:57:19 -0300, Ethan Furman et...@stoneleaf.us  
escribió:

Steven D'Aprano wrote:

On Tue, 20 Oct 2009 14:45:49 -0700, Zac Burns wrote:



My preference would be that failIfEqual checks both != and ==. This is
practical, and would benefit almost all use cases. If != isn't not
== (IEEE NaNs I hear is the only known use case)



  numpy uses == and != as element-wise operators:


Two issues:  1) Sounds like we should have two more Asserts --  
failIfNotEqual, and assertNotNotEqual to handle the dichotomy in 
Python;  and 2) Does this mean (looking at Mark Dickinson's post) that 
2.7 and  3.1 are now broken?


1) assertEqual and assertNotEqual test for == and != respectively. The  
failXXX methods are being deprecated. Why do you think we need more  
asserts?


Ignorance, of course.  :)  I didn't know those were there.  Hopefully 
the OP will also now realize those are there.


2) Not exactly, but there are still inconsistencies (e.g. 
assertDictEqual  and assertMultiLineEqual use != instead of ==, and some 
assertion messages  use the wrong terminology)


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


attribute access and indirection

2009-10-22 Thread Ethan Furman

Greetings, List!

Say I have an old-fashioned dbf style table, with a single name field of
50 characters:

  names = dbf.Table(':memory:', 'name C(40)')

Then I add a bunch of names from who-knows-where:

  for name in some_iterable():
names.append((name))

Now I want to know how many start with a 'J'...
I have two options, 1) brute force:

  matches = [rec for rec in names if rec.name[0] == 'J']

or, 2) binary search after ordering:

  names.order('name[:1]')
  matches = names.search('J', startswith=True)

So far so good.  Now it gets a little more complicated.  In my use case
I am trying to match records from one database to records from a another
database;  therefore, I do _not_ know what text I will be searching for,
only the fields I will be using.

If I only had one criteria, I'd still be okay:

  different_table.order('zipcode[:5], last_name')
  for record in original_table:
matches = different_table.search([record.zipcode[:5], last_name])

However, I have three different sets of matches:
  'first_name[:1], last_name, city, dlvryaddrs[:4]'
  'first_name[:1], last_name[:5], dlvryaddrs[:8]'
  'first_name, last_name, city, state'

This is not a problem for the ordering, as I can just do
  for criteria in (choices):
different_table.order(criteria)

The problem comes at the matching stage:  the .search method is
expecting a list of the pieces it is supposed to find, so what I need is
a way to apply, for example, 'first_name[:1], last_name[:5],
dlvryaddrs[:8]', to the current record to yield the text to search for.

Current code follows, more comments towards the end.

code
import dbf
import shutil
from collections import defaultdict
from cookbook.utils import index

source_tables = [ '/temp/kaz15514',
  '/temp/kks15515',
  '/temp/kmn15585',
  '/temp/knv15516',
  '/temp/ktx15722',
  '/temp/kwa15584',
  '/temp/mco15902',
  '/temp/msq15994' ]

counts = defaultdict(int)

for i in index(source_tables):
source_tables[i] = dbf.Table(source_tables[i])

shutil.copy('z:/orders/25105/mbk16508_02', '.')
match_back = dbf.Table('mbk16508_02')
match_back.add_fields('f1ltcta4 C(100), f1l5a8 C(100), ftltctst C(100)')

for field, criteria in \
   (('f1ltcta4', 'first_name[:1], last_name, city, dlvryaddrs[:4]'),
('f1l5a8', 'first_name[:1], last_name[:5], dlvryaddrs[:8]'),
('ftltctst', 'first_name, last_name, city, state'))
match_back.order(criteria)
for table in source_tables:
counts = defaultdict(int)
for record in match_back:
matches = table.search(?)
.
.
.
/code

The only idea I have at the moment is to parse the string (much like I
do in the order method), and after the string is parsed pluck out the
the needed pieces.  If that is the best and/or most practical way to do
it, I was thinking of adding __call__ to the record class.  Then,
besides being able to do:

  matches = table.search([record.zip4[:5], record.dlvryaddrs])

I could also do:

  matches = table.search(record('zip4[:5], dlvryaddrs'))

or, equivalently,
  criteria = 'this, that[:7], the_other'
  matches = table.search(record(criteria))

Any better ideas?  Am I missing anything already in the stdlib?

Any and all tips appreciated!

~Ethan~

P.S.
shameless plug  Python d-Base currently lives at
http://groups.google.com/group/python-dbase, and it's main purpose in
life is to ease the transition between old dbf files and newer sql
tables.  It can, however, be used for read/write access to dBase III and
VFP 6 tables, including memo fields.

Success stories and bug reports both equally welcome!  :D
/shameless plug

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


Re: Date strftime('%d%m%y') date to be of yesterday

2009-10-22 Thread D'Arcy J.M. Cain
On Thu, 22 Oct 2009 10:56:07 +
baboucarr sanneh sanne...@hotmail.com wrote:
  By the way, the convention on this list is to bottom-post,
 
 okay i got that will be doing so from now on :)thnx

Thanks but what the previous poster forgot to mention was that you
should also trim the text that you are replying to.  Notice how I
trimmed everything up to now down to two lines.  This gives you the
gist of the conversation so far but makes it easier to read.  People
reading the exchange will get enough out of the above to remind
themselves where we are in the conversation and if necessary they can
simply go back and read the entire thread in the archives.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bad operand type for unary +: tuple

2009-10-22 Thread Frank Millman
Diez B. Roggisch wrote:
 Frank Millman wrote:


 t = ('a', 'b', 'c')
 t2 = 'x', + t[1:]
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: bad operand type for unary +: 'tuple'




 the operator precedence. Sure you want to write

 (a, -b, c)

 to form a tuple with a negated (or actually all other kinds of 
 expressions)
 value in it. So python made -/+ and more or less all other operators
 precede the comma, which is the actual tuple-operator. And consequently,

 a, +(c, d)

 tries to *first* apply + to the tuple (c, d) - which isn't defined.


Makes total sense. Thanks, Diez

Frank



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


Re: equivalent to globals(), locals() for nonlocal variables?

2009-10-22 Thread Lie Ryan

geremy condra wrote:

I decided to play around with nonlocal declarations today, and was
somewhat surprised when a call to nonlocals() resulted in 'nonlocals
is not defined'. Is there an a standard equivalent to globals() or
locals() for variables in outer nested scopes?

Geremy Condra


Not that I know of, but you can, to certain extent, do something like this:

def outer():
def inner():
print nonlocals
nonlocals = locals()
inner()
outer()
--
http://mail.python.org/mailman/listinfo/python-list


pyodbc - problem passing None as parameter

2009-10-22 Thread Frank Millman
Hi all

I posted the following to the pyodbc google group, but got no reply - it 
seems a bit quiet there. I hope someone here can help.

I am using pyodbc version 2.1.6 on Windows Server 2003, connecting to Sql 
Server 2005.

This works -

 cur.execute('select ?', None)
pyodbc.Cursor object at 0x00A91368
 cur.fetchall()
[(None, )]

This does not work -

 cur.execute('select * from ctrl.dirusers where todate is ?', None)
Traceback (most recent call last):
  File stdin, line 1, in module pyodbc.ProgrammingError: ('42000', 
[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax 
near @P1'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server 
Driver][SQL Server]Statement(s) could not be prepared. (8180))

You may notice that the statement is not strictly DB-API 2.0 compliant. 
pyodbc has an extension that allows you to supply arguments directly, 
instead off putting them inside a tuple. I have tried with and without a 
tuple - the result is the same.

Any assistance will be appreciated.

Thanks
Frank Millman



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


Re: Object Relational Mappers are evil (a meditation)

2009-10-22 Thread J Kenneth King
Aaron Watters aaron.watt...@gmail.com writes:

 On Oct 16, 10:35 am, mario ruggier mario.rugg...@gmail.com wrote:
 On Oct 5, 4:25 pm, Aaron Watters aaron.watt...@gmail.com wrote:

  Occasionally I fantasize about making a non-trivial change
  to one of these programs, but I strongly resist going further
  than that because the ORM meatgrinder makes it somewhere
  between extremely unpleasant and impossible to make any
  non-trivial changes to a non-trivial program, especially after
  it has been populated with data.

 Object-relational mappers are like putting lipstick on a 
 pig:http://gizmoweblog.blogspot.com/2006/10/putting-lipstick-on-pig.html

 m ;-)

 Cute, but wrong.  Using ORMs is better than using Object databases.

 In my case I use Python to un data created by java/hibernate.
 If I was using a java based object database I would be simply stuck.
 At least if you use an ORM you have a way to access the information
 without writing a program in the programming language that the
 ORM was defined in.  Anyway, thanks for all the great comments on
 this thread from all you Sarcopterygii and Haplorrhini out there.

Data persistence isn't a one-size fits all problem.  It really depends
on the needs of the system.  Object databases solve the problem of
storing complex object graphs, deeply nested data structures, and
serializing language-specific objects like continuations or
what-have-you (but I think that last one is yet unsolved).  We all know
what RDBMS' are good for.  Neither is perfect for solving every data
persistence situation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyodbc - problem passing None as parameter

2009-10-22 Thread Tim Golden

Frank Millman wrote:
I posted the following to the pyodbc google group, but got no reply - it 
seems a bit quiet there. I hope someone here can help.


I am using pyodbc version 2.1.6 on Windows Server 2003, connecting to Sql 
Server 2005.


This works -


cur.execute('select ?', None)

pyodbc.Cursor object at 0x00A91368

cur.fetchall()

[(None, )]

This does not work -


cur.execute('select * from ctrl.dirusers where todate is ?', None)

Traceback (most recent call last):
  File stdin, line 1, in module pyodbc.ProgrammingError: ('42000', 
[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax 
near @P1'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server 
Driver][SQL Server]Statement(s) could not be prepared. (8180))


You may notice that the statement is not strictly DB-API 2.0 compliant. 
pyodbc has an extension that allows you to supply arguments directly, 
instead off putting them inside a tuple. I have tried with and without a 
tuple - the result is the same.


I would estimate that it's because you're using
where todate is ? in your WHERE clause, which
can only possibly be followed by a NULL -- thus making
it a not-meaningfully parameterisable query.

Unfortunately, neither will using where todate = ? work
helpfully with a None. The dbapi doesn't specify what a
compliant module should do so you probably need to do this:

... WHERE todate = ? OR (todate IS NULL AND ? IS NULL)

or possibly:

... WHERE ISNULL (todate, 'domain-specific-null') = ISNULL (?, 
'domain-specific-null')


if you need this kind of functionality.

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


Unloading a module

2009-10-22 Thread lallous

Hello Group,

If a reference to an imported module reaches zero will Python cleanup 
everything related to that module and unload the compiled code, etc, etc...?


For example:

import sys
m = [__import__(str(x)) for x in xrange(1,4)]
del sys.modules['1']
del m[0]
print m

Is module['1'] really unloaded or just it is not reachable but still loaded?

Thanks,
Elias 


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


Re: a splitting headache

2009-10-22 Thread John Posner

Carl Banks wrote:

snip

s.split() and s.split(sep) do different things, and there is no string
sep that can make s.split(sep) behave like s.split().  That's not
unheard of but it does go against our typical expectations.  It would
have been a better library design if s.split() and s.split(sep) were
different methods.
  


It looks like they *were* different methods. The Oct 1996 edition of 
Programming Python (O'Reilly  Assoc.), based on Python 1.3, describes 
two separate functions in the string module in Chapter 16:


string.split()
string.splitfields(delim)

-John

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


Re: Python socket won't connect on Windows

2009-10-22 Thread Grant Edwards
On 2009-10-22, Florian Berger flo...@arcor.de wrote:

 I think I narrowed it down to the fact that Python 2.x on
 WinXP won't connect in this setup.

 Does anyone have a hint what to do?

I'd probably fire up Wireshark and capture the network traffic
to/from the remote host when the Python app attempts to connect
and when another client connects.

-- 
Grant Edwards   grante Yow! I just remembered
  at   something about a TOAD!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


fastcgi Access Checking

2009-10-22 Thread Robin Becker
I'm trying to do FastCgiAccessChecker with a django project; the base idea is to 
use the django controlled logins to control access to an apache down load area.


My original idea was to make django responsible for the FastCgiAccessChecker 
script itself since we're running django as an external fcgi socket server using 
flup.


I managed to get apache to accept the long running socket server as the 
FastCgiAccessChecker, but all attempts at using the access check seem to fail 
with some kind of fastcgi protocol error


..server.fcgi aborted: protocol error: invalid FCGI_END_REQUEST status: 3 
!= FCGI_REQUEST_COMPLETE(0)


it seems that 3 refers to a bad role, but I'm not sure who is detecting this 
problem.


Any ideas welcome. I ask here because my queries elsewhere have vanished.

I should add that I have two solutions to the problem of getting the validation 
done, but both involve extra fcgi scripts. One imports django and does the 
checking directly, the second uses urllib2 to forward the validation request 
using the original django http application.

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


Re: Supporting homework (was: Re: Checking a Number for Palindromic Behavior)

2009-10-22 Thread rurpy
On 10/22/2009 02:24 AM, Andre Engels wrote:
 On Thu, Oct 22, 2009 at 7:04 AM, Dieter Maurer die...@handshake.de wrote:
 Steven D'Aprano ste...@remove.this.cybersource.com.au writes on 20 Oct 
 2009 05:35:18 GMT:
 As far as I'm concerned, asking for help on homework without being honest
 up-front about it and making an effort first, is cheating by breaking the
 social contract. Anyone who rewards cheaters by giving them the answer
 they want is part of the problem. Whether cheaters prosper in the long
 run or not, they make life more difficult for the rest of us, and should
 be discouraged.

 A few days ago, I have read an impressive book: Albert Jacquard: Mon 
 utopie.
 The author has been a university professor (among others for
 population genectics, a discipline between mathematics and biologie).
 One of the corner therories in his book: mankind has reached the current
 level of development not mainly due to exceptional work by individuals
 but by the high level of cooperation between individuals.

 In this view, asking for help (i.e. seeking communication/cooperation)
 with individual tasks should probably be highly encouraged not discouraged.
 At least, it is highly doubtful that the paradigm each for himself,
 the most ruthless wins will be adequate for the huge problems mankind
 will face in the near future (defeating hunger, preventing drastic
 climate changes, natural resources exhaustion, ); intensive
 cooperation seems to be necessary.

 I think you are much mis-interpreting the quoted text here. Steven is
 arguing against asking for help on homework **without being honest
 up-front about it and making an effort first**.

This are several issues the originating thread.
q) How a posted question can be categorized:
 q1) A posted question
   q1a) is a homework problem.
q1a1) Poster was up front about it.
q1a2) Poster failed to mention it was homework.
(AFAICR, Steven was the only one to include this honesty issue.)
   q1b) isn't a homework problem.
 q2) The poster
   q2a) supplied code or other evidence that he tried to code a
solution.
   q2b) didn't supply such evidence.

r) And how it should be responded to:
 r1) What kind of answer to provide.
  r1a) No answer.
  r1b) Hints, possibly a number of them sequentially.
  r1c) Actual example code.
 r2) Who should make the decision about (r1).
  r2a) One of the group's wes.
  r2b) Each participant based on his/her own judgment.

While you say Steven is concerned about the combination
q1a.q2b concern about q2b is really independent of q1.

 We are all willing to
 help people who say For such-and-such homework assignment I created
 this-and-that program but I still cannot work out how to do so-and-so
 part. The problems come when someone shoves a simple problem at us,
 and basically says I must write this simple program, please do it for
 me. The canned response for that is What have you tried and where
 did you get problems? - look for a way to cooperate with people, to
 help them where that is necessary. What is being argued against is to
 just give the people the code in such a case. Steven and others are
 *looking for* cooperation, not shying away from it. Cooperation in the
 form of try to do it yourself, and if that fails, we will help you.
 What we don't want is 'cooperation' in the form just shove your
 problem on our plate and consider yourself done.

That kind cooperation is similar to the cooperation
demanded by police when interrogating a suspect, i.e.
it is not really cooperation, it is coercion (we will
punish you (by not answering your question) unless you
do what we tell you to).  The power to provide an answer
or not resides exclusively with the answerer, the
questioner has almost nothing to bargain with.
(Although the concept of cooperation seems fuzzy
enough that it could be argued over forever.)

While there are undoubtedly cheaters and those who
want to (as the stereotype goes) get an answer without
doing any work themselves for either their programming
course or to prevent us from feeling taken advantage
of, I personally feel that many cases do not fit that
stereotype -- the posters have made an attempt on the
problem and simply failed to mention it, or were too
intimidated by the problem to attempt code, or did provide
evidence but in a form that does not satisfy one of the
regulars, or some other perfectly innocent explanation.
Thus, in general, I prefer to cooperate with them by
answering their question.  Of course if it becomes
clear that the poster really is taking advantage of
my (or our) cooperation then I will stop cooperating
with him/her.

It is rather like the legal systems of many countries
that consider the harm done by punishing the innocent
more evil than the harm done by failing to punish the
guilty.

Overall, I think that cooperating with those asking
questions here will improve the tone of this group,
improve the image of the python community, attract
more people to Python, and ultimately further 

Re: a splitting headache

2009-10-22 Thread Mensanator
On Oct 22, 8:17 am, David C. Ullrich dullr...@sprynet.com wrote:
 On Wed, 21 Oct 2009 14:43:48 -0700 (PDT), Mensanator





 mensana...@aol.com wrote:
 On Oct 21, 2:46 pm, David C Ullrich dullr...@sprynet.com wrote:
  On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
   On Oct 20, 1:51 pm, David C Ullrich dullr...@sprynet.com wrote:
   On Thu, 15 Oct 2009 18:18:09 -0700, Mensanator wrote:
All I wanted to do is split a binary number into two lists, a list of
blocks of consecutive ones and another list of blocks of consecutive
zeroes.

But no, you can't do that.

c = '001110'
c.split('0')
['', '', '1', '', '', '', '11', '']

Ok, the consecutive delimiters appear as empty strings for reasons
unknown (except for the first one). Except when they start or end the
string in which case the first one is included.

Maybe there's a reason for this inconsistent behaviour but you won't
find it in the documentation.

   Wanna bet? I'm not sure whether you're claiming that the behavior is
   not specified in the docs or the reason for it. The behavior certainly
   is specified. I conjecture you think the behavior itself is not
   specified,

   The problem is that the docs give a single example

   '1,,2'.split(',')
   ['1','','2']

   ignoring the special case of leading/trailing delimiters. Yes, if you
   think it through, ',1,,2,'.split(',') should return ['','1','','2','']
   for exactly the reasons you give.

   Trouble is, we often find ourselves doing ' 1  2  '.split() which
   returns
   ['1','2'].

   I'm not saying either behaviour is wrong, it's just not obvious that the
   one behaviour doesn't follow from the other and the documentation could
   be
   a little clearer on this matter. It might make a bit more sense to
   actually
   mention the slpit(sep) behavior that split() doesn't do.

  Have you _read_ the docs?

 Yes.

  They're quite clear on the difference
  between no sep (or sep=None) and sep=something:

 I disagree that they are quite clear. The first paragraph makes no
 mention of leading or trailing delimiters and they show no example
 of such usage. An example would at least force me to think about it
 if it isn't specifically mentioned in the paragraph.

 One could infer from the second paragraph that, as it doesn't return
 empty stings from leading and trailing whitespace, slpit(sep) does
 for leading/trailing delimiters. Of course, why would I even be
 reading
 this paragraph when I'm trying to understand split(sep)?

 A skightly less sarcastic answer than what I just posted:

And a slightly less sarcastic reply.


 I don't see why you _should_ need to read the second paragraph
 to infer that leading delimiters will return empty strings when
 you do split(sep). That's exactly what one would expect!

Yes, AFTER you read the docs. But prior to opening them, coupled
with a long history of using split(), there is no reason to expect
such behaviour at all.

 As I pointed out the other day, if you're splitting ',,p' with
 sep = ',' that means you're looking for strings _separated by_
 commas. That means you're asking for [s1, s2, ...] where
 s1 is the part of the string preceding the first comma,
 s2 is the part of the string after the first comma but
 before the second comma, etc. And that means s1 = ''
 here.

It behaves much like the CSV module, which I'm very familiar
with from Excel. But when importing into Excel, you have the
option of treating consecutive delimiters as one, but unlike
split(), a single leading delimiter will NOT be thrown away.
I would wager that the body of Excel users is vastly greater
than the body of Python programmers. It doesn't hurt to
explicitly point out the obvious, because what's obvious may
differ from people's experience.


 That's what split on commas _means_. It's also exactly
 what you want in typical applications, for example
 parsing comma-separated data. The fact that s.split()
 does _not_ include an empty string at the start if s
 begins with whitespace is that counterintuitive part;
 that's why it's specified in the second paragraph
 (whether you believe it or not, _that's_ what
 confused _me_ once. At which point I read the docs...)
 I suppose it makes sense given a typical use case of
 s.split(), where s is text and we want to find a list of
 the words in s.

Right, what I wanted was to extract the 'words' consisting
of blocks of contiguous 1-bits from a binary number and simply
discard the 0's. I was then going to do the same process only
delimiting on 1's to get blocks of 0's. What I was expecting
was split(sep) to work similar to split() as it is somewhat
unusal for the algorithm to change. I still think the
documentation could do a better job explaining this.


 Really. I can't understand why you would _expect_
 s.split(sep) to do anything other than

 def split(s, sep):
   res = []
   acc = ''
   for c in s:
     if c in sep:
       res.append(acc)
       acc = ''
     else:
       acc = acc 

Re: a splitting headache

2009-10-22 Thread Mensanator
On Oct 22, 10:05 am, John Posner jjpos...@optimum.net wrote:
 Carl Banks wrote:

 snip

  s.split() and s.split(sep) do different things, and there is no string
  sep that can make s.split(sep) behave like s.split().  That's not
  unheard of but it does go against our typical expectations.  It would
  have been a better library design if s.split() and s.split(sep) were
  different methods.

 It looks like they *were* different methods. The Oct 1996 edition of
 Programming Python (O'Reilly  Assoc.), based on Python 1.3, describes
 two separate functions in the string module in Chapter 16:

  string.split()
  string.splitfields(delim)

That's interesting. If string.splitfields(delim) was equivalent to
str.split(sep), it would have been useful to add the phrase
str.split(sep) is equivalent to the old string.splitfields(delim)
which no longer exists. to the docs. That way, a search on
splitfields would direct the user to str.split(sep) rather than
simply throw a dialog box saying No topics found. No one ever
considers making life easy for the user.


 -John

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


Re: Help with code = Extract numerical value to variable

2009-10-22 Thread Peter Pearson
On Thu, 22 Oct 2009 10:27:57 -0700 (PDT), Steve wrote:
 I have some data that I'm performing some analysis on.
 How do I grab the numerical value if it's present and ignore
 otherwise. So in the following example
 I would have assign the following values to my var
 16
 20
 2
 7
 0


 In Field6
 Sample String data is
 sold: 16
 sold: 20
 sold: 2
 sold: 0
 sold: storefront
 7
 0
storefront
 sold
 null

What result do you want from these lines:
sold: 1 2 3
sold: 123x 4
sold: 5 y 6
sold: 3-2
sold: 3 - 2
sold: -3
sold: 1.5
sold: 1e6
sold: 2*2

-- 
To email me, substitute nowhere-spamcop, invalid-net.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with code = Extract numerical value to variable

2009-10-22 Thread rurpy
On Oct 22, 11:27 am, Steve zerocostprod...@gmail.com wrote:
 I have some data that I'm performing some analysis on.
 How do I grab the numerical value if it's present and ignore
 otherwise. So in the following example
 I would have assign the following values to my var
 16
 20
 2
 7
 0

 In Field6
 Sample String data is
 sold: 16
 sold: 20
 sold: 2
 sold: 0
 sold: storefront
 7
 0
 storefront
 sold
 null

So you want a list of any number that
occurs in the file, if it occurs at the
start of the line, or is preceded by a
space character?  And you don't want
any duplicates in the list?  Is the order
of the results important?  That is, would
a result of 16,20,2,0,7 be acceptable?
Or how about 20,2,16,7,0?

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


Re: Cpython optimization

2009-10-22 Thread Stefan Behnel
Francesco Bochicchio wrote:
 As a simple and plain python user, I would value a version of cython that 
 can be used to built faster executables out of almost-python code (that 
 is python code with a few additional restructions). Maybe using typing 
 inference to avoid declaring explicitely the variable types.

Sorry, type inference has already landed and will be in Cython 0.12. Plus,
you do not need to declare variables in Cython, but you may, if you choose to.

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


Re: a splitting headache

2009-10-22 Thread rurpy
On 10/22/2009 07:17 AM, David C. Ullrich wrote:
 On Wed, 21 Oct 2009 14:43:48 -0700 (PDT), Mensanator
 mensana...@aol.com wrote:

On Oct 21, 2:46 pm, David C Ullrich dullr...@sprynet.com wrote:
 On Tue, 20 Oct 2009 15:22:55 -0700, Mensanator wrote:
  On Oct 20, 1:51 pm, David C Ullrich dullr...@sprynet.com wrote:
  On Thu, 15 Oct 2009 18:18:09 -0700, Mensanator wrote:
[...]
 Have you _read_ the docs?

Yes.

 They're quite clear on the difference
 between no sep (or sep=None) and sep=something:

I disagree that they are quite clear. The first paragraph makes no
mention of leading or trailing delimiters and they show no example
of such usage. An example would at least force me to think about it
if it isn't specifically mentioned in the paragraph.

One could infer from the second paragraph that, as it doesn't return
empty stings from leading and trailing whitespace, slpit(sep) does
for leading/trailing delimiters. Of course, why would I even be
reading
this paragraph when I'm trying to understand split(sep)?

 A skightly less sarcastic answer than what I just posted:

 I don't see why you _should_ need to read the second paragraph
 to infer that leading delimiters will return empty strings when
 you do split(sep). That's exactly what one would expect!

It is very dangerous for a documentation writer
to decide not to document something because, that's
what everyone would expect.  It relies on the
writer actually knowing what everyone would expect
which, given the wide range of backgrounds and
experience of the readers, is asking a lot.
Just look at the different expectation of how
Python should work expressed in posts to this
group by people coming from other languages.

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


Re: subprocess executing shell

2009-10-22 Thread Nobody
On Wed, 21 Oct 2009 11:24:37 -0400, Tim Arnold wrote:

 Hi, I'm writing a script to capture a command on the commandline and run it 
 on a remote server.
 I guess I don't understand subprocess because the code below exec's the 
 user's .cshrc file even though by default shell=False in the Popen call.

Using shell=True causes Popen to explicitly invoke the command via a
shell, i.e. /bin/sh -c command on Unix or cmd /c command on
Windows. If you use shell=False (the default), it uses fork()+exec() or
CreateProcess().

If the command which you are running ends up invoking a shell (as rsh
probably does), that's nothing to do with Popen.

In particular, if csh is being invoked, that isn't Popen's doing. It will
use either /bin/sh on Unix or %COMSPEC% (which is typically cmd.exe) on
Windows.

 Since the shell is executing in the child process anyway, is the only 
 difference when using shell=True is that environment variables can be 
 expanded in the command to be executed?

The difference is that the shell gets involved, so you can use environment
variables, backticks, redirections, pipelines, shell-builtins etc. It also
means that you need to quote or escape spaces and shell metacharacters
within arguments if you want them to be treated literally.

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


Re: a simple unicode question

2009-10-22 Thread rurpy
On 10/22/2009 03:23 AM, Gabriel Genellina wrote:
 En Wed, 21 Oct 2009 15:14:32 -0300, ru...@yahoo.com escribió:

 On Oct 21, 4:59 am, Bruno Desthuilliers bruno.
 42.desthuilli...@websiteburo.invalid wrote:
 beSTEfar a écrit :
 (snip)
   When parsing strings, use Regular Expressions.

 And now you have _two_ problems g

 For some simple parsing problems, Python's string methods are powerful
 enough to make REs overkill. And for any complex enough parsing (any
 recursive construct for example - think XML, HTML, any programming
 language etc), REs are just NOT enough by themselves - you need a full
 blown parser.

 But keep in mind that many XML, HTML, etc parsing problems
 are restricted to a subset where you know the nesting depth
 is limited (often to 0 or 1), and for that large set of
 problems, RE's *are* enough.

 I don't think so. Nesting isn't the only problem. RE's cannot handle
 comments, by example. And you must support unquoted attributes, single and
 double quotes, any attribute ordering, empty tags, arbitrary whitespace...
 If you don't, you are not reading XML (or HTML), only a specific file
 format that resembles XML but actually isn't.

OK, then let me rephrase my point as: in the real world it is often
not necessary to parse XML in it's full generality; parsing, as you
put it, a specific file format that resembles XML is all that is
really needed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cpython optimization

2009-10-22 Thread geremy condra
On Wed, Oct 21, 2009 at 1:28 PM, Qrees qre...@gmail.com wrote:
 Hello

 As my Master's dissertation I chose Cpython optimization. That's why
 i'd like to ask what are your suggestions what can be optimized. Well,
 I know that quite a lot. I've downloaded the source code (I plan to
 work on Cpython 2.6 and I've downloaded 2.6.3 release). By looking at
 the code I've found comment's like this can be optimized by... etc.
 but maybe you guide me what should I concentrate on in my work?

 I've 6-7 month  for this and If I create something decent I can
 publish it.

 Thank you in advance for any help

Could always port it to CUDA ;)

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


unicode and dbf files

2009-10-22 Thread Ethan Furman

Greetings, all!

I would like to add unicode support to my dbf project.  The dbf header 
has a one-byte field to hold the encoding of the file.  For example, 
\x03 is code-page 437 MS-DOS.


My google-fu is apparently not up to the task of locating a complete 
resource that has a list of the 256 possible values and their 
corresponding code pages.


So far I have found this, plus variations:
http://support.microsoft.com/kb/129631

Does anyone know of anything more complete?

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


Re: Python socket won't connect on Windows

2009-10-22 Thread Florian Berger
Hi Grant,

thanks for the reply!

 I'd probably fire up Wireshark and capture the network traffic
 to/from the remote host when the Python app attempts to connect
 and when another client connects.

Yes, low level traffic analyzing would have been the next logical step.
However, mysteriously things started to work after several reboots and
restarts. Probably a Windows / WinSock issue I don't need to fully
understand. ^^

Thanks anyway!

Florian

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


Re: Windows file paths, again

2009-10-22 Thread Matt McCredie
Dan Guido dguido at gmail.com writes:

 
 Hi Anthony,
 
 Thanks for your reply, but I don't think your tests have any control
 characters in them. Try again with a \v, a \n, or a \x in your input
 and I think you'll find it doesn't work as expected.
 
 --
 Dan Guido


Why don't you try it yourself? He gave you the code. I changed cfg.ini to
contain the following:

[foo]
bar=C:\x\n\r\a\01\x32\foo.py


Which produced the following output:
C:\x\n\r\a\01\x32\foo.py
'C:\\x\\n\\r\\a\\01\\x32\\foo.py'

Looks like config parser worked just fine to me. There is a difference between a
python string literal written inside of a python script and a string read from a
file. When reading from a file (or the registry) what you see is what you get.
There is no need to do so much work. 

Matt McCredie




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


Re: a simple unicode question

2009-10-22 Thread Gabriel Genellina

En Thu, 22 Oct 2009 17:08:21 -0300, ru...@yahoo.com escribió:


On 10/22/2009 03:23 AM, Gabriel Genellina wrote:

En Wed, 21 Oct 2009 15:14:32 -0300, ru...@yahoo.com escribió:


On Oct 21, 4:59 am, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:

beSTEfar a écrit :
(snip)
  When parsing strings, use Regular Expressions.

And now you have _two_ problems g

For some simple parsing problems, Python's string methods are powerful
enough to make REs overkill. And for any complex enough parsing (any
recursive construct for example - think XML, HTML, any programming
language etc), REs are just NOT enough by themselves - you need a full
blown parser.


But keep in mind that many XML, HTML, etc parsing problems
are restricted to a subset where you know the nesting depth
is limited (often to 0 or 1), and for that large set of
problems, RE's *are* enough.


I don't think so. Nesting isn't the only problem. RE's cannot handle
comments, by example. And you must support unquoted attributes, single  
and
double quotes, any attribute ordering, empty tags, arbitrary  
whitespace...

If you don't, you are not reading XML (or HTML), only a specific file
format that resembles XML but actually isn't.


OK, then let me rephrase my point as: in the real world it is often
not necessary to parse XML in it's full generality; parsing, as you
put it, a specific file format that resembles XML is all that is
really needed.


Given that using a real XML parser like ElementTree is as easy as (or even  
easier than) building a regular expression, and more robust, and more  
likely to survive small changes in the input format, why use the worse  
solution?

RE's are good in solving some problems, but parsing XML isn't one of those.

--
Gabriel Genellina

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


Parsing a large number of parms to a print statement.

2009-10-22 Thread KB
Hi,

I have to pass over 150 parameters to a print statement ala:

print %s text %s other text %s 150'th unique text %s % (v
[0], v[1], ... v[150])

I can't use a for loop like I normally would over the list v due to
the different text fragments between each var.

Is there a lambda function I can use in place of '% (v[0],v[1]...v
[150])' ???

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


Re: Parsing a large number of parms to a print statement.

2009-10-22 Thread Ethan Furman

KB wrote:

Hi,

I have to pass over 150 parameters to a print statement ala:

print %s text %s other text %s 150'th unique text %s % (v
[0], v[1], ... v[150])

I can't use a for loop like I normally would over the list v due to
the different text fragments between each var.

Is there a lambda function I can use in place of '% (v[0],v[1]...v
[150])' ???

Thanks in advance.


Actually, you are only sending one parameter to print.

Is v iterable?  _And_ does v have 150 values?  _And_ can you say 
tuple(v) and get (v[0], v[1], v[2], ..., v[149])?  If so, try:


print %s blah %s blah blah %s   % tuple(v)

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


Re:

2009-10-22 Thread John Posner

Mensanator wrote:

That's interesting. If string.splitfields(delim) was equivalent to
str.split(sep), it would have been useful to add the phrase
str.split(sep) is equivalent to the old string.splitfields(delim)
which no longer exists. to the docs. That way, a search on
splitfields would direct the user to str.split(sep) rather than
simply throw a dialog box saying No topics found. No one ever
considers making life easy for the user.
  


I'm not sure what Python documentation you're consulting. I have Python 
2.6.3rc1 on Windows XP. I launched the ...\doc\python263c1.chm help 
file, and searched for splitfields. Here's what I got:


 string.splitfields(/s/[, /sep/[, /maxsplit/]])
   This function behaves identically to split() #string.split. (In
   the past, split() #string.split was only used with one argument,
   while splitfields() #string.splitfields was only used with two
   arguments.)


-John

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


Re: Parsing a large number of parms to a print statement.

2009-10-22 Thread MRAB

KB wrote:

Hi,

I have to pass over 150 parameters to a print statement ala:

print %s text %s other text %s 150'th unique text %s % (v
[0], v[1], ... v[150])

I can't use a for loop like I normally would over the list v due to
the different text fragments between each var.

Is there a lambda function I can use in place of '% (v[0],v[1]...v
[150])' ???


print %s text %s other text %s 150'th unique text %s % tuple(v)

If v is already a tuple then that's not necessary! :-)

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


Re: Parsing a large number of parms to a print statement.

2009-10-22 Thread Benjamin Kaplan
On Thu, Oct 22, 2009 at 5:16 PM, KB ke...@nekotaku.com wrote:
 Hi,

 I have to pass over 150 parameters to a print statement ala:

 print %s text %s other text %s 150'th unique text %s % (v
 [0], v[1], ... v[150])

 I can't use a for loop like I normally would over the list v due to
 the different text fragments between each var.

 Is there a lambda function I can use in place of '% (v[0],v[1]...v
 [150])' ???

 Thanks in advance.

Why use a lambda?

long string with lots of params % tuple(v)



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

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


Re: Parsing a large number of parms to a print statement.

2009-10-22 Thread Paul Rubin
KB ke...@nekotaku.com writes:
 I have to pass over 150 parameters to a print statement ala:
 
 print %s text %s other text %s 150'th unique text %s % (v
 [0], v[1], ... v[150])
 
 I can't use a for loop like I normally would over the list v due to
 the different text fragments between each var.

print %s text ... % tuple(v[:150])

But what you're trying to do looks bizarre.  Find a way to make the
constant strings inside the print statement part of the data.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a splitting headache

2009-10-22 Thread John Posner

[resend, with Subject line corrected and formatting crud deleted]

Mensanator wrote:

That's interesting. If string.splitfields(delim) was equivalent to
str.split(sep), it would have been useful to add the phrase
str.split(sep) is equivalent to the old string.splitfields(delim)
which no longer exists. to the docs. That way, a search on
splitfields would direct the user to str.split(sep) rather than
simply throw a dialog box saying No topics found. No one ever
considers making life easy for the user.
  


I'm not sure what Python documentation you're consulting. I have Python 
2.6.3rc1 on Windows XP. I launched the ...\doc\python263c1.chm help 
file, and searched for splitfields. Here's what I got:


string.splitfields(/s/[, /sep/[, /maxsplit/]])
  This function behaves identically to split(). (In
  the past, split() was only used with one argument,
  while splitfields() was only used with two
  arguments.)


-John


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


Re: Parsing a large number of parms to a print statement.

2009-10-22 Thread Andre Engels
On Thu, Oct 22, 2009 at 11:16 PM, KB ke...@nekotaku.com wrote:
 Hi,

 I have to pass over 150 parameters to a print statement ala:

 print %s text %s other text %s 150'th unique text %s % (v
 [0], v[1], ... v[150])

 I can't use a for loop like I normally would over the list v due to
 the different text fragments between each var.

 Is there a lambda function I can use in place of '% (v[0],v[1]...v
 [150])' ???

It's not a lambda function, but what about

print %s text %s other text %s 150'th unique text %s % tuple(v)




-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Please help with regular expression finding multiple floats

2009-10-22 Thread Jeremy
I have text that looks like the following (but all in one string with
'\n' separating the lines):

1.E-08   1.58024E-06 0.0048
1.E-07   2.98403E-05 0.0018
1.E-06   8.85470E-06 0.0026
1.E-05   6.08120E-06 0.0032
1.E-03   1.61817E-05 0.0022
1.E+00   8.34460E-05 0.0014
2.E+00   2.31616E-05 0.0017
5.E+00   2.42717E-05 0.0017
  total  1.93417E-04 0.0012

I want to capture the two or three floating point numbers in each line
and store them in a tuple.  I want to find all such tuples such that I
have
[('1.E-08', '1.58024E-06', '0.0048'),
 ('1.E-07', '2.98403E-05', '0.0018'),
 ('1.E-06', '8.85470E-06', '0.0026'),
 ('1.E-05', '6.08120E-06', '0.0032'),
 ('1.E-03', '1.61817E-05', '0.0022'),
 ('1.E+00', '8.34460E-05', '0.0014'),
 ('2.E+00', '2.31616E-05', '0.0017'),
 ('5.E+00', '2.42717E-05', '0.0017')
 ('1.93417E-04', '0.0012')]

as a result.  I have the regular expression pattern

fp1 = '([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\s+'

which can find a floating point number followed by some space.  I can
find three floats with

found = re.findall('%s%s%s' %fp1, text)

My question is, how can I use regular expressions to find two OR three
or even an arbitrary number of floats without repeating %s?  Is this
possible?

Thanks,
Jeremy




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


Re: Help with code = Extract numerical value to variable

2009-10-22 Thread Steve
If there is a number in the line I want the number otherwise I want a
0
I don't think I can use strip because the lines have no standards


Thanks again
Steve

On Oct 22, 1:53 pm, ru...@yahoo.com wrote:
 On Oct 22, 11:27 am, Steve zerocostprod...@gmail.com wrote:





  I have some data that I'm performing some analysis on.
  How do I grab the numerical value if it's present and ignore
  otherwise. So in the following example
  I would have assign the following values to my var
  16
  20
  2
  7
  0

  In Field6
  Sample String data is
  sold: 16
  sold: 20
  sold: 2
  sold: 0
  sold: storefront
  7
  0
  storefront
  sold
  null

 So you want a list of any number that
 occurs in the file, if it occurs at the
 start of the line, or is preceded by a
 space character?  And you don't want
 any duplicates in the list?  Is the order
 of the results important?  That is, would
 a result of 16,20,2,0,7 be acceptable?
 Or how about 20,2,16,7,0?- Hide quoted text -

 - Show quoted text -

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


Re: a splitting headache

2009-10-22 Thread Mensanator
On Oct 22, 4:35 pm, John Posner jjpos...@optimum.net wrote:
 [resend, with Subject line corrected and formatting crud deleted]

 Mensanator wrote:
  That's interesting. If string.splitfields(delim) was equivalent to
  str.split(sep), it would have been useful to add the phrase
  str.split(sep) is equivalent to the old string.splitfields(delim)
  which no longer exists. to the docs. That way, a search on
  splitfields would direct the user to str.split(sep) rather than
  simply throw a dialog box saying No topics found. No one ever
  considers making life easy for the user.

 I'm not sure what Python documentation you're consulting. I have Python
 2.6.3rc1 on Windows XP. I launched the ...\doc\python263c1.chm help
 file, and searched for splitfields. Here's what I got:

  string.splitfields(/s/[, /sep/[, /maxsplit/]])
    This function behaves identically to split(). (In
    the past, split() was only used with one argument,
    while splitfields() was only used with two
    arguments.)

I got No Topics Found in the 3.1 docs. Still, the possibility
exists that someone has an old Python source code that they want
to convert to 3.1. I for one, never had a copy of Python 1.3.


 -John

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


Re: Parsing a large number of parms to a print statement.

2009-10-22 Thread KB
Excuse the top-post, but thanks to all, the tuple was the way to go.

On Oct 22, 2:16 pm, KB ke...@nekotaku.com wrote:
 Hi,

 I have to pass over 150 parameters to a print statement ala:

 print %s text %s other text %s 150'th unique text %s % (v
 [0], v[1], ... v[150])

 I can't use a for loop like I normally would over the list v due to
 the different text fragments between each var.

 Is there a lambda function I can use in place of '% (v[0],v[1]...v
 [150])' ???

 Thanks in advance.

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


Re: Please help with regular expression finding multiple floats

2009-10-22 Thread Rhodri James

On Thu, 22 Oct 2009 23:26:01 +0100, Jeremy jlcon...@gmail.com wrote:


I have text that looks like the following (but all in one string with
'\n' separating the lines):

1.E-08   1.58024E-06 0.0048

[snip]

5.E+00   2.42717E-05 0.0017
  total  1.93417E-04 0.0012

I want to capture the two or three floating point numbers in each line
and store them in a tuple.  I want to find all such tuples such that I
have
[('1.E-08', '1.58024E-06', '0.0048'),

[snip]

 ('5.E+00', '2.42717E-05', '0.0017')
 ('1.93417E-04', '0.0012')]

as a result.  I have the regular expression pattern

fp1 = '([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\s+'

which can find a floating point number followed by some space.


Hmm.  Is .01 really valid?  Oh well, let's assume so.  I'd
seriously recommend using a raw string r'' to define fp1
with though; it's a good habit to get into with regular expressions,
and when (not if) the fact that none of your backslashes are
escaped matters, you won't waste hours wondering what just bit you.


 I can
find three floats with

found = re.findall('%s%s%s' %fp1, text)

My question is, how can I use regular expressions to find two OR three
or even an arbitrary number of floats without repeating %s?  Is this
possible?


Yes.  On the off-chance that this is homework, I'll just observe that
the only difference between detecting repeated digits (say) and repeated
float-expressions is exactly what you apply the repetition operators to.
The documentation for the 're' module at python.org is your friend!

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


python pyodbc - connect error

2009-10-22 Thread Threader Slash
Hello Everybody... here we go - my question:

1. I am using Eclipse IDE with Python 2.5 and pyodbc25 - winXP; need to read
content from a
Lotus Notes database, so run some basic query like - SELECT personname FROM
tablename.
2. 'import pyodbc' is ok - python see it!
3. But it doesn't connect, when I try to run
conn = pyodbc.connect(DRIVER={Lotus NotesSQL Driver};SERVER=local;UID=John
Meyer;PWD=yellowbird;DATABASE=mydb.nsf)

It gives me the error:
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data
source name not found and no default driver specified (0)
(SQLDriverConnectW)')

Please, any hint or suggestion? Thanks in advance. ThreaderSlash
-- 
http://mail.python.org/mailman/listinfo/python-list


PySerial

2009-10-22 Thread Ronn Ross
I'm using pySerial to connect to a serial port (rs232) on a windows xp
machine. I'm using python interactive interpretor to interact with the
device. I type the following:
import serial
ser = serial.Serial(2)
ser.write(command)

But this does nothing to the control. I have been able to connect via puTTY
to verify that the command and the device are working. Next I tried to open
the port before
writing. It looks like this:
import serial
ser = serial.Serial(2)
ser.open()

It returns that an error. It states that I do not have permissions? I don't
know how to resolve either issue. Any help would be greatly appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >