Re: comments? storing a function in an object

2009-07-20 Thread Gabriel Genellina

En Mon, 20 Jul 2009 22:53:59 -0300, Esmail  escribió:


Gabriel Genellina wrote:
 >
If you follow the above suggestions, you'll see that your Function  
class becomes almost useless: a normal function already IS an object,  
so you don't have to wrap it inside ANOTHER object unless you need very  
special features.


Hello Gabriel,

In general I would agree with you, but in my specific case
I want so store some additional meta-data with each function, such
as the valid range for input values, where the max or minimum are  
located,

the name/source for the function etc. I am creating list of functions
for use in testing optimization code, so it seems best to store this
data along with the function I am going to optimize in order to verify
the results for a given range (for instance).


You can store all meta-data in the function itself:

py> def triangle(b, h):
...   "area of triangle: b*h/2"
...   return b*h/2
...
py> triangle.foo = "some value"
py> triangle.foo
'some value'

Python already knows some properties:

py> triangle.func_code.co_argcount
2
py> triangle.func_doc
'area of triangle: b*h/2'
py> triangle.__doc__
'area of triangle: b*h/2'

You may use this variant of Carl Banks proposal - this is a factory  
function that returns new function objects:


def inline_function_factory(name, args, expr):
  ns = {}
  exec '''def %s(%s):
%r
return %s''' % (
name, args, expr, expr) in ns
  function = ns[name]
  return function

py> sqr = inline_function_factory("square", "x", "x*x")
py> sqr(3)
9
py> sqr.__doc__
'x*x'
py> sqr


Wrapping a function object isn't necesarily bad, but perhaps you're doing  
things more complicated than should be.


--
Gabriel Genellina

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


Re: Why aren't OrderedDicts comparable with < etc?

2009-07-20 Thread Jack Diederich
On Mon, Jul 20, 2009 at 10:00 AM, Steven
D'Aprano wrote:
> On Mon, 20 Jul 2009 09:34:24 +, Sion Arrowsmith wrote:
>
>> Terry Reedy   wrote:
>>>Sion Arrowsmith wrote:
 Jack Diederich   wrote:
> It isn't an OrderedDict thing, it is a comparison thing.  Two regular
> dicts also raise an error if you try to LT them.
 Python 2.5.2
>>> d1 = dict((str(i), i) for i in range (10)) d2 = dict((str(i), i)
>>> for i in range (20)) d1 < d2
 True
>>>Try reversing the definitions of d1 and d2. The dicts are probably being
>>>compared by id (address), which is the 2.x CPython default.
>>
>> Like this?
>>
> d1 = dict((str(i), i) for i in range (20))
> d2 = dict((str(i), i) for i in range (10))
> d1 < d2
>> False
> id(d1) < id(d2)
>> True
>>
>> I didn't know that comparison for anything other than equality defaulted
>> to using id. That really is rather broken, and I'm glad 3.0 fixed it.
>
>
> I don't think comparisons other than equality use id. That would be
> rather insane. If anyone can demonstrate such comparisons in a built-in
> or standard library class, I'd like to see it.
>
>
> For the record, dicts have been comparable with < and > since at least
> Python 1.5:
>
> $ python1.5
> Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat
> 4.1.2-27)] on linux2
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam

 {1: 'a', 2: 'b'} < {2: 'b', 3: 'a'}
> 1
>
>
> Reading the docs:
>
> http://docs.python.org/library/stdtypes.html#comparisons
> http://docs.python.org/library/stdtypes.html#mapping-types-dict
>
> I can only suggest that dicts compare in an arbitrary but consistent
> fashion.

I should have specified 3.x but since we were talking about
OrderedDicts (only in 3.1) I didn't say it explicitly.   Earlier
versions of python were very permissive with comparisons -- it was
rare that any cmp() raised an error and the ultimate fallback was on
the object's id.  This is one of the non-backwards compatible changes
in 3k.  Now comparing two of the same thing that don't have an obvious
ordering is an error.  Is a dict "greater than" if it has a larger
size?  if its max key is larger?  what does "max key" mean when the
keys aren't even comparable?.  Comparing things that aren't extremely
similar is an error now also.

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


python function for retrieving key and encryption

2009-07-20 Thread jayshree
M2Crypto package not showing the 'recipient_public_key.pem' file at
linux terminal .how do i get/connect with recipient public key.

exactly i need to check how can i open this file through linux
commands.

import M2Crypto def encrypt(): recip = M2Crypto.RSA.load_pub_key(open
('recipient_public_key.pem','rb').read()) print recip; plaintext =
whatever i need to encrypt msg = recip.public_encrypt
(plaintext,RSA.pkcs1_padding) print msg;

after calling the function its not giving any output and even any
error

i also tried as 'Will' said

pk = open('public_key.pem','rb').read() print pk; rsa =
M2Crypto.RSA.load_pub_key(pk)

whats the mistake i am not getting .will somebody help me out.
is something wrong in opening 'recipient_public_key.pem'. is M2Crypto
contain this file inbuilt .from where this file taking public key of
the recipient i'. what this file contain and how it will work .should
i need to create such a file for my purpose.if it is then how can i
create this  and how it will retrieve the key,where i recognize my
recipient to get his public key .is something like database at server.

please give me a quick response..
looking for your answer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comments? storing a function in an object

2009-07-20 Thread I V
On Mon, 20 Jul 2009 21:53:59 -0400, Esmail wrote:
> In general I would agree with you, but in my specific case I want so
> store some additional meta-data with each function, such as the valid
> range for input values, where the max or minimum are located, the
> name/source for the function etc. I am creating list of functions for
> use in testing optimization code, so it seems best to store this data
> along with the function I am going to optimize in order to verify the
> results for a given range (for instance).

You can set attributes on functions, so if your class is just storing 
this data, rather than altering the behavior of the function, you may be 
able to just use a function:

def f(x, y):
"x * y"
return x * y

f.arguments_max = [1000, 255]

A function also already knows how many arguments it takes, which you can 
access as f.func_code.co_argcount
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any suggestions to synchronize typed text and speech ?

2009-07-20 Thread Che M
On Jul 19, 4:15 pm, Stef Mientki  wrote:
> hello,
>
> I'm using Scintilla as a wxPython widget with great pleasure.
> I now have an application where I want to make notes during a conversation,
> but also want to record the speech during that conversation.
> I'm using Scintilla as a wxPython widget for editing and PyAudio for the
> speech recording,
> until so far everything works fine.
>
> Here the problem part:
> I need to synchronize the typed text with the sound during playback.
> So if I click somewhere in the sound recording,
> the line of text, typed that moment should be highlighted.
> And vise versa, if the cursor in the text is moved and some special key
> is pressed,
> the sound starting 10 or 20seconds earlier should be playbacked.
>
> I though of adding bookmarks (because these are fixed in the text), and
> keep a list of bookmarks and sound pointers.
> This idea should work, but there are only 31 bookmarks.
>
> Any other suggestions ?
>
> thanks,
> Stef Mientki

Stef, it occurs to me now that you might be useful to look at
Transana:
http://www.transana.org/

>From their site:

Transana is software for professional researchers who want to
analyze digital video or audio data. Transana lets you analyze
and manage your data in very sophisticated ways. Transcribe it,
identify analytically interesting clips, assign keywords to clips,
arrange and rearrange clips, create complex collections of
interrelated clips, explore relationships between applied keywords,
and share your analysis with colleagues.

It is written in Python, uses Scintilla, and is open source (GPL):
http://www.transana.org/developers/index.htm

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


Re: ignore special characters in python regex

2009-07-20 Thread John Machin
On Jul 21, 3:02 pm, Astan Chee  wrote:
> Hi,
> I'm reading text from a file (per line) and I want to do a regex using
> these lines but I want the regex to ignore any special characters and
> treat them like normal strings.
> Is there a regex function that can do this?

It would help if you were to say

(1) what "ignore ... characters" means -- pretend they don't exist?
(2) what are "special chararacters" -- non-alphanumeric?
(3) what "treat them like normal strings" means
(4) how you expect these special characters to be (a) ignored and (b)
"treated like normal strings" /at the same time/.

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


Re: clean way prepend an element to a numpy array

2009-07-20 Thread bdb112
On Jul 21, 2:13 pm, Ben Finney  wrote:
> bdb112  writes:
> > If I want to add an element at the beginning of an array, it seems
> > like I must make a list, insert in place, then make an array again.
>
> The NumPy ‘ndarray’ type (which is what you get by default from the
> ‘array’ factory function) is a far more complex type than (and is not
> derived from) the Python list.
>
> For manipulating them, you'll want to study the NumPy documentation
> http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html>.
>

Yes, I had had a look through that - nothing there that allows writing
a succint
clear statement (except for my .resize example in the original post),
although if efficiency was
a concern, then maybe resize and shift right, but that would really
obscure the code.

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


Re: ignore special characters in python regex

2009-07-20 Thread Frank Buss
Astan Chee wrote:

> I'm reading text from a file (per line) and I want to do a regex using 
> these lines but I want the regex to ignore any special characters and 
> treat them like normal strings.
> Is there a regex function that can do this?

Maybe re.escape helps?

-- 
Frank Buss, f...@frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de
-- 
http://mail.python.org/mailman/listinfo/python-list


C-API, tp_dictoffset vs tp_members

2009-07-20 Thread Ulrich Eckhardt
Hi!

When would I use PyObject_SetAttrString/tp_dictoffset instead of tp_members? 

I have a predefined set of members, some of which are optional. The problem 
I had with an embedded dictionary was that I can't see its elements using 
"dir()". Now I just converted to using tp_members, and it still seems to 
work correctly for the cases I tested. Even better, I can declare the fields 
as read-only then and add doc-strings. So, I wonder, what made the original 
author[2] use tp_dictoffset instead? 

In case you wonder, I'm looking at the Python bindings for GDB[1], file 
gdb/python/python-type.c, struct field_object.


Thanks!

Uli


[1] http://sourceware.org/gdb/wiki/PythonGdb
[2] Yes I could ask them, but I'd like to get an understanding of the pros 
and cons.


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


Re: any suggestions to synchronize typed text and speech ?

2009-07-20 Thread Frank Buss
Stef Mientki wrote:

> Here the problem part:
> I need to synchronize the typed text with the sound during playback.
> So if I click somewhere in the sound recording,
> the line of text, typed that moment should be highlighted.
> And vise versa, if the cursor in the text is moved and some special key 
> is pressed,
> the sound starting 10 or 20seconds earlier should be playbacked.

You could use some screen recording tools, e.g.
http://www.techsmith.com/camtasia.asp on Windows. Most tools allows you to
record speech while recording the screen.

-- 
Frank Buss, f...@frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de
-- 
http://mail.python.org/mailman/listinfo/python-list


ignore special characters in python regex

2009-07-20 Thread Astan Chee

Hi,
I'm reading text from a file (per line) and I want to do a regex using 
these lines but I want the regex to ignore any special characters and 
treat them like normal strings.

Is there a regex function that can do this?
Here is what I have so far:
fp = open('file.txt','r')
notes = fp.readlines()
fp.close()
strin = "this is what I want"
for note in notes:
if re.search(r""+ str(note) + "",strin):
  print "Found " + str(note) + " in " + strin

Thanks for any help
--
http://mail.python.org/mailman/listinfo/python-list


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread Frank Buss
Scott Burson wrote:

