Re: How do I converted a null (0) terminated string to a Python string?

2006-09-13 Thread John Machin

Michael top-posted [again]:
>
> John Machin wrote:
> > Michael top-posted [corrected]:
> > > John Machin wrote:
> > > > Michael wrote:
> > > > > Hi All,
> > > > >
> > > > > I've received (via UDP) a null terminated string and need to convert 
> > > > > it
> > > > > into a Python string. Can anyone tell me how this is done? If it 
> > > > > helps,
> > > > > I know the number of characters in the string.
> > > > >
> > > >
> > > > I think you mean NUL, not null.
> > > >
> > > > What have you received it into, if it's not a Python string?
> > > >
> > > > You probably need/want this:
> > > >
> > > > if strg[-1] == "\0":
> > > > strg = strg[:-1]
> > > > alternatively:
> > > > strg = strg.rstrip("\0") # requires Python 2.2.2 or later
> > > >
> > > > It's possible you may be talking about a fixed length string which
> > > > contains useful_stuff + "\0" + padding -- in that case you need
> > > >
> > > > strg = strg.split("\0")[0] # grab upto (but not including) the first
> > > > NUL (if any)
> > > >
> > > > If you're not sure what you've got, print repr(the_input_string)
> > > >
> > > > HTH,
> > > > John
> > > Thank you very much for your responses. To answer some of the
> > > questions... Yes, I am in Python receiving a C language 0 terminated
> > > string that was sent to my Python program in a UDP packet (which is how
> > > I know the count). Are your responses still correct given this
> > > clarification?
> >
> > My responses are correct. Your "clarification" indicates to me that you
> > are going by what you are told, not by inspection of (several instances
> > of) the packet contents, using repr(). It's up to you whether you want
> > to be skeptical about the packet contents or not. I certainly wouldn't
> > be throwing the last byte away without checking that it was in fact a
> > NUL.
> >
> > Cheers,
> > John
> John,
>
> Thanks for your reply. Just wondering... how are Python strings
> formatted? Evidently they're not 0 terminated.

A Python string is an object. The details of the internal storage may
vary between implementations. CPython  has 8-bit str objects and 16-bit
or 32-bit Unicode objects. In IronPython, (str is Unicode) is true, and
they are 16 bits. In any case the object knows its own length without
having to scan for a terminator. Thus, a string can contain NULs.

Having said all that, the CPython str implementation does have an
additional byte at the end; this is set to zero and is not counted in
the length. However you never see that and don't really need to know
unless you are writing an extension module in C -- it's handy to know
that you don't have to append a NUL if you want to call a C library
function.

Cheers,
John

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


Re: Refactor a buffered class...

2006-09-13 Thread lh84777
thanks a lot to all, i help me to learn a lot !

(i finally use the generator trick, it is great...)

best regards.

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


Re: [IronPython] [ANN] IronPython Community Edition 1.0r1

2006-09-13 Thread M. David Peterson
http://www.oreillynet.com/windows/blog/2006/09/seo_sanghyeonipce_ironpython_c.htmlSeo, do you have a blog I can point people to?
Either way, Thanks!  This will make things TONS easier in regards to running IronPython on Mono. :)On 9/13/06, Sanghyeon Seo <
[EMAIL PROTECTED]> wrote:I am happy to announce IronPython Community Edition (IPCE for short)
1.0 revision 1, based on IronPython 1.0, to the world.Get it here:http://sparcs.kaist.ac.kr/~tinuviel/download/IPCE-1.0r1.zip
Binary is built with Mono 1.1.17.1.Benefits of this edition:1. You don't need to fight Mono with non-working line editing orwhite-on-white "blind" console on Linux or Mac. A fix for this issue
and fixed binary is already included.2. You don't need to edit makefile to build from the source on Mono.3. Various bugfixes are included: patches are available here:
http://sparcs.kaist.ac.kr/~tinuviel/fepy/patches/1.0/patch-ironpython-mono-consolepatch-ironpython-mono-makefileDiscussed above.patch-ironpython-co-flagsThis patch fixes an issue that co_flags reports **-argument only
function to have *-argument as well.patch-ironpython-codedom-empty-returnThis patch fixes an issue that CodeDom generator doesn't handle emptyreturn statements.patch-ironpython-oldstyle-setattr
This patch fixes an issue that __setattr__ wasn't called for old-style classes.patch-ironpython-os-utimeThis patch fixes an issue that os.utime didn't set modified time andset access time wrong.
patch-ironpython-re-backslash-escapeThis patch fixes an issue that backslash escape \\ wasn't properlyhandled in regular _expression_.--Seo Sanghyeon___
users mailing listusers@lists.ironpython.comhttp://lists.ironpython.com/listinfo.cgi/users-ironpython.com
-- /M:DM. David Petersonhttp://mdavid.name | http://www.oreillynet.com/pub/au/2354

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

Re: Are Python's reserved words reserved in places they dont need to be?

2006-09-13 Thread Cliff Wells
On Wed, 2006-09-13 at 10:30 +0200, Fredrik Lundh wrote:
> Antoon Pardon wrote:
> 
> > One place where I would use such a feature is in a unittest
> > package.  I think being able to write self.assert or self.raise
> > looks better than having to append an underscore.
> 
> patch here:
> 
> http://mail.python.org/pipermail/python-list/2001-June/047996.html


Did you happen to remember this post or is Google *really* your friend?


Cliff

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


Re: How do I converted a null (0) terminated string to a Python string?

2006-09-13 Thread Michael
John,

Thanks for your reply. Just wondering... how are Python strings
formatted? Evidently they're not 0 terminated.

Thanks again,
MDM

John Machin wrote:
> Michael top-posted [corrected]:
> > John Machin wrote:
> > > Michael wrote:
> > > > Hi All,
> > > >
> > > > I've received (via UDP) a null terminated string and need to convert it
> > > > into a Python string. Can anyone tell me how this is done? If it helps,
> > > > I know the number of characters in the string.
> > > >
> > >
> > > I think you mean NUL, not null.
> > >
> > > What have you received it into, if it's not a Python string?
> > >
> > > You probably need/want this:
> > >
> > > if strg[-1] == "\0":
> > > strg = strg[:-1]
> > > alternatively:
> > > strg = strg.rstrip("\0") # requires Python 2.2.2 or later
> > >
> > > It's possible you may be talking about a fixed length string which
> > > contains useful_stuff + "\0" + padding -- in that case you need
> > >
> > > strg = strg.split("\0")[0] # grab upto (but not including) the first
> > > NUL (if any)
> > >
> > > If you're not sure what you've got, print repr(the_input_string)
> > >
> > > HTH,
> > > John
> > Thank you very much for your responses. To answer some of the
> > questions... Yes, I am in Python receiving a C language 0 terminated
> > string that was sent to my Python program in a UDP packet (which is how
> > I know the count). Are your responses still correct given this
> > clarification?
>
> My responses are correct. Your "clarification" indicates to me that you
> are going by what you are told, not by inspection of (several instances
> of) the packet contents, using repr(). It's up to you whether you want
> to be skeptical about the packet contents or not. I certainly wouldn't
> be throwing the last byte away without checking that it was in fact a
> NUL. 
> 
> Cheers,
> John

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


Re: [ANN] IronPython Community Edition 1.0r1

2006-09-13 Thread Sanghyeon Seo
2006/9/14, Sanghyeon Seo <[EMAIL PROTECTED]>:
> I am happy to announce IronPython Community Edition (IPCE for short)
> 1.0 revision 1, based on IronPython 1.0, to the world.

I haven't included Python standard library or my DB-API for IronPython
modules or useful third party modules like ElementTree and
BeautifulSoup in this revision, because I was too lazy to write an
extensive license statements required to do so. :(

Will do that next time.

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


[ANN] IronPython Community Edition 1.0r1

2006-09-13 Thread Sanghyeon Seo
I am happy to announce IronPython Community Edition (IPCE for short)
1.0 revision 1, based on IronPython 1.0, to the world.

Get it here:
http://sparcs.kaist.ac.kr/~tinuviel/download/IPCE-1.0r1.zip

Binary is built with Mono 1.1.17.1.

Benefits of this edition:

1. You don't need to fight Mono with non-working line editing or
white-on-white "blind" console on Linux or Mac. A fix for this issue
and fixed binary is already included.

2. You don't need to edit makefile to build from the source on Mono.

3. Various bugfixes are included: patches are available here:
http://sparcs.kaist.ac.kr/~tinuviel/fepy/patches/1.0/

patch-ironpython-mono-console
patch-ironpython-mono-makefile
Discussed above.

patch-ironpython-co-flags
This patch fixes an issue that co_flags reports **-argument only
function to have *-argument as well.

patch-ironpython-codedom-empty-return
This patch fixes an issue that CodeDom generator doesn't handle empty
return statements.

patch-ironpython-oldstyle-setattr
This patch fixes an issue that __setattr__ wasn't called for old-style classes.

patch-ironpython-os-utime
This patch fixes an issue that os.utime didn't set modified time and
set access time wrong.

patch-ironpython-re-backslash-escape
This patch fixes an issue that backslash escape \\ wasn't properly
handled in regular expression.

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


Re: How do I converted a null (0) terminated string to a Python string?

2006-09-13 Thread John Machin

Michael top-posted [corrected]:
> John Machin wrote:
> > Michael wrote:
> > > Hi All,
> > >
> > > I've received (via UDP) a null terminated string and need to convert it
> > > into a Python string. Can anyone tell me how this is done? If it helps,
> > > I know the number of characters in the string.
> > >
> >
> > I think you mean NUL, not null.
> >
> > What have you received it into, if it's not a Python string?
> >
> > You probably need/want this:
> >
> > if strg[-1] == "\0":
> > strg = strg[:-1]
> > alternatively:
> > strg = strg.rstrip("\0") # requires Python 2.2.2 or later
> >
> > It's possible you may be talking about a fixed length string which
> > contains useful_stuff + "\0" + padding -- in that case you need
> >
> > strg = strg.split("\0")[0] # grab upto (but not including) the first
> > NUL (if any)
> >
> > If you're not sure what you've got, print repr(the_input_string)
> >
> > HTH,
> > John
> Thank you very much for your responses. To answer some of the
> questions... Yes, I am in Python receiving a C language 0 terminated
> string that was sent to my Python program in a UDP packet (which is how
> I know the count). Are your responses still correct given this
> clarification?

My responses are correct. Your "clarification" indicates to me that you
are going by what you are told, not by inspection of (several instances
of) the packet contents, using repr(). It's up to you whether you want
to be skeptical about the packet contents or not. I certainly wouldn't
be throwing the last byte away without checking that it was in fact a
NUL. 

Cheers,
John

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


Re: stock quotes

2006-09-13 Thread Bryan
Donlingerfelt wrote:
> I would like to download stock quotes from the web, store them, do
> calculations and sort the results.  However I am fairly new and don't have a
> clue how to parse the results of a web page download.   I can get to the
> site, but do not know how to request the certain data  need.  Does anyone
> know how to do this?  I would really appreciate it.  Thanks.
> 
> 

i recently wrote a moinmoin macro which i believe does exactly what you want. 
even though you aren't writing a moinmoin macro, all the stuff you need is here.

usage: [[stock(amzn,goog,yhoo)]]

note that the string 'amzn,goog,yahoo' is passed in as the symbols variable and 
is placed as-is onto the url.  you will receive one .csv file from yahoo with 
*all* the ticker info for all symbols you requested... very cool :)  then for 
each row in the csv file, i pull out each column (data) and set a red or green 
color based on whether the stock is up or down for the day as well as providing 
a link to the yahoo finance site (finance.google.com in my latest version) when 
that symbol is clicked.  and finally return an html table with the data.

i hope this helps you.  i apologize in advance if this code doesn't come 
through 
the newsgroup formatted properly.



import urllib
import csv
def execute(macro, symbols):
 color = 'black'
 try:
 reader = 
csv.reader(urllib.urlopen('http://finance.yahoo.com/d/quotes.csv?s=%s&f=sl1d1t1c1ohgv&e=.csv'
 
% symbols))
 data = []
 for symbol, trade, date, time, change, opened, hi, low, volume in 
reader:
 num = float(change)
 if num > 0:
 color = 'green'
 elif num < 0:
 color = 'red'
 percent = 100 * float(change) / (float(trade) - float(change))
 data.append('http://finance.yahoo.com/q?s=%s";>%s%s (%s / 
%.2f%%)' % (symbol, symbol, color, trade, change, percent))
 return '%s' % ''.join(data)
 except:
 return '%s: Stock information unavailable' % symbols



bryan

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


Re: FtpUtils Progress Bar

2006-09-13 Thread Justin Ezequiel
[EMAIL PROTECTED] wrote:
>
> Does anyone have an example on how to show the progress of the
> upload/download when using ftputil?
>

haven't used ftputil in quite a while ...
but using ftplib...

import ftplib

class Callback(object):
def __init__(self, totalsize, fp):
self.totalsize = totalsize
self.fp = fp
self.received = 0

def __call__(self, data):
self.fp.write(data)
self.received += len(data)
print '\r%.3f%%' % (100.0*self.received/self.totalsize),

