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

2009-07-20 Thread Carl Banks
On Jul 19, 10:18 pm, Tim Daneliuk  wrote:
> Uh Carl ... are you familiar with the concept of mocking humor?

You got me, lip hurts bad. :)


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


Re: invoke method on many instances

2009-07-20 Thread Gabriel Genellina
En Sat, 18 Jul 2009 12:31:46 -0300, Alan G Isaac   
escribió:



On Fri, 17 Jul 2009 05:19:50 +, Alan G Isaac wrote:

def apply2(itr, methodname, *args, **kwargs):
f = operator.methodcaller(methodname, *args, **kwargs)
for item in itr:
f(item)



On 7/17/2009 3:45 AM Steven D'Aprano apparently wrote:

for obj in objects:
getattr(obj, methodname)(*args, **kwargs)



Are there any obvious considerations in choosing
between those two?


The operator.methodcaller version is faster in my tests for large  
collections, but slightly slower when you have very few elements.



import operator
import timeit

class X:
  def method(self, x, y, **kw): pass

def apply1(itr, methodname, *args, **kwargs):
for item in itr:
getattr(item, methodname)(*args, **kwargs)

def apply2(itr, methodname, *args, **kwargs):
f = operator.methodcaller(methodname, *args, **kwargs)
for item in itr:
f(item)

L=[X() for _ in range(3000)]
apply1(L,'method', 1, 2, foo=3)
apply2(L,'method', 1, 2, foo=3)

timeit.timeit(setup="from __main__ import apply1,apply2,L",  
stmt="apply1(L,'method', 1, 2, foo=3)", number=1000)
timeit.timeit(setup="from __main__ import apply1,apply2,L",  
stmt="apply2(L,'method', 1, 2, foo=3)", number=1000)



--
Gabriel Genellina

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


Re: Mechanize not recognized by py2exe

2009-07-20 Thread Gabriel Genellina
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


Re: tough-to-explain Python

2009-07-20 Thread greg

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.

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.

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!


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.

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


Re: any suggestions to synchronize typed text and speech ?

2009-07-20 Thread Stef Mientki

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


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


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

2009-07-20 Thread Sion Arrowsmith
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.

-- 
\S

   under construction

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


Mutable Strings - Any libraries that offer this?

2009-07-20 Thread casebash
Hi,

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?

Thanks,

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


Pep 342 (val = yield MyGenerator(foo)), synchronous os.system() that doesn't block gui event loops

2009-07-20 Thread Ville Vainio
Has anyone implementing something like what the subject line
indicates?

The idea:

To run functions that execute a series of system commands without
blocking the ui, *and* without adding state machine logic.

The syntax would be something like:

def work():

  showstatus("building")
  r = yield runshell("make")
  showstatus("installing")
  r = yield runshell("make install")
  showstatus("Success")

mygui.startwork(work)
# returns immediately, runs work() gradually in the background.


The catch is that showstatus() would need to be run in the mainloop,
so running the whole thing in a thread is a no-go.

I imagine runshell() would be implemented in terms of QProcess, or
subprocess.Popen/os.system and a worker thread.

Anyone done this already, or do I have to roll my own?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pep 342 (val = yield MyGenerator(foo)), synchronous os.system() that doesn't block gui event loops

2009-07-20 Thread Ville M. Vainio
On Jul 20, 1:12 pm, Ville Vainio  wrote:

> Has anyone implementing something like what the subject line

ImplentED.

I don't think this is that hard to do in the first place, but a
"generic" solution that can be easily tuned for different gui
mainloops would be nice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mutable Strings - Any libraries that offer this?

2009-07-20 Thread Carl Banks
On Jul 20, 2:57 am, casebash  wrote:
> Hi,
>
> 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 just did a brief search on Python Packaging Index (pypi.python.org)
and saw nothing.  You might have better luck.

I suspect there is not a mutable string class partly because there is
little demand, partly because it'd be hard to make an object that is
usable everywhere a string is.  For instance, a third-party string
object might not work with the re module.

The core does have some classes that are kind of like strings but
mutable.  The array module can create mutable arrays of characters
which are somewhat like strings.  Depending on your use case some
other things might suffice (such as mmap,  io.StringIO, or even a list
of characters).


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


Re: Pep 342 (val = yield MyGenerator(foo)), synchronous os.system() that doesn't block gui event loops

2009-07-20 Thread Ville M. Vainio
On Jul 20, 1:12 pm, Ville Vainio  wrote:

> I imagine runshell() would be implemented in terms of QProcess, or
> subprocess.Popen/os.system and a worker thread.

Actually, the problem is that of general serialization of worker
thread operations. That is, it could be something akin to:

res = yield run_in_thread(lambda : os.system('make'))

run_in_thread would basically grab a worked thread, execute the
callable, and allow the generator to proceed after the thread is done.
Now, the only thing to do is the "generator dispatcher" in gui
mainloop that finds the correct generator and makes it proceed...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mutable Strings - Any libraries that offer this?

2009-07-20 Thread Ben Finney
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.

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.

-- 
 \ “As scarce as truth is, the supply has always been in excess of |
  `\   the demand.” —Josh Billings |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On out-of-date Python Applications

2009-07-20 Thread John Machin
On Jul 20, 1:47 am, John Machin  wrote:
> On 20/07/2009 12:24 AM, Virgil Stokes wrote:
> > John Machin wrote:
> >> On Jul 19, 6:04 pm, Virgil Stokes  wrote:
> >>> I am not a heavy user of Python; but, I do work with it and some of its
> >>> application packages (e.g. PyODE), in an academic setting.
> >>> Many of these applications packages have a Windows installer which
> >>> usually works fine. However, I also try to keep up with the latest
> >>> release of Python, and this is where I often have problems. That is, the
> >>> latest Windows installer provided for some of these applications will
> >>> not install on the latest version of Python.
> > Actually John,
> > My question was about the more general case --- how to help with
> > upgrading applications; but, I will try to address your email.
> >> Otherwise: What does "will not install" mean?
> > This means that when the Windows installer is executed it informs you
> > that you do not have a match between the application and the Python that
> > it finds on your Windows PC. You can easily find this out for yourself
> > by trying to install PyODE on a Windows platform with a Python version
> > later than 2.5.x.
> >> Are these pure Python
> >> packages or do they include C extensions (binary (pyd) or source?)?
> > Obviously, this depends on the application. In the particular case that
> > I mentioned (PyODE) I believe that there is a mix of C binaries and
> > Python code.
> >> At
> >> what stage of the installation does the installation fail?
> > In the initial stages.
> >> With what
> >> error message(s)?
> > In one specific case, the message is (paraphrasing) "You do not have
> > Python 2.5 installed" --- the installation is then aborted.
> >> With what versions of Python?
>
> > I have only Python 2.6.2 on my home Windows Vista PC and PyODE does not
> > have a Windows Installer for Python 2.6.
>
> >>> I do understand that there can be a time lag between the release of
> >>> Python applications and the latest Python. I also appreciate the work of
> >>> the people that are responsible for these applications.
>
> >>> My question is --- Is there anything I, as a user of an application
> >>> package that is out-of-date with respect to the latest Python, can do to
> >>> help in this process of bringing an application  up-to-date?
> > Note, again John, my question was about how I might assist (help) with
> > the updating of applications;
>
> Your answers have been very helpful in determining exactly what your
> problem is; thank you.
>
> > but, thank you for your interest in this.
> > Perhaps, only the owner/responsible programmer for the application can
> > create a Windows installer,
>
> Given a source distribution, a suitable C++ compiler, and the suspension
> of Murphy's Law, anyone should be able to (a) install it on their own
> machine (b) make a Windows installer.
>
> > or perhaps others could assist with this ---
>
> Perhaps indeed ...
>
> > this is what my question was about. I would be glad to assist if
> > possible :-)
>
> Suggestions:
>
> (1) contact the pyODE maintainer and ask, or check out the project's
> forums on sourceforge
>
> (2) if you have a C++ compiler on your Windows box: get the source
> distribution, unpack it, ensure that the ODE_BASE in the setup.py points
> to your (existing) ODE 0.7 installation, do
>      \python26\python setup.py install
> and stand well back.
>
> I have just tried this and got a ton of warnings from the compile and 3
> errors from the link:
>
> build\lib.win32-2.6\ode.pyd : fatal error LNK1120: 3 unresolved externals
> error: command '"C:\Program Files\Microsoft Visual Studio
> 9.0\VC\BIN\link.exe"' failed with exit status 1120

Update: The problem is evidently with the lib(s) available with ODE
0.7 (or 0.8 -- there are conflicting stories about which one to use
with PyODE); they were compiled with VS2003 AFAICT and the complained-
of symbols are not supplied by VS2009 which is what I'm using to try
and build PyODE for Python 2.6 .

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.

As all I know about VS9 is that somewhere inside the ferschlugginer
100 Mb download there's a C compiler that does the right thing when
distutils pushes its button, I'm going to have to punt this back to
you to follow up on suggestion (1) ... skip asking the pyODE
maintainer (last heard saying little time available and he wasn't
even /using/ pyODE any more); try asking on the pyODE and ODE mailing-
lists has anyone contemplated a Python 2.6 / win32 / VS 2009 build of
pyODE.

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


Re: Mutable Strings - Any libraries that offer this?

2009-07-20 Thread John Machin
On Jul 20, 9:08 pm, 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.
>
> 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.
>

OK, I'll bite: where does the Python 3.x bytearray type fit into your
taxonomy? At first glance it appears to be mutable and have a fair
swag of functionality.
-- 
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 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.
-- 
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 William Dode
On 19-07-2009, Mark Dufour wrote:
> Hi all,
>
> 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 :

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

-- 
William Dodé - http://flibuste.net
Informaticien Indépendant
-- 
http://mail.python.org/mailman/listinfo/python-list


Design question.

2009-07-20 Thread Lacrima
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)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design question.

2009-07-20 Thread Diez B. Roggisch
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
-- 
http://mail.python.org/mailman/listinfo/python-list


A lot of problem with pygame.mixer module!

2009-07-20 Thread Alex
hi at all,
As email object I 'm not be able to run my program when compiled with
py2exe.
Everythink  works fine until I try to make an exe.
After that, it crash and in the log:

C:\dist\sponge.exe:97: RuntimeWarning: use mixer: DLL load failed: The
specified module could not be found.
Traceback (most recent call last):
  File "sponge.py", line 97, in 
  File "pygame\__init__.pyo", line 70, in __getattr__
NotImplementedError: mixer module not available

The code about pygame.mixer is only:

pygame.mixer.init()
music = pygame.mixer.Sound("popcorn.ogg")
music.play()

in the dist folder there is SDL_mixer.dll so...HOW can I solve this
problem ??
thanks in advance
Alex
Below my setup.py

# py2exe setup program
from distutils.core import setup
import py2exe
import pygame
from modulefinder import Module
#from pygame import mixer
import ImageGrab
import sys
import os
import Tkinter
import glob, shutil
sys.argv.append("py2exe")

VERSION = '1.0'
AUTHOR_NAME = 'Your Name'
AUTHOR_EMAIL = '[email protected]'
AUTHOR_URL = "http://www.urlofyourgamesite.com/";
PRODUCT_NAME = "Sponge"
SCRIPT_MAIN = 'sponge.py'
VERSIONSTRING = PRODUCT_NAME + " ALPHA " + VERSION
ICONFILE = 'icon.ico'

# Remove the build tree on exit automatically
REMOVE_BUILD_ON_EXIT = True

if os.path.exists('dist/'): shutil.rmtree('dist/')

extra_files = [ ("",[ICONFILE,'WinLockDll.dll','popcorn.ogg']),
   #("data",glob.glob(os.path.join('data','*.dat'))),
   #("gfx",glob.glob(os.path.join('gfx','*.jpg'))),
   #("gfx",glob.glob(os.path.join('gfx','*.png'))),
   ("fonts",glob.glob(os.path.join('fonts','*.ttf'))),
   ("music",glob.glob(os.path.join('music','*.ogg')))]
   #("snd",glob.glob(os.path.join('snd','*.wav')))]

# List of all modules to automatically exclude from distribution build
# This gets rid of extra modules that aren't necessary for proper
functioning of app
# You should only put things in this list if you know exactly what you
DON'T need
# This has the benefit of drastically reducing the size of your dist

MODULE_EXCLUDES =[
'email',
'AppKit',
'Foundation',
'bdb',
'difflib',
'tcl',
#'Tkinter',
#'Tkconstants',
'curses',
'distutils',
'setuptools',
'urllib',
'urllib2',
'urlparse',
'BaseHTTPServer',
'_LWPCookieJar',
'_MozillaCookieJar',
'ftplib',
'gopherlib',
'_ssl',
'htmllib',
'httplib',
'mimetools',
'mimetypes',
'rfc822',
'tty',
'webbrowser',
'socket',
'hashlib',
#'base64',
'compiler',
'pydoc'
]

INCLUDE_STUFF = ['encodings',"encodings.latin_1"]

setup(windows=[
 {'script': SCRIPT_MAIN,
   'other_resources': [(u"VERSIONTAG",1,VERSIONSTRING)],
   'icon_resources': [(1,ICONFILE)]}],
 options = {"py2exe": {
 "optimize": 2,
 "includes": INCLUDE_STUFF,
 "compressed": 1,
 "ascii": 1,
 #"bundle_files": 1,
 "ignores":
['tcl','AppKit','Numeric','Foundation'],
 "excludes": MODULE_EXCLUDES} },
  name = PRODUCT_NAME,
  version = VERSION,
  data_files = extra_files,
  #zipfile = None,
  author = AUTHOR_NAME,
  author_email = AUTHOR_EMAIL,
  url = AUTHOR_URL)

# Create the /save folder for inclusion with the installer
#shutil.copytree('save','dist/save')

#if os.path.exists('dist/tcl'): shutil.rmtree('dist/tcl')

# Remove the build tree
if REMOVE_BUILD_ON_EXIT:
 shutil.rmtree('build/')

if os.path.exists('dist/tcl84.dll'): os.unlink('dist/tcl84.dll')
if os.path.exists('dist/tk84.dll'): os.unlink('dist/tk84.dll')
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2009-07-20 Thread Neal Becker
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?


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


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: [email protected]

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


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


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


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


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


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


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


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 ([email protected])   <*> 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: 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


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


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


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


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


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: 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: 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: 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
[email protected] (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 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: 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: 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 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: 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: 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: 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: 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: 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: 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


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: 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 - [email protected] - 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


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


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


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: 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: [email protected]
-- 
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: 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 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: 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: 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 ([email protected])   <*> 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: 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: 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: 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: 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 / [email protected]
-- 
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: 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: 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: 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 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: 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: 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 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 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: [email protected]
-- 
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
>[email protected] (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 ([email protected])   <*> 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: 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: 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: 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: 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: 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: 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
[email protected] (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: 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


  1   2   >