> Have you looked at ECL?
> 
> http://ecls.sourceforge.net/
> 
> I've used it only a little, so I can't vouch for its stability, but it
> fits the threading and license requirements (well, some corporate
> lawyers have trouble with the LGPL, but I think it's usable).

I didn't tried it myself, but looks like it is not very stable:

http://www.mail-archive.com/application-buil...@lispniks.com/msg01069.html

-- 
Frank Buss, f...@frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mechanize not recognized by py2exe

2009-07-20 Thread OrcaSoul


Gabriel Genellina-7 wrote:
> 
> En Fri, 17 Jul 2009 15:51:11 -0300, Stephen M. Olds   
> escribió:
> 
>> I have a Python script getData.py that uses Mechanize, and runs fine  
>> under the
>> interpreter. It was installed using easy_install - and the install  
>> seemed to
>> indicate it was completed.
>>
>> The problem is, when I try to compile it using py2exe while in the  
>> folder of the
>> script, and using the run line command:
>>
>> python getData.py py2exe
>>
>> I get the warning: "Import error: No Module named mechanize"...
>>
>> I checked the environmental path and find the following:
>> %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program  
>> Files (x86)\Python;C:\Python25\Lib\site-packages;C:\Program
>> Files (x86)\Common Files\Adobe\AGL
> 
> The system PATH is irrelevant here - it's only used by Windows to locate  
> the Python executable. I don't see a reason to list  
> C:\Python25\Lib\site-packages here.
> You're mostly interested in sys.path instead (that is, the 'path'  
> attribute in the 'sys' Python module)
> 
>> I did a search for mechanize and find an egg file in  
>> C:\Python25\Lib\site-packages
>> named mechanize-0.1.7b-py2.5.
>>
>> Not really understanding the "egg" thing, what do I have here that needs  
>> to be
>> done?
> 
> I'm not an egg expert either, and I try to avoid them as a plague. But I  
> *think* you can delete the .egg and re-install it using easy_install with  
> the -Z option.
> 
> -- 
> Gabriel Genellina
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Gabriel, that was the kick in the pants I needed! Thanks - after over a week
searching through the same 15 web pages these old eyes simply blurred over
and I missed that one...I had tried the -a option, but that's what got me
the eggs...

So, thanks for the help...it's too late to name my first born after you, but
I did have a cat named Gabriel - she was a great cat!

Stephen

-- 
View this message in context: 
http://www.nabble.com/Mechanize-not-recognized-by-py2exe-tp24540012p24581545.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: clean way prepend an element to a numpy array

2009-07-20 Thread Ben Finney
bdb112  writes:

> If I want to add an element at the beginning of an array, it seems
> like I must make a list, insert in place, then make an array again.

The NumPy ‘ndarray’ type (which is what you get by default from the
‘array’ factory function) is a far more complex type than (and is not
derived from) the Python list.

For manipulating them, you'll want to study the NumPy documentation
http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html>.