if __name__ == '__main__':
host = 'ftp.microsoft.com'
src = '/deskapps/games/public/Hellbender/heltrial.exe'
c = ftplib.FTP(host)
c.login()
size = c.size(src)
dest = 'heltrial.exe'
f = open(dest, 'wb')
w = Callback(size, f)
c.set_pasv(0)
c.retrbinary('RETR %s' % src, w, 32768)
f.close()
c.quit()

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


Re: How do I converted a null (0) terminated string to a Python string?

2006-09-13 Thread Michael
Thank you very much for your responses. To answer some of the
questions... Yes, I am in Python receiving a C language 0 terminated
string that was sent to my Python program in a UDP packet (which is how
I know the count). Are your responses still correct given this
clarification?

Thanks much,
MDM

John Machin wrote:
> Michael wrote:
> > Hi All,
> >
> > I've received (via UDP) a null terminated string and need to convert it
> > into a Python string. Can anyone tell me how this is done? If it helps,
> > I know the number of characters in the string.
> >
>
> I think you mean NUL, not null.
>
> What have you received it into, if it's not a Python string?
>
> You probably need/want this:
>
> if strg[-1] == "\0":
> strg = strg[:-1]
> alternatively:
> strg = strg.rstrip("\0") # requires Python 2.2.2 or later
>
> It's possible you may be talking about a fixed length string which
> contains useful_stuff + "\0" + padding -- in that case you need
>
> strg = strg.split("\0")[0] # grab upto (but not including) the first
> NUL (if any)
>
> If you're not sure what you've got, print repr(the_input_string)
> 
> HTH,
> John

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


Re: parameter files

2006-09-13 Thread Gabriel Genellina

At Thursday 14/9/2006 01:10, Russ wrote:


> I would try a configuration file, instead of a python module.
> See ConfigParser:
> .
> You can save values for each "run" in a separate [section].
> Execfile is a pretty big hammer for this.

Hey, that looks interesting, but those docs don't do it for me. Can you
point me to some more extensive examples of how to use ConfigParser?


Just forget about interpolation and such; declare a section for each 
run in your config file:


[run_name_one]
a=123
b=Test
c=4.0

[run_two]
a=456
b=Whatever
c=0.1

config = ConfigParser.ConfigParser()
config.read(filename)
a = config.getint('run_two','a') # a==456
b = config.get('run_name_one','b') # b=='Test'
section = 'run_two'
c = config.getfloat(section,'c') # c==0.1


Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: time-based point system

2006-09-13 Thread Jay
I'm sorry.  I never considered what you said about the relationship
about the input and output.  I'll take my thread elsewhere to a math
board.


Erik Max Francis wrote:
> Jay wrote:
>
> > That function is absolutely no good for this situation.
> >
> > 1. Take a small number.
> > 5.4348809719085693
> >
> > 2. Put it in the function.
> > f(5.4348809719085693) = 1/5.4348809719085693
> >
> > 3. Get a large number???
> > 0.18399666987533483
> >
> > That number is even smaller.  I want a large one coming out.
>
> f(x) = 1/x is just one example of a function that has the property of
> being a "negative function" -- the smaller number you put in, the larger
> number you get out, and vice versa.  Your statement didn't clearly
> indicate that the outputs need to be bigger than the inputs, just that
> they need to be bigger the smaller the outputs are.  The more general
> function would be f(x) = A/(x - B).  Choose A and B as desired so that
> f(x) > x for all x you care about.  Or choose another function, like
> f(x) = A - B x or any number of other functions.  There literally are an
> infinite number of possibilities.
>
> The point is, as I've already said, you haven't given nearly enough
> information to give you a useful answer.  You haven't indicated, for
> instance, anything at all about the domain or range of the function that
> you want:  What values do you need to plug in?  What range of values do
> you need to get out?  Once you have clarified to yourself what
> properties you want, that will help you define the function.
>
> At this point you're the only one who knows what properties you want,
> and unless you define them up front, it results in a very unsatisfactory
> guessing game of proposing a function, you telling me what's wrong with
> it, and repeat until either or both of us get bored.
>
> And, by the way, this is a question about mathematics, and so has
> nothing to do specifically with Python.
>
> --
> Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
>   San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
>Get married, but never to a man who is home all day.
> -- George Bernard Shaw

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


Re: time-based point system

2006-09-13 Thread Gabriel Genellina

At Thursday 14/9/2006 00:46, Jay wrote:


Okay, this is a game.  So the points are abstract.  It's like an arcade
game in respect to the points.  They don't actually mean or represent
anything.  The only point is to get a high score.  The idea is that the
faster the user acts (or reacts) the greater amount of points they'll
receive.  Simplified, I need a fuction or statement that takes in a
small number and spits out a big number.  The smaller the input, the
larger the output.


1/x, or 1000/x, or 1000-x, or 1000*exp(-x) or ...
All decline differently, play drawing them and choose whatever tastes you more.



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: time-based point system

2006-09-13 Thread Erik Max Francis
Jay wrote:

> That function is absolutely no good for this situation.
> 
> 1. Take a small number.
> 5.4348809719085693
> 
> 2. Put it in the function.
> f(5.4348809719085693) = 1/5.4348809719085693
> 
> 3. Get a large number???
> 0.18399666987533483
> 
> That number is even smaller.  I want a large one coming out.

f(x) = 1/x is just one example of a function that has the property of 
being a "negative function" -- the smaller number you put in, the larger 
number you get out, and vice versa.  Your statement didn't clearly 
indicate that the outputs need to be bigger than the inputs, just that 
they need to be bigger the smaller the outputs are.  The more general 
function would be f(x) = A/(x - B).  Choose A and B as desired so that 
f(x) > x for all x you care about.  Or choose another function, like 
f(x) = A - B x or any number of other functions.  There literally are an 
infinite number of possibilities.

The point is, as I've already said, you haven't given nearly enough 
information to give you a useful answer.  You haven't indicated, for 
instance, anything at all about the domain or range of the function that 
you want:  What values do you need to plug in?  What range of values do 
you need to get out?  Once you have clarified to yourself what 
properties you want, that will help you define the function.

At this point you're the only one who knows what properties you want, 
and unless you define them up front, it results in a very unsatisfactory 
guessing game of proposing a function, you telling me what's wrong with 
it, and repeat until either or both of us get bored.

And, by the way, this is a question about mathematics, and so has 
nothing to do specifically with Python.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Get married, but never to a man who is home all day.
-- George Bernard Shaw
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parameter files

2006-09-13 Thread Russ

> I would try a configuration file, instead of a python module.
> See ConfigParser:
> .
> You can save values for each "run" in a separate [section].
> Execfile is a pretty big hammer for this.

Hey, that looks interesting, but those docs don't do it for me. Can you
point me to some more extensive examples of how to use ConfigParser?
Thanks.

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


Re: How do I converted a null (0) terminated string to a Python string?

2006-09-13 Thread John Machin
Michael wrote:
> Hi All,
>
> I've received (via UDP) a null terminated string and need to convert it
> into a Python string. Can anyone tell me how this is done? If it helps,
> I know the number of characters in the string.
>

I think you mean NUL, not null.

What have you received it into, if it's not a Python string?

You probably need/want this:

if strg[-1] == "\0":
strg = strg[:-1]
alternatively:
strg = strg.rstrip("\0") # requires Python 2.2.2 or later

It's possible you may be talking about a fixed length string which
contains useful_stuff + "\0" + padding -- in that case you need

strg = strg.split("\0")[0] # grab upto (but not including) the first
NUL (if any)

If you're not sure what you've got, print repr(the_input_string)

HTH,
John

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


Re: FtpUtils Progress Bar

2006-09-13 Thread George Sakkis
[EMAIL PROTECTED] wrote:
> Hi,
> I can successfully upload and download files using Stefan's Schwarzer's
> ftputil script.
>
> The problem is that as some of the files are quite large you cannot see
> how much has been downloaded/uploaded.
> Even a percentage or just dots going across the screen would be better
> than nothing.
>
> Does anyone have an example on how to show the progress of the
> upload/download when using ftputil?

You'll probably have more luck asking at
http://codespeak.net/mailman/listinfo/ftputil.

George

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


Re: How to build extensions on Windows?

2006-09-13 Thread Martin v. Löwis
John Machin schrieb:
> Hi Martin, I do hope you don't regret opening Pandora's box :-)
> 
> Does the following look about right?

Technically, yes. I wonder whether it will generate unreadable error
messages, though (one would have to try).

> I was somewhat bemused by the limit of 200 bytes on the module name in
> the error message-- I woild have thought about 20 was more appropriate.
> Sorry but I can't test this (Windows box, don't have whatever version
> of C compiler is necessary to compile Python).

I'm not sure where this limit comes from, either. This would need to
be researched to find out whether it is just nonsensical, or, if
there is a rationale for it, whether it applies to the path name as
well.

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


Re: time-based point system

2006-09-13 Thread Jay
That function is absolutely no good for this situation.

1. Take a small number.
5.4348809719085693

2. Put it in the function.
f(5.4348809719085693) = 1/5.4348809719085693

3. Get a large number???
0.18399666987533483

That number is even smaller.  I want a large one coming out.

Erik Max Francis wrote:
> Jay wrote:
>
> > Okay, this is a game.  So the points are abstract.  It's like an arcade
> > game in respect to the points.  They don't actually mean or represent
> > anything.  The only point is to get a high score.  The idea is that the
> > faster the user acts (or reacts) the greater amount of points they'll
> > receive.  Simplified, I need a fuction or statement that takes in a
> > small number and spits out a big number.  The smaller the input, the
> > larger the output.
>
> There are any number of functions which fit this property, like f(x) =
> 1/x.  You'll have to define more clearly what properties of this
> negative function you want to narrow it down beyond that.
>
> --
> Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
>   San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
>Get married, but never to a man who is home all day.
> -- George Bernard Shaw

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


Re: Newbie - ? get IDLE going on cygwin

2006-09-13 Thread David J. Braden
Jason Tishler wrote:
> Dave,
> 
> On Wed, Sep 13, 2006 at 03:33:01PM +, David J. Braden wrote:
>> I can now confirm that, yes, IDLE pops up w/o menus under cygwin.
> 
> You should be able to workaround this problem by executing idle with the
> "-n" option:
> 
> $ idle -n
> 
> Jason
> 

Worked great. This "exercise" has also raised my comfort level with the 
whole endeavor. To get rebaseall going, I was told to install the 
*entire* cygwin package. Good time to paint a couple of rooms, clean the 
gutters, ... But that install, plus your last suggestion, have me 
further along, to be sure. I am really impressed by the number of tools 
out there that work with, or were developed specifically for, Python.

Regards,
DaveB - /not/ a professional programmer. Just a very well-trained nerd.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to build extensions on Windows?

2006-09-13 Thread Martin v. Löwis
Fuzzyman schrieb:
> More interestingly, someone reported on Python-dev recently a speed
> improvement of around 30% (from memory) by compiling with VC 8. I know
> the grumble (almost certainly correctly) about Microsoft's 'odd'
> interpretation of the C standards in VC 8, but it looks like there are
> major benefits to switching...

You may or may not know that it is futile arguing about compiler
switching for released versions of Python, i.e. 2.3, 2.4, and 2.5.
Whether or not it might be a good idea: it can't be done, for
compatibility with prior releases.

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


Re: Looking for the Perfect Editor

2006-09-13 Thread Jay
I, too, am a hardcore fan of jEdit.  It's nice to finally see some user
support on this forum.  :-)


Wildemar Wildenburger wrote:
> stu wrote:
> > jedit
> >
> > http://www.jedit.org/
>
> Finally! I usually try to stay out of these discussions; yet I'm always
> disappointed at how few people seem to be using jEdit and how long it
> takes them to come out of their holes.
> 
> So let me enforce that:
> 
> jEdit
> www.jedit.org
> 
> wildemar

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


Re: How do I converted a null (0) terminated string to a Python string?

2006-09-13 Thread Steve Holden
Michael wrote:
> Hi All,
> 
> I've received (via UDP) a null terminated string and need to convert it
> into a Python string. Can anyone tell me how this is done? If it helps,
> I know the number of characters in the string.
> 
> Thanks,
> M. McDonnell
> 
Have you received this string in Python or in C? If the former, then 
just throw away the last character of the string you've received and 
you're done!

s = s[:-1]

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: time-based point system

2006-09-13 Thread Erik Max Francis
Jay wrote:

> Okay, this is a game.  So the points are abstract.  It's like an arcade
> game in respect to the points.  They don't actually mean or represent
> anything.  The only point is to get a high score.  The idea is that the
> faster the user acts (or reacts) the greater amount of points they'll
> receive.  Simplified, I need a fuction or statement that takes in a
> small number and spits out a big number.  The smaller the input, the
> larger the output.

There are any number of functions which fit this property, like f(x) = 
1/x.  You'll have to define more clearly what properties of this 
negative function you want to narrow it down beyond that.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Get married, but never to a man who is home all day.
-- George Bernard Shaw
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: time-based point system

2006-09-13 Thread Jay
Okay, this is a game.  So the points are abstract.  It's like an arcade
game in respect to the points.  They don't actually mean or represent
anything.  The only point is to get a high score.  The idea is that the
faster the user acts (or reacts) the greater amount of points they'll
receive.  Simplified, I need a fuction or statement that takes in a
small number and spits out a big number.  The smaller the input, the
larger the output.


Erik Max Francis wrote:
> Jay wrote:
>
> > I'm writing a game script and the point system will be based upon time.
> >  The less time there is between event one and event two, the higher
> > score you'll get for event two.  However, I've got a problem figuring
> > how to do this.  Here's why.  I don't want the score system to just be
> > a straight charted system.  Y'know, like if the time is between x and y
> > then the points you get are z.  I want to mathematically figure out the
> > pointage.  That's what I can't figure out how to do.  If it were such
> > that the more time there is, the more points there are, that would be
> > easy.  I could just multiply the time by something or other.  Or, if
> > there was a time limit between the two events, that, too, would be easy
> > because I could subtract the amount of time spent from the possible
> > amount of time and multiply by something for points.  Neither of these
> > are the case.  Any suggestions?
>
> You haven't indicated what _is_ the case, so this question cannot yet be
> answered.  You have to specify what the points measure, how they measure
> it, and how they change over time.  Once you do that, you can define (or
> get help defining) how to calculate them.  As it is you've not given
> nearly enough information to answer your question.
>
> --
> Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
>   San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
>Get married, but never to a man who is home all day.
> -- George Bernard Shaw

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


How do I converted a null (0) terminated string to a Python string?

2006-09-13 Thread Michael
Hi All,

I've received (via UDP) a null terminated string and need to convert it
into a Python string. Can anyone tell me how this is done? If it helps,
I know the number of characters in the string.

Thanks,
M. McDonnell

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


Re: Looking for the Perfect Editor

2006-09-13 Thread David J. Braden
stu wrote:
> Wildemar Wildenburger wrote:
>> Finally! I usually try to stay out of these discussions; yet I'm always
>> disappointed at how few people seem to be using jEdit and how long it
>> takes them to come out of their holes.
> 
> well when people start reccomending things like textpad which is crap.
> textpad requires payment, and if someone is gonna pay for it
> they might as well buy ultraedit instead..
> 
> but they need to atleast checkout jedit first :)
> 
> with its plugins for jython + jpydebug...
> 
> -stu
> 

Hi Stu und "Willie",

I'm a total newbie to Python, and what(for me) are appropriate tools. I 
will be running it under (sigh) Windows. I'm using IDLE for the time 
being, aided by Notepad++. I don't yet know what jython is about, or 
for, but I'm up for trying jedit for python. Which plugins give me a 
good start for scientific stuff? I am not interested in Web/html apps.
And is there an IDE out there that lets us create GUI dialogs along the 
lines of what MS provides with Excel and, I assume, VB?

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


Re: stock quotes

2006-09-13 Thread skip

don> I would like to download stock quotes from the web, store them, do
don> calculations and sort the results.  However I am fairly new and
don> don't have a clue how to parse the results of a web page download.
don> I can get to the site, but do not know how to request the certain
don> data need.  Does anyone know how to do this?  I would really
don> appreciate it.

Before you launch into a screen scraping exercise, you might want to check
around to see if there are any web services apis which already provide stock
quotes.  This might be a good place to start:

http://www.programmableweb.com/

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


Re: time-based point system

2006-09-13 Thread Erik Max Francis
Jay wrote:

> I'm writing a game script and the point system will be based upon time.
>  The less time there is between event one and event two, the higher
> score you'll get for event two.  However, I've got a problem figuring
> how to do this.  Here's why.  I don't want the score system to just be
> a straight charted system.  Y'know, like if the time is between x and y
> then the points you get are z.  I want to mathematically figure out the
> pointage.  That's what I can't figure out how to do.  If it were such
> that the more time there is, the more points there are, that would be
> easy.  I could just multiply the time by something or other.  Or, if
> there was a time limit between the two events, that, too, would be easy
> because I could subtract the amount of time spent from the possible
> amount of time and multiply by something for points.  Neither of these
> are the case.  Any suggestions?

You haven't indicated what _is_ the case, so this question cannot yet be 
answered.  You have to specify what the points measure, how they measure 
it, and how they change over time.  Once you do that, you can define (or 
get help defining) how to calculate them.  As it is you've not given 
nearly enough information to answer your question.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Get married, but never to a man who is home all day.
-- George Bernard Shaw
-- 
http://mail.python.org/mailman/listinfo/python-list


time-based point system

2006-09-13 Thread Jay
I'm writing a game script and the point system will be based upon time.
 The less time there is between event one and event two, the higher
score you'll get for event two.  However, I've got a problem figuring
how to do this.  Here's why.  I don't want the score system to just be
a straight charted system.  Y'know, like if the time is between x and y
then the points you get are z.  I want to mathematically figure out the
pointage.  That's what I can't figure out how to do.  If it were such
that the more time there is, the more points there are, that would be
easy.  I could just multiply the time by something or other.  Or, if
there was a time limit between the two events, that, too, would be easy
because I could subtract the amount of time spent from the possible
amount of time and multiply by something for points.  Neither of these
are the case.  Any suggestions?

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


Re: auto upgrade scripts?

2006-09-13 Thread alex23
[EMAIL PROTECTED] wrote:
> In my case I want my program to check for (e.g.) bug-fix releases on
> some location (network drive or ftp), and if available, allow to
> automatically download and install them.

Have you looked into PEAK's setuptools?

http://peak.telecommunity.com/DevCenter/setuptools
http://peak.telecommunity.com/DevCenter/EasyInstall
http://peak.telecommunity.com/DevCenter/PythonEggs

That might be a reasonable place to start.

-alex23

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


Re: FtpUtils Progress Bar

2006-09-13 Thread Timothy Smith
[EMAIL PROTECTED] wrote:
> Hi,
> I can successfully upload and download files using Stefan's Schwarzer's
> ftputil script.
>
> The problem is that as some of the files are quite large you cannot see
> how much has been downloaded/uploaded.
> Even a percentage or just dots going across the screen would be better
> than nothing.
>
> Does anyone have an example on how to show the progress of the
> upload/download when using ftputil?
>
> Thanks in advance.
>
> Kind regards
> Ian Cook
>
>   
try this

def _reporthook(numblocks, blocksize, filesize, url=None):
base = os.path.basename(url)
try:
percent = 
min((numblocks*blocksize*100)/filesize, 100)
except:
percent = 100
if numblocks != 0:
   print str(percent)+'%')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linear regression in 3 dimensions

2006-09-13 Thread David J. Braden
Andrew McLean wrote:
> Bernhard,
> 
> Levenberg-Marquardt is a good solution when you want to solve a general 
> non-linear least-squares problem. As Robert said, the OPs problem is 
> linear and Robert's solution exploits that. Using LM here is unnecessary 
> and I suspect a fair bit less efficient (i.e. slower).
> 
> - Andrew
> 
> 
> [EMAIL PROTECTED] wrote:
>> Hi Robert,
>>
>> I'm using the scipy package for such problems. In the submodule
>> scipy.optimize there is an implmentation of a least-square fitting
>> algorithm (Levenberg-Marquardt) called leastsq.
>>
>> You have to define a function that computes the residuals between your
>> model and the data points:
>>
>> import scipy.optimize
>>
>> def model(parameter, x, y):
>> a, b, c = parameter
>> return a*x + b*y + c
>>
>> def residual(parameter, data, x, y):
>> res = []
>> for _x in x:
>> for _y in y:
>> res.append(data-model(parameter,x,y)
>> return res
>>
>> params0 = [1., 1.,1.]
>> result = scipy.optimize.leastsq(resdiual, params0, (data,x,y))
>> fittedParams = result[0]
>>
>> If you haven't used numeric, numpy or scipy before, you should take a
>> look at an introduction. It uses some nice extended array objects,
>> where you can use some neat index tricks and compute values of array
>> items without looping through it.
>>
>> Cheers! Bernhard
>>

<>

Hi Bernhard,
I am just starting to learn Python; could you plz tell me specifically 
the introduction(s) you have in mind?

TIA,
DaveB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stock quotes

2006-09-13 Thread Larry Bates
Donlingerfelt wrote:
> I would like to download stock quotes from the web, store them, do
> calculations and sort the results.  However I am fairly new and don't have a
> clue how to parse the results of a web page download.   I can get to the
> site, but do not know how to request the certain data  need.  Does anyone
> know how to do this?  I would really appreciate it.  Thanks.
> 
> 
It depends:

If the HTML on the page(s) you want to process is clean and well formed it
can be pretty easy.  Download elementree from:

http://effbot.org/zone/element-index.htm

This will be included in Python 2.5 standard library, but for 2.4 and
older you need to download it.

If the HTML on the page(s) is not clean or well formed.  Parsing the
HTML can be "messey".  There is a module called BeautifulSoup that is
pretty good at this.  You will need to get it from:

http://www.crummy.com/software/BeautifulSoup/#Download

In addition you will want to use the standard library urllib module
to connect to and read the information you want to parse.

Start with urllib and get it to read your HTML first, then use either
elementtree or beautifulsoup to parse it and extract the data you
want to get.

Note: If the web page gets changed, it can break your program.

Hope information helps.

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


Re: Python to JavaScript Compiler? Anyone written such a beast?

2006-09-13 Thread Ben Finney
[EMAIL PROTECTED] writes:

> Of course, I'm not talking about something that would transform any
> Python code into semantically JavaScript code, but simply something
> that would analyze a "restricted" Python source file, and spit out
> equivalent JavaScript.

You may be looking for Pyjamas:

http://pyjamas.pyworks.org/>

-- 
 \Hercules Grytpype-Thynne: "Well, Neddie, I'm going to be |
  `\  frank."  Ned Seagoon: "Right, I'll be Tom."  Count Moriarty: |
_o__)"I'll be Gladys." *slap*  -- The Goon Show, _World War I_ |
Ben Finney

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


Re: stock quotes

2006-09-13 Thread George Sakkis
Donlingerfelt wrote:
> I would like to download stock quotes from the web, store them, do
> calculations and sort the results.  However I am fairly new and don't have a
> clue how to parse the results of a web page download.   I can get to the
> site, but do not know how to request the certain data  need.  Does anyone
> know how to do this?  I would really appreciate it.  Thanks.

This will get you started:
http://www.crummy.com/software/BeautifulSoup/

George

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


FtpUtils Progress Bar

2006-09-13 Thread iwcook58
Hi,
I can successfully upload and download files using Stefan's Schwarzer's
ftputil script.

The problem is that as some of the files are quite large you cannot see
how much has been downloaded/uploaded.
Even a percentage or just dots going across the screen would be better
than nothing.

Does anyone have an example on how to show the progress of the
upload/download when using ftputil?

Thanks in advance.

Kind regards
Ian Cook

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


Re: Scientific computing and data visualization.

2006-09-13 Thread David J. Braden
Fie Pye wrote:
> Hallo
>   
>   I would like to have a high class open source tools for scientific 
> computing and powerful 2D and 3D data visualisation. Therefore I chose 
> python, numpy and scipy as a base. Now I am in search for a visualisation 
> tool. I tried matplotlib and py_opendx with OpenDx. OpenDx seems to me very 
> good but the project py_opendx looks like closed. After py_opendx instalation 
> and subsequent testing I got an error that needs discussion with author or an 
> experienced user. Unfortunately a mail to author returned as undeliverable.
>   
>   Does anybody now about suitable visualisation tool?
>   
>   Does anybody have an experience with OpenDx and py_opendx instalation?
>   
>   Thanks for your response.
>   
>   fiepye
> 
> 
> 

What sort of "scientific computing" and visualization do you have in 
mind? I enjoy R for much of my work. See http://www.r-project.org/

Plz let us know what you have discovered, and what you have settled on.

Tchuss,
DaveB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to JavaScript Compiler? Anyone written such a beast?

2006-09-13 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Of course, I'm not talking about something that would transform
> any Python code into semantically JavaScript code, but simply
> something that would analyze a "restricted" Python source file,
> and spit out equivalent JavaScript. The big advantage (as far
> as I'm concerned) is that one could make use of some of the
> syntactic shortcuts that JavaScript doesn't offer, that the Python
> syntax checker generally does a better job than the JS one, and
> (perhaps most importantly) this could be configured to put in 
> 'instrumentation',
> such as checks to make sure than an attempt to access an undefined
> attribute actually throws an error.
> 
> Color me curious,
> Ken
> 
Take a look at the PyPy project, which has produced a JavaScript 
back-end (thugh I suspect it's more of a curiosity than a practical 
solution). It might suit your needs, though, and they've had a Summer of 
Code project going on it.

 http://codespeak.net/pypy/dist/pypy/doc/news.html

and specifically

 http://codespeak.net/pypy/dist/pypy/doc/getting-started.html

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread George Sakkis
Grant Edwards wrote:
> On 2006-09-13, John Henry <[EMAIL PROTECTED]> wrote:

> > So, if I understand you correctly, I must make the reference
> > to a more elaborate representation.  Like:
> >
> >i=[1,]
> >j=i
> >j[0]=2
> >print i
> >
> > in order to get 2 printed.
> >
> > Correct?
>
> I suppose, for some values of "correct".  You've bound the
> names "i" and "j" to the same mutable object, then mutated that
> object.  Afterwards "i" and "i" still refer to that mutated
> object.

Another way to explain why this is so, without fuzzy terms like "a more
elaborate representation", is that although the statements "x = 2" and
"x[0] = 2" look both as "assignments" syntactically, they work quite
differently under the hood. The former binds a name ("x") to an object
("2"). The latter is syntactic sugar for a method call:
x.__setitem__(0,2). If x happens to be a list, this is equivalent to
calling the unbound method list.__setitem__(x,0,2) which, as you
already know, mutates the list x. The important thing to remember
though is that the effect of something like "x[0] = 2" depends on the
type of x. Any class can define a __setitem__(index,value) method with
arbitrary semantics; it is not (and cannot be) forced to mutate x. The
bottom line is that you can't tell in advance what "x[0] = 2" will do
without knowing the type of x. A binding OTOH like "x=2" has always the
same semantics: make the name "x" refer to the object "2".

Similarly to "x[0] = 2", something like "x.foo = 2" looks like an
assignment but it's again syntactic sugar for a (different) method
call: x.__setattr__('foo',2). All the above about __setitem__ hold for
__setattr__ too.


HTH,
George

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


Python to JavaScript Compiler? Anyone written such a beast?

2006-09-13 Thread kenneth . m . mcdonald
Of course, I'm not talking about something that would transform
any Python code into semantically JavaScript code, but simply
something that would analyze a "restricted" Python source file,
and spit out equivalent JavaScript. The big advantage (as far
as I'm concerned) is that one could make use of some of the
syntactic shortcuts that JavaScript doesn't offer, that the Python
syntax checker generally does a better job than the JS one, and
(perhaps most importantly) this could be configured to put in 'instrumentation',
such as checks to make sure than an attempt to access an undefined
attribute actually throws an error.

Color me curious,
Ken

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


Re: threads and return values

2006-09-13 Thread Paul Rubin
Paul Rubin  writes:
> import Queue
> q = Queue()

Oops, meant 

  q = Queue.Queue()
-- 
http://mail.python.org/mailman/listinfo/python-list


stock quotes

2006-09-13 Thread Donlingerfelt
I would like to download stock quotes from the web, store them, do
calculations and sort the results.  However I am fairly new and don't have a
clue how to parse the results of a web page download.   I can get to the
site, but do not know how to request the certain data  need.  Does anyone
know how to do this?  I would really appreciate it.  Thanks.


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


Re: best small database?

2006-09-13 Thread Blair P. Houghton

Fredrik Lundh wrote:
> Blair P. Houghton wrote:
>
> > Can't be any harder than switching between incompatible filesystems,
> > unless you assume it should "just work...".
>
> so what file systems are you using that don't support file names and
> binary data ?

Mmmm, no.

I'm saying that the change from Oracle 9 to Oracle 10 is like changing
from ffs to fat32.

They have different structures related to the location and
identification of every stored object.  Sometimes different storage
structures (block sizes, block organization, fragmentation rules, etc.)
for the insides of a file.

A filesystem is a specialized database that stores generalized data.

The value of a database program and its data storage system is that you
can get the filesystem out of the way, and deal only in one layer of
searching and retrieval.

A DB may be only trivially more efficient when the data are a
collection of very large objects with a few externally associated
attributes that can all be found in the average filesystem's directory
structures; but a DB doing raw accesses on a bare disk is a big
improvement in speed when dealing with a huge collection of relatively
small data, each with a relatively large number of inconsistently
associated attributes.

The tradeoff is that you end up giving your DB vendor the option of
making you have to offload and reload that disk if they change their
system between versions.

--Blair

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


Re: threads and return values

2006-09-13 Thread Paul Rubin
Timothy Smith <[EMAIL PROTECTED]> writes:
> t = Thread(target=lambda:
> WeeklyReportPDF.MakeReport(self.UserNameValue,
> self.PassWordValue,ReportType,self.db))
> t.start()
> 
> which works just fine, BUT how do i get access to the return value of
> WeeklyReportPDF.MakeReport() ??

You can't.  Make the function send you a message through some
synchronized communication mechanism.  The Pythonic favorite way to do
that is with Queue, even when it's just one value (untested):

import Queue
q = Queue()
t = Thread(target = lambda q=q: q.put(WeeklyReportPDF.MakeReport(...)))
t.start()
...

Now if you say

value = q.get()

the caller will block until WeeklyReportPDF.MakeReport returns.  If
you say

value = q.get(False)

the False argument says not to block, so if WeeklyReportPDF.MakeReport
hasn't yet returned, q.get will raise the Queue.Empty exception, which
you can then catch and deal with.  Another arg lets you specify a
timeout:

value = q.get(False, 3.0)

blocks for up to 3 seconds, then raises Queue.Empty.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parameter files

2006-09-13 Thread gry
Russ wrote:
> I have a python module (file) that has a set of parameters associated
> with it. Let's say the module is called "code.py." I would like to keep
> the parameter assignments in a separate file so that I can save a copy
> for each "run" without having to save the entire code.py file. Let's
> say the parameter file is called "parameters.py."
>
> Normally, code.py would simply import the parameters.py file. However,
> I don't want the parameters to be accessible to any other file that
> imports the code.py file. to prevent such access, I preface the name of
> each parameter with an underscore. But then the parameters aren't even
> visible in code.py! So I decided to use "execfile" instead of import so
> the parameters are visible.
>
> That solved the problem, but I am just wondering if there is a better
> and/or more standard way to handle a situation like this. Any
> suggestions? Thanks.

I would try a configuration file, instead of a python module.
See ConfigParser:
.
You can save values for each "run" in a separate [section].
Execfile is a pretty big hammer for this.

-- George

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


threads and return values

2006-09-13 Thread Timothy Smith
say i'm issuing

t = Thread(target=lambda: WeeklyReportPDF.MakeReport(self.UserNameValue, 
self.PassWordValue,ReportType,self.db))
t.start()

which works just fine, BUT how do i get access to the return value of 
WeeklyReportPDF.MakeReport() ??

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


Re: How to build extensions on Windows?

2006-09-13 Thread John Machin
Martin v. Löwis wrote:
> John Machin schrieb:
> > Any support for the radical notion of the error message giving the full
> > path of the file that it's complaining about? If so, I'll lob in an
> > enhancement request in the morning ...
>
> A patch would be appreciated much more so.
>

Hi Martin, I do hope you don't regret opening Pandora's box :-)

Does the following look about right?
I was somewhat bemused by the limit of 200 bytes on the module name in
the error message-- I woild have thought about 20 was more appropriate.
Sorry but I can't test this (Windows box, don't have whatever version
of C compiler is necessary to compile Python).

Cheers,
John
8<---
--- Python/importdl.c.orig  2006-09-14 09:53:59.984375000 +1000
+++ Python/importdl.c   2006-09-14 09:55:53.62500 +1000
@@ -44,8 +44,8 @@
return NULL;
if (p == NULL) {
PyErr_Format(PyExc_ImportError,
-  "dynamic module does not define init function
(init%.200s)",
-shortname);
+  "dynamic module (%s) does not define init function
(init%.200s)",
+pathname, shortname);
return NULL;
}
 oldcontext = _Py_PackageContext;
8<---

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


Re: table (ascii text) lin ayout recognition

2006-09-13 Thread bearophileHUGS
Here you can find an improved version:

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

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


Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
Fuzzyman:
> Can you delete values from a dictionary whilst iterating over its items ?

Try the code, it works. I am not iterating on the dict, I am not using
dict.iteritems(), that produces a lazy iterable, I am using
dict.items() that produces a list of (key,value) pairs. And I am not
removing elements from that list :-)

Hugs,
bearophile

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


Re: Delete items in nested dictionary based on value.

2006-09-13 Thread John McMonagle

> 
> Assuming dict_sweep worked perfectly it would take input like this:
> 
> A_in = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}
> 
> B_in = {1: {1: {1: None, 2: {1: None}}, 2: 2, 3: None}
> 
> and output this:
> 
> A_out = {1: {2: 2, 3: {2: 2}}, 2: 2}
> 
> B_out = {2:2}
> 
> This dict_sweep above obviously doesn't work and I'm rather afraid of
> hitting python's recursion limit. Does anyone see a way to modify
> dict_sweep in it's current state to perform dictionary sweeps like
> this? What about a non-recursive implementation of dict_sweep?
> 

How about this:

A_in = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}

def dict_sweep(dictin):

for key in dictin.keys():   
if dictin.get(key) == None:
del dictin[key]
elif type(dictin[key]) is dict:
dictin[key] = dict_sweep(dictin[key])
return dictin

A_out = dict_sweep(A_in)
print A_out
 



Running the above returns:

{1: {2: 2, 3: {2: 2}}, 2: 2}

Regards,

John




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

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


Re: How to build extensions on Windows?

2006-09-13 Thread Fuzzyman

Martin v. Löwis wrote:
> Kevin D. Smith schrieb:
> > Then there is Mike Fletcher's web page
> > (http://www.vrplumber.com/programming/mstoolkit/) that describes in
> > detail how to build extensions, but most of the links to external
> > software are no longer valid.  I think it's safe to say that I am
> > completely lost, as there appears to be no authoritative, up-to-date
> > description on how to make this work.
>
> If all else fails, buy a copy of Visual Studio 2003. They are available
> fairly cheap at Ebay.
>

For some value of 'cheap'. They seem to go for about £100 on ebay in
the UK. :-(

More interestingly, someone reported on Python-dev recently a speed
improvement of around 30% (from memory) by compiling with VC 8. I know
the grumble (almost certainly correctly) about Microsoft's 'odd'
interpretation of the C standards in VC 8, but it looks like there are
major benefits to switching...

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Regards,
> Martin

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


Re: Delete items in nested dictionary based on value.

2006-09-13 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> Better:
>
> def clean(d):
> for key,val in d.items():
> if isinstance(val, dict):
> val = clean(val)
> if val is None or val == {}:
> del d[key]
> return d

Can you delete values from a dictionary whilst iterating over its items
?

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

>
> a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}
> print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2}
> b = {1: {1: {1: None, 2: {1: None}}}, 2: 2, 3: None}
> print clean(b) # Out: {2: 2}
> c = {1: {1: {1: None, 2: {1: None}}}, 2: 2, 3: 0}
> print clean(c) # Out: {2: 2, 3: 0}

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


Re: Delete items in nested dictionary based on value.

2006-09-13 Thread Dale Strickland-Clark
Brian L. Troutwine wrote:

> I've got a problem that I can't seem to get my head around and hoped
> somebody might help me out a bit:
> 
> I've got a dictionary, A, that is arbitarily large and may contains
> ints, None and more dictionaries which themselves may contain ints,
> None and more dictionaries. Each of the sub-dictionaries is also
> arbitrarily large. When pretty printing A, in the context I'm using A
> for, it's rather helpful to remove all key:value pairs where value is
> None. So I'd like to be able to define a function dict_sweep to recurse
> through A and del all the keys with None as a value.
> 
> I feel like the solution is right on the tip of my tounge, so to speak,
> but I just can't quite get it. Anyway, here's the best I've come up
> with:

How about this:

def dict_sweep(dictionary):
for k, v in dictionary.items():
if v is None:
del dictionary[k]
if type(v) == type({}):
dict_sweep(v)
#if len(v) == 0:
#   del dictionary[k]


A_in = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}

B_in = {1: {1: {1: None, 2: {1: None}}, 2: 2, 3: None}}

dict_sweep(A_in)
dict_sweep(B_in)
print A_in
print B_in

>>> {1: {2: 2, 3: {2: 2}}, 2: 2}
>>> {1: {2: 2}}


It doesn't produce the output you expect for B_in, but your brackets didn't
match and I'm not sure where the extra close should be. Also, I suspect
you're wanting to delete empty dictionaries but I don't see that mentioned
in the text. If that is so, include the two commented statements.
-- 
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

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


Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
Better:

def clean(d):
for key,val in d.items():
if isinstance(val, dict):
val = clean(val)
if val is None or val == {}:
del d[key]
return d

a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}
print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2}
b = {1: {1: {1: None, 2: {1: None}}}, 2: 2, 3: None}
print clean(b) # Out: {2: 2}
c = {1: {1: {1: None, 2: {1: None}}}, 2: 2, 3: 0}
print clean(c) # Out: {2: 2, 3: 0}

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


Status of PyXPCOM?

2006-09-13 Thread kenneth . m . mcdonald
I'm waiting for PyXPCOM with bated breath, but always have a
hard time figuring out what is actually happening with it--the
ActiveState mailing list is mostly inactive, and web searches
Always turn up very old, out of date pages. If it weren't for the 
fact that I know Mark Hammond is working,very, very hard on it,
I'd almost swear it was a dead project.

Is there a place to keep track of the status of this project?
I'm trying to write an application using FF as a base, but am of
course being hampered greatly by the limitations of JavaScript.
If I knew that PyXPCOM would, in a reasonable time frame,
be ready for pure Python/DOM guys like me (i.e. not C++/
XPCOM gurus) to let me interact with/program to the DOM
from Python, I'd just put off what I'm doing right now until
PyXPCOM was ready.

And of course, I'd really like to start contributing some DOM-
related Python code to the community also.

Thanks,
Ken

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


Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
My first try, not much tested:

def clean(d):
for key,val in d.items():
if isinstance(val, dict):
val = clean(val)
if not val:
del d[key]
return d

a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}
print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2}
b = {1: {1: {1: None, 2: {1: None}}}, 2: 2, 3: None}
print clean(b) # Out: {2: 2}

Recursivity overflow problem: you can increase the recursivity limit,
of if you think you need it after some tests on your real data, then
you can use a stack (a python list, using append and pop methods) to
simulate recursivity. You probably don't have 300+ levels of nesting.

Bye,
bearophile

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


Re: How to build extensions on Windows?

2006-09-13 Thread John Machin

Fredrik Lundh wrote:
> John Machin wrote:
>
> > Any support for the radical notion of the error message giving the full
> > path of the file that it's complaining about? If so, I'll lob in an
> > enhancement request in the morning ...
>
> there's always "python -vv", of course.

Thank you; I wasn't aware of that. Given that (as at 2.4.3) searching
the .chm docs for "interpreter", "command", and "option" don't yield
any pointers to the interpreter command line options, and given that
python -h gives no clue:
"""
-u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
 see man page for details on internal buffering relating to
'-u'
-v : verbose (trace import statements) (also PYTHONVERBOSE=x)
-V : print the Python version number and exit
-W arg : warning control (arg is action:message:category:module:lineno)
"""

could you please explain "of course"? I'm not sure how the general
populace could have known, apart from vague recollections of some Unix
utilities using a -v, -vv, -vvv etc convention.

TIA,
John

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


parameter files

2006-09-13 Thread Russ
I have a python module (file) that has a set of parameters associated
with it. Let's say the module is called "code.py." I would like to keep
the parameter assignments in a separate file so that I can save a copy
for each "run" without having to save the entire code.py file. Let's
say the parameter file is called "parameters.py."

Normally, code.py would simply import the parameters.py file. However,
I don't want the parameters to be accessible to any other file that
imports the code.py file. to prevent such access, I preface the name of
each parameter with an underscore. But then the parameters aren't even
visible in code.py! So I decided to use "execfile" instead of import so
the parameters are visible.

That solved the problem, but I am just wondering if there is a better
and/or more standard way to handle a situation like this. Any
suggestions? Thanks.

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


Delete items in nested dictionary based on value.

2006-09-13 Thread Brian L. Troutwine
I've got a problem that I can't seem to get my head around and hoped
somebody might help me out a bit:

I've got a dictionary, A, that is arbitarily large and may contains
ints, None and more dictionaries which themselves may contain ints,
None and more dictionaries. Each of the sub-dictionaries is also
arbitrarily large. When pretty printing A, in the context I'm using A
for, it's rather helpful to remove all key:value pairs where value is
None. So I'd like to be able to define a function dict_sweep to recurse
through A and del all the keys with None as a value.

I feel like the solution is right on the tip of my tounge, so to speak,
but I just can't quite get it. Anyway, here's the best I've come up
with:

def dict_sweep(dictionary, key_value):
"""Sweep through dictionary, deleting any key:value where
value is None.

"""
# Find key at position key_value.
key = dictionary.keys()[key_value]

# If the key value is a dictionary we want to move into it.
# Therefore we call rec_rem on dictionary[key] with a
# key_value of 0
if type(dictionary[key]) is type({}):
dict_sweep(dictionary[key], 0)

# If the value isn't a dictionary we care only that it's not None.
# If it is None we nuke it and call rec_rem on the current
# dictionary with key_value incrimented by one.
elif dictionary[key] is None:
del dictionary[key]
dict_sweep(dictionary, key_value+1)

# If the value isn't a dictionary and the value isn't None then
# we still want to walk through to the next value in the
# dictionary, so call rec_rem with key_value+1
else:
dict_sweep(dictionary, key_value+1)

Assuming dict_sweep worked perfectly it would take input like this:

A_in = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}

B_in = {1: {1: {1: None, 2: {1: None}}, 2: 2, 3: None}

and output this:

A_out = {1: {2: 2, 3: {2: 2}}, 2: 2}

B_out = {2:2}

This dict_sweep above obviously doesn't work and I'm rather afraid of
hitting python's recursion limit. Does anyone see a way to modify
dict_sweep in it's current state to perform dictionary sweeps like
this? What about a non-recursive implementation of dict_sweep?

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


Statistical distribution of object size

2006-09-13 Thread [EMAIL PROTECTED]
Hi,

In a typical heavy-use python application (say running Zope for
dukehealth.org) what is the (statistical) distribution of the the size
of objects? (i.e. start up server, stop time when it has been under
load for a few hours, and put each object into a bucket marked with the
number of bytes it is allocated, and maybe labeled with object type,
say dict, list, other). Does anyone know of any research on this?

I would do this myself, but my website only has one user...

Thanks for any info,
David

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


Re: how are dictionary literals handled by the interpreter?

2006-09-13 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> > I wrote up a quick little set of tests, I was acutally comparing ways
> > of doing "case" behavior just to get some performance information.  Now
> > two of my test cases had almost identical results which was not at all
> > what I expected.  Ultimately I realized I don't really know how
> > literals are treated within the interpreter.
> >
> > The two implementations I was looking at were:
> >
> > class caseFunction(object):
> > def __init__(self):
> > self.caseDict = {'a':"retval = 'a'",
> > 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
> >
> > "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
> >  "i":"retval='i'"}
> >
> > def doIt(self,a):
> > exec(self.caseDict.get(a))
> > return retval
>
> Have you considered eliminating the exec() wart just doing:
Sorry I misread exec as dict in my earlier reply.  I did have another
class based implementation that used functions in the class.  That was
the only one that performed well against if/else.  And only for large
number of cases.  When I compared the two implementations I stated here
- that's where I wondered about my understanding of dictionary literals
with regards to performance.  I could also rewrite the function version
to store functions in the dictionary instead of statements for exec -
but here I was just wanting to compare retrieving a dictionary class
member, vs reading a dictionary literal.  I think the code did a good
job of isolating that as the only change - and that is validated by
using the dissassembler.

>
> self.caseDict = {'a'='a', 'b'='b'}
> 
> def doIt(self, a):
> return self.caseDict[a]
>
> (or the get call)
> Or for more complex cases going with something like:
>
> class caseFunction(object):
> def __init__(self):
> self.caseDict = {'a':self.do_a, 'b':self.do_b}
> def do_a(self):
> return 'a'
> def do_b(self):
> return 'b'
> def doIt(self, a):
> return self.caseDict[a]()
>
> or eliminating the init and
> def doIt(self, a):
> return getattr(self, "do_"+a)()
>
> ?  Obviously with these two you might want a bit more complexity for a
> default if the attribute/dict entry is missing, but the simple case
> shows the idea.

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


Re: how are dictionary literals handled by the interpreter?

2006-09-13 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> > I wrote up a quick little set of tests, I was acutally comparing ways
> > of doing "case" behavior just to get some performance information.  Now
> > two of my test cases had almost identical results which was not at all
> > what I expected.  Ultimately I realized I don't really know how
> > literals are treated within the interpreter.
> >
> > The two implementations I was looking at were:
> >
> > class caseFunction(object):
> > def __init__(self):
> > self.caseDict = {'a':"retval = 'a'",
> > 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
> >
> > "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
> >  "i":"retval='i'"}
> >
> > def doIt(self,a):
> > exec(self.caseDict.get(a))
> > return retval
>
> Have you considered eliminating the exec() wart just doing:

thr dict wart was added - needlessly simply to see if there was a
difference.  case4 was a reaction to the odd timings.  I wouldn't use
it ever in the real world as it is totally unnecessary.

>
> self.caseDict = {'a'='a', 'b'='b'}
> 
> def doIt(self, a):
> return self.caseDict[a]
>
> (or the get call)
> Or for more complex cases going with something like:
>
> class caseFunction(object):
> def __init__(self):
> self.caseDict = {'a':self.do_a, 'b':self.do_b}
> def do_a(self):
> return 'a'
> def do_b(self):
> return 'b'
> def doIt(self, a):
> return self.caseDict[a]()
>
> or eliminating the init and
> def doIt(self, a):
> return getattr(self, "do_"+a)()
>

This is clever, but really only works for this contrived example.  If I
wanted to base my cases on an object Still I like it's elimination
of seemingly redundant dictionary.  The original purpose of all of this
was to get a feel for performance differences between endless if/else
statements and a dictionary for performing switch/case type stuff.

The upshot of all of this, is I will probably stick to the if/else
construct except for fairly complex cases for two reasons

1) only in the most braindead version of an if/else construction  is
dictionary faster for small (ie less than 20) different cases.
2) dictionary method won't work if I want an switch could match
multiple case conditions




> ?  Obviously with these two you might want a bit more complexity for a
> default if the attribute/dict entry is missing, but the simple case
> shows the idea.

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


Re: win32service (wxpython) -- i cannot install service

2006-09-13 Thread Larry Bates
Larry Bates wrote:
> kkt49 wrote:
>> under code service install => ok
>>
>> _svc_name_ = r'moin_service'
>> _svc_display_name_ = r'moin_service'
>> start_cmd = r"c:\mmde\moin.exe"
>> #info = ['', '', '']
>>
>> def __init__(self):
>> #self._svc_name = info[0]
>> #self._svc_display_name_ = info[1]
>> #self.start_cmd = info[2]
>>
>> but, i want dynamic _svc_name_  and start_cmd
> 
> Services aren't dynamic in nature.  They are static, are
> given names (that are used to start, stop, etc.) and get
> installed into servicemanager on Windows workstation or
> server.  Their behavior could be dynamic, that is you could
> change what they do by communicating with them via external
> means.
> 
> I think you better back up and tell us what you are trying
> to do at a higher level.  Perhaps we can help more.
> 
> -Larry

Sorry, after I clicked send I "think" I understand what you
want.  You can't make a .EXE program run as a service by
starting it as a service.  If thats not what you are trying
to do, give us some more high-level info about what it is
that you are trying to accomplish.

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


Re: win32service (wxpython) -- i cannot install service

2006-09-13 Thread Larry Bates
kkt49 wrote:
> under code service install => ok
> 
> _svc_name_ = r'moin_service'
> _svc_display_name_ = r'moin_service'
> start_cmd = r"c:\mmde\moin.exe"
> #info = ['', '', '']
> 
> def __init__(self):
> #self._svc_name = info[0]
> #self._svc_display_name_ = info[1]
> #self.start_cmd = info[2]
> 
> but, i want dynamic _svc_name_  and start_cmd

Services aren't dynamic in nature.  They are static, are
given names (that are used to start, stop, etc.) and get
installed into servicemanager on Windows workstation or
server.  Their behavior could be dynamic, that is you could
change what they do by communicating with them via external
means.

I think you better back up and tell us what you are trying
to do at a higher level.  Perhaps we can help more.

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


Re: how are dictionary literals handled by the interpreter?

2006-09-13 Thread [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
> I wrote up a quick little set of tests, I was acutally comparing ways
> of doing "case" behavior just to get some performance information.  Now
> two of my test cases had almost identical results which was not at all
> what I expected.  Ultimately I realized I don't really know how
> literals are treated within the interpreter.
>
> The two implementations I was looking at were:
>
> class caseFunction(object):
> def __init__(self):
> self.caseDict = {'a':"retval = 'a'",
> 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
>
> "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
>  "i":"retval='i'"}
>
> def doIt(self,a):
> exec(self.caseDict.get(a))
> return retval

Have you considered eliminating the exec() wart just doing:

self.caseDict = {'a'='a', 'b'='b'}

def doIt(self, a):
return self.caseDict[a]

(or the get call)
Or for more complex cases going with something like:

class caseFunction(object):
def __init__(self):
self.caseDict = {'a':self.do_a, 'b':self.do_b}
def do_a(self):
return 'a'
def do_b(self):
return 'b'
def doIt(self, a):
return self.caseDict[a]()

or eliminating the init and
def doIt(self, a):
return getattr(self, "do_"+a)()

?  Obviously with these two you might want a bit more complexity for a
default if the attribute/dict entry is missing, but the simple case
shows the idea.

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


Re: Python blogging software

2006-09-13 Thread Fuzzyman

Cliff Wells wrote:
> On Wed, 2006-09-13 at 08:22 -0700, Fuzzyman wrote:
> > Cliff Wells wrote:
> > > On Wed, 2006-09-13 at 00:29 -0700, Cliff Wells wrote:
> > >
> > > > Anyone aware of any functional (doesn't need to be complete, beta is
> > > > fine) blog software written in Python?
> > >
> > > Hmph.  And as soon as I hit send I find
> > >
> > >  http://wiki.python.org/moin/PythonBlogSoftware
> > >
> > > Okay, so is there any *not* on that list that should be considered (and
> > > perhaps added to the list)?
> >
> > Firedrop2 is a client-side blog program (generates static HTML to be
> > uploaded to your webserver).
>
> I looked at this but didn't care for it as it doesn't appear to allow
> for comments (feature-wise it's a few steps down from Frog, which I
> already have working).
>

Because it is client side (rather than running on the server), it has
no built in comments facility. I use Haloscan for comments, but I'm
always on the look out for a neat comments system to integrate with
Firedrop.

I personally prefer the 'client side' approach, as it makes migrating
content to another server trivially easy.

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


ReadError, "not a bzip2 file"

2006-09-13 Thread itzel
Hello!!
In using tarfile to group thousands of small files from a directory and
then compress it. I already compress a group of files in my pc, but I
need do it in a server and I'm testing the same procedure, but it
doesn't work . A "ReadError" appear: "not a bzip2 file". I'm using this
script:

import os
import tarfile

dstfolder = '/somepath/to/output'## server
fileorfoldertobackup = '/home/username'  ##  server
dst = '%s.tar.bz2' % os.path.join(dstfolder,
os.path.basename(fileorfoldertobackup))
out = tarfile.TarFile.open(dst, 'w:bz2')
out.add(fileorfoldertobackup,
arcname=os.path.basename(fileorfoldertobackup))
out.close()

What I´m doing wrong? Is necesary install a python version into the
server??

Thanks!!

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


Re: Looking for the Perfect Editor

2006-09-13 Thread stu

Wildemar Wildenburger wrote:
>
> Finally! I usually try to stay out of these discussions; yet I'm always
> disappointed at how few people seem to be using jEdit and how long it
> takes them to come out of their holes.

well when people start reccomending things like textpad which is crap.
textpad requires payment, and if someone is gonna pay for it
they might as well buy ultraedit instead..

but they need to atleast checkout jedit first :)

with its plugins for jython + jpydebug...

-stu

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


Re: how are dictionary literals handled by the interpreter?

2006-09-13 Thread [EMAIL PROTECTED]

Jason wrote:
> [EMAIL PROTECTED] wrote:
> > I wrote up a quick little set of tests, I was acutally comparing ways
> > of doing "case" behavior just to get some performance information.  Now
> > two of my test cases had almost identical results which was not at all
> > what I expected.  Ultimately I realized I don't really know how
> > literals are treated within the interpreter.
> >

the lengthy dictionaries were due to my initial testing comparing
if/ifelse constructs to dictionary cases.. btw if/ifelse seems a lot
faster till you get to at least 12 cases, and for most applications,
the number of cases would be even higher before dictionaries beat a
bunch of ifs

> > The two implementations I was looking at were:
> >
> > class caseFunction(object):
> > def __init__(self):
> > self.caseDict = {'a':"retval = 'a'",
> > 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
> >
> > "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
> >  "i":"retval='i'"}
> >
> > def doIt(self,a):
> > exec(self.caseDict.get(a))
> > return retval
> >
> >
> >
> > def caseFunc3(a):
> > exec(  {'a':"retval = 'a'",
> > 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
> >
> > "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
> >  "i":"retval='i'"}.get(a))
> > return retval
> >
> >
> > I had expected caseFunc3 to be slower.  I had thought the interpreter
> > would be recreating the dictionary each time, but that doesn't seem to
> > be the case since performance of the class version and the function
> > version are nearly identical on most runs.  If i rewrite caseFunc3 as:
> >
> > def caseFunc4(a):
> > exec(  dict({'a':"retval = 'a'",
> > 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
> >
> > "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
> >  "i":"retval='i'"}).get(a))
> > return retval
> >
> > now with the explicit use of dict, i see the performace of the
> > functional version decline as I initially expected.
> >
> > So what is happeneing in caseFunc3.  It seems as though the literal is
> > "cached".  The other hypothesis I came up with is the name lookup for
> > self.caseDict takes the same amount of time as creating the dictionary
> > literal - but that doesn't make sense to me.
> >
> > Thanks
>
> Why not check to see what the interpreter is doing?  Rather than
> dealing with your overly complicated dictionaries, I've made a simple,
> one case dictionary.  I've also done a similar bit to replicate your
> doIt method.
>
Thanks, i didn't know about dis.  So this is very useful.

> >>> def case3(a):
> ... exec( {'a': "retval = 'a'"}.get(a) )
> ... return retval
> ...
> >>> case3('a')
> 'a'
> >>> def case4(a):
> ... exec( dict({'a': "retval = 'a'"}).get(a) )
> ... return retval
> ...
> >>> case4('a')
> 'a'
> >>> class caseFunction(object):
> ... def doIt(self, a):
> ... exec(self.caseDict.get(a))
> ... return retval
> ...
>
> Then, use the dis module to disassemble the function objects:
> >>> import dis
> >>> dis.dis(case3)
>   2   0 BUILD_MAP0
>   3 DUP_TOP
>   4 LOAD_CONST   1 ('a')
>   7 LOAD_CONST   2 ("retval = 'a'")
>  10 ROT_THREE
>  11 STORE_SUBSCR
>  12 LOAD_ATTR0 (get)
>  15 LOAD_FAST0 (a)
>  18 CALL_FUNCTION1
>  21 LOAD_CONST   0 (None)
>  24 DUP_TOP
>  25 EXEC_STMT
>
>   3  26 LOAD_NAME2 (retval)
>  29 RETURN_VALUE
> >>> dis.dis(case4)
>   2   0 LOAD_NAME0 (dict)
>   3 BUILD_MAP0
>   6 DUP_TOP
>   7 LOAD_CONST   1 ('a')
>  10 LOAD_CONST   2 ("retval = 'a'")
>  13 ROT_THREE
>  14 STORE_SUBSCR
>  15 CALL_FUNCTION1
>  18 LOAD_ATTR1 (get)
>  21 LOAD_FAST0 (a)
>  24 CALL_FUNCTION1
>  27 LOAD_CONST   0 (None)
>  30 DUP_TOP
>  31 EXEC_STMT
>
>   3  32 LOAD_NAME3 (retval)
>  35 RETURN_VALUE
> >>> dis.dis(caseFunction.doIt)
>   3   0 LOAD_FAST0 (self)
>   3 LOAD_ATTR1 (caseDict)
>   6 LOAD_ATTR2 (get)
>   9 LOAD_FAST1 (a)
>  12 CALL_FUNCTION1
>  15 LOAD_CONST   0 (None)
>  18 DUP_TOP
>  19 EXEC_STMT
>
>   4  20 LOAD_NAME4 (retval)
>  23 RETURN_VALUE
> >>>
>
> Take a look at what happens before the 'get' attribute is l

Re: Python blogging software

2006-09-13 Thread Cliff Wells
On Wed, 2006-09-13 at 08:22 -0700, Fuzzyman wrote:
> Cliff Wells wrote:
> > On Wed, 2006-09-13 at 00:29 -0700, Cliff Wells wrote:
> >
> > > Anyone aware of any functional (doesn't need to be complete, beta is
> > > fine) blog software written in Python?
> >
> > Hmph.  And as soon as I hit send I find
> >
> >  http://wiki.python.org/moin/PythonBlogSoftware
> >
> > Okay, so is there any *not* on that list that should be considered (and
> > perhaps added to the list)?
> 
> Firedrop2 is a client-side blog program (generates static HTML to be
> uploaded to your webserver).

I looked at this but didn't care for it as it doesn't appear to allow
for comments (feature-wise it's a few steps down from Frog, which I
already have working).

For anyone who's interested, what I finally settled on was Bitakora.  It
violated one of my own requirements (it runs on Zope), but because it's
multiuser and quite featureful and modern, the tradeoff seemed worth it:
  
http://www.codesyntax.com/bitakora/about

I will say that installing it was something of a pain.  If the Zope guys
want to know why Zope has been left behind, one of the first things I'd
suggest is to clean up zope.org.  Bitakora has several dependencies and
nearly all of the links to these dependencies led me on a wild goose
chase of broken links, multiple incompatible versions, incompatible
forks, etc.  

For those who might follow in my footsteps, the dependencies (with
correct links to correct versions) are:

Epoz: http://iungo.org/products/Epoz/
Localizer: http://www.ikaaro.org/localizer
TextIndexNG2: http://opensource.zopyx.biz/OpenSource/TextIndexNG
CookieCrumbler: http://hathawaymix.org/Software/CookieCrumbler

It also depends on BTreeFolder2, but that's included in the latest Zope
2.8 series.

I think the worst of all of these was surprisingly Epoz.  There are at
least three distinct branches of this product: the original
(deprecated), it's replacement (kupu), and a fork (which happens to be
the correct one).  The information on zope.org gives little indication
that there might be such a fork (but is quite happy to lead you in
circles).  I noticed that several of the products mentioned the pain of
maintaining software on zope.org (and so had moved their software
elsewhere), so this is probably the root of the problem.

Anyway, Zope complaints aside, Bitakora is really great and I'd
recommend that anyone looking for a friendly, multiuser blog take a
look.


Regards,
Cliff


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


Re: urllib en https

2006-09-13 Thread Cecil Westerhof
Cecil Westerhof wrote:

> Something went wrong with my last post. So, again:
> 
> I have a strange problem. I wrote a script that uses urllib.urlopen to
> fetch a page through https. In Python 2.2.2 this works without a problem.
> But when I use the script in Python 2.4.1 (which is more recent) I get:
> 
> Traceback (most recent call last):
> File "", line 1, in ?
> File "/usr/local/lib/python2.4/urllib.py", line 79, in urlopen
> return opener.open(url, data)
> File "/usr/local/lib/python2.4/urllib.py", line 177, in open
> return self.open_unknown(fullurl, data)
> File "/usr/local/lib/python2.4/urllib.py", line 189, in open_unknown
> raise IOError, ('url error', 'unknown url type', type)
> IOError: [Errno url error] unknown url type: 'https'

I found the problem. The first Python was compiled with ssl support enabled
and the second without ssl support enabled.

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

Re: When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread John Henry
Thanks for the reply, Grant.

I am not doing things like that - I am just trying to clear up in my
mind the Python concepts.

I understand it now.



Grant Edwards wrote:
> On 2006-09-13, John Henry <[EMAIL PROTECTED]> wrote:
> > Thanks for the reply, both to Laszlo and Steve.
> >
> > Okay, I understand what you're saying.
> >
> > But what if I need to make a "pointer" to a simple variable.
>
> There's no such thing as a "simple variable".  There are
> mutable objects and immutable objects.  Names are bound to
> objects.
>
>   x = 3
>
> The name "x" is bound to an immutable integer object who's
> value is 3.
>
> > For instance, in C:
> >
> >int i=1
> >int *j=&i
> >
> >*j = 2
> >print i
> >
> > and you get 2 printed.
> >
> > In Python,
> >
> >i=1
>
> The name "i" is bound to an immutable integer object who's value is 1.
>
> >j=i
>
> The name "j" is bound to an immutable integer object who's
> value is 1. That may or may not be the same object to which
> "i" is bound.
>
> >j=2
>
> Now the name "j" is bound to an immutable integer object who's
> value is 2.  Rebinding the name "j" to a different object has
> no effect on the object to which "i" is bound.
>
> >print i
> >
> > and you get 1 printed.
>
> Because you've changed neither the object to which "i" is bound
> nor the value of that object (you can't change the values of
> integer objects).
>
> > So, if I understand you correctly, I must make the reference
> > to a more elaborate representation.  Like:
> >
> >i=[1,]
> >j=i
> >j[0]=2
> >print i
> >
> > in order to get 2 printed.
> >
> > Correct?
>
> I suppose, for some values of "correct".  You've bound the
> names "i" and "j" to the same mutable object, then mutated that
> object.  Afterwards "i" and "i" still refer to that mutated
> object.
>
> That'll work as a rather clumsy imitation of the C code, but I
> don't really see what it is you're trying to accomplish. Trying
> to write C code using Python isn't going to be fun or productive[1].
>
> When using Python, you should write Python code. ;)
>
> If you'll explain the actual problem you're trying solve for
> which you think you need C-style "pointers", then somebody will
> be happy to show you how that problem is solved using Python.
>
> [1] There are people here who probably think it fun, but only
> as a brain-teaser.
>
> --
> Grant Edwards   grante Yow!  After THIS, let's go
>   at   to PHILADELPHIA and have
>visi.comTRIPLETS!!

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


Re: urllib en https

2006-09-13 Thread [EMAIL PROTECTED]
please provide a sample program, which has the minimal functionality
necessary to reproduce this error. I've checked and the syntax hasn't
changed. Perhaps it's with the string you are passing as "fullurl".
Anyways, I can't really troubleshoot more than that without some code.

Cecil Westerhof wrote:
> Something went wrong with my last post. So, again:
>
> I have a strange problem. I wrote a script that uses urllib.urlopen to fetch
> a page through https. In Python 2.2.2 this works without a problem. But
> when I use the script in Python 2.4.1 (which is more recent) I get:
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/local/lib/python2.4/urllib.py", line 79, in urlopen
> return opener.open(url, data)
>   File "/usr/local/lib/python2.4/urllib.py", line 177, in open
> return self.open_unknown(fullurl, data)
>   File "/usr/local/lib/python2.4/urllib.py", line 189, in open_unknown
> raise IOError, ('url error', 'unknown url type', type)
> IOError: [Errno url error] unknown url type: 'https'
> 
> What is happening here? And how can I solve this?

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


Re: When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread Grant Edwards
On 2006-09-13, John Henry <[EMAIL PROTECTED]> wrote:
> Thanks for the reply, both to Laszlo and Steve.
>
> Okay, I understand what you're saying.
>
> But what if I need to make a "pointer" to a simple variable.

There's no such thing as a "simple variable".  There are
mutable objects and immutable objects.  Names are bound to
objects.

  x = 3

The name "x" is bound to an immutable integer object who's
value is 3.  

> For instance, in C:
>
>int i=1
>int *j=&i
>
>*j = 2
>print i
>
> and you get 2 printed.
>
> In Python,
>
>i=1

The name "i" is bound to an immutable integer object who's value is 1.

>j=i

The name "j" is bound to an immutable integer object who's
value is 1. That may or may not be the same object to which
"i" is bound.

>j=2

Now the name "j" is bound to an immutable integer object who's
value is 2.  Rebinding the name "j" to a different object has
no effect on the object to which "i" is bound.

>print i
>
> and you get 1 printed.

Because you've changed neither the object to which "i" is bound
nor the value of that object (you can't change the values of
integer objects).

> So, if I understand you correctly, I must make the reference
> to a more elaborate representation.  Like:
>
>i=[1,]
>j=i
>j[0]=2
>print i
>
> in order to get 2 printed.
>
> Correct?

I suppose, for some values of "correct".  You've bound the
names "i" and "j" to the same mutable object, then mutated that
object.  Afterwards "i" and "i" still refer to that mutated
object.

That'll work as a rather clumsy imitation of the C code, but I
don't really see what it is you're trying to accomplish. Trying
to write C code using Python isn't going to be fun or productive[1]. 

When using Python, you should write Python code. ;)

If you'll explain the actual problem you're trying solve for
which you think you need C-style "pointers", then somebody will
be happy to show you how that problem is solved using Python.

[1] There are people here who probably think it fun, but only
as a brain-teaser.

-- 
Grant Edwards   grante Yow!  After THIS, let's go
  at   to PHILADELPHIA and have
   visi.comTRIPLETS!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how are dictionary literals handled by the interpreter?

2006-09-13 Thread Jason
[EMAIL PROTECTED] wrote:
> I wrote up a quick little set of tests, I was acutally comparing ways
> of doing "case" behavior just to get some performance information.  Now
> two of my test cases had almost identical results which was not at all
> what I expected.  Ultimately I realized I don't really know how
> literals are treated within the interpreter.
>
> The two implementations I was looking at were:
>
> class caseFunction(object):
> def __init__(self):
> self.caseDict = {'a':"retval = 'a'",
> 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
>
> "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
>  "i":"retval='i'"}
>
> def doIt(self,a):
> exec(self.caseDict.get(a))
> return retval
>
>
>
> def caseFunc3(a):
> exec(  {'a':"retval = 'a'",
> 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
>
> "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
>  "i":"retval='i'"}.get(a))
> return retval
>
>
> I had expected caseFunc3 to be slower.  I had thought the interpreter
> would be recreating the dictionary each time, but that doesn't seem to
> be the case since performance of the class version and the function
> version are nearly identical on most runs.  If i rewrite caseFunc3 as:
>
> def caseFunc4(a):
> exec(  dict({'a':"retval = 'a'",
> 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
>
> "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
>  "i":"retval='i'"}).get(a))
> return retval
>
> now with the explicit use of dict, i see the performace of the
> functional version decline as I initially expected.
>
> So what is happeneing in caseFunc3.  It seems as though the literal is
> "cached".  The other hypothesis I came up with is the name lookup for
> self.caseDict takes the same amount of time as creating the dictionary
> literal - but that doesn't make sense to me.
>
> Thanks

Why not check to see what the interpreter is doing?  Rather than
dealing with your overly complicated dictionaries, I've made a simple,
one case dictionary.  I've also done a similar bit to replicate your
doIt method.

>>> def case3(a):
... exec( {'a': "retval = 'a'"}.get(a) )
... return retval
...
>>> case3('a')
'a'
>>> def case4(a):
... exec( dict({'a': "retval = 'a'"}).get(a) )
... return retval
...
>>> case4('a')
'a'
>>> class caseFunction(object):
... def doIt(self, a):
... exec(self.caseDict.get(a))
... return retval
...

Then, use the dis module to disassemble the function objects:
>>> import dis
>>> dis.dis(case3)
  2   0 BUILD_MAP0
  3 DUP_TOP
  4 LOAD_CONST   1 ('a')
  7 LOAD_CONST   2 ("retval = 'a'")
 10 ROT_THREE
 11 STORE_SUBSCR
 12 LOAD_ATTR0 (get)
 15 LOAD_FAST0 (a)
 18 CALL_FUNCTION1
 21 LOAD_CONST   0 (None)
 24 DUP_TOP
 25 EXEC_STMT

  3  26 LOAD_NAME2 (retval)
 29 RETURN_VALUE
>>> dis.dis(case4)
  2   0 LOAD_NAME0 (dict)
  3 BUILD_MAP0
  6 DUP_TOP
  7 LOAD_CONST   1 ('a')
 10 LOAD_CONST   2 ("retval = 'a'")
 13 ROT_THREE
 14 STORE_SUBSCR
 15 CALL_FUNCTION1
 18 LOAD_ATTR1 (get)
 21 LOAD_FAST0 (a)
 24 CALL_FUNCTION1
 27 LOAD_CONST   0 (None)
 30 DUP_TOP
 31 EXEC_STMT

  3  32 LOAD_NAME3 (retval)
 35 RETURN_VALUE
>>> dis.dis(caseFunction.doIt)
  3   0 LOAD_FAST0 (self)
  3 LOAD_ATTR1 (caseDict)
  6 LOAD_ATTR2 (get)
  9 LOAD_FAST1 (a)
 12 CALL_FUNCTION1
 15 LOAD_CONST   0 (None)
 18 DUP_TOP
 19 EXEC_STMT

  4  20 LOAD_NAME4 (retval)
 23 RETURN_VALUE
>>>

Take a look at what happens before the 'get' attribute is loaded in
each case.  In case 3, you've simply created a dictionary literal,
which is a very fast operation under Python.  In case 4, you've created
a dictionary literal, then you call the dict() function.  The dict
function will create a dictionary from the supplied dictionary, and
return the shallow copy.

Case 3 is slower, but the Python developers have worked to make
dictionary creation and look-up very fast.  Did you use the timeit
module to test your functions?

--Jason

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


Colorado Python seminar in November

2006-09-13 Thread Mark Lutz
Just a reminder that the Fall 2006 Colorado Python seminar
is now less than 2 months away.  Space is limited, so plan
now to come join us for a week of in-depth Python training
in the Colorado Rockies.  For details, please see the
original announcement below.



Mark Lutz's Python Training Services is pleased to announce
that our Fall 2006 public Colorado seminar is now open.
This 5-day Python training event will be held November 6
through November 10.

This year, our Fall seminar will be held at Historic Crag's
Lodge, a resort in Estes Park, Colorado.  Estes Park is a
mountain town 80 miles from Denver's airport, and gateway
to Rocky Mountain National Park.

This in an all-inclusive event.  Come spend 5 days mastering
Python in the beautiful Colorado Rockies, and let us handle
the details of your visit.  We will be providing students
with rooms at the resort, three full meals per day, a guided
sightseeing tour, shuttle service to and from the Denver
airport, and our new "Snake Charmers" T-shirt.

Besides the included amenities, the extended format of this
session will allow for in-depth coverage of class topics.
Like all our public classes, this seminar will be taught by
best-selling Python author and trainer Mark Lutz, and is
open to individual enrollments.

For more details, please see our web page:

http://home.earthlink.net/~python-training/public.html

--Python Training Services

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


Re: When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread John Henry
Thanks for the reply, both to Laszlo and Steve.

Okay, I understand what you're saying.

But what if I need to make a "pointer" to a simple variable.

For instance, in C:

   int i=1
   int *j=&i

   *j = 2
   print i

and you get 2 printed.

In Python,

   i=1
   j=i
   j=2
   print i

and you get 1 printed.

So, if I understand you correctly, I must make the reference to a more
elaborate representation.  Like:

   i=[1,]
   j=i
   j[0]=2
   print i

in order to get 2 printed.

Correct?


Steve Holden wrote:
> John Henry wrote:
> > Hi list,
> >
> > Just to make sure I understand this.
> >
> > Since there is no "pointer" type in Python, I like to know how I do
> > that.
> >
> > For instance, if I do:
> >
> >...some_huge_list is a huge list...
> >some_huge_list[0]=1
> >aref = some_huge_list
> >aref[0]=0
> >print some_huge_list[0]
> >
> > we know that the answere will be 0.  In this case, aref is really a
> > reference.
> >
> > But what if the right hand side is a simple variable (say an int)?  Can
> > I "reference" it somehow?  Should I assume that:
> >
> >aref = _any_type_other_than_simple_one
> >
> > be a reference, and not a copy?
> >
> Yes. Attributes are always object references. The assignment is actually
> the binding of a specific object to a name in some namespace, (r to an
> element of a sequence or other container object.
>
> This applies *whatever* the type of the RHS experession: the expression
> is evaluated to yield an object, and a reference to the object is stored
> in the name or container element.
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb   http://holdenweb.blogspot.com
> Recent Ramblings http://del.icio.us/steve.holden

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


urllib en https

2006-09-13 Thread Cecil Westerhof
Something went wrong with my last post. So, again:

I have a strange problem. I wrote a script that uses urllib.urlopen to fetch
a page through https. In Python 2.2.2 this works without a problem. But
when I use the script in Python 2.4.1 (which is more recent) I get:

Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/local/lib/python2.4/urllib.py", line 79, in urlopen
return opener.open(url, data)
  File "/usr/local/lib/python2.4/urllib.py", line 177, in open
return self.open_unknown(fullurl, data)
  File "/usr/local/lib/python2.4/urllib.py", line 189, in open_unknown
raise IOError, ('url error', 'unknown url type', type)
IOError: [Errno url error] unknown url type: 'https'

What is happening here? And how can I solve this?

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

urllib en https

2006-09-13 Thread Cecil Westerhof
I have a strange problem. I wrote a script that uses urllib.urlopen to fetch
a page through https. In Python 2.2.2 this works without a problem. But
when I use the script in Python  I get:

Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/local/lib/python2.4/urllib.py", line 79, in urlopen
return opener.open(url, data)
  File "/usr/local/lib/python2.4/urllib.py", line 177, in open
return self.open_unknown(fullurl, data)
  File "/usr/local/lib/python2.4/urllib.py", line 189, in open_unknown
raise IOError, ('url error', 'unknown url type', type)
IOError: [Errno url error] unknown url type: 'https'

What is happening here? And how can I solve this?

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


Re: page contents are not refreshed

2006-09-13 Thread waylan
Steve Holden wrote:
> waylan wrote:
[snip]
> >
> >>from mod_python import apache
> >>from time import strftime, gmtime
> >>
> >
> > def curtime():
> > return strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
> >
> >
> >>def handler(req):
> >> req.content_type = "text/plain"
> >> req.send_http_header()
> >> req.write(str(curtime()))
> >> return apache.OK
> >
> >
> This is a very long way round for a shortcut (though it does have the
> merit of working). Why not just
>
> def handler(req):
>   req.content_type = "text/plain"
>   req.send_http_header()
>   curtime = strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
>   req.write(str(curtime))
>   return apache.OK
>
> Or even
>
> def handler(req):
>   req.content_type = "text/plain"
>   req.send_http_header()
>   req.write(strftime("%a, %d %b %Y %H:%M:%S +", gmtime()))
>   return apache.OK
>

While Steve's examples certainly do the trick in this limited case, I
assumed that the original poster was just starting with mod_python and
I was simply trying to explain the bigger picture for future reference.
As one develops more sophisticated code, simply adding it to the
`handler` function becomes less desirable. Reacognizing that anything
that must be reevaluated on each request must be callable will be a
bigger help IMHO.

Steve's examples work because the current time is evaluated within
`handler` and :

>>> callable(handler)
True

While in the the original example:

>>> callable(curtime)
False

Yet in my example:

>>> callable(curtime)
True

Finally, by way of explaination:

>>> callable.__doc__
'callable(object) -> bool\n\nReturn whether the object is callable
(i.e., some kind of function).\nNote that classes are callable, as are
instances with a __call__() method.'

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


Re: eval(repr(object)) hardly ever works

2006-09-13 Thread [EMAIL PROTECTED]
Matthew Wilson wrote:
> I understand that idea of an object's __repr__ method is to return a
> string representation that can then be eval()'d back to life, but it
> seems to me that it doesn't always work.

Just to reinforce something Skip mentioned:

If you're looking for a way to serialize an object into a string, and
then later turn that string back into an object, you probably want the
pickle module (the marshal module is similar but is really intended for
internal use; unless you know exactly why you're picking one over the
other, using pickle is probably the right call).

http://docs.python.org/lib/module-pickle.html

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


Re: Python blogging software

2006-09-13 Thread Pierre Quentel
Hi,

There is a blog demo in Karrigell : http://karrigell.sourceforge.net

There is a project called KarriBlog aiming to offer a more complete
application, it's still beta but you can see it working on this site
(in French) : http://www.salvatore.exolia.net/site

Regards,
Pierre

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


Idle 1.1.3 class browser + a few questions

2006-09-13 Thread hg
Hi,

Is there a way to:

1) open the class browser automatically on the file opening
2) have the class browser updated when functions/classes ... are added
to the file
3) have a vertical scroll bar
4) have line numbers

Thanks,

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


Re: page contents are not refreshed

2006-09-13 Thread tobiah
Browser Cache?

Gleb Rybkin wrote:
> when running apache, mod_python in windows.
> 
> This looks pretty strange. Creating a simple python file that shows
> current time will correctly display the time in apache the first time,
> but freezes afterwards and shows the same time on all subsequent clicks
> as long as the file is not modified.
> 
> Any ideas what's wrong? Thanks.
> 
> from mod_python import apache
> from time import strftime, gmtime
> 
> curtime = strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
> def handler(req):
>  req.content_type = "text/plain"
>  req.send_http_header()
>  req.write(str(curtime))
>  return apache.OK
> 

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Dice gen and analyser script for RPGs: comments sought

2006-09-13 Thread Steven Bethard
George Sakkis wrote:
> * [personal preference]: Don't leave space between *every* operator in
> expressions, group them based on precedence. E.g. instead of "(n *
> sigmaSq - sigma * sigma) / (n * n)", I read it easier as "(n*sigmaSq -
> sigma*sigma) / (n*n).

The spaced-out version is more `PEP 8`_ compliant.  Under "Whitespace in 
Expressions and Statements -> Other Recommendations" it says "Use spaces 
around arithmetic operators" and gives a few examples of "Yes" usage 
that look much like the OP's usage.

That said, I also tend to omit the spaces around multiplicative 
operators (though I'm slowly training myself out of that).  As you say, 
in the end, this is really a matter of personal preference.

.. _PEP 8: http://www.python.org/dev/peps/pep-0008/


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


Re: page contents are not refreshed

2006-09-13 Thread Steve Holden
waylan wrote:
> Gleb Rybkin wrote:
> 
>>when running apache, mod_python in windows.
>>
>>This looks pretty strange. Creating a simple python file that shows
>>current time will correctly display the time in apache the first time,
>>but freezes afterwards and shows the same time on all subsequent clicks
>>as long as the file is not modified.
>>
>>Any ideas what's wrong? Thanks.
> 
> 
> The first time the page was requested mod_python compiled and loaded
> your code. Every request after that mod_python refers to the already
> loaded code in memory in which your expression had already been
> evaluated the first time.
> 
> Therefore, you need to make curtime a 'callable object' so that it will
> be re-evaluated on each request. Unfortunelty, I don't recall if simply
> wraping your strftime() expression in a function will be enough or if
> its more complex that that. That said, I **think** this should work:
> 
>>from mod_python import apache
>>from time import strftime, gmtime
>>
> 
> def curtime():
> return strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
> 
> 
>>def handler(req):
>> req.content_type = "text/plain"
>> req.send_http_header()
>> req.write(str(curtime()))
>> return apache.OK
> 
> 
This is a very long way round for a shortcut (though it does have the 
merit of working). Why not just

def handler(req):
  req.content_type = "text/plain"
  req.send_http_header()
  curtime = strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
  req.write(str(curtime))
  return apache.OK

Or even

def handler(req):
  req.content_type = "text/plain"
  req.send_http_header()
  req.write(strftime("%a, %d %b %Y %H:%M:%S +", gmtime()))
  return apache.OK

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Looking for the Perfect Editor

2006-09-13 Thread Wildemar Wildenburger
stu wrote:
> jedit
> 
> http://www.jedit.org/

Finally! I usually try to stay out of these discussions; yet I'm always 
disappointed at how few people seem to be using jEdit and how long it 
takes them to come out of their holes.

So let me enforce that:

jEdit
www.jedit.org

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


Re: page contents are not refreshed

2006-09-13 Thread waylan
Gleb Rybkin wrote:
> when running apache, mod_python in windows.
>
> This looks pretty strange. Creating a simple python file that shows
> current time will correctly display the time in apache the first time,
> but freezes afterwards and shows the same time on all subsequent clicks
> as long as the file is not modified.
>
> Any ideas what's wrong? Thanks.

The first time the page was requested mod_python compiled and loaded
your code. Every request after that mod_python refers to the already
loaded code in memory in which your expression had already been
evaluated the first time.

Therefore, you need to make curtime a 'callable object' so that it will
be re-evaluated on each request. Unfortunelty, I don't recall if simply
wraping your strftime() expression in a function will be enough or if
its more complex that that. That said, I **think** this should work:
>
> from mod_python import apache
> from time import strftime, gmtime
>
def curtime():
return strftime("%a, %d %b %Y %H:%M:%S +", gmtime())

> def handler(req):
>  req.content_type = "text/plain"
>  req.send_http_header()
>  req.write(str(curtime()))
>  return apache.OK

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


Re: page contents are not refreshed

2006-09-13 Thread Steve Holden
Gleb Rybkin wrote:
> when running apache, mod_python in windows.
> 
> This looks pretty strange. Creating a simple python file that shows
> current time will correctly display the time in apache the first time,
> but freezes afterwards and shows the same time on all subsequent clicks
> as long as the file is not modified.
> 
> Any ideas what's wrong? Thanks.
> 
> from mod_python import apache
> from time import strftime, gmtime
> 
> curtime = strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
> def handler(req):
>  req.content_type = "text/plain"
>  req.send_http_header()
>  req.write(str(curtime))
>  return apache.OK
> 
Try moving the assignment to curtime inside the handler function so it 
isn't just executed once when the module is imported ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


how are dictionary literals handled by the interpreter?

2006-09-13 Thread [EMAIL PROTECTED]
I wrote up a quick little set of tests, I was acutally comparing ways
of doing "case" behavior just to get some performance information.  Now
two of my test cases had almost identical results which was not at all
what I expected.  Ultimately I realized I don't really know how
literals are treated within the interpreter.

The two implementations I was looking at were:

class caseFunction(object):
def __init__(self):
self.caseDict = {'a':"retval = 'a'",
'b':"retval='b'","c":"retval='c'","d":"retval='d'",

"e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
 "i":"retval='i'"}

def doIt(self,a):
exec(self.caseDict.get(a))
return retval



def caseFunc3(a):
exec(  {'a':"retval = 'a'",
'b':"retval='b'","c":"retval='c'","d":"retval='d'",

"e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
 "i":"retval='i'"}.get(a))
return retval


I had expected caseFunc3 to be slower.  I had thought the interpreter
would be recreating the dictionary each time, but that doesn't seem to
be the case since performance of the class version and the function
version are nearly identical on most runs.  If i rewrite caseFunc3 as:

def caseFunc4(a):
exec(  dict({'a':"retval = 'a'",
'b':"retval='b'","c":"retval='c'","d":"retval='d'",

"e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
 "i":"retval='i'"}).get(a))
return retval

now with the explicit use of dict, i see the performace of the
functional version decline as I initially expected.

So what is happeneing in caseFunc3.  It seems as though the literal is
"cached".  The other hypothesis I came up with is the name lookup for
self.caseDict takes the same amount of time as creating the dictionary
literal - but that doesn't make sense to me.

Thanks

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


PumpMessages et WM_QUIT

2006-09-13 Thread swell
I have a COM server that throw events that i catch after running the
event loop thanks to pythoncom.PumpMessages(). How can i stop and exit
this loop? I tried to use win32api.PostQuitMessage() but this has no
effect ( the doc says that WM_QUIT stops the PumpMessages loop but it
doesn't)

Does someone know how to exit gracefully from this loop?

Thx
Manu

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


Re: Are Python's reserved words reserved in places they dont need to be?

2006-09-13 Thread Grant Edwards
On 2006-09-13, metaperl <[EMAIL PROTECTED]> wrote:

> One way to avoid the issue I brought up is for the syntax to
> be very regular... like Lisp or Tcl:
>
> set class "algebra"
>
> (setq class "algebra")

Unfortunately (or fortunately?) the human mind isn't very
regular and seems to prefer structured, redundant, and
irregular languages. One might suppose it makes pattern
recognition by neural networks easier.

-- 
Grant Edwards   grante Yow!  I am having a
  at   CONCEPTION--
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are Python's reserved words reserved in places they dont need to be?

2006-09-13 Thread metaperl
One way to avoid the issue I brought up is for the syntax to be very
regular... like Lisp or Tcl:

set class "algebra"

(setq class "algebra")

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


Re: Newbie - ? get IDLE going on cygwin

2006-09-13 Thread Jason Tishler
Dave,

On Wed, Sep 13, 2006 at 03:33:01PM +, David J. Braden wrote:
> I can now confirm that, yes, IDLE pops up w/o menus under cygwin.

You should be able to workaround this problem by executing idle with the
"-n" option:

$ idle -n

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread Steve Holden
John Henry wrote:
> Hi list,
> 
> Just to make sure I understand this.
> 
> Since there is no "pointer" type in Python, I like to know how I do
> that.
> 
> For instance, if I do:
> 
>...some_huge_list is a huge list...
>some_huge_list[0]=1
>aref = some_huge_list
>aref[0]=0
>print some_huge_list[0]
> 
> we know that the answere will be 0.  In this case, aref is really a
> reference.
> 
> But what if the right hand side is a simple variable (say an int)?  Can
> I "reference" it somehow?  Should I assume that:
> 
>aref = _any_type_other_than_simple_one
> 
> be a reference, and not a copy?
> 
Yes. Attributes are always object references. The assignment is actually 
the binding of a specific object to a name in some namespace, (r to an 
element of a sequence or other container object.

This applies *whatever* the type of the RHS experession: the expression 
is evaluated to yield an object, and a reference to the object is stored 
in the name or container element.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


page contents are not refreshed

2006-09-13 Thread Gleb Rybkin
when running apache, mod_python in windows.

This looks pretty strange. Creating a simple python file that shows
current time will correctly display the time in apache the first time,
but freezes afterwards and shows the same time on all subsequent clicks
as long as the file is not modified.

Any ideas what's wrong? Thanks.

from mod_python import apache
from time import strftime, gmtime

curtime = strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
def handler(req):
 req.content_type = "text/plain"
 req.send_http_header()
 req.write(str(curtime))
 return apache.OK

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


Re: Dice gen and analyser script for RPGs: comments sought

2006-09-13 Thread George Sakkis
Richard Buckle wrote:

> Comments, insights and overall evaluations are especially welcomed re:
> * Cleanliness of design
> * Pythonicity of design
> * Pythonicity of code
> * Efficiency of code
> * Quality of docstrings
> * Conformance with modern docstring standards
> * Conformance with coding standards e.g. PEP 8
>
> I look forward to receiving your comments and criticisms.

Here are some random (and less random) comments in no particular order,
with minimal or no justification; if you're not sure why some point is
good advice, simply ask :) I did just a "shallow parsing", meaning I
didn't attempt to understand what it's actually doing, check for
correctness, algorithm optimizations or major refactorings.

* Instead of importing sets, have the following snippet to be able to
use the builtin set (available since 2.4):
try: set
except NameError: from sets import Set as set

* Prefer new-style classes unless you have a good reason not to. The
change is minimal; just replace "class Dice" with "class Dice(object)".

* Replace most occurences of dict.keys, dict.values, dict.items with
dict.iterkeys, dict.itervalues, dict.iteritems respectively (unless you
write code with Py3K in mind ;-)).

* Avoid mutable default function arguments unless necessary. Instead of
a default empty list, use either an empty tuple or None (in which case
you may assign an empty list in the function's body when the argument
is None).

* Raising LookupError when a sanity check of function arguments fails
looks strange. ValueError (or a a specialised subclass of it) would be
more appropriate. 'assert' statements should also not be used for
arguments checking because they may be turned off when running the
program with '-O'.

* reduce() is discouraged; it's almost always more readable to unroll
it in a for loop.

* Are all the methods public, i.e. useful to a client of the classes ?
If not, the convention is to start the non-public methods' name with a
single underscore (or double underscore sometimes, but name mangling
often causes more problems than it solves in my experience, especially
when inheritance is involved).

* Several snippets can be condensed with list comprehensions, though
one-liners are not to everyone's taste. E.g. I'd write
histograms = []
maxDice = 10
for i in xrange(maxDice):
dice = StoryTellerDice(i)
histogram = dice.bruteforce()
histograms.append(histogram)
as histograms = [StoryTellerDice(i).bruteforce() for i in xrange(10)]

* [personal preference]: Don't leave space between *every* operator in
expressions, group them based on precedence. E.g. instead of "(n *
sigmaSq - sigma * sigma) / (n * n)", I read it easier as "(n*sigmaSq -
sigma*sigma) / (n*n).


HTH,
George

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


Re: Python blogging software

2006-09-13 Thread Irmen de Jong
Cliff Wells wrote:
> I'm currently using Frog, and it's decent, but lacks some fundamental
> features (tags for one).  Since Irmen is probably going to scrap it
> anyway, I'm kind of fishing about for something new.

That is not really true. I won't "scrap" Frog. One of the reasons
would be that I'm using it myself ;-)
Perhaps you confused it with the possible scrapping of the Snakelets
appserver it runs on? I'm thinking about rebuilding Frog on one
of the more established servers such as Turbogears.
But haven't had the time to start this.

--Irmen

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


  1   2   3   >