creating python code with dynamic file name

2009-05-14 Thread bijoy franco
hi,


How can i create python code, for which filename can be defined on the
fly..?

for example, in a blog, when each article selected, respective python code
with headline of the article as filename should be called.

thanks

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


Re: putting date strings in order

2009-05-14 Thread Peter Otten
noydb wrote:

> On May 14, 4:13 pm, Scott David Daniels  wrote:
>> Peter Otten wrote:
>> > Hm, if ordered_raster_list is guaranteed to contain one string item for
>> > every month the above can be simplified to
>>
>> > months = [
>> > 'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
>> > 'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
>> > 'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']
>>
>> > start = 2
>> > ordered_raster_list = months[start-1:] + months[:start-1]
>>
>> Or even:
>> >
>> multi_months = [
>> 'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
>> 'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
>> 'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec'] * 2
>> start = 2
>> ordered_raster_list = multi_months[start - 1: start + 11]
>>
>> --Scott David Daniels
>> scott.dani...@acm.org
> 
> Peter and Scott --
> 
> ordered_raster_list is guaranteed to have one string item for all 12
> months -- it is just NOT guaranteed to have those in chronological
> order, which is what is required, whether the data starts in january
> (thus ending in dec of same year) or august (thus ending in jul of the
> following year) or whenever.  The initial order of the list is
> dictated by when the raster (precip_) was added to it's
> container.  One would hope the rasters would be added in order, but I
> cannot count on that and shouldn't.

Then you can indeed build the list directly instead of reading it out of 
ListRasters(...) and then sorting it. 

You will get wrong results when there are missing or duplicate months anyway 
unless you work the start month into the lookup dictionary

ordered_months = months[start-1:] + months[:start-1]
month_dict = dict(zip(ordered_months, range(12)))
ordered_raster_list.sort(key=month_dict.get)

or use the modulo key.

Peter

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


Re: C API: how to replace python number object in place?

2009-05-14 Thread Carl Banks
On May 14, 8:24 pm, vava...@cpu111.math.uwaterloo.ca (Stephen Vavasis)
wrote:
> In my previous posting, I inquired how to change a python numeric object
> in place.  Several people responded that this is not possible.  Perhaps I
> should explain the larger problem that I am trying to solve, and then the
> solution will become apparent.  I have a C routine R that invokes a Python
> routine S repeatedly.  This Python routine S takes three arguments, two
> floats and an integer.  I have read the documentation explaining how R can
> use the C API to construct an argument list for invoking S.  The issue
> that baffles me is that, as far as I can tell, each time R invokes S
> again, it needs to deallocate and reallocate the three arguments.

That's correct.

(Well, not exactly: sometimes PyInt_New can use a pre-existing object
rather than to allocate a new one.  Also ints and floats I think both
use arena allocation, meaning that Python gets big chunks and creates
objects out of that.  It's not like malloc gets called for every
PyInt_New invokation.  But those are implementation details.  Just
trust that Python's been pretty well optimized by now to create new
int and float objects.)


> It
> would seem be much more efficient if R could create the argument list once
> and then modify the values inside of it for each subsequent invocation of
> S.

It really won't make that much of a difference.  Python is creating
and destroying objects all the time.  If you were to execute a line
like this in Python:

a = b + 2.0 / (0.5 * m * v * v)

It'd probably create and delete 5 intermediate number objects.
Whatever small gains you could make by eliminating a few object
allocations in your calling code would hardly be noticeable.


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


Re: Call Web Service using proxy and http authentication

2009-05-14 Thread wdveloper
On May 13, 5:26 pm, Steve Howell  wrote:
> On May 12, 12:51 pm, wdveloper  wrote:
>
>
>
> > On May 12, 8:38 pm, Steve Howell  wrote:
>
> > > On May 12, 8:59 am, wdveloper  wrote:
>
> > > > Hi everyone,
>
> > > > I am trying to call a webservice which requires an http
> > > > authentication.
> > > > To reach the ws, I must pass from a proxy http. So in the whole I need
> > > > go through two authentications before getting the ws working. I am
> > > > using SOAPpy and I'm getting quite crazy.
> > > > I am able to arrange this problem with simple http calls using urllib2
> > > > but for the ws i dont see any way out.
>
> > > > Does anyone knows how I can manage this stuff? Is there any better
> > > > solution or example code?
>
> > > Your high level description of the problem is good, but I think you'll
> > > get more help if you provide a little more detail.
>
> > > For something like this you may want to try to do more at the HTTP
> > > level, where you have a little more control over the authentication,
> > > and then find a way to hook into SOAPpy just to build and parse the
> > > payloads.
>
> > > How good is your understanding of HTTP?  Do you know the basics of how
> > > headers work?  You might want to brush up a little on HTTP just to
> > > help understand what's going on; it will almost certainly be valuable
> > > for future projects as well.
>
> > > To understand how the proxy works in particular, if you can use the
> > > proxy to access a normal html-serving website, you can use the "Live
> > > HTTP Headers" tool under Firefox to see what's going on.
>
> > > But before all that, I would maybe just post a little more detail on
> > > the problem.  Maybe show code you've written so far, and any error
> > > messages/tracebacks, to better indicate where you are stuck.
>
> > Thank you very much Steve,
>
> > I do have a good understanding of http and its headers rules, and of
> > course I can work on that.
> > On the other hand, I am new to python and SOAPpy toolkit and I dont
> > have much of an experience working with ws in general.
>
> > When it comes of working with simple call to WS, everything is
> > successfull; problems start cause I dont know how to use the toolkit
> > to compose the http request. I should code it in the way that it
> > connects to my proper proxy and it gets authenticated in the server
> > exposing the service.
>
> > What I have is something like:
> > from SOAPpy import WSDL
>
> > wsdl = 'http://myws?wsdl'
> > my_http_proxy = '10.x.x.x:8080'
> > proxy = WSDL.Proxy(wsdl, http_proxy=my_http_proxy)
> > res = proxy.myService( myparam='...' )
>
> > What I get is that connection reaches timeout since the server doesnt
> > see me coming from the right proxy.
> > First problem, I can't see where I can put my proxy authentication
> > username and password.
> > Second, when I will be able to pass through the right proxy, I need to
> > authenticate on the server via http through my credential.
>
> Have you looked at the URLopener class?

At the end what I did is to use the authentication components offered
by urllib2.
Just I had to hand write the SOAP message outcoming, losing the chance
to use SOAPpy.
Anyway it seems to work this way,
thanks again
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API: how to replace python number object in place?

2009-05-14 Thread Stephen Vavasis
In my previous posting, I inquired how to change a python numeric object 
in place.  Several people responded that this is not possible.  Perhaps I 
should explain the larger problem that I am trying to solve, and then the 
solution will become apparent.  I have a C routine R that invokes a Python 
routine S repeatedly.  This Python routine S takes three arguments, two 
floats and an integer.  I have read the documentation explaining how R can 
use the C API to construct an argument list for invoking S.  The issue 
that baffles me is that, as far as I can tell, each time R invokes S 
again, it needs to deallocate and reallocate the three arguments.  It 
would seem be much more efficient if R could create the argument list once 
and then modify the values inside of it for each subsequent invocation of 
S.

-- Steve Vavasis


In article ,
Scott David Daniels   wrote:

>If you do figurte out how to do what you want, you will put us in the
>old FORTRAN trap:  People can write code that changes the value of a
>constant.
>The code:
> month = 12 # make it december
> inches_per_foot = 12
> make_previous(month)
> print ('Month is now: %s, inches_per_foot = %s' % (
>month, inches_per_foot))
>might print:
> Month is now: 11, inches_per_foot = 11
>
>--Scott David Daniels
>scott.dani...@acm.org


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


UpLib 1.7.6 available

2009-05-14 Thread Bill Janssen
I've released the latest version of my UpLib personal digital library
system.

For those of you unfamiliar with UpLib, here's the abstract:

  The UpLib personal digital library system provides a secure
  long-term storage system, and a visually-oriented retrieval
  mechanism, for a wide variety of personal documents such as papers,
  photos, receipts, music, Web pages, books, clippings, and email. It
  is suitable for collections comprising tens of thousands of
  documents, and provides for ease of document entry and access as
  well as high levels of security and privacy. It is highly extensible
  through user scripting, and supports collaborative sharing of those
  extensions through a common extensions library.

It's mainly written in Python -- there's a scrap of C code for page
image zone classification, PyLucene is used for indexing and search,
and there's a fairly extensive Java client-side library, including a
document reader.

Among other things, it includes my Python IMAP server, which allows an
UpLib document repository to be used as an IMAP mail server.

http://uplib.parc.com/

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


Re: (Windows) Finding out which process has locked a file.

2009-05-14 Thread Gabriel Genellina

En Thu, 14 May 2009 08:42:07 -0300, Lawrence D'Oliveiro escribió:

In message <787d6072-3381-40bd-
af20-8e1a40405...@h23g2000vbc.googlegroups.com>, CinnamonDonkey wrote:


I have a script running which occa[s]ionally fails because it is trying
to delete a file in use by another process. When this happens I want
it to log which process has the lock.


Maybe there is no such process. Maybe it's just the Dimdows filesystem
randomly returning a failure on its own. How would you know?


Oh, c'mon, that's just nonsense and doesn't help anybody.

--
Gabriel Genellina

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


Re: How to get all named args in a dict?

2009-05-14 Thread John Machin
On May 15, 10:46 am, Dave Angel  wrote:
> kj wrote:
> > In  Dave Angel 
> >  writes:
>
> >> kj wrote:
>
> >>> In  Terry Reedy 
> >>>  writes:
>
>  kj wrote:
>
> > Suppose I have the following:
>
> > def foo(x=None, y=None, z=None):
> >     d = {"x": x, "y": y, "z": z}
> >     return bar(d)
>
> > I.e. foo takes a whole bunch of named arguments and ends up calling
> > a function bar that takes a single dictionary as argument, and this
> > dictionary has the same keys as in foo's signature, so to speak.
>
> > Is there some builtin variable that would be the same as the variable
> > d, and would thus obviate the need to explicitly bind d?
>
>  Use the built-in function locals()
>
> >>> def f(a,b):
>
>         x=locals()
>         print(x)
>
> >>> f(1,2)
>
>  {'a': 1, 'b': 2}
>
> >>> That's *exactly* what I was looking for.  Thanks!
>
> >>> kynn
>
> >> You already had a better answer from Chris Rebert:
>
> >> def foo(**kwargs):
> >>    return bar(kwargs)
>
> >> kwargs at this point is exactly a dictionary of the named arguments to foo.
>
> > I disagree.  If I defined foo as you show above, then there is no
> > error checking on the named parameters passed to foo; anything
> > goes.
>
> >> Because if you try to do anything in this function, you'll probably be
> >> adding more local variables. And then they'd be passed to bar as well.
>
> > That problem is easily solved: just make "x = locals()" the first
> > statement in the definition of foo.
>
> > kynn
>
> Well, you caught me by surprise.  The name and number of locals is
> determined at compile time, not at run time.  But when I run an
> experiment, it seems you're right, that the dict changes as the function
> executes.

So don't call it again!

> In Python 2.62 at least, the following function gives the following results:
>
> def myfunc(x, y):
>     print  locals()
>     s = 42
>     print locals()
>
> myfunc(y=12, x=33)
>
> {'y': 12, 'x': 33}
> {'y': 12, 'x': 33, 's': 42, 'r': {'y': 12, 'x': 33}}
> {'y': 12, 'x': 33}
>
> So, if one wanted to call bar, but not till after one had defined new
> locals, you could do the following:
>
> def foo(x=None, y=None, z=None):
>      args = locals().copy()
>      a = new stuff
>      dosomestuff with a, and maybe y
>      bar(args)
>
> A shallow copy would be adequate in this case.

As I (thought I had) demonstrated, *NO* copy would be adequate in that
case.

> Thanks for the correction.

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


Re: capture stdout and stderror from within a Windows Service?

2009-05-14 Thread David Lyon
On Thu, 14 May 2009 11:16:51 -0500, Grant Edwards  wrote:
> On 2009-05-14, Chris Curvey  wrote:
>> I'm trying to get this invocation right, and it is escaping me.  How
>> can I capture the stdout and stderr if I launch a subprocess using
>> subprocess.check_call()?  The twist here is that the call is running
>> from within a Windows service.
>>
>> I've tried:
>>
>> check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
>> "An integer is required"]
>>
>> check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
>> [raises an exception "An integer is required"]

In the past, windows services have never been allowed to make any output
to the console or the GDI or get any user input. Rules said they could 
send stuff to syslog etc.

All writing can go to logfiles and so forth...

I've never heard of that being allowable

David

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


Re: introspection question: get return type

2009-05-14 Thread George Sakkis
On May 14, 3:55 pm, a...@pythoncraft.com (Aahz) wrote:
> In article <4a0c6e42$0$12031$426a7...@news.free.fr>,
> Bruno Desthuilliers   wrote:
>
> >Marco Mariani a écrit :
> >> Bruno Desthuilliers wrote:
>
> >>> Oh, you meant the "return type" ? Nope, no way. It just doesn't make
> >>> sense given Python's dynamic typing.
>
> >> Unless he's really trying to write in Nohtyp,
>
> >You meant "Notype" ?-)
>
> Marco's spelling is correct.  Try "Nohtyp".reverse()

I tried it:

>>> "Nohtyp".reverse()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'str' object has no attribute 'reverse'

This newfangled Nohtyp language is no good, I want my money back.

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


Re: Need advice on distributing small module

2009-05-14 Thread Carl Banks
On May 14, 1:26 pm, kj  wrote:
> I've written a tiny module that I'd like to make available online
> from my website.  This module is not "production-grade" code; it
> is meant only as an illustration, but still I'd like to make its
> download and installation as painless as possible.
>
> I could simply bundle everything into a .tgz file, but I'd like
> the distribution to conform to the expectations of Python users,
> as far as the installation sequence is concerned.  I'm fairly new
> to Python, and would appreciate your advice on this last point.

First of all, if it's just a single module, I recommend that one of
the options is to allow the file to be downloaded as-is, with no
packaging, because a lot of Python users would find it least
cumbersome to simply drop the file right into the site-packages
directory.  The README file would be a separate download or just a
page on the website.

For more official-looking packages, you want to create a setup.py file
that lists your module's build information and meta-information.  Read
the section of the Python documentation entitled "Distributing Python
Modules" for information on how to write a setup file.  Once you write
it, you can run python setup.py sdist and it'll build a distrribution
for you.


> The module has only one non-standard dependency, described by the
> following code:
>
> if sys.version_info[:2] >= (2, 6):
>     import json
> else:
>     import simplejson as json
>
> If possible, I'd like to make distribution procedure such that if
> necessary it also installs json or simplejson (as the case may be).

Next recommendation: just tell your users to download and install json
if they want to use the module.  A small demo module shouldn't be
taking the initiative to install a fairly large package on the user's
behalf.

Furthermore, some users have extreme hatred for software that
"helpfully" downloads and installs other packages without asking
first.

If you want to proceed along these lines in spite of this, the way to
do it is to add some information to setup.py that lists dependencies.
There is a script, easy_install.py, that uses this information to
install dependencies automatically.  However, I don't know the details
of how to do that.


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


Re: How to get all named args in a dict?

2009-05-14 Thread Dave Angel

kj wrote:

In  Dave Angel 
 writes:



  

kj wrote:


In  Terry Reedy 
 writes:

  
  

kj wrote:



Suppose I have the following:

def foo(x=None, y=None, z=None):
d = {"x": x, "y": y, "z": z}
return bar(d)

I.e. foo takes a whole bunch of named arguments and ends up calling
a function bar that takes a single dictionary as argument, and this
dictionary has the same keys as in foo's signature, so to speak.

Is there some builtin variable that would be the same as the variable
d, and would thus obviate the need to explicitly bind d?
  
  
  
  

Use the built-in function locals()



def f(a,b):
  
  

x=locals()
print(x)


  
  

f(1,2)
  
  

{'a': 1, 'b': 2}



That's *exactly* what I was looking for.  Thanks!

kynn


  
  

You already had a better answer from Chris Rebert:



  

def foo(**kwargs):
   return bar(kwargs)



  

kwargs at this point is exactly a dictionary of the named arguments to foo.



I disagree.  If I defined foo as you show above, then there is no
error checking on the named parameters passed to foo; anything
goes.

  
Because if you try to do anything in this function, you'll probably be 
adding more local variables. And then they'd be passed to bar as well.



That problem is easily solved: just make "x = locals()" the first
statement in the definition of foo.

kynn
  
Well, you caught me by surprise.  The name and number of locals is 
determined at compile time, not at run time.  But when I run an 
experiment, it seems you're right, that the dict changes as the function 
executes.


In Python 2.62 at least, the following function gives the following results:

def myfunc(x, y):
   print  locals()
   s = 42
   print locals()

myfunc(y=12, x=33)

{'y': 12, 'x': 33}
{'y': 12, 'x': 33, 's': 42, 'r': {'y': 12, 'x': 33}}
{'y': 12, 'x': 33}


So, if one wanted to call bar, but not till after one had defined new 
locals, you could do the following:


def foo(x=None, y=None, z=None):
args = locals().copy()
a = new stuff
dosomestuff with a, and maybe y
bar(args)

A shallow copy would be adequate in this case.

Thanks for the correction.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get all named args in a dict?

2009-05-14 Thread John Machin
On May 15, 6:24 am, Jason Tackaberry  wrote:
> On Thu, 2009-05-14 at 20:15 +, kj wrote:
> > That problem is easily solved: just make "x = locals()" the first
> > statement in the definition of foo.
>
> That doesn't solve the problem.  You'd need locals().copy()

Dave's solution doesn't formally solve the problem because x is the
first arg of foo and re-binding x to locals() is not a good idea if
you need to use the passed-in args before calling bar().

Adding .copy() is necessary only if for some weird reason you want to
call locals() *again* before calling bar().

| >>> def foo(x=None, y=None, z=None):
| ... d = locals()
| ... print d
| ... p = 100
| ... print d
| ... print locals()
| ... print d
| ...
| >>> foo(1,2,3)
| {'y': 2, 'x': 1, 'z': 3}
| {'y': 2, 'x': 1, 'z': 3}
| {'y': 2, 'x': 1, 'z': 3, 'd': {...}, 'p': 100}
| {'y': 2, 'x': 1, 'z': 3, 'd': {...}, 'p': 100}
| >>>

Bonus: not only a side-effect, but a recursive one.

Like the manual says, _*UPDATE*_ and return a dictionary ...

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


Re: Odd list behavior

2009-05-14 Thread Rhodri James

On Thu, 14 May 2009 17:49:33 +0100, norseman  wrote:


Rhodri James wrote:
On Wed, 13 May 2009 23:08:26 +0100, norseman   
wrote:



Evan Kroske wrote:
I'm working on a simple file processing utility, and I encountered a  
weird error. If I try to get the first element of a list I'm  
splitting from a string, I get an error:

 key = string.split()[0]
Error!
 However, I can slice the list like normal, but that gives me a  
one-element-long list:

 key = string.split()[:1]
Success!
 Finally, the operation works perfectly if I initialize the list  
beforehand:

 list = string.split()
key = list[0]
Success!
 Why does this happen?




==
Take a look at the  split() command.

I think you will find you need one var on the left side for each piece  
on the right.
 Given that he's immediately indexing the split results, that's  
irrelevant.

There's no point in even guessing with out the traceback.




"...the first element of a list..."
"key = string.split()[0]"
if the list is a list of tuples the error message is correct.


What error message?  The OP still hasn't told us what error he got.

In any case, you aren't correct.  First, the str.split() method
returns a list of strings, so there are no tuples in sight.  Second,
even if it did, all that means is that "key" is a tuple, which it's
perfectly well allowed to be.

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


Re: How to get the formal args of a function object?

2009-05-14 Thread Scott David Daniels

norseman wrote:

Scott David Daniels wrote:

kj wrote:

Suppose that f is an object whose type is 'function'.
Is there a way to find out f's list of formal arguments?...


I can write a wrapper now:
def tracer(function):
def internal(*args, **kwargs):
print('calling %s(%s)' % (function.__name__,
', '.join([repr(arg) for arg in args] +
  ['%s=%r' % ka for ka in sorted(kwargs)])))
result = function(*args, **kwargs)
print('=> %r' % result)
return internal
and call like so:
>>>tracer(math.sin)(3.1415 / 6)
calling sin(0.52358334)
=> 0.49998662654663256
What would your missing something be for tracer(math.sin)?

Scott;
I'm lost with this.


Sorry, I was too telegraphic.  I was pointing out that my wrapper
function (and, indeed, lots of Python code) does something and
passes along whatever args it got.  It's obvious tracer takes a
single arg, but, tracer(math.sin) takes a single arg, while
tracer(math.atan2) takes two args.  If what your code gets is
one of these wrapped functions, it will be tricky to figure out
what the eventual arg list needed will be.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Introduction to Python course, San Francisco, Jun 2009

2009-05-14 Thread wesley chun
* FINAL REMINDER *

we have about 10-15 spaces remaining for our June course coming up in
about a month. if you have coworkers or colleagues that need to learn
Python, the weather is great up here in northern california in the
city by the bay.

there are discounts for students and teachers, as well as for
companies sending more than one attendee. finally, in this economic
crisis, if you can show you've been laidoff and collecting
unemployment, we can offer you financial aid as well.

the course will NOT be cancelled so you can make your travel
arrangements as well. hope to see you in class!

cheers,
-wesley


On Thu, Apr 9, 2009 at 3:45 PM, wesley chun  wrote:
> Need to get up-to-speed with Python as quickly as possible? Come join
> me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python
> Programming," for a comprehensive intro course coming up this June in
> beautiful Northern California! Please pass on this note to whomever
> you think may be interested. I look forward to meeting you and your
> colleagues!
>
> (Comprehensive) Introduction to Python
> Mon-Wed, 2009 Jun 15-17, 9am-5pm
>
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> (COMPREHENSIVE) INTRODUCTION TO PYTHON
>
> Although this course may appear to those new to Python, it is also
> perfect for those who have tinkered with it and want to "fill in the
> gaps" and/or want to get more in-depth formal training.  It combines
> the best of both an introduction to the language as well as a "Python
> Internals" training course.
>
> We will immerse you in the world of Python in only a few days, showing
> you more than just its syntax (which you don't really need a book to
> learn, right?). Knowing more about how Python works under the covers,
> including the relationship between data objects and memory management,
> will make you a much more effective Python programmer coming out of
> the gate. 3 hands-on labs each day will help hammer the concepts home.
>
> Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA,
> Ubuntu, YouTube, Slide, and Red Hat all use Python. Users supporting
> or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App
> Engine, Jython, IronPython, and Mailman will also benefit!
>
> FREE PREVIEW 1: you will find (and can download) a video clip of a
> live lesson that was delivered recently to get an idea of the lecture
> style and interactive classroom environment at:
>
> http://cyberwebconsulting.com (click "Python Training")
>
> FREE PREVIEW 2: Partnering with O'Reilly and Pearson, Safari Books
> Online has asked me to deliver a 1-hour webcast on Wednesday morning
> 2009 Apr 29 @ 10:30a PDT/1:30p EDT called What is
> Python?. This will be an online seminar based on a session
> that I've delivered at numerous conferences in the past. It will give
> you an idea of lecture style as well as an overview of the material
> covered in the course. Plus the first 10 registrants will receive an
> autographed copy of Core Python Programming! For more
> information:
>
> http://www.safaribooksonline.com/events/WhatIsPython.html
>
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>
> WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA
>
> WEB:   http://cyberwebconsulting.com (click "Python Training")
>
> FLYER: http://starship.python.net/crew/wesc/flyerPP1jun09.pdf
>
> LOCALS: easy freeway (101/280/380) with lots of parking plus public
> transit (BART and CalTrain) access via the San Bruno stations, easily
> accessible from all parts of the Bay Area
>
> VISITORS: free shuttle to/from the airport, free high-speed internet,
> free breakfast and regular evening receptions; fully-equipped suites
>
> See website for costs, venue info, and registration.  Discounts are
> available for multiple registrations as well as for teachers/students.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com

"Python Web Development with Django", Addison Wesley, (c) 2009
http://withdjango.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, can i ask for a little help?

2009-05-14 Thread Andrew Chung
Thank you to all who responded. You were right about the solution. That
helped alot. Now maybe i can ask if anyone has any ideas for learning, such
as websites or videos. I found one that i liked alot.

http://iamar.net/subpages/PythonVid.html

But i wondered how other people learned as beginners in the past?
Again, thank you to all of you who responded so quickly to my question. It
helped alot.

Andrew

On Wed, May 13, 2009 at 1:58 PM, Chris Rebert  wrote:

> On Wed, May 13, 2009 at 12:22 PM, warhammer1...@gmail.com
>  wrote:
> > On May 12, 9:27 pm, Chris Rebert  wrote:
> >> On Tue, May 12, 2009 at 9:18 PM, warhammer1...@gmail.com
> >>
> >>
> >>
> >>  wrote:
> >> > I loaded python 3.1
> >> > I can use the gui and i see the following:
> >>
> >> > Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit
> >> > (Intel)] on win32
> >> > Type "copyright", "credits" or "license()" for more information.
> >>
> >> > It would seem that this is working correctly and there is no path
> >> > problem.
> >> > I am running windows vista.
> >>
> >> > When i put in a test string i see this:
> >>
> >> > Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit
> >> > (Intel)] on win32
> >> > Type "copyright", "credits" or "license()" for more information.
> >>  print "hello world!"
> >> > SyntaxError: invalid syntax (, line 1)
> >>
> >> > Can anyone tell me what is wrong? I didnt expect that error
> >>
> >> The print-statement was removed in Python 3.0. Now it's just a
> >> function. You'll have to use:
> >>
> >> print("hello world!")
> >>
> >> instead.
> >>
> >> Please also read the 3.0 transition docs:
> http://docs.python.org/3.0/whatsnew/3.0.html
> >> Note that Python 3.0 differs significantly from Python 2.x
> >>
> >> Cheers,
> >> Chris
> >> --http://blog.rebertia.com
> >
> > Hi Chris,
> > Thank you for the pointer! that sure helped alot.
> > Do you think i should be using a different version of python? I dont
> > normally do much programming. I used to do some C along time ago. I
> > want to get into something again and python seems to be popular.
>
> You should probably use Python v2.6 instead for the time being; most
> libraries have yet to be ported to Python 3.0, so 2.6 has many more
> libraries available for it currently. Python 3.0 is also mostly the
> same as 2.6, so learning 2.6 won't be a waste of time and will help
> you when the full transition to 3.0 is eventually made.
>
> > Could you also tell me who uses python in IT areas? I see alot of
> > python and Mysql. And i see python developer jobs as standalone too.
>
> See http://www.python.org/about/apps/ and
> http://www.python.org/about/success/
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to import MV module

2009-05-14 Thread MRAB

guangshan chen wrote:

Hi MRAB,

Thanks. That is not what I am doing.
It seems only there is MV module used. I also googled a lot.

I just try to delete MV in the program. I found the program still can be 
run without any problem.

So maybe the MV module is not used.


From the trackback I can see that the module is imported as just "MV",
so if the module is actually being used then "MV" will occur elsewhere
in the program. If it doesn't, then deleting it from that line won't be
a problem, but if it _is_ used elsewhere, then it _will_ be a problem -
and it's just that it hasn't happened yet! :-)


Guangshan

On May 14, 2009, at 5:04 PM, MRAB wrote:


guangshan chen wrote:

Hi all,
I am new. I just want to run a python program.
When I run it, python can not find MV module. The follow is the error 
information:

Traceback (most recent call last):
  File "MakeCouplerRestart.py", line 22, in 
import MV,struct,Numeric,string
ImportError: No module named MV
Could any one tell me how to import MV module. Where is it?

It's not a standard part of Python.

I've Googled for it and I've found a website about climate data
analysis:

http://www2-pcmdi.llnl.gov/

Is that what you're doing?

>

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


Re: Representing a Tree in Python

2009-05-14 Thread Benjamin Edwards
On May 13, 8:27 pm, CTO  wrote:
> On May 13, 8:19 am, bearophileh...@lycos.com wrote:
>
> > godshorse, you may use the "shortestPaths" method of this graph class
> > of mine:http://sourceforge.net/projects/pynetwork/
>
> > (It uses the same Dijkstra code by Eppstein).
> > (Once you have all distances from a node to the other ones, it's not
> > too much difficult to find the tree you talk about).
>
> > Also see the Minimum spanning 
> > tree:http://en.wikipedia.org/wiki/Minimum_spanning_tree
>
> > Bye,
> > bearophile
>
> Let me add a caution to what bearophile says here- a minimum spanning
> tree minimizes
> the weight of the *whole tree*, not the individual paths in that tree,
> which seems
> to be what you're going after. Those can be pretty different things.
>
> Geremy Condra

no love for floyds algorithm. so simple :D

http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python system with exemplary organization/coding style

2009-05-14 Thread CTO
On May 14, 7:01 pm, TomF  wrote:
> I'm looking for a medium-sized Python system with very good coding
> style and good code organization, so I can learn from it.  I'm reading
> various books on Python with advice on such things but I'd prefer to
> see a real system.
>
> By medium-sized I mean 5-20 classes, 5-20 files, etc; a code base that
> has some complexity but isn't overwhelming.
>
> Thanks,
> -Tom

I'd recommend screenlets. Good documentation and pretty good style,
and
they have some external dependencies so you can see how that operates,
and of course you can see what your code is and isn't doing pretty
quickly.

http://www.screenlets.org>

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


Python system with exemplary organization/coding style

2009-05-14 Thread TomF
I'm looking for a medium-sized Python system with very good coding 
style and good code organization, so I can learn from it.  I'm reading 
various books on Python with advice on such things but I'd prefer to 
see a real system.


By medium-sized I mean 5-20 classes, 5-20 files, etc; a code base that 
has some complexity but isn't overwhelming.


Thanks,
-Tom

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


Re: Returning dictionary from a function

2009-05-14 Thread kk
John,

Thanks for pointing out the loop issue. I just typed these sloppy
lines the demonstrate the issue, they were not part of any code by any
means.  I will make sure that I will post cleaner lines next time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe + win32com + DAO

2009-05-14 Thread Trevor
I think the problem I am experiencing bears a resemblance to the
content of this post:

http://mail.python.org/pipermail/python-list/2001-February/071421.html

Does anyone know what the GUID for the DAO 3.6 library is (or can
explain how I can find it)?

On May 12, 11:00 pm, David Lyon  wrote:
> On Tue, 12 May 2009 22:06:42 -0700 (PDT), Trevor 
> wrote:
>
> > I do not believe your assertion applies to the following line of code:
>
> > daoEngine = win32com.client.Dispatch(r'DAO.DBEngine.36')
>
> It doesn't. I'm simply suggesting that it is possible you are opening
> the database in Access or something in Administrator/dba mode. That
> could be causing an exclusive lock on the database so that no sub
> task can then open it.
>
> i have seen this on old versions of Access.
>
> To provide excellent performance, microsoft used to load the whole
> database into memory if it could. And just operate mostly from there.
>
> > is it possible to obtain more
> > verbose error output from Python modules?  The error message in the
> > original post was generated from:
>
> > print sys.exc_info()[0]
>
> possibly but i'm not sure how...
>
> David

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


Circular relationship: object - type

2009-05-14 Thread Mohan Parthasarathy
Hi,

I have read several articles and emails:

http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html#relationships-transitivity-figure
http://mail.python.org/pipermail/python-list/2007-February/600128.html

 I understand how type serves to be the default metaclass when an object is
created and it also can be changed. I also read a few examples on why this
metaclass can be a powerful concept. What I fail to understand is the
circular relationship between object and type. Why does type have to be
subclassed from object ? Just to make "Everything is an object and all
objects are  inherited from object class".

Why can't just type be the class from which object class is instantiated ?
Why does it have to be a subclass of object also ?

Sorry if this has been answered before.

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


Re: Returning dictionary from a function

2009-05-14 Thread John Machin
On May 15, 7:38 am, kk  wrote:
> Hi
>
> I am working on something here and I cannot get the full dictionary
> out of a function. I am sure I am missing something here.
>
> Anyways here is a simple code that repeats my problem. Basically I am
> just trying to get that values function to return the diky as a
> dictionary so that I can query values later.
>
> thanks
>
> def values(x):
>     diky={}
>     for a in range(x):
>         a=a+100

And you have a SECOND problem ... rebinding your loop counter is
likely to confuse anybody (including yourself!) who tries to
understand (let alone maintain!) your code. If you want a to have
values 0, 100, 200, 300, 400 as the loop is traversed, you should use

   for a in range(0, 500, 100):

or maybe you want 100, , 104 which would be produced by
EITHER
   for a in range(100, 105):
OR
   for c in range(5):
   a = c + 100

>         diky={chr(a):a}

Note that chr(a) will cause an exception when a >= 256 ... do you need
unichr()?

AND what is the point of this dicky diky anyway? Have you considered
the ord() function?

>
>         print diky
>     return diky
>
> b=values(5)
> print type(b),len(b), b['f'] # gives error
> print type(b),len(b), b['h'] # does not give error

As expected; the last value of a was 104 and ord('h') == 104 ...

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


Re: how to import MV module

2009-05-14 Thread guangshan chen

Hi MRAB,

Thanks. That is not what I am doing.
It seems only there is MV module used. I also googled a lot.

I just try to delete MV in the program. I found the program still can  
be run without any problem.

So maybe the MV module is not used.

Guangshan

On May 14, 2009, at 5:04 PM, MRAB wrote:


guangshan chen wrote:

Hi all,
I am new. I just want to run a python program.
When I run it, python can not find MV module. The follow is the  
error information:

Traceback (most recent call last):
  File "MakeCouplerRestart.py", line 22, in 
import MV,struct,Numeric,string
ImportError: No module named MV
Could any one tell me how to import MV module. Where is it?

It's not a standard part of Python.

I've Googled for it and I've found a website about climate data
analysis:

http://www2-pcmdi.llnl.gov/

Is that what you're doing?
--
http://mail.python.org/mailman/listinfo/python-list


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


Re: Q's on my first python script

2009-05-14 Thread Marius Gedminas
On May 10, 6:56 pm, Steven D'Aprano  wrote:
> > 4. What's the python way to emit warnings?  (The script below should
> >    warn the user that arguments after the first one are ignored.)
>
> import warnings
> warnings.warn("The end of the world is coming!")

The warnings module is used for warnings about program code, not user
input.

import logging
logging.warn("Oh noes, you passed me two arguments instead of one!")

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


Re: Q's on my first python script

2009-05-14 Thread Marius Gedminas
On May 11, 12:30 pm, Nick Craig-Wood  wrote:
>     def __init__(self):
>         usage = '''Usage: %prog [options] YYMMDD
>            %prog -h|--help
> '''
>         parser = OptionParser(usage=usage)
>         parser.add_option("-n", "--no-newline", dest="nonl",
>                           action="store_true", help="omit newline in output")
>         (options, args) = parser.parse_args();
>         try:
>             weekday = self.wkday_abbrev(args[0])
>         except BadDateString, e:
>             print usage
>             print e
>             sys.exit(1)

I would recommend printing error messages to sys.stderr.

BTW, in this particular case you may want to use

 parser.error(e)

instead of print + sys.exit.

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


Re: Returning dictionary from a function

2009-05-14 Thread kk
Hi


Thank you so much. It makes perfect sense. I actually tried the second
suggested syntax before posting here but it was inside of my actual
code which probably had another problem. The suggested solution works
perfectly.

thanks again

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


Re: Nimrod programming language

2009-05-14 Thread MRAB

bearophileh...@lycos.com wrote:

Piet van Oostrum:

You may not have seen it, but Fortran and Algol 60 belong to that
category.


I see. It seems my ignorance is unbounded, even for the things I like.
I am very sorry.


Some early versions of Basic were also flexible when it came to spaces.
The example I remember is:

FORD=STOP

Variable name were a single letter, optionally followed by a digit, so
that's:

FOR D = S TO P
--
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (May 14)

2009-05-14 Thread Gabriel Genellina
QOTW:  "Tail recursion *unifies* message passing and function calling.
*This* is the reason tail recursion is cool." - JRM
http://funcall.blogspot.com/2009/05/you-knew-id-say-something-part-iii.html


First beta of Python 3.1 released
http://groups.google.com/group/comp.lang.python/t/29d24e950df2bcc6/

Python-coded scripts can do what LINQ does in expressing queries as
SQL against a list of rows and columns:
http://groups.google.com/group/comp.lang.python/msg/8c67d72703979c55
SQLite is quite wonderful.

Chaining generators efficiently
http://groups.google.com/group/comp.lang.python/t/f7503fd51f113976/

Decorating a method is slightly harder than decorating a plain function:
http://groups.google.com/group/comp.lang.python/t/956ce6027df6f8e4/

heapq.merge() lacks a `key` argument, but it would be very useful:
http://groups.google.com/group/comp.lang.python/t/52ed18a35654d2b1/

Python syntax as a friendlier alternative to those cryptic functional
languages
http://groups.google.com/group/comp.lang.python/t/5f02a42f22e896f3/
On a third hand, JRM argues that tail recursion would only help
Python, despite the decisions of BDFL.

http://funcall.blogspot.com/2009/05/you-knew-id-say-something-part-iii.html

The right way to use an "else" clause in a try/except/else:
http://groups.google.com/group/comp.lang.python/t/c599b522d4e59f54/

Simple way of handling and logging errors:
http://groups.google.com/group/comp.lang.python/t/4a77fa363f247f78/
http://groups.google.com/group/comp.lang.python/t/fd85bc9de4a23713/

Experienced Pythonistas comment on a simple program:
http://groups.google.com/group/comp.lang.python/t/5ac3a909e38c4ee4/

Serving an image in a web application does not necesarily require a file
stored on disk:
http://groups.google.com/group/comp.lang.python/t/721d5e6ab3b1cbd7/

Double-clicking a .py file doesn't work: how to fix file associations
on Windows
http://groups.google.com/group/comp.lang.python/t/8837a113342c63bc/

A long thread, started as a request for comments on PEP 382, now
discussing how evil .pth files are, and other issues involving eggs,
setuptools, easy _install, distutils and even GNU stow:
http://groups.google.com/group/comp.lang.python/t/aebfb3311a2f5eb6/

In case you missed it: 'import antigravity' in action!
http://groups.google.com/group/comp.lang.python/t/9e8d5ebb5423b0af/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiasts":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?a

Re: Returning dictionary from a function

2009-05-14 Thread MRAB

kk wrote:

Hi

I am working on something here and I cannot get the full dictionary
out of a function. I am sure I am missing something here.

Anyways here is a simple code that repeats my problem. Basically I am
just trying to get that values function to return the diky as a
dictionary so that I can query values later.

thanks




def values(x):
diky={}
for a in range(x):
a=a+100
diky={chr(a):a}


Here you're discarding the current dict and assigning another to diky.
It think you mean:

diky[chr(a)] = a



print diky


Here you're printing out the entire dict.


return diky


b=values(5)
print type(b),len(b), b['f'] # gives error
print type(b),len(b), b['h'] # does not give error


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


Re: Returning dictionary from a function

2009-05-14 Thread bearophileHUGS
kk:
>I am sure I am missing something here.<

This instruction created a new dicky dict for every iteration:
diky={chr(a):a}

What you want is to add items to the same dict, that you later output.
The normal way to do it is:
diky[chr(a)] = a

Your fixed code:

def values(x):
diky = {}
for i in xrange(x):
i += 100
diky[chr(i)] = i
print diky
return diky

b = values(5)
print type(b), len(b), b['f']
print type(b), len(b), b['h']

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


Re: Returning dictionary from a function

2009-05-14 Thread smard...@gmail.com
def values(x):
diky={}
for a in range(x):
a=a+100
diky[chr(a)] = a
return diky

it is not working b/c you are creating a new dictionary with each
iteration of the loop, rather you want to update the same dictionary
with the new value you have..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-14 Thread noydb
On May 14, 4:13 pm, Scott David Daniels  wrote:
> Peter Otten wrote:
> > Hm, if ordered_raster_list is guaranteed to contain one string item for
> > every month the above can be simplified to
>
> > months = [
> >     'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
> >     'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
> >     'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']
>
> > start = 2
> > ordered_raster_list = months[start-1:] + months[:start-1]
>
> Or even:
>  >
>      multi_months = [
>          'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
>          'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
>          'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec'] * 2
>      start = 2
>      ordered_raster_list = multi_months[start - 1: start + 11]
>
> --Scott David Daniels
> scott.dani...@acm.org

Peter and Scott --

ordered_raster_list is guaranteed to have one string item for all 12
months -- it is just NOT guaranteed to have those in chronological
order, which is what is required, whether the data starts in january
(thus ending in dec of same year) or august (thus ending in jul of the
following year) or whenever.  The initial order of the list is
dictated by when the raster (precip_) was added to it's
container.  One would hope the rasters would be added in order, but I
cannot count on that and shouldn't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning dictionary from a function

2009-05-14 Thread Diez B. Roggisch

kk schrieb:

Hi

I am working on something here and I cannot get the full dictionary
out of a function. I am sure I am missing something here.

Anyways here is a simple code that repeats my problem. Basically I am
just trying to get that values function to return the diky as a
dictionary so that I can query values later.

thanks




def values(x):
diky={}
for a in range(x):
a=a+100
diky={chr(a):a}

print diky
return diky


b=values(5)
print type(b),len(b), b['f'] # gives error
print type(b),len(b), b['h'] # does not give error


You are creating a new dictionary over and over.

dikiy[chr(a)] = a

is what you want inside the loop.

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


Re: Returning dictionary from a function

2009-05-14 Thread Jeff McNeil
On May 14, 5:44 pm, kk  wrote:
> Btw my main problem is that when I assign the function to 'b' variable
> I only get the last key from the dictionary. Sorry about that I forgot
> to mention the main issue.


You're creating a new dictionary with each iteration of your loop, use
d[k] = v syntax instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to import MV module

2009-05-14 Thread MRAB

guangshan chen wrote:

Hi all,

I am new. I just want to run a python program.

When I run it, python can not find MV module. The follow is the error 
information:

Traceback (most recent call last):
  File "MakeCouplerRestart.py", line 22, in 
import MV,struct,Numeric,string
ImportError: No module named MV

Could any one tell me how to import MV module. Where is it?


It's not a standard part of Python.

I've Googled for it and I've found a website about climate data
analysis:

http://www2-pcmdi.llnl.gov/

Is that what you're doing?
--
http://mail.python.org/mailman/listinfo/python-list


Re: python copy method alters type

2009-05-14 Thread Terry Reedy

Zhenhai Zhang wrote:

Really weired; Here is my code:

   a = ["a", 1, 3, 4]
   print "a:", a
 c = copy(a)


SyntaxError: unexpected indent
If you correct that, you would get a NameError


   c[0] = "c"
   c[1] = 2
   print "c:", c
   print "a:",a


When posting, copy and paste the complete code that you actually ran to 
get the purported output.


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


Re: Nimrod programming language

2009-05-14 Thread bearophileHUGS
Piet van Oostrum:
> You may not have seen it, but Fortran and Algol 60 belong to that
> category.

I see. It seems my ignorance is unbounded, even for the things I like.
I am very sorry.

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


Re: introspection question: get return type

2009-05-14 Thread Terry Reedy

Aahz wrote:

In article <4a0c6e42$0$12031$426a7...@news.free.fr>,
Bruno Desthuilliers   wrote:

Marco Mariani a �crit :

Bruno Desthuilliers wrote:
Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.

Unless he's really trying to write in Nohtyp,

You meant "Notype" ?-)


Marco's spelling is correct.


Right. Nohtyp is an abbreviation for Noh-type, which is very traditionalist.


Try "Nohtyp".reverse()


which give us the anti-traditionalist (Monty) Python style of play.

tjr




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


Re: Returning dictionary from a function

2009-05-14 Thread kk
Btw my main problem is that when I assign the function to 'b' variable
I only get the last key from the dictionary. Sorry about that I forgot
to mention the main issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the formal args of a function object?

2009-05-14 Thread norseman

Scott David Daniels wrote:

kj wrote:

Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passedbut I'm missing something like the hypothetical attribute
FORMAL_ARGS above.


I can write a wrapper now:

def tracer(function):
def internal(*args, **kwargs):
print('calling %s(%s)' % (function.__name__,
', '.join([repr(arg) for arg in args] +
  ['%s=%r' % ka for ka in sorted(kwargs)])))
result = function(*args, **kwargs)
print('=> %r' % result)
return internal

and call like so:
tracer(math.sin)(3.1415 / 6)

calling sin(0.52358334)
=> 0.49998662654663256

What would your missing something be for tracer(math.sin)?

--Scott David Daniels
scott.dani...@acm.org

=
Scott;
I'm lost with this.

If you use the same and add that it prints both the first_token/second 
and the first_token multiplied by second and pass it (pi, 6, 7)  what 
happens then?


ie - function mysin only expects pi and 6 and is to print both pi/6 and 
pi*6.  The 7 is an error, not supposed to be there.




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


Block-Local Variables using "with"

2009-05-14 Thread Gunter Henriksen
Presuming there is a reason to want block-local variables,
does this seem like a good way to do something like it?

@contextlib.contextmanager
def blocklocal(**kwargs):
bl = type('', (object,), {})()
for (k, v) in kwargs.items():
bl.__setattr__(k, v)
yield bl
for k in bl.__dict__.copy():
bl.__delattr__(k)

with blocklocal(a=12, b="hello") as bl:
bl.c = "world"
print(bl.a, bl.b, bl.c)

The "bl" variable would still be there but empty.
Are there cleaner ways? (without nested "def"s)
-- 
http://mail.python.org/mailman/listinfo/python-list


Returning dictionary from a function

2009-05-14 Thread kk
Hi

I am working on something here and I cannot get the full dictionary
out of a function. I am sure I am missing something here.

Anyways here is a simple code that repeats my problem. Basically I am
just trying to get that values function to return the diky as a
dictionary so that I can query values later.

thanks




def values(x):
diky={}
for a in range(x):
a=a+100
diky={chr(a):a}

print diky
return diky


b=values(5)
print type(b),len(b), b['f'] # gives error
print type(b),len(b), b['h'] # does not give error
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distributed locking

2009-05-14 Thread Piet van Oostrum
> James  (J) wrote:

>J> Hey all, I'm looking for suggestions on how to tackle distributed
>J> locking across several Python programs on several different machines.

Have you looked at the multiprocessing package? It has distributed
Locks's with timeouts which might well fit your requirements.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


how to import MV module

2009-05-14 Thread guangshan chen

Hi all,

I am new. I just want to run a python program.

When I run it, python can not find MV module. The follow is the error  
information:

Traceback (most recent call last):
  File "MakeCouplerRestart.py", line 22, in 
import MV,struct,Numeric,string
ImportError: No module named MV

Could any one tell me how to import MV module. Where is it?

Thanks..

Guangshan

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


Re: How to get the formal args of a function object?

2009-05-14 Thread norseman

kj wrote:


Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passed.  Specifically, I'd like the wrapper to look as shown below:

def _wrap(f):
def wrapper(self, *params):
n_expected = len(f.FORMAL_ARGS)
n_received = len(params)
if n_received is not n_expected:
raise RuntimeError("Wrong number of arguments passed "
   "to %s" % f.__name__)
return self.send_jsonrpc_request(f.__name__, params)
return wrapper

...but I'm missing something like the hypothetical attribute
FORMAL_ARGS above.

TIA!

Kynn



I've never tried that approach.  But the attempt brings back memories.

Mind you I was using a compiler, not an interpreter.

Language was assembly

it outlines like this:

1st time called:

compile actual code   # boo-koo bytes
if token count test OK
  compile the call to the code# just the call (1 or 2 words)
else
  print current program address
  compile in a string denoting error"ERROR-ERROR"
   to force a quit (crash)


2nd time and on

do not compile actual code   # Zero bytes
if token count test OK
  compile the call to the code   # just the call (1 or 2 words)
else
  print current program address
  compile in a string denoting error"ERROR-ERROR"
   to force a quit (crash)

Helps to print the assembly 'prn' file and look for your error flag 
BEFORE trying to run program. :)


compiler token stack (storage) delta before/after packet loaded is
tested with size expected and compiler directives adjusted accordingly.

I have no idea how to do this with an interpreter.  Maybe someone who 
reads this can figure it out.  If so - I want a copy (Please.)


Even:
def funct_foo(t1,t2,t3):
  call_token_check(3)  will not tell the incoming number
   they are on a stack or something
   somewhere else in memory.
With an interpreter this becomes an expensive overhead. Mine was only 
costly at compile time. Not at run time. And it shortened the code and 
the development time.




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


Re: Nimrod programming language

2009-05-14 Thread Piet van Oostrum
> bearophileh...@lycos.com (b) wrote:

>b> Nimrod also seems to ignore underscores inside names, seeing them as
>b> blanks. Some languages ignore underscores inside number literals, but
>b> I have never seen a language ignoring them into names too.

You may not have seen it, but Fortran and Algol 60 belong to that
category. 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API: how to replace python number object in place?

2009-05-14 Thread Hrvoje Niksic
vava...@cpu111.math.uwaterloo.ca (Stephen Vavasis) writes:

> If x is a C variable of type PyObject*, and I happen to know already
> that the object is of a numeric type, say int, is there a way to
> change the value of x in place to a different number?  In the C/API
> documentation I found routines to increment or decrement it in
> place, but I didn't find a routine to simply replace its value by a
> different value.

The only thing you can do is change x to point to a different object,
with the new desired value.  That is how the "in place" number
modification functions work.

Which routines to increment or decrement the number are you referring
to, exactly?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the formal args of a function object?

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 12:31 PM, kj  wrote:
>
>
> Suppose that f is an object whose type is 'function'.
>
> Is there a way to find out f's list of formal arguments?
>
> The reason for this is that I'm trying to write a decorator and
> I'd like the wrapper to be able to check the number of arguments
> passed.  Specifically, I'd like the wrapper to look as shown below:
>
> def _wrap(f):
>    def wrapper(self, *params):
>        n_expected = len(f.FORMAL_ARGS)
>        n_received = len(params)
>        if n_received is not n_expected:
>            raise RuntimeError("Wrong number of arguments passed "
>                               "to %s" % f.__name__)
>        return self.send_jsonrpc_request(f.__name__, params)
>    return wrapper
>
> ...but I'm missing something like the hypothetical attribute
> FORMAL_ARGS above.

Take a look at inspect.getargspec(func):
http://docs.python.org/library/inspect.html#inspect.getargspec

Cheers,
Chris
-- 
http://blog.rebertia.com

> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.

P.S. Have you considered making your address obfuscation just slightly
less of a pain in the ass? It's particularly annoying compared to
others'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the formal args of a function object?

2009-05-14 Thread Scott David Daniels

kj wrote:

Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passedbut I'm missing something like the hypothetical attribute
FORMAL_ARGS above.


I can write a wrapper now:

def tracer(function):
def internal(*args, **kwargs):
print('calling %s(%s)' % (function.__name__,
', '.join([repr(arg) for arg in args] +
  ['%s=%r' % ka for ka in sorted(kwargs)])))
result = function(*args, **kwargs)
print('=> %r' % result)
return internal

and call like so:
tracer(math.sin)(3.1415 / 6)

calling sin(0.52358334)
=> 0.49998662654663256

What would your missing something be for tracer(math.sin)?

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: OS independent file associate ?

2009-05-14 Thread norseman

Stef Mientki wrote:

hello,

I would like to make my programs available under the "standard" OS's, 
like Windows, Linux  (,Mac)
One of the problems I encounter, is launching of files through their 
file associates (probably a windows only terminology ;-)
Now I can detect the OS, but only the main OS and not e.g. Ubuntu / 
Gnome or whatever I've to detect.
Through trial and error I found a working mechanism under Ubuntu, but as 
I have to specify "gnome", I doubt this will work under other Linux 
systems.


any good solutions available ?

thanks,
Stef Mientki

   import subprocess
   CHM = '../numpy.chm'

   # works under Ubuntu
   subprocess.Popen( "gnome-open " + CHM , shell = True )

   # doesn't work under Ubuntu
   # (the list should be converted to a number of arguments,
   #but that doesn't seem to work under Ubuntu.
   subprocess.Popen( [ "gnome-open" , CHM] ,shell = True )

   # works under Windows
   subprocess.Popen( CHM , shell = True )

   # works better under windows
   win32help.HtmlHelp ( Win32_Viewer,
str(CHM),
win32help.HH_DISPLAY_INDEX,
str ( keyword ) )

 



General algorithm  which I have used for years.
Convert to specific syntax of compiler/interpreter/whatever...


Get OS from an OS call   Python has  platform   for that
Get the version  Python has  uname  for that
Get the version  Linux has   uname -a   for that

Pick your OS you use most and put that test first
  if it fails, try 2nd
  it it fails, try 3rd
  .
  .
each try uses the files suited to OS attempted


FYI
import platform
help(platform)
  (read)

os_is= platform.system()
  test for os_is == which



platform.dist()   check the doc - not sure this one does anything useful

platform.uname()  check the doc - Test it on Ubuntu, may be useful



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


Re: How to get the formal args of a function object?

2009-05-14 Thread Jeff McNeil
You can pull it out of f.func_code.co_varnames, but I don't believe
that's a very good approach. I tend to veer away from code objects
myself.

If you know how many arguments are passed into the wrapped function
when it's defined, you can write a function that returns your
decorator. As an example...

def validate_params(c):
def the_decorator(f):
def wrapper(*args):
if len(args) != c:
raise Exception("Bad things, Man.")
return f(*args)
return wrapper
return the_decorator

@validate_params(2)
def add(a,b):
return a+b

add(1,2)
add(1,2,3)

$ ./test.py
Traceback (most recent call last):
  File "test.py", line 16, in 
add(1,2,3)
  File "test.py", line 5, in wrapper
raise Exception("Bad things, Man.")
Exception: Bad things, Man.

Jeff



On May 14, 3:31 pm, kj  wrote:
> Suppose that f is an object whose type is 'function'.
>
> Is there a way to find out f's list of formal arguments?
>
> The reason for this is that I'm trying to write a decorator and
> I'd like the wrapper to be able to check the number of arguments
> passed.  Specifically, I'd like the wrapper to look as shown below:
>
> def _wrap(f):
>     def wrapper(self, *params):
>         n_expected = len(f.FORMAL_ARGS)
>         n_received = len(params)
>         if n_received is not n_expected:
>             raise RuntimeError("Wrong number of arguments passed "
>                                "to %s" % f.__name__)
>         return self.send_jsonrpc_request(f.__name__, params)
>     return wrapper
>
> ...but I'm missing something like the hypothetical attribute
> FORMAL_ARGS above.
>
> TIA!
>
> Kynn
>
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.

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


Re: How to get all named args in a dict?

2009-05-14 Thread Jason Tackaberry
On Thu, 2009-05-14 at 20:15 +, kj wrote:
> That problem is easily solved: just make "x = locals()" the first
> statement in the definition of foo.

That doesn't solve the problem.  You'd need locals().copy()

Cheers,
Jason.

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


Need advice on distributing small module

2009-05-14 Thread kj



I've written a tiny module that I'd like to make available online
from my website.  This module is not "production-grade" code; it
is meant only as an illustration, but still I'd like to make its
download and installation as painless as possible.

I could simply bundle everything into a .tgz file, but I'd like
the distribution to conform to the expectations of Python users,
as far as the installation sequence is concerned.  I'm fairly new
to Python, and would appreciate your advice on this last point.

The module has only one non-standard dependency, described by the
following code:

if sys.version_info[:2] >= (2, 6):
import json
else:
import simplejson as json

If possible, I'd like to make distribution procedure such that if
necessary it also installs json or simplejson (as the case may be).

The actual package would contain the module file and a README file.

Is there a standard tool I can use to create this distribution?

TIA!

kynn
-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API: how to replace python number object in place?

2009-05-14 Thread Scott David Daniels

Stephen Vavasis wrote:
If x is a C variable of type PyObject*, and I happen to know already that 
the object is of a numeric type, say int, is there a way to change the 
value of x in place to a different number?  In the C/API documentation I 
found routines to increment or decrement it in place, but I didn't find a 
routine to simply replace its value by a different value.  (I suppose I 
could change it to the new value via an increment or decrement, but this 
is ugly as well as being susceptible to overflow problems and roundoff 
errors in the case of floats.)


Thanks,
Steve Vavasis

If you do figurte out how to do what you want, you will put us in the
old FORTRAN trap:  People can write code that changes the value of a
constant.
The code:
month = 12 # make it december
inches_per_foot = 12
make_previous(month)
print ('Month is now: %s, inches_per_foot = %s' % (
   month, inches_per_foot))
might print:
Month is now: 11, inches_per_foot = 11

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get all named args in a dict?

2009-05-14 Thread kj
In  Dave Angel 
 writes:



>kj wrote:
>> In  Terry Reedy 
>>  writes:
>>
>>   
>>> kj wrote:
>>> 
 Suppose I have the following:

 def foo(x=None, y=None, z=None):
 d = {"x": x, "y": y, "z": z}
 return bar(d)

 I.e. foo takes a whole bunch of named arguments and ends up calling
 a function bar that takes a single dictionary as argument, and this
 dictionary has the same keys as in foo's signature, so to speak.

 Is there some builtin variable that would be the same as the variable
 d, and would thus obviate the need to explicitly bind d?
   
>>
>>   
>>> Use the built-in function locals()
>>> 
>> def f(a,b):
>>   
>>> x=locals()
>>> print(x)
>>> 
>>
>>   
>> f(1,2)
>>   
>>> {'a': 1, 'b': 2}
>>> 
>>
>> That's *exactly* what I was looking for.  Thanks!
>>
>> kynn
>>
>>
>>   
>You already had a better answer from Chris Rebert:

>def foo(**kwargs):
>return bar(kwargs)

>kwargs at this point is exactly a dictionary of the named arguments to foo.

I disagree.  If I defined foo as you show above, then there is no
error checking on the named parameters passed to foo; anything
goes.

>Because if you try to do anything in this function, you'll probably be 
>adding more local variables. And then they'd be passed to bar as well.

That problem is easily solved: just make "x = locals()" the first
statement in the definition of foo.

kynn
-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-14 Thread Scott David Daniels

Peter Otten wrote:
Hm, if ordered_raster_list is guaranteed to contain one string item for 
every month the above can be simplified to


months = [
'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr', 
'precip_may', 'precip_jun', 'precip_jul', 'precip_aug', 
'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']


start = 2
ordered_raster_list = months[start-1:] + months[:start-1]


Or even:
>
multi_months = [
'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec'] * 2
start = 2
ordered_raster_list = multi_months[start - 1: start + 11]

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: introspection question: get return type

2009-05-14 Thread Aahz
In article <4a0c6e42$0$12031$426a7...@news.free.fr>,
Bruno Desthuilliers   wrote:
>Marco Mariani a écrit :
>> Bruno Desthuilliers wrote:
>>> 
>>> Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
>>> sense given Python's dynamic typing.
>>
>> Unless he's really trying to write in Nohtyp,
>
>You meant "Notype" ?-)

Marco's spelling is correct.  Try "Nohtyp".reverse()
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get the formal args of a function object?

2009-05-14 Thread kj


Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passed.  Specifically, I'd like the wrapper to look as shown below:

def _wrap(f):
def wrapper(self, *params):
n_expected = len(f.FORMAL_ARGS)
n_received = len(params)
if n_received is not n_expected:
raise RuntimeError("Wrong number of arguments passed "
   "to %s" % f.__name__)
return self.send_jsonrpc_request(f.__name__, params)
return wrapper

...but I'm missing something like the hypothetical attribute
FORMAL_ARGS above.

TIA!

Kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When *don't* I use 'self' in classes?

2009-05-14 Thread Bruno Desthuilliers

Tim Chase a écrit :
(snip)



 try:
   self.ser = Serial()
   self.ser.baudrate = DEFAULT_BAUD
   self.ser.open()
 except SomeSpecificException:
   print "Fail!"



Please make it:


  try:
self.ser = Serial()
self.ser.baudrate = DEFAULT_BAUD
self.ser.open()
  except SomeSpecificException, e:
print "Fail! reason : %s" % e
--
http://mail.python.org/mailman/listinfo/python-list


Re: introspection question: get return type

2009-05-14 Thread Bruno Desthuilliers

Marco Mariani a écrit :

Bruno Desthuilliers wrote:

Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.


I thought that the OP was writing a tool to document not-very-dynamic code.




Unless he's really trying to write in Nohtyp,


You meant "Notype" ?-)

the language where value 
types are more important than values ;)


Hence it's name !-)
--
http://mail.python.org/mailman/listinfo/python-list


OS independent file associate ?

2009-05-14 Thread Stef Mientki

hello,

I would like to make my programs available under the "standard" OS's, 
like Windows, Linux  (,Mac)
One of the problems I encounter, is launching of files through their 
file associates (probably a windows only terminology ;-)
Now I can detect the OS, but only the main OS and not e.g. Ubuntu / 
Gnome or whatever I've to detect.
Through trial and error I found a working mechanism under Ubuntu, but as 
I have to specify "gnome", I doubt this will work under other Linux systems.


any good solutions available ?

thanks,
Stef Mientki

   import subprocess
   CHM = '../numpy.chm'

   # works under Ubuntu
   subprocess.Popen( "gnome-open " + CHM , shell = True )

   # doesn't work under Ubuntu
   # (the list should be converted to a number of arguments,
   #but that doesn't seem to work under Ubuntu.
   subprocess.Popen( [ "gnome-open" , CHM] ,shell = True )

   # works under Windows
   subprocess.Popen( CHM , shell = True )

   # works better under windows
   win32help.HtmlHelp ( Win32_Viewer,
str(CHM),
win32help.HH_DISPLAY_INDEX,
str ( keyword ) )

  
--

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


Re: How to get all named args in a dict?

2009-05-14 Thread Dave Angel



kj wrote:

In  Terry Reedy 
 writes:

  

kj wrote:


Suppose I have the following:

def foo(x=None, y=None, z=None):
d = {"x": x, "y": y, "z": z}
return bar(d)

I.e. foo takes a whole bunch of named arguments and ends up calling
a function bar that takes a single dictionary as argument, and this
dictionary has the same keys as in foo's signature, so to speak.

Is there some builtin variable that would be the same as the variable
d, and would thus obviate the need to explicitly bind d?
  


  

Use the built-in function locals()


def f(a,b):
  

x=locals()
print(x)



  

f(1,2)
  

{'a': 1, 'b': 2}



That's *exactly* what I was looking for.  Thanks!

kynn


  

You already had a better answer from Chris Rebert:

def foo(**kwargs):
   return bar(kwargs)

kwargs at this point is exactly a dictionary of the named arguments to foo.

Because if you try to do anything in this function, you'll probably be 
adding more local variables. And then they'd be passed to bar as well.



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


Re: C API: how to replace python number object in place?

2009-05-14 Thread Benjamin Peterson
Stephen Vavasis  cpu111.math.uwaterloo.ca> writes:

> 
> If x is a C variable of type PyObject*, and I happen to know already that 
> the object is of a numeric type, say int, is there a way to change the 
> value of x in place to a different number?  In the C/API documentation I 
> found routines to increment or decrement it in place, but I didn't find a 
> routine to simply replace its value by a different value.  (I suppose I 
> could change it to the new value via an increment or decrement, but this 
> is ugly as well as being susceptible to overflow problems and roundoff 
> errors in the case of floats.)

Even in the C-API, Python ints and longs are immutable. You can convert it to a
C int and work with it, otherwise you have to use the APIs which create new
objects: PyNumber_Add etc...



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


Re: how to consume .NET webservice

2009-05-14 Thread Дамјан Георгиевски
>> OpenOfficeXML document format AKA ODF? ;)
> 
> No...Office Open XML, which is used in Microsoft Office 2007 and which
> Microsoft rammed through the ISO:
> http://en.wikipedia.org/wiki/Office_Open_XML

Even worse, Microsoft Office 2007 doesn't even implement the ISO 
standard for Open XML.

-- 
дамјан ( http://softver.org.mk/damjan/ )

Our national drug is alcohol,
we tend to regard the use any other drug with special horror.
-- William S. Burroughs


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


Re: putting date strings in order

2009-05-14 Thread Peter Otten
noydb wrote:

> On May 12, 12:26 pm, John Machin  wrote:
>> On May 13, 1:58 am, Jaime Fernandez del Rio 
>> wrote:
>>
>>
>>
>>
>>
>> > On Tue, May 12, 2009 at 5:02 PM, MRAB 
>> > wrote:
>> > > John Machin wrote:
>>
>> > >> MRAB  mrabarnett.plus.com> writes:
>>
>> > >>> Sort the list, passing a function as the 'key' argument. The
>> > >>> function should return an integer for the month, eg 0 for 'jan', 1
>> > >>> for 'feb'. If you want to have a different start month then add
>>
>> > >> and if you don't like what that produces, try subtract :-)
>>
>> > > Oops!
>>
>> > >>> the appropriate
>> > >>> integer for that month (eg 0 for 'jan', 1 for 'feb') and then
>> > >>> modulo 12 to make it wrap around (there are only 12 months in a
>> > >>> year), returning the result.
>>
>> > > Actually, subtract the start month, add 12, and then modulo 12.
>>
>> > Both on my Linux and my Windows pythons, modulos of negative numbers
>> > are properly taken, returning always the correct positive number
>> > between 0 and 11. I seem to recall, from my distant past, that Perl
>> > took pride on this being a language feature. Anyone knows if that is
>> > not the case with python, and so not adding 12 before taking the
>> > modulo could result in wrong results in some implementations?
>>
>> If that happens, it's a
>> bug.http://docs.python.org/reference/expressions.html#binary-arithmetic-
o...
>>
>> If you look at function i_divmod() in the 2.x branch's Objects/
>> intobject.c, you'll be reassured to see that it doesn't just take
>> whatever C serves up :-)- Hide quoted text -
>>
>> - Show quoted text -
> 
> Thanks to those who provided suggestions.  I ended up using code
> similar to what Jaime provided above first -- truly eloquent and
> simple, especially compared to my original thoughts of several messy
> loops.  I knew it could be done way better.  Thanks very much Jaime!!
> That was a good learning experience for me.
> 
> fairly finished portion of code:
> 
> ordered_raster_list = []
> 
> pRasters = gp.ListRasters("precip_*", "All") # an enumeration object,
> arcgis method
> pRast = pRasters.next()
> while pRast:
> ##month = pRast[-3:]
> ##print month
> print pRast
> ordered_raster_list.append(pRast)
> pRast = pRasters.next()
> 
> 
> print ordered_raster_list #unordered at this point
> 
> # create a dictionary dictating the order of the the precip_
> rasters
> monthsD = {"precip_jan" : 1, "precip_feb" : 2, "precip_mar" : 3,
> "precip_apr" : 4, "precip_may" : 5, "precip_jun" : 6,
>"precip_jul" : 7, "precip_aug" : 8, "precip_sep" : 9,
> "precip_oct" : 10, "precip_nov" : 11, "precip_dec" : 12}
> 
> # sort the list based on the dictionary
> ordered_raster_list.sort(None, lambda x : monthsD[x])
> 
> print ordered_raster_list #ordered
> 
> start = 2 #user to define, starting month
> 
> ordered_raster_list = ordered_raster_list[start - 1:] +
> ordered_raster_list[:start - 1]
> 
> print ordered_raster_list #ordered but starting in the middle, feb in
> this case, ending with jan

Hm, if ordered_raster_list is guaranteed to contain one string item for 
every month the above can be simplified to

months = [
'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr', 
'precip_may', 'precip_jun', 'precip_jul', 'precip_aug', 
'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']

start = 2
ordered_raster_list = months[start-1:] + months[:start-1]

print ordered_raster_list

What am I missing?

Peter

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


Re: putting date strings in order

2009-05-14 Thread noydb
On May 12, 12:26 pm, John Machin  wrote:
> On May 13, 1:58 am, Jaime Fernandez del Rio 
> wrote:
>
>
>
>
>
> > On Tue, May 12, 2009 at 5:02 PM, MRAB  wrote:
> > > John Machin wrote:
>
> > >> MRAB  mrabarnett.plus.com> writes:
>
> > >>> Sort the list, passing a function as the 'key' argument. The function
> > >>> should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
> > >>> you want to have a different start month then add
>
> > >> and if you don't like what that produces, try subtract :-)
>
> > > Oops!
>
> > >>> the appropriate
> > >>> integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
> > >>> to make it wrap around (there are only 12 months in a year), returning
> > >>> the result.
>
> > > Actually, subtract the start month, add 12, and then modulo 12.
>
> > Both on my Linux and my Windows pythons, modulos of negative numbers
> > are properly taken, returning always the correct positive number
> > between 0 and 11. I seem to recall, from my distant past, that Perl
> > took pride on this being a language feature. Anyone knows if that is
> > not the case with python, and so not adding 12 before taking the
> > modulo could result in wrong results in some implementations?
>
> If that happens, it's a 
> bug.http://docs.python.org/reference/expressions.html#binary-arithmetic-o...
>
> If you look at function i_divmod() in the 2.x branch's Objects/
> intobject.c, you'll be reassured to see that it doesn't just take
> whatever C serves up :-)- Hide quoted text -
>
> - Show quoted text -

Thanks to those who provided suggestions.  I ended up using code
similar to what Jaime provided above first -- truly eloquent and
simple, especially compared to my original thoughts of several messy
loops.  I knew it could be done way better.  Thanks very much Jaime!!
That was a good learning experience for me.

fairly finished portion of code:

ordered_raster_list = []

pRasters = gp.ListRasters("precip_*", "All") # an enumeration object,
arcgis method
pRast = pRasters.next()
while pRast:
##month = pRast[-3:]
##print month
print pRast
ordered_raster_list.append(pRast)
pRast = pRasters.next()


print ordered_raster_list #unordered at this point

# create a dictionary dictating the order of the the precip_
rasters
monthsD = {"precip_jan" : 1, "precip_feb" : 2, "precip_mar" : 3,
"precip_apr" : 4, "precip_may" : 5, "precip_jun" : 6,
   "precip_jul" : 7, "precip_aug" : 8, "precip_sep" : 9,
"precip_oct" : 10, "precip_nov" : 11, "precip_dec" : 12}

# sort the list based on the dictionary
ordered_raster_list.sort(None, lambda x : monthsD[x])

print ordered_raster_list #ordered

start = 2 #user to define, starting month

ordered_raster_list = ordered_raster_list[start - 1:] +
ordered_raster_list[:start - 1]

print ordered_raster_list #ordered but starting in the middle, feb in
this case, ending with jan
-- 
http://mail.python.org/mailman/listinfo/python-list


C API: how to replace python number object in place?

2009-05-14 Thread Stephen Vavasis
If x is a C variable of type PyObject*, and I happen to know already that 
the object is of a numeric type, say int, is there a way to change the 
value of x in place to a different number?  In the C/API documentation I 
found routines to increment or decrement it in place, but I didn't find a 
routine to simply replace its value by a different value.  (I suppose I 
could change it to the new value via an increment or decrement, but this 
is ugly as well as being susceptible to overflow problems and roundoff 
errors in the case of floats.)

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


Re: itertools question

2009-05-14 Thread Lie Ryan

Chris Rebert wrote:

They really should just add grouper() to itertools rather than leaving
it as a recipe. People keep asking for it so often...


I've just added it to the issue tracker: http://bugs.python.org/issue6021
--
http://mail.python.org/mailman/listinfo/python-list


Re: DOM implementation

2009-05-14 Thread Emanuele D'Arrigo
Thank you Paul for your reply!

I'm looking into pxdom right now and it looks very good and useful!

Thank you again!

Manu

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


Re: capture stdout and stderror from within a Windows Service?

2009-05-14 Thread norseman

Chris Curvey wrote:

I'm trying to get this invocation right, and it is escaping me.  How
can I capture the stdout and stderr if I launch a subprocess using
subprocess.check_call()?  The twist here is that the call is running
from within a Windows service.

I've tried:

check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
"An integer is required"]


mycmd.exe isn't open (running). the mycmd.exe is supposed to be a fn.
How did you start it?



check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
[raises an exception "An integer is required"]

==
I think you need to run the .exe from your .py using the subprocess 
module's commands and hook in at that time to stdin, stdout, 

get the fn and use check_call() to see if .exe has something to say.

Check subprocess's help/man and so forth.

I know that if you start a program via os.Popen2's popen3 things work as 
expected.  How you would redirect I/O in an arbitrary already running 
program in Windows is a good question.



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


Re: Odd list behavior

2009-05-14 Thread norseman

Rhodri James wrote:

On Wed, 13 May 2009 23:08:26 +0100, norseman  wrote:


Evan Kroske wrote:
I'm working on a simple file processing utility, and I encountered a 
weird error. If I try to get the first element of a list I'm 
splitting from a string, I get an error:

 key = string.split()[0]
Error!
 However, I can slice the list like normal, but that gives me a 
one-element-long list:

 key = string.split()[:1]
Success!
 Finally, the operation works perfectly if I initialize the list 
beforehand:

 list = string.split()
key = list[0]
Success!
 Why does this happen?




==
Take a look at the  split() command.

I think you will find you need one var on the left side for each piece 
on the right.


Given that he's immediately indexing the split results, that's irrelevant.
There's no point in even guessing with out the traceback.



"...the first element of a list..."
"key = string.split()[0]"
if the list is a list of tuples the error message is correct.
same for a list of key:value pairs
he will need one var on left for each piece of [0]
 k,v=  list.split(key:value)??!!


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


Re: urllib2 slow for multiple requests

2009-05-14 Thread Richard Brodie

"Tomas Svarovsky"  wrote in message 
news:747b0d4f-f9fd-4fa6-bb6d-0a4365f32...@b1g2000vbc.googlegroups.com...

> This is a good point, but then it would manifest regardless of the
> language used AFAIK. And this is not the case, ruby and php
> implementations are working quite fine.

What I meant was: not reading the data and leaving the connection
open is going to force the server to handle all 100 requests concurrently.
I'm guessing that's not what your other implementations do.
What happens to the timing if you call response.read(), response.close() ? 


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


Re: about Python doc reader

2009-05-14 Thread norseman

Tim Golden wrote:

norseman wrote:

I did try these.

Doc at once:
outputs two x'0D' and the file.  Then it appends x'0D' x'0D' x'0A' 
x'0D' x'0A' to end of file even though source file itself has no EOL.

( EOL is EndOfLine  aka newline )

That's  cr cr There are two blank lines at begining.
cr cr lf cr lfThere is no EOL in source
  Any idea what those are about?
One crlf is probably from python's print text, but the other?

The lines=
appends   [u'\r', u'\r', u"  to begining of output
and   \r"]x'0D'x'0A'   to the end even though there is no EOL in source.

output is understood:u'\r'  is Apple EOL
the crlf is probably from print lines.


Not clear what you're doing to get there. This is the (wrapped) output 
from my interpreter, using Word 2003. As you can see, new

doc: one "\r", nothing more.


Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
 >>> import win32com.client
 >>> word = win32com.client.gencache.EnsureDispatch ("Word.Application")
 >>> doc = word.Documents.Add ()
 >>> print repr (doc.Range ().Text)
u'\r'
 >>>




==
The original "do it this way" snippets were:

import win32com.client

doc = win32com.client.GetObject ("c:/temp/temp.doc")
text = doc.Range ().Text



Note that this will give you a unicode object with \r line-delimiters.
You could read para by para if that were more useful:


import win32com.client

doc = win32com.client.GetObject ("c:/temp/temp.doc")
lines = [p.Range () for p in doc.Paragraphs]




and I added:

print textafter "text =" line above

print lines   after "lines =" line above

then ran file using   python test.py >letmesee
followed by viewing letmesee in hex



Steve



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


Re: capture stdout and stderror from within a Windows Service?

2009-05-14 Thread Grant Edwards
On 2009-05-14, Chris Curvey  wrote:
> I'm trying to get this invocation right, and it is escaping me.  How
> can I capture the stdout and stderr if I launch a subprocess using
> subprocess.check_call()?  The twist here is that the call is running
> from within a Windows service.
>
> I've tried:
>
> check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
> "An integer is required"]
>
> check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
> [raises an exception "An integer is required"]

An educated guess...

By default, subprocess will use the existing stdin, stdout, and
stderr filedescriptors for the child process. Since services
presumably don't have valid file descriptors for stdin, stdout,
and stderr, you probably have to tell subprocess to use pipes
for all three.  Otherwise, it will default to using the invalid
or nonexistant file descriptors of the parent.

[If you reply, I proably won't see it.  All posts from google
groups are plonked by my newsreader configuration.  It was
somewhat of a fluke that I came across your posting.]

-- 
Grant Edwards   grante Yow! On the road, ZIPPY
  at   is a pinhead without a
   visi.compurpose, but never without
   a POINT.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: matplotlib - overlaying plots.

2009-05-14 Thread norseman

Ant wrote:

Hi All,

I am trying to get matplotlib to overlay a couple of graphs, but am
getting nowhere. I originally thought that the following may work:


x = [1,2,3,4,5]
y = [2,4,6,8,10]
y2 = [1,4,9,16,25]



plot(x, y)
plot(x, y2)


Now this works as desired, however, the actual case I have is more
like this:


x = [1,2,3,4,5]
y = [2,4,6,8,10]
y2 = [.0001, .0002, .0003, .0004, .0005]


Now the graph is useless, since the results are plotted on the same
axis. What I really want is two different sets of axes, each scaled
appropriately, but overlayed.

The data I actually have, is one set of axes plotting distance against
elevation, and a second plotting distance against speed. The former
has (y-coord) units in the range 0-2000 ft and the latter 0 - 0.01
miles/second. I want them on the same graph, so points can be easily
correlated, but overlayed so that each line has a different scale on
the y-axis. The closest I can get is to have two subplots, one above
the other.

Thanks in advance,

Ant.



==
Use scalers to 'sync' the axis (x or y or both on the page)
The 'scales' along the axis need to match or you get your problem.

You know - like trying to do 1:1 but one is meters and the other feet.
That case needs two different graphs (or CAD drawings) each with its own 
legend.  The scales are not the same.  ie... 100meters is not 100feet

By scalling to same units/distance on graph you get overlay ability.

my first thought on your 0-2000ft and miles/sec is to convert miles to 
feet and multiply time by enough to be integer values and see if you get 
a better visual


one graph means one set of units per axis
 or
plot each and scale one to the other
  (in CAD it's a case of meters/3.28083_ to reduce to feet units
  .3048 * meters if using International scaler
  meters/3.2808(infinitely repeating 3s) is US Standard.
  The difference cost us a mars rover.
  You don't seem to be metric vs US but you do have miss matched units.
  miles vs feet, time vs (feet)elevation
  or whatever the units distance/elevation may be.
  )
target_size / 2nd_graph unit => scaler for that axis (mostly)
  since the units are not completely the same type you may need
  to experiment.
same units would be  time time  hours days seconds
 linear linear  meter feet mile
 angular angularmils degrees rads
and so forth.

HTH


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


Re: capture stdout and stderror from within a Windows Service?

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 8:57 AM, Chris Curvey  wrote:
> I'm trying to get this invocation right, and it is escaping me.  How
> can I capture the stdout and stderr if I launch a subprocess using
> subprocess.check_call()?  The twist here is that the call is running
> from within a Windows service.
>
> I've tried:
>
> check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
> "An integer is required"]
>
> check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
> [raises an exception "An integer is required"]

Providing the full exception Tracebacks would be highly recommended.

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Assigning a list to a key of a dict

2009-05-14 Thread Gary Herron

Wells wrote:

Why can't I do this?

teams = { "SEA": "Seattle Mariners" }
for team, name in teams.items():
teams[team]["roster"] = ["player1", "player2"]
  


Because,
 team will be "SEA",
so 
 teams[team] will be  "Seattle Mariners"

and
 "Seattle Mariners"["roster"] makes no sense.



Gary Herron



I get an error:

Traceback (most recent call last):
  File "./gamelogs.py", line 53, in 
teams[team]["roster"] = ["player1", "player2"]
TypeError: 'str' object does not support item assignment

You can see that I am trying to make a key called "roster" for each
team item in the dictionary, which is a list of players.
  


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


Re: Assigning a list to a key of a dict

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 8:45 AM, Wells  wrote:
> Why can't I do this?
>
> teams = { "SEA": "Seattle Mariners" }
> for team, name in teams.items():
>        teams[team]["roster"] = ["player1", "player2"]
> I get an error:
>
> Traceback (most recent call last):
>  File "./gamelogs.py", line 53, in 
>    teams[team]["roster"] = ["player1", "player2"]
> TypeError: 'str' object does not support item assignment

teams - a dict of str to str
teams[team] - a string (specifically, "Seattle Mariners" in this case)
teams[team]["roster"] - um, you can't subscript a string by another
string; you can subscript it only by integer indices

> You can see that I am trying to make a key called "roster" for each
> team item in the dictionary, which is a list of players.

I'd say you need to restructure your data structure by introducing
another level of dictionaries:

teams = { "SEA": {"full_name":"Seattle Mariners"} }
for team, name in teams.items():
teams[team]["roster"] = ["player1", "player2"]
print teams
#output: {'SEA': {'full_name': 'Seattle Mariners', 'roster':
['player1', 'player2']}}

Of course, it would probably be nicer if you did this using objects
(e.g. define a Team class and have `teams` be a dict of str to Team.

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools question

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 8:53 AM, Ned Deily  wrote:
> In article ,
>  Neal Becker  wrote:
>> Is there any canned iterator adaptor that will
>>
>> transform:
>> in = [1,2,3]
>>
>> into:
>> out = [(1,2,3,4), (5,6,7,8),...]
>>
>> That is, each time next() is called, a tuple of the next N items is
>> returned.
>
> This topic was discussed here just a few days ago:
>
> 

They really should just add grouper() to itertools rather than leaving
it as a recipe. People keep asking for it so often...

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: introspection question: get return type

2009-05-14 Thread Marco Mariani

Bruno Desthuilliers wrote:

Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.


I thought that the OP was writing a tool to document not-very-dynamic code.

Unless he's really trying to write in Nohtyp, the language where value 
types are more important than values ;)


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


capture stdout and stderror from within a Windows Service?

2009-05-14 Thread Chris Curvey
I'm trying to get this invocation right, and it is escaping me.  How
can I capture the stdout and stderr if I launch a subprocess using
subprocess.check_call()?  The twist here is that the call is running
from within a Windows service.

I've tried:

check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
"An integer is required"]

check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
[raises an exception "An integer is required"]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When *don't* I use 'self' in classes?

2009-05-14 Thread Adam Gaskins
Thanks a lot everyone! This really cleared it up for me! :)

"Adam Gaskins"  wrote in message 
news:rxhol.41113$5n7.8...@newsfe09.iad...
>I am a bit confused as too when, if ever, it is not appropriate to prepend 
>'self' to objects in a class. All of the examples of how to use 'self' that 
>I find seem to be short and very simple (as examples tent to be). I 
>appologize if I am asking an ignorant question here, but I want to get off 
>on the right foot. Here's an example of what I mean:
>
> import serial
> class foo:
>def __init(self, comport):
>self.comport = comport
>self.baudrate = 9600 #default
>self.ser = serial
>try:
>self.ser.Serial()
>self.ser.baudrate = self.baudrate
>self.ser.open()
>except:
>print 'Serial port could not be opened'
>
> === OR ===
> import serial
> class foo:
>def __init(self, comport):
>self.comport = comport
>self.baudrate = 9600 #default
>try:
>ser = serial.Serial()
>ser.baudrate = self.baudrate
>ser.open()
>except:
>print 'Serial port could not be opened'
>
> There may be a typo in here, this is just a random example similar to 
> something I'm working with, but which one of these are more 'proper'? If I 
> am importing a library do I still prepend it's object with self when I use 
> it in my class? I suppose my question is just basically... when do you NOT 
> prepent an object in a class with 'self'?
>
> I'm not even sure I'm using the term 'object' correctly here. Feel free to 
> set me straight, but I hope my example makes it clear what I am asking.
>
> Thanks a lot, this ng has already been super helpful as I take my 
> crash-course in to python! :P
> 


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


Re: Assigning a list to a key of a dict

2009-05-14 Thread Diez B. Roggisch
Wells wrote:

> Why can't I do this?
> 
> teams = { "SEA": "Seattle Mariners" }
> for team, name in teams.items():
> teams[team]["roster"] = ["player1", "player2"]
> 
> I get an error:
> 
> Traceback (most recent call last):
>   File "./gamelogs.py", line 53, in 
> teams[team]["roster"] = ["player1", "player2"]
> TypeError: 'str' object does not support item assignment
> 
> You can see that I am trying to make a key called "roster" for each
> team item in the dictionary, which is a list of players.

This is not a list as key, it's a nested dictionary. There are several
approaches to this:

 - make your keys tuples, like this:

>>> teams[(team, "roster") = [...]

 - use setedfault:

>>> teams.setdefault(team, {})["roster"] = ['player1']

 - defaultdict

>>> from collections import *
>>> defaultdict

>>> teams = defaultdict(dict)
>>> teams["team"]["roster"] = ["player1"]
>>> teams
defaultdict(, {'team': {'roster': ['player1']}})
>>>   

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


Re: How to get all named args in a dict?

2009-05-14 Thread kj
In  Terry Reedy 
 writes:

>kj wrote:
>> 
>> Suppose I have the following:
>> 
>> def foo(x=None, y=None, z=None):
>> d = {"x": x, "y": y, "z": z}
>> return bar(d)
>> 
>> I.e. foo takes a whole bunch of named arguments and ends up calling
>> a function bar that takes a single dictionary as argument, and this
>> dictionary has the same keys as in foo's signature, so to speak.
>> 
>> Is there some builtin variable that would be the same as the variable
>> d, and would thus obviate the need to explicitly bind d?

>Use the built-in function locals()
> >>> def f(a,b):
>   x=locals()
>   print(x)

> >>> f(1,2)
>{'a': 1, 'b': 2}

That's *exactly* what I was looking for.  Thanks!

kynn


-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools question

2009-05-14 Thread Ned Deily
In article ,
 Neal Becker  wrote:
> Is there any canned iterator adaptor that will 
> 
> transform:
> in = [1,2,3]
> 
> into:
> out = [(1,2,3,4), (5,6,7,8),...]
> 
> That is, each time next() is called, a tuple of the next N items is 
> returned.

This topic was discussed here just a few days ago:



-- 
 Ned Deily,
 n...@acm.org

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


Assigning a list to a key of a dict

2009-05-14 Thread Wells
Why can't I do this?

teams = { "SEA": "Seattle Mariners" }
for team, name in teams.items():
teams[team]["roster"] = ["player1", "player2"]

I get an error:

Traceback (most recent call last):
  File "./gamelogs.py", line 53, in 
teams[team]["roster"] = ["player1", "player2"]
TypeError: 'str' object does not support item assignment

You can see that I am trying to make a key called "roster" for each
team item in the dictionary, which is a list of players.
-- 
http://mail.python.org/mailman/listinfo/python-list


Toronto PyCamp 2009

2009-05-14 Thread Chris Calloway
For beginners, this ultra-low-cost Python Boot Camp developed by the 
Triangle Zope and Python Users Group makes you productive so you can get 
your work done quickly. PyCamp emphasizes the features which make Python 
a simpler and more efficient language. Following along by example speeds 
your learning process in a modern high-tech classroom. Become a 
self-sufficient Python developer in just five days at PyCamp!


The University or Toronto Department of Physics brings PyCamp to 
Toronto, July 13-17, 2009.


Register today at http://trizpug.org/boot-camp/pycamp-toronto-2009/

--
Sincerely,

Chris Calloway
http://www.secoora.org
office: 332 Chapman Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599



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


Re: matplotlib - overlaying plots.

2009-05-14 Thread Ant
On May 14, 3:52 pm, Hyuga  wrote:
...
> On the other hand, I just took a peek at the matplotlib example
> gallery, which is very diverse, and it has an example that I think is
> exactly what you're looking 
> for:http://matplotlib.sourceforge.net/examples/api/two_scales.html

Superb - spot on. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools question

2009-05-14 Thread Lie Ryan

Neal Becker wrote:
Is there any canned iterator adaptor that will 


transform:
in = [1,2,3]

into:
out = [(1,2,3,4), (5,6,7,8),...]

That is, each time next() is called, a tuple of the next N items is 
returned.







An option, might be better since it handles infinite list correctly:

>>> lst = [1, 4, 2, 5, 7, 3, 2, 5, 7, 3, 2, 6, 3, 2, 6, 8, 4, 2]
>>> d = 4
>>> for x in itertools.groupby(enumerate(lst), lambda x: x[0] // d):
... print(list(x[1]))
...
[(0, 1), (1, 4), (2, 2), (3, 5)]
[(4, 7), (5, 3), (6, 2), (7, 5)]
[(8, 7), (9, 3), (10, 2), (11, 6)]
[(12, 3), (13, 2), (14, 6), (15, 8)]
[(16, 4), (17, 2)]
>>> [list(x[1]) for x in itertools.groupby(enumerate(lst), lambda x: 
x[0] // d)]
[[(0, 1), (1, 4), (2, 2), (3, 5)], [(4, 7), (5, 3), (6, 2), (7, 5)], 
[(8, 7), (9, 3), (10, 2), (11, 6)], [(12, 3), (13, 2), (14, 6), (15, 
8)], [(16, 4), (17, 2)]]


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


Re: PythonCard - My app stuck when button clicked

2009-05-14 Thread daved170
On May 14, 2:37 pm, Dave Angel  wrote:
> daved170 wrote:
> > On May 13, 7:42 pm, Dave Angel  wrote:
>
> >> daved170 wrote:
>
> >>> Hi there,
> >>> I'm newbie in pythonCard.
> >>> I have an application with 2 buttons : START , STOP
> >>> Start execute a while(1) loop that execute my calculations.
> >>> Stop suppose to raise a flag that will end that loop.
>
> >>> Whenever I pish the START button my GUI is stuck. the calculation
> >>> executes but I can't push the STOP button.
>
> >>> I added thread that START start a thread that execute my calculations.
> >>> I also added a Global variable that will hold the indication if the
> >>> loop should continue.
> >>> The problem now is that the thread ignore that variable and loop
> >>> forever.
>
> >>> Is there a simple way to make sure that the GUI won't stuck (without
> >>> threads)?
> >>> And if there isn't such way I would appriciet it very much if anyone
> >>> could post an example of how to make my thread read that variable
> >>> Thanks
> >>> Dave
>
> >> I don't know PythonCard, but most GUI's are similar enough that the
> >> concepts will work, even though the details differ.  I'll assume that
> >> PythonCard has a traditional event loop, from which all events are
> >> dispatched.
>
> >> If your loop is fairly small, then you should keep it to one thread.  
> >> Debugging it will usually be much easier.  The trick is to break the
> >> task into pieces (each piece might be once around what is now a loop),
> >> and invoke one piece each time the event loop empties.  I can't tell you
> >> how to do that without seeing your loop, but it's not usually very hard.
>
> >> Now, there is some way of POSTing an event to the event loop.  That puts
> >> the event *after* all the events that are already there, but returns
> >> control immediately.  So create a custom event, and POST it from the
> >> START button's button-pressed event.  That will fire off one "loop" of
> >> the special task, in other words, make one function call to your new
> >> function.  Then at the end of the function, POST it again, unless the
> >> STOP button has been pressed in the meantime.
>
> >> An optimization for this is to use coroutines, which are usually done
> >> with a generator.  It's much trickier to describe, but much easier to
> >> accomplish.  Roughly, you'd take your existing loop, and put a yield
> >> statement in it at appropriate place(s).  Then the custom event is
> >> simply a call to the .next() function of that generator.
>
> >> Now, threading isn't that tough either, depending on how much data is
> >> being shared between the thread and the main program.  You say that
> >> sharing a global flag isn't working, but it should.  So how about if you
> >> show us some code, and somebody'll spot the trouble.  For example, is
> >> the thread defined in the same module as the App?  Global only shares
> >> between a single module.  Another reason globals might seem to fail is
> >> if you tried to do mutual imports between two or more modules.  (A
> >> imports B, which imports A).  Sometimes that fails in mysterious ways.
>
> >> Make a simple (stripped) example of what you're trying, and we'll try to
> >> find the problem.  Without concrete code, we end up with ambiguities
> >> like the above usage of two different meanings for "the loop."- Hide 
> >> quoted text -
>
> >> - Show quoted text -
>
> > Thank's Dave,
> > Here my code, It's a very simple app. the Start button starts a TCP/IP
> > communication and the Stop should dtop it and kill the client.
> > I'll be thankful if you'll be able to spot my mistake.
> > Thanks again
> > Dave
>
> > #Global Variable
> > bStopLoop =alse
>
> > #Global Function
> > def execute(sockObj):
> >    while(!bStopLoop):
> >       str =ockObj.recv(1024)
> >       tmpStr =Hello " + str
> >       sockObj.send(tmpStr)
>
> > #Thread handle class
> > class myThread(threading.Thread):
> >    def __init__(self,sockObj):
> >       threading.Thread.__init__(self)
> >       bStopLoop =alse
> >       self.sockObj =ockObj
>
> >    def run(self):
> >       execute(self.SockObj)
>
> > # GUI
> > class GUI(model.Background)
>
> >    def on_Start_mouseclick(self,event):
> >    try:
> >       event.target.enable =alse
> >       event.target.redraw()
> >       self.components.Start.enable =alse
> >       self.currThread =yThread(self.sockObj)
> >       self.currThread.Start()
> >       wx.SafeYield(self)
> >       self.components.Start.enable =rue
> >    except:
> >       .
>
> >    def on_Stop_mouseclick(self,event):
> >       bStopLoop =rue
>
> In the two methods that try to change bStopLoop, you don't declare it
> global.  Add the line "global bStopLoop"  to beginning of both
>
> on_Start_mouseclick() and on_Stop_mouseclick(), and (my preference) to 
> function execute()
>
> The semantics of global versus local variables for non-nested 
> functions/methods is roughly:   if a function or method assigns to a name, 
> it's taken to be a local, unless it's explicitly dec

Re: (Windows) Finding out which process has locked a file.

2009-05-14 Thread David Lyon

> In message <787d6072-3381-40bd-
> af20-8e1a40405...@h23g2000vbc.googlegroups.com>, CinnamonDonkey wrote:
> 
>> I have a script running which occa[s]ionally fails because it is trying
>> to delete a file in use by another process. When this happens I want
>> it to log which process has the lock.

Maybe there is something on sysinternals.com that you can download
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about Python doc reader

2009-05-14 Thread Tim Golden

norseman wrote:

I did try these.

Doc at once:
outputs two x'0D' and the file.  Then it appends x'0D' x'0D' x'0A' x'0D' 
x'0A' to end of file even though source file itself has no EOL.

( EOL is EndOfLine  aka newline )

That's  cr cr There are two blank lines at begining.
cr cr lf cr lfThere is no EOL in source
  Any idea what those are about?
One crlf is probably from python's print text, but the other?

The lines=
appends   [u'\r', u'\r', u"  to begining of output
and   \r"]x'0D'x'0A'   to the end even though there is no EOL in source.

output is understood:u'\r'  is Apple EOL
the crlf is probably from print lines.


Not clear what you're doing to get there. This is the (wrapped) 
output from my interpreter, using Word 2003. As you can see, new

doc: one "\r", nothing more.


Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more 
information.

>>> import win32com.client
>>> word = win32com.client.gencache.EnsureDispatch 
("Word.Application")

>>> doc = word.Documents.Add ()
>>> print repr (doc.Range ().Text)
u'\r'
>>>



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


Re: matplotlib - overlaying plots.

2009-05-14 Thread Hyuga
On May 14, 7:41 am, Ant  wrote:
> Hi All,
>
> I am trying to get matplotlib to overlay a couple of graphs, but am
> getting nowhere. I originally thought that the following may work:
>
> >>> x = [1,2,3,4,5]
> >>> y = [2,4,6,8,10]
> >>> y2 = [1,4,9,16,25]
> >>> plot(x, y)
> >>> plot(x, y2)
>
> Now this works as desired, however, the actual case I have is more
> like this:
>
> >>> x = [1,2,3,4,5]
> >>> y = [2,4,6,8,10]
> >>> y2 = [.0001, .0002, .0003, .0004, .0005]
>
> Now the graph is useless, since the results are plotted on the same
> axis. What I really want is two different sets of axes, each scaled
> appropriately, but overlayed.
>
> The data I actually have, is one set of axes plotting distance against
> elevation, and a second plotting distance against speed. The former
> has (y-coord) units in the range 0-2000 ft and the latter 0 - 0.01
> miles/second. I want them on the same graph, so points can be easily
> correlated, but overlayed so that each line has a different scale on
> the y-axis. The closest I can get is to have two subplots, one above
> the other.
>
> Thanks in advance,
>
> Ant.

Just scale up the y-axis values of your second graph 200,000 times,
and specify in label that the y-axis for the second graph is velocity
scaled up 20x for comparison purposes.  Nothing wrong with that--
it's done all the time.

On the other hand, I just took a peek at the matplotlib example
gallery, which is very diverse, and it has an example that I think is
exactly what you're looking for: 
http://matplotlib.sourceforge.net/examples/api/two_scales.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools question

2009-05-14 Thread Peter Otten
Neal Becker wrote:

> Is there any canned iterator adaptor that will
> 
> transform:
> in = [1,2,3]
> 
> into:
> out = [(1,2,3,4), (5,6,7,8),...]
> 
> That is, each time next() is called, a tuple of the next N items is
> returned.

Depending on what you want to do with items that don't make a complete N-
tuple:

>>> from itertools import *
>>> items = range(10)

>>> list(izip(*(iter(items),)*3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]

>>> list(izip_longest(*(iter(items),)*3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]

>>> list(takewhile(bool, imap(tuple, starmap(islice, repeat((iter(items), 
3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]

Peter

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


Re: Nimrod programming language

2009-05-14 Thread MRAB

bearophileh...@lycos.com wrote:

rump...@web.de:

Eventually the "rope" data structure (that the compiler uses heavily)
will become a proper part of the library:


Ropes are a complex data structure, that it has some downsides too.
Python tries to keep its implementation too simple, this avoids lot of
troubles (and is one of the not much visible design ideas that have
determined the success of Python).



I've seen that in Nimrod the following names are the same one:
justaname JustAName just_a_name just__aname Justaname

So like Pascal (and unlike Python/C) it doesn't tell apart names just
on the base of their case (this is positive for newbie programmers,
they usually use the convention of natural written language where
'Hello' and 'hello' are the same word, they need some time to learn
the case-sensitivity).

Nimrod also seems to ignore underscores inside names, seeing them as
blanks. Some languages ignore underscores inside number literals, but
I have never seen a language ignoring them into names too.

In a class if you have a method like:
change_table_color
Isn't much good to also have a method named:
changeTableColor
Good programming practice tells you to avoid names that can be
confused (as 'chop' and 'chomp' in the string functions of D Phobos
lib). To avoid that most languages adopt a convention, so for example
in Python the change_table_color is the only used name, Java uses
changeTableColor, etc. Such conventions solve most of such problems.

So I don't know how much I like this design detail of Nimrod.

In Python you often see code like:
node = Node()

Sometimes in a case-sensitive language I'd like to have a compilation
warning switch that tells me that in a namespace there are two or more
names that differ only on character case or underscore count. This may
help avoid some bugs. A language may even enforce this as a syntax
error, so you have to write things like:
n = Node()
Or:
anode = Node()


Does Nimrod accept non-ASCII names? If so, is "I" the same character as
"i"? In most languages using the Latin alphabet they would be, but in 
Turkish they wouldn't.

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


Re: itertools question

2009-05-14 Thread Nick Craig-Wood
Neal Becker  wrote:
>  Is there any canned iterator adaptor that will 
> 
>  transform:
>  in = [1,2,3]
> 
>  into:
>  out = [(1,2,3,4), (5,6,7,8),...]
> 
>  That is, each time next() is called, a tuple of the next N items is 
>  returned.

This is my best effort... not using itertools as my brain doesn't seem
to work that way!

class Grouper(object):
def __init__(self, n, i):
self.n = n
self.i = iter(i)
def __iter__(self):
while True:
out = tuple(self.i.next() for _ in xrange(self.n))
if not out:
break
yield out

g = Grouper(5, xrange(20))
print list(g)

g = Grouper(4, xrange(19))
print list(g)

Which produces

[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18)]


-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 slow for multiple requests

2009-05-14 Thread cgoldberg
> It might be, if the local server doesn't scale well enough to handle
> 100 concurrent requests.

true.. I didn't think of that.  I was assuming the client machine
wasn't resource constrained.  That would definitely lead to inaccurate
timings if that was the case.




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


  1   2   >