-- 
 \ “Are you pondering what I'm pondering?” “I think so, Brain, but |
  `\I don't think Kay Ballard's in the union.” —_Pinky and The |
_o__)   Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


clean way prepend an element to a numpy array

2009-07-20 Thread bdb112
If I want to add an element at the beginning of an array, it seems
like I must make a list, insert in place, then make an array again.

Of course, lists can be efficient too, and the insert() funtion works
nicely in that case, but sometimes arrays are the best choice

e.g.
x=array([1,2,3])
# to put the element 0 at the head of the array
listx=list(x)
listx.insert(0,0)
x=array(listx)
# this extra effort distracts from the clarity of the code, and must
slow things a little.

# While I appreciate that array operations that cause memory re-
allocation and copying are to be
#  avoided if at all possible, sometimes this is the best compromise
between clarity and efficiency

# A nicer piece of code would be

x.insert(0,0)
#or
x.prepend(0)

# It is a little easier to grow an array at the end (if it is not
referenced)
x.resize(4)

I saw this interest syntax on this site
x[:0]=0

I guess that is cute, but could be confusing(and doesn't work)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comments? storing a function in an object

2009-07-20 Thread Carl Banks
On Jul 20, 9:22 am, Esmail  wrote:
> def funct1(x):
>      ''' small test function '''
>      return x * x
>
> def funct2(x, y):
>      ''' small test function '''
>      return x + y
>
> def funct3(x):
>      ''' small test function '''
>      return 1000 + (x*x + x) * math.cos(x)
>
> def main():
>      """ main method """
>      print 'in main'
>
>      fn1 = Function(funct1, 'x * x', 1)
>      fn2 = Function(funct2, 'x + y', 2)
>      fn3 = Function(funct3, '1000 + (x*x + x) * cos(x)', 1)


If you are defining all of the functions are in-line like this (and I
assume you are because you seem to need a function object), I'd just
exec the string representation.  This is to support the DRY
principle.  You could do something like this:


class Function(object):
def __init__(self,args,body):
ns = {}
exec '''def func(%s): return %s''' in ns
self.fn = ns['func']
self.fn_str = body
self.num_vars = args.count(',')+1


You have to be REALLY REALLY careful not to pass any user-supplied
data to it if this is a server running on your computer, of course.
(If it's an application running on the user's computer it doesn't
matter.)

Still wouldn't be a bad idea to pass it through some kind of validator
for extra protection.


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


Re: are user defined classes hashable?

2009-07-20 Thread Aahz
In article <373d6c69-6965-4a88-bdd2-8028ef850...@k6g2000yqn.googlegroups.com>,
Hyuga   wrote:
>
>Regardless, Nicolas's example can be applied to the class too:
>
 class Foo(object):
>   pass
>
 hash(Foo)
>11443104
 id(Foo)
>11443104
>
>class objects are just objects of type 'type'.

Not quite.  They certainly default that way, but changing the metaclass
changes a class's type::

class M(type): 
pass

class C(object): 
pass

class C2(object):
__metaclass__ = M

print type(C)
print type(C2)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"The volume of a pizza of thickness 'a' and radius 'z' is
given by pi*z*z*a"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-20 Thread Ethan Furman

[fixed for bottom-posting]

Dr. Phillip M. Feldman wrote:

MRAB-2 wrote:





What values should 'xor' return? IMHO, if only one of the values is true
then it should return that value, otherwise it should return False.

1 xor 0 => 1
0 xor 2 => 2
1 xor 2 => False
0 xor 0 => False

This is because it's a Boolean operator, so it should fall back to
Boolean values when necessary, like 'not':

not 0 => True
not 1 => False

Also:

x and y and z => (x and y) and z
x or y or z => (x or y) or z

therefore:

x xor y xor z => (x xor y) xor z


> Suppose that 'xor' returns the value that is true when only one value is
> true, and False otherwise.  This definition of xor doesn't have the 
standard

> associative property, that is,
>
> (a xor b) xor c
>
> will not necessarily equal
>
> a xor (b xor c)
>
> To see that this is the case, let a= 1, b= 2, and c= 3.
>
> (a xor b) xor c
>
> yields 3, while
>
> a xor (b xor c)
>
> yields 1.  So, I'd prefer an xor operator that simply returns True or 
False.

>
> Phillip
>

You are, of course, free to write your version however it makes sense to 
you and your team.  :)


Since the 'and' and 'or' already return objects (and objects evaluate to 
true or false), then 'xor' should behave likewise, IMO.  I expect that 
would be the case if it were ever added to the language.


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


Re: comments? storing a function in an object

2009-07-20 Thread Esmail

Hi Francesco,

Those were great suggestions!

Re 1: I used the __doc__ attribute to eliminate the parameter in the
  constructor as you suggested. Also, much easier to specify the
  character string with the actual function than later to match it
  up like I was.

class Function(object):
""" class to represent a function """

def __init__(self, fn, num_vars):
""" the function, its string representation, and the number of 
variables """

self.fn = fn
self.fn_str = fn.__doc__
self.num_vars = num_vars


Re 2: I will need to read up on __call__ to see how to use it here ..


Re 3: I think I still need to have my own exception handler as I am
  using the 'extended call syntax' now (I just learned about this
  yesterday) and I will always just supply one argument, the
  list. Or perhaps my custom exception will be superfluous once I
  figure out __call__ ..?


Thank you for taking the time to help, always good to learn new things.

Esmail

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


Re: tough-to-explain Python

2009-07-20 Thread Paul Rubin
Simon Forman  writes:
> But I'm glad it's there to study, these are wheels I don't have to
> invent for myself.

http://dwheeler.com/essays/high-assurance-floss.html

might be an interesting place to start.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comments? storing a function in an object

2009-07-20 Thread Esmail

Gabriel Genellina wrote:
>
If you follow the above suggestions, you'll see that your Function class 
becomes almost useless: a normal function already IS an object, so you 
don't have to wrap it inside ANOTHER object unless you need very special 
features.


Hello Gabriel,

In general I would agree with you, but in my specific case
I want so store some additional meta-data with each function, such
as the valid range for input values, where the max or minimum are located,
the name/source for the function etc. I am creating list of functions
for use in testing optimization code, so it seems best to store this
data along with the function I am going to optimize in order to verify
the results for a given range (for instance).

Esmail


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


Re: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!)

2009-07-20 Thread D'Arcy J.M. Cain
On 20 Jul 2009 17:10:55 -0700
a...@pythoncraft.com (Aahz) wrote:
> >I understand what you want but I can't see how a toolkit can do that.
> >How do you program "graceful?"  It seems pretty application specific.
> 
> Presumably the JS toolkit generates both code and HTML.  Actions that
> normally get executed by JS should degrade to plain HTML links and form
> submits (or possibly not display at all if it's a pure convenience).

As I said, I do understand what you are after but I still think it is a
judgement call.  What defines "convenience?"  How does the library know
what is essential and what is pretty?

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


Re: tough-to-explain Python

2009-07-20 Thread Simon Forman
On Jul 20, 4:00 am, greg  wrote:
> Calroc wrote:
> > It may be that flawless software is an unreachable asymptote, like the
> > speed of light for matter, but I'm (recently!) convinced that it's a
> > goal worthy of exploration and effort.
>
> Seems to me that once you get beyond the toy program
> stage and try to apply correctness proving to real
> world programming problems, you run up against the
> problem of what exactly you mean by "correct".
>
> Once the requirements get beyond a certain level of
> complexity, deciding whether the specifications
> themselves are correct becomes just as difficult as
> deciding whether the program meets them.

I agree.  You could prove that a game renders geometry without
crashing, but not that it's fun.  Or in an accounting package you
could prove that it never loses a cent in tracking accounts and
payments, or that its graph-rendering code does correctly render data
(without introducing artifacts, for instance), but not that it will
let you notice trends.

> Then there's the fact that very often we don't
> even know what the exact requirements are, and it's
> only by trying to write and use the program that
> we discover what they really are -- or at least,
> get a better idea of what they are, because the
> process is usually iterative, with no clear end
> point.

Aye, if you're still exploring your solution space your requirements
are perforce somewhat nebulous.

> So in theory, correctness proofs are a fine idea,
> and might even be doble on a small scale, but the
> real world is huge and messy!

Very true, but I think it is still worthy to build larger systems from
proven components combined in provably correct ways, at least to the
extent possible.

> > Just because it's unattainable doesn't make it undesirable.  And who
> > knows? Maybe the horse will learn to sing.
>
> Striving to find ways of writing less bugs is a
> worthy goal, but I think of it more in terms of
> adopting patterns of thought and programming that
> make it more likely you will write code that does
> what you had in mind, rather than a separate
> "proof" process that you go through afterwards.

I would consider formal methods exactly "patterns of thought and
programming that make it more likely you will write code that does
what you had in mind", in fact that's why I'm excited about them.

My understanding (so far) is that you (hope to) /derive/ correct code
using formal logic, rather than writing code and then proving its
soundness.

The real win, IMO, is teaching computers as a logical, mathematical
activity (that can certainly depart for realms less rigorously
defined.)

I think anyone who can spontaneously solve a Sudoku puzzle has enough
native grasp of "formal" methods of reasoning to learn how to derive
working programs logically.  Making the formal methods explicit gives
you the strongest available confidence that you are reasoning, and
programming, correctly.

This is not to say that "incorrect" (or unproven or unprovable)
programs are never useful or necessary.  However, I do feel that it's
better to learn the "correct" way, and then introduce ambiguity, than
to simply throw e.g. Java at some poor student and let them find solid
ground "catch as catch can".


~Simon

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


Re: tough-to-explain Python

2009-07-20 Thread Simon Forman
On Jul 19, 2:51 pm, Paul Rubin  wrote:
> Calroc  writes:
> > I'm engaged presently in starting a school to teach programming from
> > the ground up, based roughly on the curriculum outlined in the article
> > I mentioned. ...
> > I'm excited about formal methods because one, I just heard about them,
>
> Formal methods are a big and complicated subject.  Right after you
> heard about them is probably not the best time to start teaching them.
> Better get to understand them yourself first.

Very good point.

But I'm glad it's there to study, these are wheels I don't have to
invent for myself.

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


Re: Design question.

2009-07-20 Thread Dave Angel

Lacrima wrote:

On Jul 20, 4:05 pm, Jean-Michel Pichavant 
wrote:
  

Lacrima wrote:


Hello!
  
I am newbie in python and I have really simple question, but I need

your advice to know how to do best.
I need to store a number of dictionaries in certain place. I've
decided to store them in a separate module.
Like this:
dicts.py
---
dict1 =}
dict2 =}
dict3 =}
  
Then, when I need any dictionary, I can access it:

import dicts
dicts.dict1
  



Hi, Jean-Michel!

Thanks for your answer.
I am not going to have names like dicts.py and dict1,dict2. That was
just example. I wanted to know if it is correct to have dictionaries
on a module level. Now I know that this is correct. I want to collect
in one module a number of dictionaries, every of which describes a
separate web service. And my function in another module will import
required dictionary, depending on what web service should be used.
Thanks again for the help.

With regards,
Max.
(sorry if my English isn't very proper)

  
It makes a lot of sense to store several dictionaries in a module, if 
they describe parallel things, or alternate ways of accessing something 
(like web services).


However, you might want to consider how they'll be accessed.  If another 
module is going to "import required dictionary," then you have some 
means of selection.  Perhaps that selection should be in the same 
module, or at least the data structure to select it should be in the 
same module.


Let's say you have four choices right now.  And you add a fifth later.  
Do you want to have to edit both the "function in the other module" as 
well as this module?


This is similar to a feature that some programs have, "plug-ins."   
There a customer can add an additional runtime just by dropping a new 
.py file in the appropriate directory, and the program will find it and 
add it to its "list of features."


So I'm just suggesting you figure out how the program might evolve, and 
set up the data so changes may be localized, if practical.  This turns 
out usually to be parallel to the notion of naming things and grouping 
them by similarity of functionality.


DaveA


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


Re: locale doesn' format

2009-07-20 Thread Дамјан Георгиевски


>> I want to format values to the german form eg. 1.034,56 but
>> locale.format() doesn't work for me.
> 
> seems to work here

In 2.6 this is good too:

>>> import decimal, locale
>>> locale.setlocale(locale.LC_ALL, 'mk_MK.UTF-8')
>>> '{0:n}'.format(1234.56)
'1 234,56'


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

A: Because it reverses the logical flow of conversation.
Q: Why is top posting frowned upon?

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


Re: locale doesn' format

2009-07-20 Thread Дамјан Георгиевски
> I want to format values to the german form eg. 1.034,56 but
> locale.format() doesn't work for me.

seems to work here


>>> import decimal, locale
>>> locale.setlocale(locale.LC_ALL, 'mk_MK.UTF-8')
'mk_MK.UTF-8'
>>> locale.localeconv()['grouping']
[3, 3, 0]
>>> locale.localeconv()['thousands_sep']
' '
>>> locale.localeconv()['decimal_point']
','
>>> locale.format('%f', 1034.56,True)
'1 034,56'
>>> locale.format('%d', 1034.56,True)
'1 034'



ps.
you can copy/paste the above in .txt file and then run/test it with:
python -m doctest -v  check.txt


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

  Begin...the rest is easy.

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


Re: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!)

2009-07-20 Thread Aahz
In article ,
D'Arcy J.M. Cain  wrote:
>On 20 Jul 2009 09:00:33 -0700
>a...@pythoncraft.com (Aahz) wrote:
>>
>> Out of curiosity, are there any JavaScript toolkits that generate code
>> that degrades gracefully when JavaScript is disabled?
>
>I understand what you want but I can't see how a toolkit can do that.
>How do you program "graceful?"  It seems pretty application specific.

Presumably the JS toolkit generates both code and HTML.  Actions that
normally get executed by JS should degrade to plain HTML links and form
submits (or possibly not display at all if it's a pure convenience).
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"The volume of a pizza of thickness 'a' and radius 'z' is
given by pi*z*z*a"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Piet van Oostrum
> Paul Moore  (PM) wrote:

>PM> 2009/7/20 Chris Rebert :
>>> On Mon, Jul 20, 2009 at 2:23 PM, Piet van Oostrum wrote:
> x = [2,1,3]
> print sorted(x)[0]
>DB> 3
 
 What kind of Python produces that?
>>> 
>>> Assuming you're referring to the latter example, it was added in version 2.4
>>> If you meant the former example, I think that's purely pseudo-Python.

>PM> I think he was referring to the fact that the result should be 1, not 3.

The underlying thought was that you should copy and paste examples from
a real Python interpreter.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Hrvoje Niksic
Chris Rebert  writes:

>>> x = [2,1,3]
>>> print sorted(x)[0]
>>>DB> 3
>>
>> What kind of Python produces that?
>
> Assuming you're referring to the latter example, it was added in version 2.4
> If you meant the former example, I think that's purely pseudo-Python.

sorted([2, 1, 3])[0] evaluates to 1, not 3.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Hrvoje Niksic
Phillip B Oldham  writes:

> On Jul 20, 6:08 pm, Duncan Booth  wrote:
>> The main reason why you need both lists and tuples is that because a tuple
>> of immutable objects is itself immutable you can use it as a dictionary
>> key.
>
> Really? That sounds interesting, although I can't think of any real-
> world cases where you'd use something like that.

An application visiting files on a filesystem recursively needs a
dictionary or set keyed by (st_dev, st_ino) to make sure it doesn't
visit the same file twice.  Memoization implementation (of a cache for
results of function application) might need to use a dictionary to map
function arguments, a tuple, to the function result.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Christian Heimes
Niels L. Ellegaard wrote:
> Phillip B Oldham  writes:
> 
>> We often find we need to do manipulations like the above without
>> changing the order of the original list, and languages like JS allow
>> this. We can't work out how to do this in python though, other than
>> duplicating the list, sorting, reversing, then discarding.
> 
> If you just want a one-liner, and you don't care about speed you can
> do the following (but I don't think this is considered best practice)

sorted() already returns a new list not a generator as you might assume.

Christian

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


Re: Compilation problem with Python < 2.6 and db >= 4.7

2009-07-20 Thread kiorky
Martin v. Löwis a écrit :
>> Is there a way to make the bsddb module compile against db>=4.7 for python < 
>> 2.6
>> (2.4.6, 2.5.4)?
> 
> I don't think so, no.
> 
>> I didn't find something on it.
> 
> If you don't want to use pybsddb either, for fear of incompatible API,
> your only choice is to port _bsddb.c to the newer db versions. BSDDB
> is in the tradition of both breaking the data format and the API
> frequently, so we (python-dev) have given up on it.

Yup, i understand.
I will be lazy and fall back as all packaging systems do, and keep in the
minitage packages tree both db versions.
Thanks for confirmation.

> 
> Regards,
> Martin


-- 
--
Cordialement,
KiOrKY
GPG Key FingerPrint: 0x1A1194B7681112AF


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


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread vippstar
On Jul 21, 1:22 am, Paul Rubin  wrote:
> vippstar  writes:
> > > I don't see how to implement such a thing in my code,
> > Write a function:
>
> >   (if (< x y)
> >       ValueError
> >       (/ x y))
>
> I meant changing the behavior of integer division in python.
You'd either have to hack an implementation or change the standard (I
just noticed python doesn't have one).

> > Wouldn't that mean 3/2 would also evaluate to ValueError?
>
> Yes, the idea was that one can take the view that integer division
> should not be allowed except through a 'div' function or some such.
You brought up 3/2 == ValueError as a more appropriate value for the
integer division to evaluate, rather than 0. I thought you meant
specifically those kinds of divisions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compilation problem with Python < 2.6 and db >= 4.7

2009-07-20 Thread Martin v. Löwis
> Is there a way to make the bsddb module compile against db>=4.7 for python < 
> 2.6
> (2.4.6, 2.5.4)?

I don't think so, no.

> I didn't find something on it.

If you don't want to use pybsddb either, for fear of incompatible API,
your only choice is to port _bsddb.c to the newer db versions. BSDDB
is in the tradition of both breaking the data format and the API
frequently, so we (python-dev) have given up on it.

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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Niels L. Ellegaard
Phillip B Oldham  writes:

> We often find we need to do manipulations like the above without
> changing the order of the original list, and languages like JS allow
> this. We can't work out how to do this in python though, other than
> duplicating the list, sorting, reversing, then discarding.

If you just want a one-liner, and you don't care about speed you can
do the following (but I don't think this is considered best practice)

>>> x = [2,1,3]
>>> print list(sorted(x))   
[1, 2, 3]
>>> print x
[2, 1, 3]

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


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread Paul Rubin
vippstar  writes:
> > I don't see how to implement such a thing in my code,
> Write a function:
> 
>   (if (< x y)
>   ValueError
>   (/ x y))

I meant changing the behavior of integer division in python.

> Wouldn't that mean 3/2 would also evaluate to ValueError?

Yes, the idea was that one can take the view that integer division
should not be allowed except through a 'div' function or some such.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Essential Reference, 4th Edition - Now Available!

2009-07-20 Thread Jonathan Corbet
On Sun, 19 Jul 2009 11:03:05 -0500
David Beazley  wrote:

> I'm pleased to announce the release of the Python Essential Reference,
> 4th edition, now available at a bookstore near you. More than a year
> in development, this edition covers Python 2.6, Python 3, and a wide
> variety of new library modules.

And here I am still using my old, dog-eared second edition...  Any
chance of getting a copy of the 4th for an LWN review?

Thanks,

jon
-- 
Jonathan Corbet / LWN.net / cor...@lwn.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread Scott Burson
On Jul 19, 11:31 am, Frank Buss  wrote:
> I don't know of a free modern and stable Lisp implementation with
> mulithreading support for Windows, with a licence with which you can use it
> in closed source commercial programs

Have you looked at ECL?

http://ecls.sourceforge.net/

I've used it only a little, so I can't vouch for its stability, but it
fits the threading and license requirements (well, some corporate
lawyers have trouble with the LGPL, but I think it's usable).

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


Re: locale doesn' format

2009-07-20 Thread Jerry Hill
On Mon, Jul 20, 2009 at 5:07 PM, Egon Frerich wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> I want to format values to the german form eg. 1.034,56 but
> locale.format() doesn't work for me.
>
> Here is a little test program:
...
> k1 = locale.format_string('%12s',k,True)

I don't think you want to be using '%s' to format numbers in your
format strings.  Instead, use '%f' to format floating point values.

As I understand it, a %s in a format string actually calls str() on
the object that you pass into the formatting function, and I don't
think that floats (or Decimal.Decimal objects) take locale into
account when you do that.

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


Re: Auto-generate GUI from a database table structure

2009-07-20 Thread Gabriel Genellina
En Mon, 20 Jul 2009 12:09:47 -0300, Boyd, Craig1
escribió:


I am trying to write a couple screens to update three or four database  
tables on Oracle 10g and I was wondering if there was a way to  
automatically generate some kind of GUI shell based on the tables that I  
could then fill in with the logic / functionality I need.


I've never actually used it, but the DABO project seems to provide what  
you want: http://dabodev.com/


--
Gabriel Genellina

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


Re: any suggestions to synchronize typed text and speech ?

2009-07-20 Thread Aahz
In article ,
Stef Mientki   wrote:
>
>I was afraid of that too, so I dropped the question in several places,
>and the writer of Scintilla himself came with the perfect answer.

...which was?...
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"The volume of a pizza of thickness 'a' and radius 'z' is
given by pi*z*z*a"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import pydoc and then use it?

2009-07-20 Thread Albert Hopkins
On Mon, 2009-07-20 at 13:38 -0700, mrstevegross wrote:
> I know how to use pydoc from the command line. However, because of
> complicated environmental setup, it would be preferable to run it
> within a python script as a native API call. That is, my python runner
> looks a bit like this:
> 
>   import pydoc
>   pydoc.generate_html_docs_for(someFile)
> 
> However, it's not clear to me from the pydoc documentation which
> function calls I need to use to make this behavior work. Any ideas?

Did you try 'pydoc pydoc'? ;)

>>> import pydoc
>>> htmldoc = pydoc.HTMLDoc()
>>> htmldoc_for_pydoc = htmldoc(pydoc)
>>> print htmldoc_for_pydoc

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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Paul Moore
2009/7/20 Chris Rebert :
> On Mon, Jul 20, 2009 at 2:23 PM, Piet van Oostrum wrote:
>>> x = [2,1,3]
>>> print sorted(x)[0]
>>>DB> 3
>>
>> What kind of Python produces that?
>
> Assuming you're referring to the latter example, it was added in version 2.4
> If you meant the former example, I think that's purely pseudo-Python.

I think he was referring to the fact that the result should be 1, not 3.

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


Re: comments? storing a function in an object

2009-07-20 Thread Gabriel Genellina
En Mon, 20 Jul 2009 14:44:16 -0300, Francesco Bochicchio  
 escribió:



On Jul 20, 6:22 pm, Esmail  wrote:

Hello all,

I am trying to store a function and some associated information in an
object so that I can later have series of functions in a list that I can
evaluate one at a time.

Right now I am only storing the function itself, the number of
arguments it expects and its string representation. I may add other
information such as the acceptable range for the parameters or other
characteristics such as maximum or minimum.

I wonder if anyone could comment on my implementation and offer
suggestions or constructive criticisms?

The 'loading' of the functions is a bit tedious and of course care
has to be taken to make sure the string representation corresponds to
the actual function computed. It would be nice if there was an
automatic way to convert the function to its string representation.

Comments or problems with the approach I have taken?

Thanks,
Esmail

--

#!/usr/bin/env python

#
# store and represent functions
#

import math

class FunctionException(Exception):
     """ custom exception """
     def __init__(self, value):
         self.parameter = value

     def __str__(self):
         return repr(self.parameter)

class Function(object):
     """ class to represent a function """

     def __init__(self, fn, fn_str, num_vars):
         """
         the function, its string representation, and the number of  
variables

         """
         self.fn = fn
         self.fn_str = fn_str
         self.num_vars = num_vars

     def eval_fn(self, variables):
         """ size of variables should equal num_vars .. else problem """
         if len(variables) == self.num_vars:
             result = self.fn(*variables)
             return result
         else:
             raise FunctionException('invalid number of args provided -  
'+

                                     'received %d, expected %d'
                                     %(len(variables), self.num_vars))

     def str(self):
         """ return string representation of function """
         return self.fn_str

def funct1(x):
     ''' small test function '''
     return x * x

def funct2(x, y):
     ''' small test function '''
     return x + y

def funct3(x):
     ''' small test function '''
     return 1000 + (x*x + x) * math.cos(x)

def main():
     """ main method """
     print 'in main'

     fn1 = Function(funct1, 'x * x', 1)
     fn2 = Function(funct2, 'x + y', 2)
     fn3 = Function(funct3, '1000 + (x*x + x) * cos(x)', 1)

     for i in range(-10, 10):
         try:

             print 'f(', [i],') =',
             print fn3.str(), ' => ',
             print fn3.eval_fn([i])

         except FunctionException, (ex):
             print ex.parameter

if __name__ == '__main__':
     main()



I can offer some small suggestions: it is up to you to evaluate if
they make sense for your app:

1. use __doc__ function standard attribute for function description
(your fn_str); this meanst that
   you do not need fm_str in the constructor and you have to do e.g. :

def funct2(x, y):
  ''' x + y '''
  return x + y

then funct2.__doc__  becomes the string you want to associate to the
function

2. Use __call__ instead of eval_fn : this way, the instance of your
Function became a 'callable' and can be used
   everywhere a function is needed. You can do:

   f = Function(...)
   f( some_args )

3. If you call a python function with wrong number of arguments, it
already raises a TypeError exception which contains
   - with different wording - the same information of your
FunctionException : consider removing the check and using the
   python error instead


If you follow the above suggestions, you'll see that your Function class  
becomes almost useless: a normal function already IS an object, so you  
don't have to wrap it inside ANOTHER object unless you need very special  
features.


--
Gabriel Genellina

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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Chris Rebert
On Mon, Jul 20, 2009 at 2:23 PM, Piet van Oostrum wrote:
>> Duncan Booth  (DB) wrote:
>
>>DB> Phillip B Oldham  wrote:
 This make a lot more sense to us, and follows the convention from
 other languages. It would also mean chaining methods to manipulate
 lists would be easier:

>>> x = [2,1,3]
>>> print x.sort()[0]
 3
>>> print x
 [2,1,3]
>
>>DB> You already have a way to do what you want:
>
>> x = [2,1,3]
>> print sorted(x)[0]
>>DB> 3
>
> What kind of Python produces that?

Assuming you're referring to the latter example, it was added in version 2.4
If you meant the former example, I think that's purely pseudo-Python.

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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Piet van Oostrum
> Duncan Booth  (DB) wrote:

>DB> Phillip B Oldham  wrote:
>>> This make a lot more sense to us, and follows the convention from
>>> other languages. It would also mean chaining methods to manipulate
>>> lists would be easier:
>>> 
>> x = [2,1,3]
>> print x.sort()[0]
>>> 3
>> print x
>>> [2,1,3]

>DB> You already have a way to do what you want:

> x = [2,1,3]
> print sorted(x)[0]
>DB> 3

What kind of Python produces that?
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


locale doesn' format

2009-07-20 Thread Egon Frerich

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

I want to format values to the german form eg. 1.034,56 but
locale.format() doesn't work for me.

Here is a little test program:

import decimal, locale

print locale.getdefaultlocale()
print locale.localeconv()
locale.setlocale(locale.LC_ALL, ('de_DE', 'UTF-8'))
print locale.localeconv()
k = decimal.Decimal('1034.56')
#k = 1034.56
print 'k', k, type(k)
k1 = locale.format_string('%12s',k,True)
print 'k1', k1, type(k1)
k1a = locale.format('%12s',k,True,True)
print 'k1a', k1a, type(k1a)
k2 = unicode(k1)
print 'k2',k2,type(k2)
print k1.find(',')
print k1a.find(',')
print k2.find(',')
ab = locale.localeconv()['decimal_point']
print 'ab', ab
print locale.localeconv()['decimal_point'].find(',')
print locale.localeconv()['mon_decimal_point'].find(',')
ac = locale.localeconv()['mon_decimal_point']
print 'ac', ac, len(ac)
print locale.localeconv()

k1, k1a, k2 are printed as 1034.56

Egon

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFKZNyaZRiDo9Iq4qIRAuqhAKCW3x7iDbrxUDp3M/qHabwbw92osQCgi6N2
mmgb54LACmrd/Wi4BRi2iZo=
=psal
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Shed Skin 0.2, an experimental (restricted) Python-to-C++ compiler

2009-07-20 Thread James Matthews
I like this, I am going to run this as a test. I also want to see the source
code on how they compile the dynamic variables.

On Mon, Jul 20, 2009 at 10:20 PM, srepmub  wrote:

>
> > Nice timings, can you please show me the Python, Java and C code
> > versions? I may do more tests.
>
> also, which shedskin options did you use? did you use -bw, to disable
> bounds and wrap-around checking? this can make quite a difference for
> code that does a lot of indexing. if the code uses random numbers,
> then -r can also make a big difference, to use C rand(), instead of
> Python compatible random numbers.
>
> and which C++ compiler flags did you use? the default -O2, or
> something like -O3 -fomit-frame-pointer -msse2..?
>
>
> thanks,
> mark.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list


How to import pydoc and then use it?

2009-07-20 Thread mrstevegross
I know how to use pydoc from the command line. However, because of
complicated environmental setup, it would be preferable to run it
within a python script as a native API call. That is, my python runner
looks a bit like this:

  import pydoc
  pydoc.generate_html_docs_for(someFile)

However, it's not clear to me from the pydoc documentation which
function calls I need to use to make this behavior work. Any ideas?

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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread J. Cliff Dyer
On Mon, 2009-07-20 at 12:26 -0700, Phillip B Oldham wrote:
> On Jul 20, 6:08 pm, Duncan Booth  wrote:
> > The main reason why you need both lists and tuples is that because a tuple
> > of immutable objects is itself immutable you can use it as a dictionary
> > key.
> 
> Really? That sounds interesting, although I can't think of any real-
> world cases where you'd use something like that.

Well, if you wanted to index a dictionary by coordinates, you might do
something like this:


fleet = {}
fleet[9,4] = 'destroyer'
fleet[8,4] = 'destroyer'
fleet[3,5] = 'aircraftcarrier'
fleet[4,5] = 'aircraftcarrier'
fleet[5,5] = 'aircraftcarrier'
fleet[6,5] = 'aircraftcarrier'
fleet[8,0] = 'battleship'
fleet[8,1] = 'battleship'
fleet[8,2] = 'battleship'


def checkattack(x, y, fleet):
if x,y in fleet:
return "You hit my %s' % fleet[x,y]

Maybe not the best implementation of Battleship, but you get the idea.



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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Marcus Wanner

On 7/20/2009 3:26 PM, Phillip B Oldham wrote:

On Jul 20, 6:08 pm, Duncan Booth  wrote:

The main reason why you need both lists and tuples is that because a tuple
of immutable objects is itself immutable you can use it as a dictionary
key.


Really? That sounds interesting, although I can't think of any real-
world cases where you'd use something like that.
Actually, that would be very useful in the program from "any suggestions 
to synchronize typed text and speech ?"...i.e. have a dictionary key of 
(hour, minute, second).


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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Duncan Booth
Phillip B Oldham  wrote:

> On Jul 20, 6:08 pm, Duncan Booth  wrote:
>> The main reason why you need both lists and tuples is that because a
>> tuple of immutable objects is itself immutable you can use it as a
>> dictionary key.
> 
> Really? That sounds interesting, although I can't think of any real-
> world cases where you'd use something like that.
> 

How about a multi-dimensional sparse array?

>>> d = {}
>>> d[1,2] = 'a'
>>> d[5,7] = 'b'

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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Phillip B Oldham
On Jul 20, 6:08 pm, Duncan Booth  wrote:
> The main reason why you need both lists and tuples is that because a tuple
> of immutable objects is itself immutable you can use it as a dictionary
> key.

Really? That sounds interesting, although I can't think of any real-
world cases where you'd use something like that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Shed Skin 0.2, an experimental (restricted) Python-to-C++ compiler

2009-07-20 Thread srepmub

> Nice timings, can you please show me the Python, Java and C code
> versions? I may do more tests.

also, which shedskin options did you use? did you use -bw, to disable
bounds and wrap-around checking? this can make quite a difference for
code that does a lot of indexing. if the code uses random numbers,
then -r can also make a big difference, to use C rand(), instead of
Python compatible random numbers.

and which C++ compiler flags did you use? the default -O2, or
something like -O3 -fomit-frame-pointer -msse2..?


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


Re: ANN: Shed Skin 0.2, an experimental (restricted) Python-to-C++ compiler

2009-07-20 Thread Bearophile
Skip Montanaro:
> I read just enough French to know that "avec" means "with", but I don't
> understand the difference between "avec malloc *int" and "avec []".  Can you
> explain please?

Maybe it's the time difference between using a Python list from Cython
and using a C "array" allocated with a malloc from Cython.

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


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread vippstar
On Jul 20, 7:50 pm, Paul Rubin  wrote:
> vippstar  writes:
> > > I wonder whether 2/3 => ValueError is preferable.
>
> > Not all software wants this. It shouldn't be part of the language but
> > rather part of your code if you need such a feature. (for instance, to
> > distinguish between 2/3 and divisions with 0 dividend).
>
> I don't see how to implement such a thing in my code,
Write a function:

  (if (< x y)
  ValueError
  (/ x y))

This will return 0 only if the dividend = 0, not in integer division x/
y with y > x, which will return ValueError. Of course, ValueError must
not be an integer, because that could be the result of an integer
division. If it's not possible to return multiple types, then the
function can make use of some error handling mechanism.

> if I believe that the ring of integers doesn't have any concept
> of division and so attempts to divide integers should be treated
> as errors.

Wouldn't that mean 3/2 would also evaluate to ValueError? But 3/2 = 1
in integer division, not 0, like 2/3. Regardless, it's a specialized
requirement, and thus should either be implemented by the programmer
or the language could provide it if it's specialized, (for instance, I
wouldn't require a language to provide text manipulation features, but
I expect them from perl because it's not a general all purpose
language [the name designates that, however it can be used as one -
like lisp])

> course the present / operator is useful, but I could do just as well
> with the divmod function which I think is more explicit.
What? Python? Aww.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Shed Skin 0.2, an experimental (restricted) Python-to-C++ compiler

2009-07-20 Thread skip

William> c 5s
William> gcj 7s
William> java 7s
William> shedskin 8s
William> python + psyco 18s
William> cython avec malloc *int 18s
William> cython 55s avec [] python
William> python 303s (5m3s)

I read just enough French to know that "avec" means "with", but I don't
understand the difference between "avec malloc *int" and "avec []".  Can you
explain please?

Thx,

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
That's more than a dress. That's an Audrey Hepburn movie. -- Jerry Maguire
-- 
http://mail.python.org/mailman/listinfo/python-list


Compilation problem with Python < 2.6 and db >= 4.7

2009-07-20 Thread kiorky
Is there a way to make the bsddb module compile against db>=4.7 for python < 2.6
(2.4.6, 2.5.4)? A patch ? A tip ?

For the moment, i have a known failure as:
gcc -pthread -fno-strict-aliasing -DNDEBUG
-I/usr/home/kiorky/minitage/dependencies/readline-5.2/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/bzip2-1.0/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/zlib-1.2/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/openssl-0.9/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/db-4.7/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/openssl-0.9/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/expat-2.0/parts/part/include  -I.
-IInclude -I./Include
-I/usr/home/kiorky/minitage/dependencies/readline-5.2/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/bzip2-1.0/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/zlib-1.2/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/openssl-0.9/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/db-4.7/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/openssl-0.9/parts/part/include
-I/usr/home/kiorky/minitage/dependencies/expat-2.0/parts/part/include -fPIC
-DPy_BUILD_CORE
-I/usr/home/kiorky/minitage/dependencies/db-4.7/parts/part/include -c
./Modules/_bsddb.c -o Modules/_bsddb.o
./Modules/_bsddb.c: In function 'DBEnv_getattr':
./Modules/_bsddb.c:5337: error: 'DB_ENV' has no member named 'db_home'
./Modules/_bsddb.c:5340: error: 'DB_ENV' has no member named 'db_home'
./Modules/_bsddb.c: In function 'init_bsddb':
./Modules/_bsddb.c:5962: error: 'DB_LOG_AUTOREMOVE' undeclared (first use in
this function)
./Modules/_bsddb.c:5962: error: (Each undeclared identifier is reported only 
once
./Modules/_bsddb.c:5962: error: for each function it appears in.)
./Modules/_bsddb.c:5963: error: 'DB_DIRECT_LOG' undeclared (first use in this
function)
./Modules/_bsddb.c:5971: error: 'DB_LOG_INMEMORY' undeclared (first use in this
function)
*** Error code 1


I looked for the one inside python >= 2.6 and it seems to have changed a lot so
backporting it seems difficult and maybe break the old API.

I didn't find something on it.

-- 
--
Cordialement,
KiOrKY
GPG Key FingerPrint: 0x1A1194B7681112AF

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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Anthony Tolle
On Jul 20, 12:27 pm, Phillip B Oldham 
wrote:
> ...
> Specifically the "differences" between lists and tuples have us
> confused and have caused many "discussions" in the office. We
> understand that lists are mutable and tuples are not, but we're a
> little lost as to why the two were kept separate from the start. They
> both perform a very similar job as far as we can tell.
> ...

There's no hard-set rules, but tuples are typically used to hold
collections of heterogeneous data, e.g. (10, "spam", 3.21).  As has
been mentioned, such a tuple can be used as a dictionary key, whereas
a list cannot be used as a dictionary key, because it is mutable.

Lists, on the other hand, typically hold collections of homogeneous
data, e.g. [1, 2, 5] or ["spam", "eggs", "sausage"].

Of course, you'll also see plenty of examples of tuples containing
homogeneous data and lists containing heterogeneous data :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem when applying Patch from issue1424152 to get https over authenticating proxies working with urllib2 in Python 2.5

2009-07-20 Thread tvashtar
On Jul 20, 4:42 pm, Nike  wrote:
> hi!
>  It's looks like a ssl error . Under the following step to help u :
>   1. takes a simple code to confirm your pupose without ssl protocol.
>   2. to confirm python version and extended libs work well
>   3. to confirm ssl work well.
>
> goog luck!
>
> nikekoo

I've reduced my code to the following:

import urllib2

p = "https://user:p...@myproxy:port";
proxy_handler = urllib2.ProxyHandler({"https": p})
urllib2.install_opener(urllib2.build_opener(proxy_handler))
request = urllib2.Request( "https://groups.google.com";)
response = urllib2.urlopen(request)

and it is now failing with:

Traceback (most recent call last):
  File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
\test.py", line 12, in 
response = urllib2.urlopen(request)
  File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 379, in open
response = self._open(req, data)
  File "C:\Python25\lib\urllib2.py", line 397, in _open
'_open', req)
  File "C:\Python25\lib\urllib2.py", line 358, in _call_chain
result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 1115, in https_open
return self.do_open(httplib.HTTPSConnection, req)
  File "C:\Python25\lib\urllib2.py", line 1082, in do_open
raise URLError(err)
urllib2.URLError: 

I thought the proxy_handler should take care of the authentication?

Thanks for your help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On out-of-date Python Applications

2009-07-20 Thread David Robinow
On Mon, Jul 20, 2009 at 12:09 PM, Virgil Stokes wrote:
> David Robinow wrote:
>
> On Mon, Jul 20, 2009 at 7:24 AM, John Machin wrote:
> ...
>
>
> The next step would be to try to compile ODE 0.7 or 0.8 with VS9 --
> however this would require "project files" for ODE for VS9, and there
> aren't any on the ODE website; it has only those for VS3 and VS5.
>
>
>
>  The ODE site is a mess.
> Go to http://www.ode.org/svn.html  and click on:   Instructions for
> accessing the repository
>  Scroll down to the section "Building with Premake"
>  (Note that there is no directory "ode/build" -- you want the "build"
> directory, which contains premake4.exe)
> I used "premake4 --with-demos --with-tests vs2008"
> I have successfully compiled ode-0.11.1 using these instructions. I
> have not yet run the tests or demos or tried to compile PyODE.
>
>
> Thanks for this information David.
> Now that you have successfully compiled ode-0.11.1, how can one finish this
> process --- compile PyODE?
>
> --V
>
Edit setup.py   Windows specific settings:
 ODE_BASE to location of your ode distribution
 create releaselib directory under lib and copy the .lib file that you built in
Visual Studio.  This will be:
   ReleaseSingleLib\ode_single.lib  or
   ReleaseDoubleLib\ode_double.lib  or one of the Debug versions
 Change the name to ode.lib.
 i.e. in CMD-speak:  %ODE_BASE%\lib\releaselib\ode.lib

I was then able to build PyODE-1.2.0

However, all the examples died with:
  ODE Message 2: mass must be > 0 <..\..\ode\src\mass.cpp:49)

I don't have time right now to debug this. Maybe somebody else can take it a
bit further.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comments? storing a function in an object

2009-07-20 Thread Francesco Bochicchio
On Jul 20, 6:22 pm, Esmail  wrote:
> Hello all,
>
> I am trying to store a function and some associated information in an
> object so that I can later have series of functions in a list that I can
> evaluate one at a time.
>
> Right now I am only storing the function itself, the number of
> arguments it expects and its string representation. I may add other
> information such as the acceptable range for the parameters or other
> characteristics such as maximum or minimum.
>
> I wonder if anyone could comment on my implementation and offer
> suggestions or constructive criticisms?
>
> The 'loading' of the functions is a bit tedious and of course care
> has to be taken to make sure the string representation corresponds to
> the actual function computed. It would be nice if there was an
> automatic way to convert the function to its string representation.
>
> Comments or problems with the approach I have taken?
>
> Thanks,
> Esmail
>
> --
>
> #!/usr/bin/env python
>
> #
> # store and represent functions
> #
>
> import math
>
> class FunctionException(Exception):
>      """ custom exception """
>      def __init__(self, value):
>          self.parameter = value
>
>      def __str__(self):
>          return repr(self.parameter)
>
> class Function(object):
>      """ class to represent a function """
>
>      def __init__(self, fn, fn_str, num_vars):
>          """
>          the function, its string representation, and the number of variables
>          """
>          self.fn = fn
>          self.fn_str = fn_str
>          self.num_vars = num_vars
>
>      def eval_fn(self, variables):
>          """ size of variables should equal num_vars .. else problem """
>          if len(variables) == self.num_vars:
>              result = self.fn(*variables)
>              return result
>          else:
>              raise FunctionException('invalid number of args provided - '+
>                                      'received %d, expected %d'
>                                      %(len(variables), self.num_vars))
>
>      def str(self):
>          """ return string representation of function """
>          return self.fn_str
>
> def funct1(x):
>      ''' small test function '''
>      return x * x
>
> def funct2(x, y):
>      ''' small test function '''
>      return x + y
>
> def funct3(x):
>      ''' small test function '''
>      return 1000 + (x*x + x) * math.cos(x)
>
> def main():
>      """ main method """
>      print 'in main'
>
>      fn1 = Function(funct1, 'x * x', 1)
>      fn2 = Function(funct2, 'x + y', 2)
>      fn3 = Function(funct3, '1000 + (x*x + x) * cos(x)', 1)
>
>      for i in range(-10, 10):
>          try:
>
>              print 'f(', [i],') =',
>              print fn3.str(), ' => ',
>              print fn3.eval_fn([i])
>
>          except FunctionException, (ex):
>              print ex.parameter
>
> if __name__ == '__main__':
>      main()


I can offer some small suggestions: it is up to you to evaluate if
they make sense for your app:

1. use __doc__ function standard attribute for function description
(your fn_str); this meanst that
   you do not need fm_str in the constructor and you have to do e.g. :

def funct2(x, y):
  ''' x + y '''
  return x + y

then funct2.__doc__  becomes the string you want to associate to the
function

2. Use __call__ instead of eval_fn : this way, the instance of your
Function became a 'callable' and can be used
   everywhere a function is needed. You can do:

   f = Function(...)
   f( some_args )

3. If you call a python function with wrong number of arguments, it
already raises a TypeError exception which contains
   - with different wording - the same information of your
FunctionException : consider removing the check and using the
   python error instead


HTH

Ciao
--
FB


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


Re: Design question.

2009-07-20 Thread Marcus Wanner

On 7/20/2009 9:42 AM, Lacrima wrote:

On Jul 20, 4:05 pm, Jean-Michel Pichavant 
wrote:

Lacrima wrote:

Hello!
I am newbie in python and I have really simple question, but I need
your advice to know how to do best.
I need to store a number of dictionaries in certain place. I've
decided to store them in a separate module.
Like this:
dicts.py
---
dict1 = {}
dict2 = {}
dict3 = {}
Then, when I need any dictionary, I can access it:
import dicts
dicts.dict1
Is it a good practice? Or should I store them as class attributes or
anything else?
Thanks in advance.
With regards, Max
(sorry if my English isn't very proper)

Defining dict as a module attribute ic correct, but try to answer the
following question:

Is dict1 an attribute/property/declension of the object/entity defined
by the module dicts ?
If yes, then your design is correct.

An correct example:
fruits.py

apple = {}
banana = {}

An incorrect one:
fruit.py
---
apple={}
bicycle={}

Basically, the rule is very straightforward, set your dict as a module
attribute only if its one of its attribute (very nice paraphrase !)
Most of people (including me) tend to have a  module, where they put
everything they have no idea about their location. This is a bad habit
and result from a uncontrolled/undocumented design. Usually documenting
objects in such modules is really painful.

Your proposal is fine from a python syntax point of view. I can't tell
of your design with names like (dicts.py and dict1,dict2) hoping you do
not intend to name them that way.

JM


Hi, Jean-Michel!

Thanks for your answer.
I am not going to have names like dicts.py and dict1,dict2. That was
just example. I wanted to know if it is correct to have dictionaries
on a module level. Now I know that this is correct. I want to collect
in one module a number of dictionaries, every of which describes a
separate web service. And my function in another module will import
required dictionary, depending on what web service should be used.
Thanks again for the help.

With regards,
Max.
(sorry if my English isn't very proper)
Yeah, you can put just about anything in a separate module/file, but 
putting unrelated things in the same module is bad...


For example, if you have apple and banana in a module, and had a 
function called slicefruit() to do something to those variables in there 
with them, then that would be good. But if you put bicycle and car and 
adjustbrakes() in the module with the fruits, or mixed the two groups in 
several modules, that would be bad.


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


Re: win32api install problem

2009-07-20 Thread MCIPERF
On Jul 20, 9:57 am, Tim Golden  wrote:
> Gerry wrote:
> > I'm running Python 2.6 under XP.
>
> > I've installed Windows 32 extensions for Python 2.6 version 1.4
> > (pywin32-214.win32-py2.6.exe).
>
> > But If I try to import win32api, I get:
>
> >   File "C:\python_projects\euler\driveletters.py", line 1, in 
> >     import win32api
> > ImportError: DLL load failed: The specified module could not be found.
>
> Used to be you'd get this error if you installed as a
> non-admin user. Don't know if that's still an issue.
> Possibility?
>
> TJG

Not a possibility (afaict) -- I am an administrator, according to the
control panel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Michiel Overtoom

Phillip wrote:


Specifically the "differences" between lists and tuples have us
confused and have caused many "discussions" in the office. We
understand that lists are mutable and tuples are not, but we're a
little lost as to why the two were kept separate from the start. They
both perform a very similar job as far as we can tell.


Yes, but because of their immutability you can use tuples as dictionary 
keys (only if they contain immutable objects).

Lists can't be used as dictionary keys.

Greetings,

--
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Valloppillil
http://www.catb.org/~esr/halloween/halloween4.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: any suggestions to synchronize typed text and speech ?

2009-07-20 Thread Marcus Wanner

On 7/20/2009 5:34 AM, Stef Mientki wrote:

thanks Marcus,

Marcus Wanner wrote:

On 7/19/2009 4:15 PM, Stef Mientki wrote:

hello,

I'm using Scintilla as a wxPython widget with great pleasure.
I now have an application where I want to make notes during a 
conversation,

but also want to record the speech during that conversation.
I'm using Scintilla as a wxPython widget for editing and PyAudio for 
the speech recording,

until so far everything works fine.

Here the problem part:
I need to synchronize the typed text with the sound during playback.
So if I click somewhere in the sound recording,
the line of text, typed that moment should be highlighted.
And vise versa, if the cursor in the text is moved and some special 
key is pressed,

the sound starting 10 or 20seconds earlier should be playbacked.

I though of adding bookmarks (because these are fixed in the text), 
and keep a list of bookmarks and sound pointers.

This idea should work, but there are only 31 bookmarks.

Any other suggestions ?

thanks,
Stef Mientki
That sounds like a very specialized type of thing, 

Well from an application point of view,
with the current netbooks,
this looks like a perfect tool for any conversation or meeting.
which only the few people with experience with wxPython, PyAudio, and 
Scintilla could help you with...



I was afraid of that too, so I dropped the question in several places,
and the writer of Scintilla himself came with the perfect answer.

cheers,Stef
But you might try having a dictionary with notes and associated times, 
or just give each note a four-digit ID number at the beginning of it 
when it's entered and use that in the dictionary (to keep keys 
shorter). Or you could just do a little hack and increase the number 
of bookmarks allowed (seeing as source is available) :p


Marcus


Glad you got a good answer from somebody. Sounds like an interesting 
project. About when would this be headed for a release? Could you post a 
link to a googlecode or sourceforge project or something so I can follow 
and/or help with development?


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


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Duncan Booth
Phillip B Oldham  wrote:

> This make a lot more sense to us, and follows the convention from
> other languages. It would also mean chaining methods to manipulate
> lists would be easier:
> 
 x = [2,1,3]
 print x.sort()[0]
> 3
 print x
> [2,1,3]

You already have a way to do what you want:

>>> x = [2,1,3]
>>> print sorted(x)[0]
3
>>> print x
[2,1,3]

as a bonus you can use 'sorted' to sort any sequence including generators 
or tuples, but the result will always be a list: if it was a list method 
then you would have to convert the sequence to a list first.

The main reason why you need both lists and tuples is that because a tuple 
of immutable objects is itself immutable you can use it as a dictionary 
key. You can't use a list as a dictionary key because if something were to 
mutate a key the dictionary structure would behave very strangely indeed.
The types 'set' and 'frozenset' both exist for the same reason.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread Marcus Wanner

On 7/20/2009 2:13 AM, Paul Rubin wrote:

Steven D'Aprano  writes:
Besides, one can legitimately disagree that 2/3 => 0 is the wrong thing 
to do. It's the right thing to do if you're doing integer maths.


I wonder whether 2/3 => ValueError is preferable.

Not for me :(
--
http://mail.python.org/mailman/listinfo/python-list


Re: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!)

2009-07-20 Thread D'Arcy J.M. Cain
On 20 Jul 2009 09:00:33 -0700
a...@pythoncraft.com (Aahz) wrote:
> Out of curiosity, are there any JavaScript toolkits that generate code
> that degrades gracefully when JavaScript is disabled?

I understand what you want but I can't see how a toolkit can do that.
How do you program "graceful?"  It seems pretty application specific.

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


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread Paul Rubin
vippstar  writes:
> > I wonder whether 2/3 => ValueError is preferable.
> 
> Not all software wants this. It shouldn't be part of the language but
> rather part of your code if you need such a feature. (for instance, to
> distinguish between 2/3 and divisions with 0 dividend).

I don't see how to implement such a thing in my code, if I believe
that the ring of integers doesn't have any concept of division and so
attempts to divide integers should be treated as errors.  Yes of
course the present / operator is useful, but I could do just as well
with the divmod function which I think is more explicit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Tycho Andersen
On Mon, Jul 20, 2009 at 11:27 AM, Phillip B
Oldham wrote:
> 
> We often find we need to do manipulations like the above without
> changing the order of the original list, and languages like JS allow
> this. We can't work out how to do this in python though, other than
> duplicating the list, sorting, reversing, then discarding.
>

I have no idea about why the design decisions were made. You might
take a look at the sorted() function:
http://docs.python.org/library/functions.html#sorted

It will do what you want.

\t
--
http://tycho.ws
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Shed Skin 0.2, an experimental (restricted) Python-to-C++ compiler

2009-07-20 Thread Bearophile
William Dode':
> I just tested it with a litle game, to find the places of horse on
> a board 5x5. The result is :
>
> c 5s
> gcj 7s
> java 7s
> shedskin 8s
> python + psyco 18s
> cython avec malloc *int 18s
> cython 55s avec [] python
> python 303s (5m3s)

Nice timings, can you please show me the Python, Java and C code
versions? I may do more tests.
The purpose of all those "example programs" in ShedSkin is to find
bugs and to find details to speedup.

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


Re: Running a Python Service under the LocalService or NetworkService Account

2009-07-20 Thread David Adamo Jr.
On Jul 20, 5:14 pm, Tim Golden  wrote:
> mistersexy wrote:
> > On Jul 20, 3:03 pm, Tim Golden  wrote:
> >> mistersexy wrote:
> >>> I am trying to create a Windows service in Python using pywin32. I do
> >>> not want this service to run under a user account. I want this service
> >>> to be able to run as a LocalService, NetworkService and the like. How
> >>> do I specify this using the win32 library? Thanks, everyone.
> >> When you "install" the service, using the HandleCommandLine
> >> option, specify --username= and --password options.
>
> >> TJG
>
> > That's exactly my point. I do not want to have to specify username and
> > password options. For instance, when creating a Windows Service
> > in .NET, it is possible to specify that the service should run using
> > the LocalService or NetworkService account. Doing this, you would not
> > need to specify username and password options. Is there a way to
> > achieve this in Python?
>
> Sorry, I misread: I mentally removed the "not" in your 'I do not want
> this service to run under a user account' and reinserted it
> further on!
>
> By default, the service will run as LocalSystem: you
> only specify a username to override that default. The value
> in Username is passed straight through to the CreateService
> Win32 API, and the docs for that:
>
>  http://msdn.microsoft.com/en-us/library/ms682450%28VS.85%29.aspx
>
> say:
>
> """
> lpServiceStartName [in, optional]
>
>     The name of the account under which the service should run. If the 
> service type is SERVICE_WIN32_OWN_PROCESS, use an account name in the form 
> DomainName\UserName. The service process will be logged on as this user. If 
> the account belongs to the built-in domain, you can specify .\UserName.
>
>     If this parameter is NULL, CreateService uses the LocalSystem account. If 
> the service type specifies SERVICE_INTERACTIVE_PROCESS, the service must run 
> in the LocalSystem account.
>
>     If this parameter is NT AUTHORITY\LocalService, CreateService uses the 
> LocalService account. If the parameter is NT AUTHORITY\NetworkService, 
> CreateService uses the NetworkService account.
>
>     A shared process can run as any user.
>
>     If the service type is SERVICE_KERNEL_DRIVER or 
> SERVICE_FILE_SYSTEM_DRIVER, the name is the driver object name that the 
> system uses to load the device driver. Specify NULL if the driver is to use a 
> default object name created by the I/O system.
>
>     A service can be configured to use a managed account or a virtual 
> account. If the service is configured to use a managed service account, the 
> name is the managed service account name. If the service is configured to use 
> a virtual account, specify the name as NT SERVICE\ServiceName. For more 
> information about managed service accounts and virtual accounts, see the 
> Service Accounts Step-by-Step Guide.
>
>         Windows Server 2008, Windows Vista, Windows Server 2003, and Windows 
> XP/2000:  Managed service accounts and virtual accounts are not supported 
> until Windows 7 and Windows Server 2008 R2.
> """
>
> So, although I haven't tried it, it looks as though you can pass
> "LocalService" or "NetworkService" and so on if you want to
> override the default LocalSystem but don't want to specify a
> username/password.
>
> TJG

I'll try this stuff. Thanks a million...I'll let everyone know how it
goes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Help understanding the decisions *behind* python?

2009-07-20 Thread Phillip B Oldham
My colleagues and I have been working with python for around 6 months
now, and while we love a lot of what python has done for us and what
it enables us to do some of the decisions behind such certain
data-types and their related methods baffle us slightly (when compared
to the decisions made in other, similarly powerful languages).

Specifically the "differences" between lists and tuples have us
confused and have caused many "discussions" in the office. We
understand that lists are mutable and tuples are not, but we're a
little lost as to why the two were kept separate from the start. They
both perform a very similar job as far as we can tell.

Consider the following:

>>> x = [2,1,3]
>>> x.sort()
>>> print x
[1, 2, 3]

Now, if the sort operations were unable to affect the original
structure of the list (as in JavaScript) you'd effectively have a
tuple which you could add/remove from, and the example above would
look more like:

>>> x = [2,1,3]
>>> print x.sort()
[1, 2, 3]
>>> print x
[2,1,3]

This make a lot more sense to us, and follows the convention from
other languages. It would also mean chaining methods to manipulate
lists would be easier:

>>> x = [2,1,3]
>>> print x.sort()[0]
3
>>> print x
[2,1,3]

We often find we need to do manipulations like the above without
changing the order of the original list, and languages like JS allow
this. We can't work out how to do this in python though, other than
duplicating the list, sorting, reversing, then discarding.

We're not looking to start any arguments or religious wars and we're
not asking that python be changed into something its not. We'd simply
like to understand the decision behind the lists and tuple structures.
We feel that in not "getting" the difference between the two types we
may be missing out on using these data structures to their full
potential.
-- 
http://mail.python.org/mailman/listinfo/python-list


comments? storing a function in an object

2009-07-20 Thread Esmail

Hello all,

I am trying to store a function and some associated information in an
object so that I can later have series of functions in a list that I can
evaluate one at a time.

Right now I am only storing the function itself, the number of
arguments it expects and its string representation. I may add other
information such as the acceptable range for the parameters or other
characteristics such as maximum or minimum.

I wonder if anyone could comment on my implementation and offer
suggestions or constructive criticisms?

The 'loading' of the functions is a bit tedious and of course care
has to be taken to make sure the string representation corresponds to
the actual function computed. It would be nice if there was an
automatic way to convert the function to its string representation.

Comments or problems with the approach I have taken?

Thanks,
Esmail

--

#!/usr/bin/env python

#
# store and represent functions
#

import math

class FunctionException(Exception):
""" custom exception """
def __init__(self, value):
self.parameter = value

def __str__(self):
return repr(self.parameter)



class Function(object):
""" class to represent a function """

def __init__(self, fn, fn_str, num_vars):
"""
the function, its string representation, and the number of variables
"""
self.fn = fn
self.fn_str = fn_str
self.num_vars = num_vars


def eval_fn(self, variables):
""" size of variables should equal num_vars .. else problem """
if len(variables) == self.num_vars:
result = self.fn(*variables)
return result
else:
raise FunctionException('invalid number of args provided - '+
'received %d, expected %d'
%(len(variables), self.num_vars))


def str(self):
""" return string representation of function """
return self.fn_str




def funct1(x):
''' small test function '''
return x * x


def funct2(x, y):
''' small test function '''
return x + y


def funct3(x):
''' small test function '''
return 1000 + (x*x + x) * math.cos(x)





def main():
""" main method """
print 'in main'

fn1 = Function(funct1, 'x * x', 1)
fn2 = Function(funct2, 'x + y', 2)
fn3 = Function(funct3, '1000 + (x*x + x) * cos(x)', 1)

for i in range(-10, 10):
try:

print 'f(', [i],') =',
print fn3.str(), ' => ',
print fn3.eval_fn([i])

except FunctionException, (ex):
print ex.parameter



if __name__ == '__main__':
main()

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


Re: Running a Python Service under the LocalService or NetworkService Account

2009-07-20 Thread Tim Golden

mistersexy wrote:

On Jul 20, 3:03 pm, Tim Golden  wrote:

mistersexy wrote:

I am trying to create a Windows service in Python using pywin32. I do
not want this service to run under a user account. I want this service
to be able to run as a LocalService, NetworkService and the like. How
do I specify this using the win32 library? Thanks, everyone.

When you "install" the service, using the HandleCommandLine
option, specify --username= and --password options.

TJG


That's exactly my point. I do not want to have to specify username and
password options. For instance, when creating a Windows Service
in .NET, it is possible to specify that the service should run using
the LocalService or NetworkService account. Doing this, you would not
need to specify username and password options. Is there a way to
achieve this in Python?


Sorry, I misread: I mentally removed the "not" in your 'I do not want
this service to run under a user account' and reinserted it
further on!

By default, the service will run as LocalSystem: you
only specify a username to override that default. The value
in Username is passed straight through to the CreateService
Win32 API, and the docs for that:

 http://msdn.microsoft.com/en-us/library/ms682450%28VS.85%29.aspx


say:

"""
lpServiceStartName [in, optional]

   The name of the account under which the service should run. If the service 
type is SERVICE_WIN32_OWN_PROCESS, use an account name in the form 
DomainName\UserName. The service process will be logged on as this user. If the 
account belongs to the built-in domain, you can specify .\UserName.

   If this parameter is NULL, CreateService uses the LocalSystem account. If 
the service type specifies SERVICE_INTERACTIVE_PROCESS, the service must run in 
the LocalSystem account.

   If this parameter is NT AUTHORITY\LocalService, CreateService uses the 
LocalService account. If the parameter is NT AUTHORITY\NetworkService, 
CreateService uses the NetworkService account.

   A shared process can run as any user.

   If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, 
the name is the driver object name that the system uses to load the device 
driver. Specify NULL if the driver is to use a default object name created by 
the I/O system.

   A service can be configured to use a managed account or a virtual account. 
If the service is configured to use a managed service account, the name is the 
managed service account name. If the service is configured to use a virtual 
account, specify the name as NT SERVICE\ServiceName. For more information about 
managed service accounts and virtual accounts, see the Service Accounts 
Step-by-Step Guide.

   Windows Server 2008, Windows Vista, Windows Server 2003, and Windows 
XP/2000:  Managed service accounts and virtual accounts are not supported until 
Windows 7 and Windows Server 2008 R2.
"""



So, although I haven't tried it, it looks as though you can pass 
"LocalService" or "NetworkService" and so on if you want to

override the default LocalSystem but don't want to specify a
username/password.

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


Re: On out-of-date Python Applications

2009-07-20 Thread Virgil Stokes




David Robinow wrote:

  On Mon, Jul 20, 2009 at 7:24 AM, John Machin wrote:
...
  
  
The next step would be to try to compile ODE 0.7 or 0.8 with VS9 --
however this would require "project files" for ODE for VS9, and there
aren't any on the ODE website; it has only those for VS3 and VS5.


  
   The ODE site is a mess.
Go to http://www.ode.org/svn.html  and click on:   Instructions for
accessing the repository
 Scroll down to the section "Building with Premake"
 (Note that there is no directory "ode/build" -- you want the "build"
directory, which contains premake4.exe)
I used "premake4 --with-demos --with-tests vs2008"
I have successfully compiled ode-0.11.1 using these instructions. I
have not yet run the tests or demos or tried to compile PyODE.
  

Thanks for this information David.
Now that you have successfully compiled ode-0.11.1, how can one finish
this process --- compile PyODE?

--V



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


JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!)

2009-07-20 Thread Aahz
In article ,
tkouts   wrote:
>
>I'm pleased to announce the new version of Porcupine Web Application
>Server, a Python based framework that provides front-end and back-end
>technologies for building modern data-centric Web 2.0 applications.
>
>  [...]
>
>QuiX, the server's integrated JavaScript toolkit, has reached the
>major milestone of supporting all the popular browsers including
>Opera, Safari 4 and IE8.  [...]

Out of curiosity, are there any JavaScript toolkits that generate code
that degrades gracefully when JavaScript is disabled?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"The volume of a pizza of thickness 'a' and radius 'z' is
given by pi*z*z*a"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running a Python Service under the LocalService or NetworkService Account

2009-07-20 Thread mistersexy
On Jul 20, 3:03 pm, Tim Golden  wrote:
> mistersexy wrote:
> > I am trying to create a Windows service in Python using pywin32. I do
> > not want this service to run under a user account. I want this service
> > to be able to run as a LocalService, NetworkService and the like. How
> > do I specify this using the win32 library? Thanks, everyone.
>
> When you "install" the service, using the HandleCommandLine
> option, specify --username= and --password options.
>
> TJG

That's exactly my point. I do not want to have to specify username and
password options. For instance, when creating a Windows Service
in .NET, it is possible to specify that the service should run using
the LocalService or NetworkService account. Doing this, you would not
need to specify username and password options. Is there a way to
achieve this in Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: are user defined classes hashable?

2009-07-20 Thread Hyuga
On Jul 19, 11:39 am, Nicolas Dandrimont 
wrote:
> * Alan G Isaac  [2009-07-19 14:46:12 +]:
>
> > Again, my question is about the class not its instances,
> > but still, checking as you suggest gives the same answer.
>
> That's what I get for answering before my coffee!

Regardless, Nicolas's example can be applied to the class too:

>>> class Foo(object):
pass

>>> hash(Foo)
11443104
>>> id(Foo)
11443104

class objects are just objects of type 'type'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem when applying Patch from issue1424152 to get https over authenticating proxies working with urllib2 in Python 2.5

2009-07-20 Thread Nike
On Jul 20, 11:11 pm, tvashtar  wrote:
> Hi,
> I'm trying to get https requests working through an authenticating
> proxy with urllib2 in Python 2.5, I'm aware that this isn't supported
> "out of the box", so applied the 
> patchhttp://bugs.python.org/file9753/http-tunnel-urllib
> linked fromhttp://bugs.python.org/issue1424152, my baseline test
> program is the following:
>
> p = "user:p...@proxy:port"
> proxy_handler = urllib2.ProxyHandler({"http": p, "https": p})
> urllib2.install_opener( urllib2.build_opener( urllib2.HTTPHandler,
>
> urllib2.HTTPSHandler,
>
> proxy_handler))
>
> request = urllib2.Request( "https://groups.google.com";)
> response = urllib2.urlopen(request)
>
> Unfortunately this doesn't work, the call stack being:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
> \urllib2.py", line 121, in urlopen
>     return _opener.open(url, data)
>   File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
> \urllib2.py", line 374, in open
>     response = self._open(req, data)
>   File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
> \urllib2.py", line 392, in _open
>     '_open', req)
>   File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
> \urllib2.py", line 353, in _call_chain
>     result = func(*args)
>   File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
> \urllib2.py", line 1108, in https_open
>     return self.do_open(httplib.HTTPSConnection, req)
>   File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
> \urllib2.py", line 1075, in do_open
>     raise URLError(err)
> urllib2.URLError:  routines:SSL23_GET_SERVER_HELLO:unknown protocol')>
>
> Does anyone know why I might be hitting this issue?
> Any help is greatly appreciated,
> thanks

hi!
 It's looks like a ssl error . Under the following step to help u :
  1. takes a simple code to confirm your pupose without ssl protocol.
  2. to confirm python version and extended libs work well
  3. to confirm ssl work well.

goog luck!

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


Problem when applying Patch from issue1424152 to get https over authenticating proxies working with urllib2 in Python 2.5

2009-07-20 Thread tvashtar
Hi,
I'm trying to get https requests working through an authenticating
proxy with urllib2 in Python 2.5, I'm aware that this isn't supported
"out of the box", so applied the patch 
http://bugs.python.org/file9753/http-tunnel-urllib
linked from http://bugs.python.org/issue1424152 , my baseline test
program is the following:

p = "user:p...@proxy:port"
proxy_handler = urllib2.ProxyHandler({"http": p, "https": p})
urllib2.install_opener( urllib2.build_opener( urllib2.HTTPHandler,
 
urllib2.HTTPSHandler,
 
proxy_handler))

request = urllib2.Request( "https://groups.google.com";)
response = urllib2.urlopen(request)

Unfortunately this doesn't work, the call stack being:

Traceback (most recent call last):
  File "", line 1, in 
  File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
\urllib2.py", line 374, in open
response = self._open(req, data)
  File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
\urllib2.py", line 392, in _open
'_open', req)
  File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
\urllib2.py", line 353, in _call_chain
result = func(*args)
  File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
\urllib2.py", line 1108, in https_open
return self.do_open(httplib.HTTPSConnection, req)
  File "D:\p4\depot\Development\HEAD\Build\ReleaseSystem\DownloadSystem
\urllib2.py", line 1075, in do_open
raise URLError(err)
urllib2.URLError: 

Does anyone know why I might be hitting this issue?
Any help is greatly appreciated,
thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposal: add setresuid() system call to python

2009-07-20 Thread Hrvoje Niksic
"Diez B. Roggisch"  writes:

To emulate the os-module-type calls, it's better to raise exceptions
than return negative values:

> def setresuid(ruid, euid, suid):
> return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid))

def setresuid(ruid, euid, suid):
res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid))
if res < 0:
raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno)))
-- 
http://mail.python.org/mailman/listinfo/python-list


Auto-generate GUI from a database table structure

2009-07-20 Thread Boyd, Craig1
Hello All,

I am REALLY new to python and still trying to figure a lot of this stuff out.
I am trying to write a couple screens to update three or four database tables 
on Oracle 10g and I was wondering if there was a way to automatically generate 
some kind of GUI shell based on the tables that I could then fill in with the 
logic / functionality I need.
I have coded and run some of the python / tcl examples that I could find so I 
kind of get that, but it appears to be a bit labor intensive.

Is there an easier way?

Thanks,

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


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread Grant Edwards
On 2009-07-20, Tim Daneliuk  wrote:

>>> In fact, picking a computer language is the most important
>>> discussion in Computer Science and eclipses even P=NP? in
>>> significance. I sure hope we can keep this thread going for a
>>> few months.
>> 
>> Please feel free to extend this flame-war along for a few
>> months on comp.lang.lisp.  Not here.
>
> Uh Carl ... are you familiar with the concept of mocking humor?

Irony on Usenet: always a bit of a gamble...

-- 
Grant Edwards   grante Yow! Vote for ME -- I'm
  at   well-tapered, half-cocked,
   visi.comill-conceived and
   TAX-DEFERRED!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mutable Strings - Any libraries that offer this?

2009-07-20 Thread Steven D'Aprano
On Mon, 20 Jul 2009 21:08:22 +1000, Ben Finney wrote:

> casebash  writes:
> 
>> I have searched this list and found out that Python doesn't have a
>> mutable string class (it had an inefficient one, but this was removed
>> in 3.0). Are there any libraries outside the core that offer this?
> 
> A mutable string would not (AFAICT) be usefully implementable as a
> subclass of the built-in string types. So even if such a type existed,
> it would not be useable with all the functionality that works with
> strings.

If applications ignore duck-typing and do isinstance(value, str), it's 
arguably the application and not the value that is broken.

Besides, with the new __isinstance__ method, surely such a mutable string 
could claim to be an instance of string without needing to inherit from 
string?


> What is it you're trying to do that makes you search for a mutable
> string type? It's likely that a better approach can be found.

When dealing with very large strings, it is wasteful to have to duplicate 
the entire string just to mutate a single character.

However, when dealing with very large strings, it's arguably better to 
use the rope data structure instead.


http://en.wikipedia.org/wiki/Rope_(computer_science)



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


Re: Mutable Strings - Any libraries that offer this?

2009-07-20 Thread Neil Hodgson
casebash:

> I have searched this list and found out that Python doesn't have a
> mutable string class (it had an inefficient one, but this was removed
> in 3.0). Are there any libraries outside the core that offer this?

   I wrote a gap buffer implementation for Python 2.5 allowing
character, unicode character and integer elements.

http://code.google.com/p/gapbuffer/

   Its not seen much use or any maintenance so is unlikely to work with
Python 3.x.

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


Re: Why aren't OrderedDicts comparable with < etc?

2009-07-20 Thread Steven D'Aprano
On Mon, 20 Jul 2009 09:34:24 +, Sion Arrowsmith wrote:

> Terry Reedy   wrote:
>>Sion Arrowsmith wrote:
>>> Jack Diederich   wrote:
 It isn't an OrderedDict thing, it is a comparison thing.  Two regular
 dicts also raise an error if you try to LT them.
>>> Python 2.5.2
>> d1 = dict((str(i), i) for i in range (10)) d2 = dict((str(i), i)
>> for i in range (20)) d1 < d2
>>> True
>>Try reversing the definitions of d1 and d2. The dicts are probably being
>>compared by id (address), which is the 2.x CPython default.
> 
> Like this?
> 
 d1 = dict((str(i), i) for i in range (20)) 
 d2 = dict((str(i), i) for i in range (10))
 d1 < d2
> False
 id(d1) < id(d2)
> True
> 
> I didn't know that comparison for anything other than equality defaulted
> to using id. That really is rather broken, and I'm glad 3.0 fixed it.


I don't think comparisons other than equality use id. That would be 
rather insane. If anyone can demonstrate such comparisons in a built-in 
or standard library class, I'd like to see it.


For the record, dicts have been comparable with < and > since at least 
Python 1.5:

$ python1.5
Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat 
4.1.2-27)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
>>> {1: 'a', 2: 'b'} < {2: 'b', 3: 'a'}
1


Reading the docs:

http://docs.python.org/library/stdtypes.html#comparisons
http://docs.python.org/library/stdtypes.html#mapping-types-dict

I can only suggest that dicts compare in an arbitrary but consistent 
fashion. What that is based on, I don't know, but based on some very 
limited testing, I'd guess it is like this:

If the two dicts have unequal length, the longer dict compares greater 
than the shorter dict.

If the two dicts are equal in length, (key, item) pairs are compared, 
probably in lexicographic order, because the order of insertion of keys 
doesn't appear to matter.


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


Re: Running a Python Service under the LocalService or NetworkService Account

2009-07-20 Thread Tim Golden

mistersexy wrote:

I am trying to create a Windows service in Python using pywin32. I do
not want this service to run under a user account. I want this service
to be able to run as a LocalService, NetworkService and the like. How
do I specify this using the win32 library? Thanks, everyone.


When you "install" the service, using the HandleCommandLine
option, specify --username= and --password options.

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


Running a Python Service under the LocalService or NetworkService Account

2009-07-20 Thread mistersexy
I am trying to create a Windows service in Python using pywin32. I do
not want this service to run under a user account. I want this service
to be able to run as a LocalService, NetworkService and the like. How
do I specify this using the win32 library? Thanks, everyone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32api install problem

2009-07-20 Thread Tim Golden

Gerry wrote:

I'm running Python 2.6 under XP.

I've installed Windows 32 extensions for Python 2.6 version 1.4
(pywin32-214.win32-py2.6.exe).

But If I try to import win32api, I get:

  File "C:\python_projects\euler\driveletters.py", line 1, in 
import win32api
ImportError: DLL load failed: The specified module could not be found.


Used to be you'd get this error if you installed as a
non-admin user. Don't know if that's still an issue.
Possibility?

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


win32api install problem

2009-07-20 Thread Gerry
I'm running Python 2.6 under XP.

I've installed Windows 32 extensions for Python 2.6 version 1.4
(pywin32-214.win32-py2.6.exe).

But If I try to import win32api, I get:

  File "C:\python_projects\euler\driveletters.py", line 1, in 
import win32api
ImportError: DLL load failed: The specified module could not be found.

\Python26\Lib\site-packages has:

03/23/2009  08:35 AM  win32
07/20/2009  09:08 AM  win32com
02/18/2009  01:21 PM  win32comext

Can anyone offer a suggestion?

Thanks,

Gerry


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


Re: Design question.

2009-07-20 Thread Lacrima
On Jul 20, 4:05 pm, Jean-Michel Pichavant 
wrote:
> Lacrima wrote:
> > Hello!
>
> > I am newbie in python and I have really simple question, but I need
> > your advice to know how to do best.
> > I need to store a number of dictionaries in certain place. I've
> > decided to store them in a separate module.
> > Like this:
> > dicts.py
> > ---
> > dict1 = {}
> > dict2 = {}
> > dict3 = {}
>
> > Then, when I need any dictionary, I can access it:
> > import dicts
> > dicts.dict1
>
> > Is it a good practice? Or should I store them as class attributes or
> > anything else?
>
> > Thanks in advance.
>
> > With regards, Max
> > (sorry if my English isn't very proper)
>
> Defining dict as a module attribute ic correct, but try to answer the
> following question:
>
> Is dict1 an attribute/property/declension of the object/entity defined
> by the module dicts ?
> If yes, then your design is correct.
>
> An correct example:
> fruits.py
> 
> apple = {}
> banana = {}
>
> An incorrect one:
> fruit.py
> ---
> apple={}
> bicycle={}
>
> Basically, the rule is very straightforward, set your dict as a module
> attribute only if its one of its attribute (very nice paraphrase !)
> Most of people (including me) tend to have a  module, where they put
> everything they have no idea about their location. This is a bad habit
> and result from a uncontrolled/undocumented design. Usually documenting
> objects in such modules is really painful.
>
> Your proposal is fine from a python syntax point of view. I can't tell
> of your design with names like (dicts.py and dict1,dict2) hoping you do
> not intend to name them that way.
>
> JM

Hi, Jean-Michel!

Thanks for your answer.
I am not going to have names like dicts.py and dict1,dict2. That was
just example. I wanted to know if it is correct to have dictionaries
on a module level. Now I know that this is correct. I want to collect
in one module a number of dictionaries, every of which describes a
separate web service. And my function in another module will import
required dictionary, depending on what web service should be used.
Thanks again for the help.

With regards,
Max.
(sorry if my English isn't very proper)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Shed Skin 0.2, an experimental (restricted) Python-to-C++ compiler

2009-07-20 Thread Stefan Behnel
William Dode wrote:
> On 19-07-2009, Mark Dufour wrote:
>> I have just released version 0.2 of Shed Skin, an experimental
>> (restricted) Python-to-C++ compiler (http://shedskin.googlecode.com).
> 
> I just tested it with a litle game, to find the places of horse on 
> a board 5x5. The result is :
>
> [...]
> shedskin 8s
> python + psyco 18s
> cython avec malloc *int 18s
> cython 55s avec [] python
> python 303s (5m3s)

Note that both Psyco and Cython make a lot less assumptions about Python
code than Shed Skin does. Psyco has the advantage of just needing to jump
in when it finds out that it can help, so it's the most broadly compatible
of the three. But Cython also supports quite a large corpus of dynamic
Python code by now. Shed Skin has a lot of restrictions, many of which are
by design. It's not intended to compile dynamic code, and I think that's a
good thing, because that's what makes it fast for the code that it
supports. Getting the same speed in Cython requires a bit more explicit
typing, simply because Cython does not assume these restrictions.

I think that all three have their raison d'être, and it currently looks
like all three are there to stay and to keep growing better. And I'm also
happy to read that some optimisations jump from one to the other. ;)

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


Re: proposal: add setresuid() system call to python

2009-07-20 Thread Diez B. Roggisch
Neal Becker wrote:


again with his notorious gmane.comp.python.general group that doesn't work
for any decent news-reader.


> Mahmoud Abdelkader wrote:
> 
>> Why don't you write a python extension module? This is a perfect
>> opportunity for that.
>> 
> I think having a module just for one system call is a bit silly.  Why not
> add to os module?

While I do agree that it's an omission, it is easy enough to get it yourself
using ctypes:


from ctypes import *
from ctypes.util import find_library

clib = CDLL(find_library("c"))
# this might be different on 64bit
__uid_t = c_uint

_setresuid = clib.setresuid
_setresuid.argtypes = [__uid_t, __uid_t, __uid_t]
_setresuid.restype = c_int

def setresuid(ruid, euid, suid):
return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid))


print setresuid(1000, 1000, 1000) # returns 0 for me
print setresuid(1001, 1001, 1001) # fails.

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


Re: Design question.

2009-07-20 Thread Jean-Michel Pichavant

Lacrima wrote:

Hello!

I am newbie in python and I have really simple question, but I need
your advice to know how to do best.
I need to store a number of dictionaries in certain place. I've
decided to store them in a separate module.
Like this:
dicts.py
---
dict1 = {}
dict2 = {}
dict3 = {}

Then, when I need any dictionary, I can access it:
import dicts
dicts.dict1

Is it a good practice? Or should I store them as class attributes or
anything else?

Thanks in advance.

With regards, Max
(sorry if my English isn't very proper)
  
Defining dict as a module attribute ic correct, but try to answer the 
following question:


Is dict1 an attribute/property/declension of the object/entity defined 
by the module dicts ?

If yes, then your design is correct.

An correct example:
fruits.py

apple = {}
banana = {}

An incorrect one:
fruit.py
---
apple={}
bicycle={}

Basically, the rule is very straightforward, set your dict as a module 
attribute only if its one of its attribute (very nice paraphrase !)
Most of people (including me) tend to have a  module, where they put 
everything they have no idea about their location. This is a bad habit 
and result from a uncontrolled/undocumented design. Usually documenting 
objects in such modules is really painful.


Your proposal is fine from a python syntax point of view. I can't tell 
of your design with names like (dicts.py and dict1,dict2) hoping you do 
not intend to name them that way.


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


Re: Design question.

2009-07-20 Thread Lacrima
On Jul 20, 3:31 pm, "Diez B. Roggisch"  wrote:
> Lacrima wrote:
> > Hello!
>
> > I am newbie in python and I have really simple question, but I need
> > your advice to know how to do best.
> > I need to store a number of dictionaries in certain place. I've
> > decided to store them in a separate module.
> > Like this:
> > dicts.py
> > ---
> > dict1 = {}
> > dict2 = {}
> > dict3 = {}
>
> > Then, when I need any dictionary, I can access it:
> > import dicts
> > dicts.dict1
>
> > Is it a good practice? Or should I store them as class attributes or
> > anything else?
>
> It's perfectly fine to use dictionaries as module-level objects for storing
> e.g. configuration-data.
>
> OTOH it's also fine to do so as class-attributes. Choosing one over the
> other has a lot to do with the actual problem you are working on.
>
> Diez

Hi!

Thank you very much for your so soon reply!

With regards,
Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Persistent variable in subprocess using multiprocessing?

2009-07-20 Thread mheavner
Piet,

The situation is 1a of your listed options, however my issue was
solved. I was stopping the subprocesses from consuming more data at
each iteration which led to the data being lost since the subprocess
worker function would then end - I now keep them alive across
iterations.

Thanks for your help, I'm new to the multiprocessing module and this
was very helpful!

On Jul 17, 4:26 am, Piet van Oostrum  wrote:
> There is stil something not clear in your description.
>
> >m> I'm using multiprocessing to spawn several subprocesses, each of which
> >m> uses a very large data structure (making it impractical to pass it via
> >m> pipes / pickling). I need to allocate this structure once when the
> >m> process is created and have it remain in memory for the duration of
> >m> the process.
>
> I have read this as that every subprocess has its own large
> data structure and that there is no connection between these.
>
> But seeing where the discussion is going I guess there might be
> different interpretations. So can you enlighten us how the situation is?
>
> 1. Each subprocess has a copy of a data structure that is prepared by the
>    master process. Therefore you want it to be passed by the fork
>    1a. the data structure is constant i.e. the subprocess doesn't change it
>    1b. the subprocess makes changes in its copy
> 2. Each subprocess has a seperate data structure not equal to the others
> 3. Something else.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p...@vanoostrum.org

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


Re: If Scheme is so good why MIT drops it?

2009-07-20 Thread vippstar
On Jul 20, 9:13 am, Paul Rubin  wrote:
> Steven D'Aprano  writes:
> > Besides, one can legitimately disagree that 2/3 => 0 is the wrong thing
> > to do. It's the right thing to do if you're doing integer maths.
>
> I wonder whether 2/3 => ValueError is preferable.

Not all software wants this. It shouldn't be part of the language but
rather part of your code if you need such a feature. (for instance, to
distinguish between 2/3 and divisions with 0 dividend).
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >