mulit-dimensional lists

2009-02-28 Thread Ms FRANCES SIMS
Hi,
  I;m not sure how I got your address but I could use a friend .
Please reply and we can talk.  I would like that.
Good day,
  Joe Pyne--
http://mail.python.org/mailman/listinfo/python-list


Re: setting PYTHONPATH to override system wide site-packages

2009-02-28 Thread Carl Banks
On Feb 28, 9:18 pm, per  wrote:
> On Feb 28, 11:53 pm, per  wrote:
>
>
>
> > On Feb 28, 11:24 pm, Carl Banks  wrote:
>
> > > On Feb 28, 7:30 pm, per  wrote:
>
> > > > hi all,
>
> > > > i recently installed a new version of a package using python setup.py
> > > > install --prefix=/my/homedir on a system where i don't have root
> > > > access. the old package still resides in /usr/lib/python2.5/site-
> > > > packages/ and i cannot erase it.
>
> > > > i set my python path as follows in ~/.cshrc
>
> > > > setenv PYTHONPATH /path/to/newpackage
>
> > > > but whenever i go to python and import the module, the version in site-
> > > > packages is loaded. how can i override this setting and make it so
> > > > python loads the version of the package that's in my home dir?
>
> > > What happens when you run the command "print sys.path" from the Python
> > > prompt?  /path/to/newpackage should be the second item, and shoud be
> > > listed in front of the site-packages dir.
>
> > > What happens when you run "print os.eviron['PYTHONPATH']" at the
> > > Python interpreter?  It's possible that the sysadmin installed a
> > > script that removes PYTHONPATH environment variable before invoking
> > > Python.  What happens when you type "which python" at the csh prompt?
>
> > > What happens when you type "ls /path/to/newpackage" at your csh
> > > prompt?  Is the module you're trying to import there?
>
> > > You approach should work.  These are just suggestions on how to
> > > diagnose the problem; we can't really help you figure out what's wrong
> > > without more information.
>
> > > Carl Banks
>
> > hi,
>
> > i am setting it programmatically now, using:
>
> > import sys
> > sys.path = []
>
> > sys.path now looks exactly like what it looked like before, except the
> > second element is my directory. yet when i do
>
> > import mymodule
> > print mymodule.__version__
>
> > i still get the old version...
>
> > any other ideas?
>
> in case it helps, it gives me this warning when i try to import the
> module
>
> /usr/lib64/python2.5/site-packages/pytz/__init__.py:29: UserWarning:
> Module dateutil was already imported from /usr/lib64/python2.5/site-
> packages/dateutil/__init__.pyc, but /usr/lib/python2.5/site-packages
> is being added to sys.path
>   from pkg_resources import resource_stream

Ok then.  When pkg_resources is involved, who knows what behavior to
expect.

pkg_resources.py is a third-party module from PEAK (which
unfortunately a number of other third-party packages depend on, so it
can be hard to keep your installation free of it, but I digress).
Among other things no one knows about, it's a sort of run-time package
version management system.  It's possible, maybe, that some module
that runs on startup specifically requested and imported the version
of dateutils that's on the system path.  Which means, if you don't
properly appease pkg_resources, it could actually ignore your version
of the package even if it's earlier in the system path.  This is only
speculation, because who actually knows what's in the mind of
pkg_resources?, but if that is the reason, I won't be the one to tell
you how to fix it.

Here's something to try, however.  Set up your PYTHONPATH as you did
before, but also create an empty pkg_resources.py file in the
directory you specified.  Warning: this might make some packages
unusable.


Not-a-fan-of-pkg_resources-ly y'rs,

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


Re: What's so wrong about execfile?

2009-02-28 Thread Michele Simionato
On Feb 28, 4:21 am, Sammo  wrote:
> Given that execfile has been removed in py3k

execfile has not been really removed, it is just spelled
differently:

>>> exec(open(myfile.py).read())

BTW, from the help message

>>> help(exec)
Help on built-in function exec in module builtins:

exec(...)
exec(object[, globals[, locals]])

Read and execute code from a object, which can be a string, a code
object or a file object.
The globals and locals are dictionaries, defaulting to the current
globals and locals.  If only globals is given, locals defaults to
it.

I would have expected

>>> exec(open('myfile.py'))

to work too. Any idea why it does not?


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


file locking...

2009-02-28 Thread bruce
Hi.

Got a bit of a question/issue that I'm trying to resolve. I'm asking this of
a few groups so bear with me.

I'm considering a situation where I have multiple processes running, and
each process is going to access a number of files in a dir. Each process
accesses a unique group of files, and then writes the group of files to
another dir. I can easily handle this by using a form of locking, where I
have the processes lock/read a file and only access the group of files in
the dir based on the  open/free status of the lockfile.

However, the issue with the approach is that it's somewhat synchronous. I'm
looking for something that might be more asynchronous/parallel, in that I'd
like to have multiple processes each access a unique group of files from the
given dir as fast as possible.

So.. Any thoughts/pointers/comments would be greatly appreciated. Any
pointers to academic research, etc.. would be useful.

thanks



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


Re: i have problem with glob.glob() in remotely directory

2009-02-28 Thread Tim Roberts
lameck kassana  wrote:
>
>i did try but still not working.But also i try  os.walk() for remote
>computer like  os.walk('\\192.168.0.45') it also failed>

Of course it did, for two different reasons.  First, you can't just walk an
IP address.  You have to specify one of the shares that the machine
exposes.  Second, you STILL have a backslash problem.

If that machine has a network share called "files", you could say
os.walk( '192.168.0.45\\files' )
or
os.walk( r'\\192.168.0.45\files' )

>Thats it is my main problem do i need any new imports besides import os

No.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: setting PYTHONPATH to override system wide site-packages

2009-02-28 Thread per
On Feb 28, 11:53 pm, per  wrote:
> On Feb 28, 11:24 pm, Carl Banks  wrote:
>
>
>
> > On Feb 28, 7:30 pm, per  wrote:
>
> > > hi all,
>
> > > i recently installed a new version of a package using python setup.py
> > > install --prefix=/my/homedir on a system where i don't have root
> > > access. the old package still resides in /usr/lib/python2.5/site-
> > > packages/ and i cannot erase it.
>
> > > i set my python path as follows in ~/.cshrc
>
> > > setenv PYTHONPATH /path/to/newpackage
>
> > > but whenever i go to python and import the module, the version in site-
> > > packages is loaded. how can i override this setting and make it so
> > > python loads the version of the package that's in my home dir?
>
> > What happens when you run the command "print sys.path" from the Python
> > prompt?  /path/to/newpackage should be the second item, and shoud be
> > listed in front of the site-packages dir.
>
> > What happens when you run "print os.eviron['PYTHONPATH']" at the
> > Python interpreter?  It's possible that the sysadmin installed a
> > script that removes PYTHONPATH environment variable before invoking
> > Python.  What happens when you type "which python" at the csh prompt?
>
> > What happens when you type "ls /path/to/newpackage" at your csh
> > prompt?  Is the module you're trying to import there?
>
> > You approach should work.  These are just suggestions on how to
> > diagnose the problem; we can't really help you figure out what's wrong
> > without more information.
>
> > Carl Banks
>
> hi,
>
> i am setting it programmatically now, using:
>
> import sys
> sys.path = []
>
> sys.path now looks exactly like what it looked like before, except the
> second element is my directory. yet when i do
>
> import mymodule
> print mymodule.__version__
>
> i still get the old version...
>
> any other ideas?

in case it helps, it gives me this warning when i try to import the
module

/usr/lib64/python2.5/site-packages/pytz/__init__.py:29: UserWarning:
Module dateutil was already imported from /usr/lib64/python2.5/site-
packages/dateutil/__init__.pyc, but /usr/lib/python2.5/site-packages
is being added to sys.path
  from pkg_resources import resource_stream
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating Zip file like java jar file

2009-02-28 Thread zaheer . agadi
On Mar 1, 1:32 am, "Gabriel Genellina"  wrote:
> En Sat, 28 Feb 2009 16:51:04 -0200,  escribió:
>
>
>
> > On Feb 28, 11:33 pm, Lie Ryan  wrote:
> >> zaheer.ag...@gmail.com wrote:
> >> > On Feb 28, 11:15 pm, "Gabriel Genellina" 
> >> > wrote:
> >> >> En Sat, 28 Feb 2009 14:34:15 -0200, 
> >> escribió:
>
> >> >>> I want to create zip file equivalent to java jar file,I created a
> >> zip
> >> >>> file of my sources and added some __main__.py
> >> >>> it says __Main__.py not found in Copyproject.zip..?
> >> >> __main__.py must exist in the root directory.
>
> >> > What do you mean by root directory..?What is this directory in
> >> > Windows..?You mean the top level folder of the project?in my case
> >> > copyproject folder..?
>
> >> root directory is the topmost directory (imagine a tree, the root is
> >> where all the branches branched from), in this case the root directory
> >> is your copyproject main folder.
>
> > I wonder, I do have the __main__.py  in the root directory,but still
> > getting
> > python.exe cannot find __main__.py in CopyProject.zip
>
> The top of the tree inside the zip file. Depth zero. Not inside any
> directory. Above anything else. Just a bare name.
>
> Open your zip using the zipfile module:
>
> import zipfile
> z = zipfile.ZipFile("xxx.zip")
> z.printdir()
>
> You should see a line starting with __main__.py *without* any / in it.
>
> > I used the following command
> > python Copyproject.zip -m __main__.py --uploadFile and also tried with
> > python Copyproject.zip --uploadFile
>
> Use the second one.
>
> > both give me the same error , I can see the sys.path contains the
> > project folder.
>

> --
> Gabriel Genellina

> Uh? Which project folder? Isn't it in the .zip?
>
 Yeah I meant zip file.
I can get to work but is it is not able to locate the packages,says
import error cant find the package and module

here is my code

import sys
import os.path as op
sys.path.insert(0, op.join(op.dirname(op.abspath(__file__)),
"somezip.zip"))

import zipfile
z = zipfile.ZipFile("somezip.zip")
z.printdir()

import some.storagepackage.somemodule
print "upload"
print "syspath",sys.path

#do something

should it not find the modules when the zip files is in sys.path..?
--
http://mail.python.org/mailman/listinfo/python-list


Re: setting PYTHONPATH to override system wide site-packages

2009-02-28 Thread per
On Feb 28, 11:24 pm, Carl Banks  wrote:
> On Feb 28, 7:30 pm, per  wrote:
>
> > hi all,
>
> > i recently installed a new version of a package using python setup.py
> > install --prefix=/my/homedir on a system where i don't have root
> > access. the old package still resides in /usr/lib/python2.5/site-
> > packages/ and i cannot erase it.
>
> > i set my python path as follows in ~/.cshrc
>
> > setenv PYTHONPATH /path/to/newpackage
>
> > but whenever i go to python and import the module, the version in site-
> > packages is loaded. how can i override this setting and make it so
> > python loads the version of the package that's in my home dir?
>
> What happens when you run the command "print sys.path" from the Python
> prompt?  /path/to/newpackage should be the second item, and shoud be
> listed in front of the site-packages dir.
>
> What happens when you run "print os.eviron['PYTHONPATH']" at the
> Python interpreter?  It's possible that the sysadmin installed a
> script that removes PYTHONPATH environment variable before invoking
> Python.  What happens when you type "which python" at the csh prompt?
>
> What happens when you type "ls /path/to/newpackage" at your csh
> prompt?  Is the module you're trying to import there?
>
> You approach should work.  These are just suggestions on how to
> diagnose the problem; we can't really help you figure out what's wrong
> without more information.
>
> Carl Banks

hi,

i am setting it programmatically now, using:

import sys
sys.path = []

sys.path now looks exactly like what it looked like before, except the
second element is my directory. yet when i do

import mymodule
print mymodule.__version__

i still get the old version...

any other ideas?
--
http://mail.python.org/mailman/listinfo/python-list


Re: setting PYTHONPATH to override system wide site-packages

2009-02-28 Thread Carl Banks
On Feb 28, 7:30 pm, per  wrote:
> hi all,
>
> i recently installed a new version of a package using python setup.py
> install --prefix=/my/homedir on a system where i don't have root
> access. the old package still resides in /usr/lib/python2.5/site-
> packages/ and i cannot erase it.
>
> i set my python path as follows in ~/.cshrc
>
> setenv PYTHONPATH /path/to/newpackage
>
> but whenever i go to python and import the module, the version in site-
> packages is loaded. how can i override this setting and make it so
> python loads the version of the package that's in my home dir?


What happens when you run the command "print sys.path" from the Python
prompt?  /path/to/newpackage should be the second item, and shoud be
listed in front of the site-packages dir.

What happens when you run "print os.eviron['PYTHONPATH']" at the
Python interpreter?  It's possible that the sysadmin installed a
script that removes PYTHONPATH environment variable before invoking
Python.  What happens when you type "which python" at the csh prompt?

What happens when you type "ls /path/to/newpackage" at your csh
prompt?  Is the module you're trying to import there?

You approach should work.  These are just suggestions on how to
diagnose the problem; we can't really help you figure out what's wrong
without more information.


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


Re: Proposed implementation for an Ordered Dictionary

2009-02-28 Thread Michele Simionato
On Mar 1, 1:43 am, Paul Rubin  wrote:
> "Colin J. Williams"  writes:
>
> >      # print [mydict[x] for x in sorted(mydict.keys)] Instance object
> > is not iterable
>
> It was a typo.  Use:
>
>     print [mydict[x] for x in sorted(mydict.keys())]

Even better

print [mydict[x] for x in sorted(mydict)]
--
http://mail.python.org/mailman/listinfo/python-list


Re: OTish: convince the team to drop VBScript

2009-02-28 Thread Carl Banks
On Feb 28, 7:10 pm, Shane Geiger  wrote:
> >> The company does use Python on rare occasions. It all comes down to
> >> the prejudices and habits of one of the programmers. His only argument
> >> I can't counter -because I don't see the problem- is that "Python
> >> modules cause problems for updates to customer's installations".
>
> This is purely an argument from ignorance, a logical fallacy.

I don't think it's an argument at all.  The guy probably had something
more specific in mind but didn't express himself well, and it might
have even been a real issue.  Python is not, unfortunately, the
easiest language to deploy applications in.

I don't think there is any deployment difficulty so great that I would
ever chose VBscript, but opinions might differ.


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


setting PYTHONPATH to override system wide site-packages

2009-02-28 Thread per
hi all,

i recently installed a new version of a package using python setup.py
install --prefix=/my/homedir on a system where i don't have root
access. the old package still resides in /usr/lib/python2.5/site-
packages/ and i cannot erase it.

i set my python path as follows in ~/.cshrc

setenv PYTHONPATH /path/to/newpackage

but whenever i go to python and import the module, the version in site-
packages is loaded. how can i override this setting and make it so
python loads the version of the package that's in my home dir?

 thanks.


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


Re: OTish: convince the team to drop VBScript

2009-02-28 Thread Shane Geiger



The company does use Python on rare occasions. It all comes down to
the prejudices and habits of one of the programmers. His only argument
I can't counter -because I don't see the problem- is that "Python
modules cause problems for updates to customer's installations".



This is purely an argument from ignorance, a logical fallacy. 

Python is one of the more flexible, cleanly designed tools you could 
have at your disposal--it is certainly more powerful, flexible and 
elegant than VBScript.  If he has any doubts about how things can be 
designed with Python, show him that py2web (a web server/development 
environment) requires no installation, can run on a USB memory stick, 
can work with multiple operating systems, and can run on a cell phone 
(see youtube demo). 





Next time you talk to him, when he say that again, interrupt him, and
say: "[citation needed]" (don't forget the parentheses).

I don't really see any reason why "python modules would cause problem
for updating customer's installations", and I can't find anything on
Google that mentioned any problem. However, I do know that upgrading
python modules is easier than upgrading most other language's
libraries[citation needed].
--
http://mail.python.org/mailman/listinfo/python-list

  



--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

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


Re: Email Program

2009-02-28 Thread Shane Geiger

J wrote:

Is it possible to make a GUI email program in Python that stores
emails, composes, ect? Also, could I create my own programming
language in Python? What are Pythons limits, or is this just a waste
of my time to learn it.
  


Python is "Turing complete," which means it is a general-purpose 
programming language.  Generally speaking, this means you can do 
anything with it that you can do with any other programming language.  
Being a higher-level language, Python is often chosen over other 
languages because it is faster to do many things in Python.


You could also create another programming language with Python.  In 
fact, another general-purpose programming language (C) was used to 
create Python.


Python makes many things easy.  For many tasks, Python saves you a lot 
of time.  It is a good general-purpose tool to know how to use well.  It 
is a good beginner's language, as it makes many of the annoying things 
about programs non-issues.




--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

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


Re: why cannot assign to function call

2009-02-28 Thread Tim Roberts
Ethan Furman  wrote:
>
>Specifically, how is a new name (pbr) different, in Python, from a new 
>name initialized as if by assignment (pbv)?  It seems to me than you end 
>up with the same thing in either case (in Python, at least), making the 
>distinction non-existent.
>
>def func(bar):
> bar.pop()
>
>Pass-by-reference:
>   foo = ['Ethan','Furman']
>   func(foo)   # bar = foo

The problem here, in my view, is the terminology.  It is true that, inside
the function "func", "bar" will refer to the same list that "foo" refers
to.  However, it is inaccurate to think of this list as "foo".  There
exists a list -- an anonymous list in object space -- and while "func" is
executing, there are two names bound to that list.  So, the "bar.pop()"
instruction changes that anonymous list, you'll see those changes if you
inspect "foo" after the call.

>Pass-by-value:
>   foo = ['Python','Rocks!']
>   func(foo)   # bar is new name for foo
>   # is this any different from above?

Yes, it's different.  If Python really had "pass by value", that function
call would pass a COPY of the list.  The function would receive the list's
"value", not the list itself.

>If I have this right, in both cases foo will be reduced to a single-item 
>list after func.  Any further explanation you care to provide will be 
>greatly appreciated!

Nope.  Under pass-by-value semantics, "func" could dance on the list to its
heart's content, and "foo" would not be changed.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Email Program

2009-02-28 Thread Lie Ryan
J wrote:
> Is it possible to make a GUI email program in Python that stores
> emails, composes, ect? Also, could I create my own programming
> language in Python? What are Pythons limits, or is this just a waste
> of my time to learn it.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Python is Turing Complete.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Email Program

2009-02-28 Thread Christian Heimes
Thomas Raef wrote:
> What a great response.

It's a correct, straight forward and short answer to the op's question.

Christian

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


RE: Email Program

2009-02-28 Thread Thomas Raef
What a great response.

> -Original Message-
> From: python-list-bounces+traef=ebasedsecurity@python.org
> [mailto:python-list-bounces+traef=ebasedsecurity@python.org] On
> Behalf Of MRAB
> Sent: Saturday, February 28, 2009 8:00 PM
> To: python-list@python.org
> Subject: Re: Email Program
> 
> J wrote:
> > Is it possible to make a GUI email program in Python that stores
> > emails, composes, ect?
> >
> Yes.
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Email Program

2009-02-28 Thread J
Is it possible to make a GUI email program in Python that stores
emails, composes, ect? Also, could I create my own programming
language in Python? What are Pythons limits, or is this just a waste
of my time to learn it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Email Program

2009-02-28 Thread MRAB

J wrote:

Is it possible to make a GUI email program in Python that stores
emails, composes, ect?


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


Email Program

2009-02-28 Thread J
Is it possible to make a GUI email program in Python that stores
emails, composes, ect?
--
http://mail.python.org/mailman/listinfo/python-list


Re: OTish: convince the team to drop VBScript

2009-02-28 Thread Lie Ryan
Christian R. wrote:
> The company does use Python on rare occasions. It all comes down to
> the prejudices and habits of one of the programmers. His only argument
> I can't counter -because I don't see the problem- is that "Python
> modules cause problems for updates to customer's installations".

Next time you talk to him, when he say that again, interrupt him, and
say: "[citation needed]" (don't forget the parentheses).

I don't really see any reason why "python modules would cause problem
for updating customer's installations", and I can't find anything on
Google that mentioned any problem. However, I do know that upgrading
python modules is easier than upgrading most other language's
libraries[citation needed].
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug report: ClientForm

2009-02-28 Thread Lie Ryan
MRAB wrote:
> Muddy Coder wrote:
>> Hi Folks,
>>
>> When it parses a form, if the VALUE of a field has not space, it works
>> very well. For example, if a dropdown list, there many options, such
>> as:
>>
>>  
>>
>> the value foo will be picked up for sure. But, if there is a space:
>>
>>  .
>>
> Values should be quoted, although you can omit the quotes if there
> aren't any spaces in the string:
> 
> 
> 
> You can see examples at http://wwwsearch.sourceforge.net/ClientForm/
> 
> 
> 
> As you can see, whitespace separates the name=value pairs.

It is also a good habit to have the quotes even when you don't use
spaces. Also, knowledge of xHTML in general should come in handy.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Proposed implementation for an Ordered Dictionary

2009-02-28 Thread Paul Rubin
"Colin J. Williams"  writes:
>  # print [mydict[x] for x in sorted(mydict.keys)] Instance object
> is not iterable

It was a typo.  Use:

print [mydict[x] for x in sorted(mydict.keys())]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Proposed implementation for an Ordered Dictionary

2009-02-28 Thread Colin J. Williams

Steven D'Aprano wrote:

Colin J. Williams wrote:


Sometimes, it's useful to be able to
obtain the data in the sorted sequence.

You might consider adding functionality
like:

def seqItems(self):
'''To return the items, sorted
by key. '''
return [self[k] for k in
self.seqKeys()]


Amazingly, the Python time-machine provides such functionality! Using just a
handful of pre-existing pieces, you can do this:

sorted(mydict.items())
sorted(mydict.keys())
[mydict[x] for x in sorted(mydict.keys)]

and any other sequence you might need. That's the beauty of a general
purpose programming language. You don't need everything to be a built-in
*wink*


Thanks, you are right, you have a neat 
way of handling the first two, they
work with an instance of Raymond 
Hettinger's. OrderedDict.


The third suggestion has a couple of 
problems, which are fixed below.


if __name__ == '__main__':
d= 
OrderedDict.fromkeys('abracadabra', 
value= 'zzz')

print(d)
print(d.seqKeys())
print(d.seqItems())
print(d.seqValues())
# Steven D'Aprano's alternative
mydict= d.copy()
print sorted(mydict.items())
print sorted(mydict.keys())
# print [mydict[x] for x in 
sorted(mydict.keys)] Instance object is 
not iterable
print(sorted(iter([(x[1], x[0]) for 
x in mydict.iteritems()]))) # This works


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


Re: Bug report: ClientForm

2009-02-28 Thread Gabriel Genellina
En Sat, 28 Feb 2009 21:01:56 -0200, Muddy Coder   
escribió:



By the way, can somebody helps me on setting parameter of uploading a
file. In ClientForm, if I need to upload a text file, I can do it by:

form.add_file(..., "text/plain")

What about a picture file? What is the counterpart of 'text/plain"?


See http://www.iana.org/assignments/media-types/image/

--
Gabriel Genellina

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


Re: Static Map

2009-02-28 Thread Andrew MacIntyre

KMCB wrote:

Hello,

I'm interested in creating a static map of a region in the US.  This
map would be set into a picture format, so I can add it to a
document.  I would like it to contain some town names and road
information.  Then I would like to add points, based on LAT and LONG,
that can be labeled with information I provide.

I have done some searching, Google Maps probably will not work because
of the License.  WuGeo does not seam to have the details.  I was
considering tw.openlayers, but do not know if that is the best
starting point.  If I could not create the picture from Python, would
use tw and then create a screen shot to get started.

Does anyone have thoughts on a better approach?


While web-centric, you might find
http://www.alistapart.com/articles/takecontrolofyourmaps
an interesting read.

--
-
Andrew I MacIntyre "These thoughts are mine alone..."
E-mail: andy...@bullseye.apana.org.au  (pref) | Snail: PO Box 370
   andy...@pcug.org.au (alt) |Belconnen ACT 2616
Web:http://www.andymac.org/   |Australia
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug report: ClientForm

2009-02-28 Thread MRAB

Muddy Coder wrote:

Hi Folks,

As directed, I got ClientForm and played with it. It is cool! However,
I also found a bug:

When it parses a form, if the VALUE of a field has not space, it works
very well. For example, if a dropdown list, there many options, such
as:

 

the value foo will be picked up for sure. But, if there is a space:

 .


Values should be quoted, although you can omit the quotes if there
aren't any spaces in the string:



You can see examples at http://wwwsearch.sourceforge.net/ClientForm/



As you can see, whitespace separates the name=value pairs.


The *bar* will be missed out. I wish this bug can be fixed in near
future.


It's not a bug.
--
http://mail.python.org/mailman/listinfo/python-list


Bug report: ClientForm

2009-02-28 Thread Muddy Coder
Hi Folks,

As directed, I got ClientForm and played with it. It is cool! However,
I also found a bug:

When it parses a form, if the VALUE of a field has not space, it works
very well. For example, if a dropdown list, there many options, such
as:

 

the value foo will be picked up for sure. But, if there is a space:

 .

The *bar* will be missed out. I wish this bug can be fixed in near
future.

By the way, can somebody helps me on setting parameter of uploading a
file. In ClientForm, if I need to upload a text file, I can do it by:

form.add_file(..., "text/plain")

What about a picture file? What is the counterpart of 'text/plain"?
Thanks!

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


Re: How best to test functions which use date.today

2009-02-28 Thread Scott David Daniels

Lie Ryan wrote:

Yuan HOng wrote:

In my project I have several date related methods which I want tested for
correctness. The functions use date.today() in several places. Since this
could change every time I run the test, I hope to find someway to fake a
date.today.
For illustration lets say I have a function:

from datetime import date
def today_is_2009():
return date.today().year == 2009

To test this I would like to write test function like:

def test_today_is_2009():
set_today(date(2008, 12, 31))
assert today_is_2009() == False
set_today(date(2009,1,1))
assert today_is_2009() == True

Try something like this:
import module_to_test as sut # "sut" -> system under test
from datetime import date

class FakeDate(object):
def __init__(self, value):
self._result = value
def today(self):
return self._result

def test_today_is_2009_too_old():
temp, sut.date = sut.date, FakeDate(date(2008, 12, 31))
try:
assert not sut.today_is_2009()
finally:
sut.date = temp

def test_today_is_2009_too_young():
temp, sut.date = sut.date, FakeDate(date(2010, 1, 1))
try:
assert not sut.today_is_2009()
finally:
sut.date = temp

def test_today_is_2009_just_right():
temp, sut.date = sut.date, FakeDate(date(2009, 1, 1))
try:
assert not sut.today_is_2009()
finally:
sut.date = temp


Note: each test should test 1 thing.

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


Re: Creating Zip file like java jar file

2009-02-28 Thread rdmurray
zaheer.ag...@gmail.com wrote:
> On Feb 28, 11:33 pm, Lie Ryan  wrote:
> > zaheer.ag...@gmail.com wrote:
> > > On Feb 28, 11:15 pm, "Gabriel Genellina" 
> > > wrote:
> > >> En Sat, 28 Feb 2009 14:34:15 -0200,  escribi=
> =F3:
> >
> > >>> I want to create zip file equivalent to java jar file,I created a zip
> > >>> file of my sources and added some __main__.py
> > >>> it says __Main__.py not found in Copyproject.zip..?
> > >> __main__.py must exist in the root directory.
> >
> > >> --
> > >> Gabriel Genellina
> >
> > > What do you mean by root directory..?What is this directory in
> > > Windows..?You mean the top level folder of the project?in my case
> > > copyproject folder..?
> >
> > root directory is the topmost directory (imagine a tree, the root is
> > where all the branches branched from), in this case the root directory
> > is your copyproject main folder.
> 
> 
> I wonder, I do have the __main__.py  in the root directory,but still getting
> python.exe cannot find __main__.py in CopyProject.zip
> 
> I used the following command
> python Copyproject.zip -m __main__.py --uploadFile and also tried with
> python Copyproject.zip --uploadFile
> both give me the same error , I can see the sys.path contains the
> project folder.

How did you create the zip?  The __main__.py file has to be at the
_top level_ of the zip file.  In other words:

zip test.zip __main.py othermodule.py somedir

works but

zip test.zip myproject

does not.

--RDM

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


Re: How best to test functions which use date.today

2009-02-28 Thread Gabriel Genellina
En Sat, 28 Feb 2009 15:35:47 -0200, Yuan HOng   
escribió:



In my project I have several date related methods which I want tested for
correctness. The functions use date.today() in several places. Since this
could change every time I run the test, I hope to find someway to fake a
date.today.

For illustration lets say I have a function:


from datetime import date
def today_is_2009():
return date.today().year == 2009

To test this I would like to write test function like:

def test_today_is_2009():
set_today(date(2008, 12, 31))
assert today_is_2009() == False
set_today(date(2009,1,1))
assert today_is_2009() == True



Instead of trying to inject a fake date, you could rewrite the function to
take a date argument:

def today_is_2009(today=None):
   if today is None:
 today = date.today()
   return today.year == 2009

Then, tests should pass a known date. This approach has a drawback -- you
don't test the case when no argument is given.

Another way is to use a fake date class, or a fake datetime module. Google  
"python mock object"


--
Gabriel Genellina

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


Re: How best to test functions which use date.today

2009-02-28 Thread rdmurray
Christian Heimes  wrote:
> Lie Ryan wrote:
> >> But this fails with:
> >>
> >> TypeError: can't set attributes of built-in/extension type
> >> 'datetime.date'
> > 
> > This is because today is an attribute. In python, we can override
> > attribute access to become a function call. I don't have python right
> > now, but try this:
> > 
> > del date.today
> > date.today = mytoday
> 
> It won't work. The datetime module is written in C. You can't modify a C
>  extension.

Hmm.  Given that, Lie, maybe what you need to do is modify your code
so that you call your own special purpose function to get 'today',
and replace _that_ for testing, using datetime's today for production.

--RDM

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


Re: Creating Zip file like java jar file

2009-02-28 Thread Gabriel Genellina

En Sat, 28 Feb 2009 16:51:04 -0200,  escribió:

On Feb 28, 11:33 pm, Lie Ryan  wrote:

zaheer.ag...@gmail.com wrote:
> On Feb 28, 11:15 pm, "Gabriel Genellina" 
> wrote:
>> En Sat, 28 Feb 2009 14:34:15 -0200,   
escribió:


>>> I want to create zip file equivalent to java jar file,I created a  
zip

>>> file of my sources and added some __main__.py
>>> it says __Main__.py not found in Copyproject.zip..?
>> __main__.py must exist in the root directory.

> What do you mean by root directory..?What is this directory in
> Windows..?You mean the top level folder of the project?in my case
> copyproject folder..?

root directory is the topmost directory (imagine a tree, the root is
where all the branches branched from), in this case the root directory
is your copyproject main folder.


I wonder, I do have the __main__.py  in the root directory,but still
getting
python.exe cannot find __main__.py in CopyProject.zip


The top of the tree inside the zip file. Depth zero. Not inside any  
directory. Above anything else. Just a bare name.


Open your zip using the zipfile module:

import zipfile
z = zipfile.ZipFile("xxx.zip")
z.printdir()

You should see a line starting with __main__.py *without* any / in it.


I used the following command
python Copyproject.zip -m __main__.py --uploadFile and also tried with
python Copyproject.zip --uploadFile


Use the second one.


both give me the same error , I can see the sys.path contains the
project folder.


Uh? Which project folder? Isn't it in the .zip?

--
Gabriel Genellina

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


OTish: convince the team to drop VBScript

2009-02-28 Thread rdmurray
"Christian R."  wrote:
> The company does use Python on rare occasions. It all comes down to
> the prejudices and habits of one of the programmers. His only argument
> I can't counter -because I don't see the problem- is that "Python
> modules cause problems for updates to customer's installations".

You don't really need arguments so much as you need negotiation, people
management and (ugh) political skills, I think.  Your task is to overcome
his prejudices, and you aren't going to do that with arguments, no matter
how good.

IMO the first thing you ought to do is dig in, really listen, and find
out what his issue is with module distribution.

Listening well is your most powerful asset.  Overcome your own prejudices
first, and his may follow :)

--RDM

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


TypeErrors

2009-02-28 Thread rdmurray
Sean Novick  wrote:
> First lookup:
> Traceback (most recent call last):
>File "F:\CSC113 Module 4 CA\sample database.py", line 72, in 
>class phonedb:
>File "F:\CSC113 Module 4 CA\sample database.py", line 146, in phonedb
>for entry in foo.lookup('reifsch'):
>File "F:\CSC113 Module 4 CA\sample database.py", line 101, in lookup
>if cmp(e, string) =3D=3D 0:
> TypeError: comparison did not return an int
>
> I do not know what this error means. I tried to look it up in help, but to no
> avail. If someone could please help or tell me where I could find an answer.
> Thanks.

The 'cmp' function (which is depricated, by the way) asks the two
arguments to compare themselves.  It does this by invoking the __cmp__
method on the first object, passing it the second.  (Actually it's more
complicated than that, but it will do as a partial explanation for now).
The __cmp__ method is expected to return an integer, which represents
the results of doing the comparison (see the docs if you want to know
the values...but as I said cmp and __cmp__ a depricated).

So, whatever 'e' is (and we can't tell from the traceback, you'll have
to work through your code to figure it out, probably by sprinkling in
'print' statements), its __cmp__ method didn't return an integer.

When you fix this, I would recommend converting to using rich comparisons
(__eq__, __lt__), etc, since __cmp__ is eventually going away (it doesn't
exist in Python 3.x).

--RDM

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


Re: why cannot assign to function call

2009-02-28 Thread rdmurray
Mark Wooding  wrote:
> Ethan Furman  writes:
> 
> > Mark Wooding wrote:
> >> Here's what I think is the defining property of pass-by-value [...]:
> >>
> >>   The callee's parameters are /new variables/, initialized /as if by
> >>   assignment/ from the values of caller's argument expressions.
> >>
> >> My soundbite definition for pass-by-reference is this:
> >>
> >>   The callee's parameters are merely /new names/ for the caller's
> >>   argument variables -- as far as that makes sense.
> >
> > Greetings, Mark!
> 
> You posted to the whole group -- probably using a wide-reply option
> while reading the mailing list.  Still, I'll give an answer here in
> order to help any other readers of the list or newsgroup.  However, as
> far as I'm concerned, this discussion is basically at an end and I'm not
> really interested in starting it up all over again.  To that end, I've
> set followups to `poster'.  I shall continue reply to private email
> which seems interested in a sensible discussion.

I just popped in to this thread, and read the whole thing in a marathon
session (why, I'm not quite sure, but somehow I found it interesting :).
I'm going to follow up here at the risk of annoying Mark, because I
think there may be a way to reconcile the language in a way that is
helpful in explaining things to Python beginners.

> > I was hoping you might be able to clarify those last two sound bites
> > for me -- I think I understand what you are saying, but I'm confused
> > about how they relate to Python...

I think this is the key point.  I am an experienced Python programmer,
and I had to think long and hard about what you were saying, Mark, in
order to understand how it applied to Python.  I think this means that
your model and/or your level of abstraction is not "natural" when trying
to understand Python programs, and I think I may have figured out why.

> > Specifically, how is a new name (pbr) different, in Python, from a new
> > name initialized as if by assignment (pbv)?  It seems to me than you
> > end up with the same thing in either case (in Python, at least),
> > making the distinction non-existent.
> 
> You've missed a level of indirection.  In particular, `names' aren't
> things that you initialize.  They're things that you /bind/ to
> variables.  The crucial difference is that, in pass-by-value, new
> variables are created as an intrinsic part of the process, whereas in
> pass-by-reference, new variables are not (usually) created, and instead
> the formal parameter names are bound to the caller's pre-existing
> argument variables.

I think that the reason Ethan missed that level of indirection is that
Python hides that level of indirection from the programmer.  And I think
that this is where the conversation between you and Steven got hung
up, Mark.  You are firmly grounded in how languages work in general,
so your conceptual model naturally includes details that Steven's
conceptual model can ignore, because he's dealing only with the model
used by Python.  He can (and wants to!) ignore the level of indirection
that Python doesn't even give him access to.

In short, there is a reason why you almost never hear the word 'variable'
from an experienced Python programmer when talking about the Python model.
That level detail is abstracted into something else by the Python
conceptual model: it becomes a namespace mapping names to objects.

> It's worth noting that I use the terms `name' and `binding' in different
> ways from most of the Python community.  This is unfortunate.  The
> discrepancy is actually because the Python meanings of these words are
> not the same as the meanings in the wider computer science and
> mathematical communities.  For example, many Python users seem to use
> `binding' to mean `assignment', which is a shame because it leaves the
> concept that is usually called `binding' without a name.  So I'll stick
> with the wider meanings.

It seems to me from reading the thread that everyone is actually in
pretty good agreement that 'name' is the symbol one types in the
program source to denote...something.  It's the something where things
get tricky.  So let's leave name itself alone.

But let's replace 'assignment' and 'binding' with the concept that is
more natural to Python's model, that of a "mapping".  A namespace maps
names to objects.  If I'm understanding you correctly, Mark, in your
model what I'm calling a namespace is the set of variable bindings in a
particular environment.  Because Python does not allow the programmer
to actually rebind a variable (Python handles the association between
name and variable completely behind the scenes), Python programmers
naturally skip past that name-to-variable binding step, and conceptually
think about the name being bound to the _value_ instead. After all,
that's the only thing they can change.  This may be unfortunate from
a precisionist viewpoint, but it is both natural and, IMO, inevitable,
because it makes thinking about Python programs m

Re: c.Win32_OperatingSystem question.

2009-02-28 Thread Tim Golden

bryan rasmussen wrote:

Maybe there's a more specific list I should ask this question on but I
don't know what it is. I'm using Tim Golden's wmi stuff, and putting
my output into an XML document.

I have the following bit of code


[.. snip ...]


At the end of that thhe only text node thaht comes out is
ComputerName, WMI is running - Am I using the wrong names for things
here? When I try to get the same values using WScript and WQL to
extract from Win32_OperatingSystem I get all the values.



I'd love to help here, but you're not making it easy. I'm not
clear if you're suggesting there's a problem with WMI or with
ElementTree or with something else. Can you narrow down, please
so I don't have to invent a code wrapper for your code fragment.
Try producing an instantly-runnable piece of code which demonstrates
the problem and I'll happily have a look from the WMI perspective at
least.

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


Static Map

2009-02-28 Thread KMCB
Hello,

I'm interested in creating a static map of a region in the US.  This
map would be set into a picture format, so I can add it to a
document.  I would like it to contain some town names and road
information.  Then I would like to add points, based on LAT and LONG,
that can be labeled with information I provide.

I have done some searching, Google Maps probably will not work because
of the License.  WuGeo does not seam to have the details.  I was
considering tw.openlayers, but do not know if that is the best
starting point.  If I could not create the picture from Python, would
use tw and then create a screen shot to get started.

Does anyone have thoughts on a better approach?

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


Re: TypeErrors

2009-02-28 Thread Benjamin Kaplan
On Sat, Feb 28, 2009 at 12:24 PM, Sean Novick  wrote:

> I'm having issues with a phone-number database.
> Here is a code snippet:
>  def menu():
>
> print '''Please make a selection from the following options:
> To add an Employee - enter: 1
>
> For a complete listing of Employees - enter: 2
> To see the 'test page' and exit the database - enter: 3'''
> print
> return input(":")
> #Start of Program
> foo = phonedb()
> loop = 1
> choice = 0
> while loop == 1:
> choice = menu()
> if choice == 1:
> print "Enter the Employee's full name: "
> n = raw_input(':')
> print "Enter the Employee's full telephone number: "
> p = raw_input(':')
> print "Enter the telephone number type:(0 = UNKNOWN, 1 = HOME,
> 2 = WORK, 3 = FAX, 4 = CELL)"
> t = raw_input(':')
> if t == '0':
> foo.add(n, p, UNKNOWN)
> if t == '1':
> foo.add(n, p, HOME)
> if t == '2':
> foo.add(n, p, WORK)
> if t == '3':
> foo.add(n, p, FAX)
> if t == '4':
> foo.add(n, p, CELL)
> print t
>
> elif choice == 2:
> print(list)
>
> loop = 0
> It works until I enter "t", then this is what I get:
> "Please make a selection from the following options:
> To add an Employee - enter: 1
>
> For a complete listing of Employees - enter: 2
> To see the 'test page' and exit the database - enter: 3"
> :1
> Enter the Employee's full name:
> :john
> Enter the Employee's full telephone number:
> :123-456-7890
> Enter the telephone number type:(0 = UNKNOWN, 1 = HOME, 2 = WORK, 3 = FAX,
> 4 = CELL)
> :1
> First lookup:
> Traceback (most recent call last):
>   File "F:\CSC113 Module 4 CA\sample database.py", line 72, in 
> class phonedb:
>   File "F:\CSC113 Module 4 CA\sample database.py", line 146, in phonedb
> for entry in foo.lookup('reifsch'):
>   File "F:\CSC113 Module 4 CA\sample database.py", line 101, in lookup
> if cmp(e, string) == 0:
> TypeError: comparison did not return an int
> >>>
> I do not know what this error means. I tried to look it up in help, but to
> no avail. If someone could please help or tell me where I could find an
> answer. Thanks.
>


Do you see the little part where it tells you? Your problem has nothing to
do with the stuff you showed us. It took place in
simple database.py, line 101. At the point "if cmp(e, string) == 0". First
of all, why are you doing cmp(e,string)==0? Use  "if e == string" instead.
It's the same thing (sometimes even calls the same code), but it's easier to
read. The problem was exactly what it said: the __cmp__ method in whatever
class e is needs to return an int. It isn't, so you get this problem Also,
in new code, it's considered better to use rich comparisons (__eq__, __ne__,
etc.) rather than __cmp__. That's another reason to use e == string. If e
uses __eq__, == will work. If e uses __cmp__, == will still work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Data Coding suggestions

2009-02-28 Thread Kurt Smith
On Sat, Feb 28, 2009 at 10:08 AM, steven.oldner  wrote:

>
> Thanks guys.  While shopping today I've thought of a few more columns
> for my data so my first item will be building the 3 DB tables and a
> way to populate them.  Since this was intended to automate what I do
> on a weekly basis, I didn't think about adding recipes since I know
> what I need for the family, but that's a good touch.
>
> Item 1. Build 3 db tables
> Item 2. Build app to populate tables.
> Item 3. Build app to read tables and print lists.
>
> Anything else?

You might take a look at the source code for the Gourmet Recipe Manager

http://grecipe-manager.sourceforge.net/

It's written in python, has a persistent database (not sure if using
sqlite3) and you might be able to adapt it to your needs.

We use it for our shopping lists here and it's great.

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


KeyedList

2009-02-28 Thread pataphor
The ordered dictionary discussion made me think of another data type
which seems to be somewhat related, a kind of ordered dictionary where
the order of the items is arbitrary. One can insert items in the middle
and still have O(1) access (I think). I have provided a very basic
implementation, it could be extended to also remove items with O(1)
access. I am wondering if the idea makes sense at all and what would be
the best name for the type itself and for its methods. 

Could it be that the ordered dictionary is a result of a way of
thinking which slowly extends what we currently have, while a
KeyedList or whatever we ultimately choose to name it is the kind of
data type we are really looking for? If accepted, I think this type
could be used for Knuth's dancing links style algorithms.

P.

#warning, embryonic, probably very buggy implementation

class Node:

def __init__(self, left = None, right = None, key = None, item =
None): self.left = left
self.right = right
self.key = key
self.item = item

class KeyedList:

def __init__(self):
self.first = Node()
self.last = Node()
self.last.left = self.first
self.first.right = self.last
self.D = {}

def append(self, key, item):
last = self.last
prev = last.left
x = Node(prev,last,key,item)
prev.right = x
last.left = x
self.D[key] = x

def insertafter(self,key1,key2,item):
left = self.D[key1]
right = left.right
x = Node(left,right,key2,item)
left.right =x
right.left =x
self.D[key2] = x

def iteritems(self):
x = self.first.right
while x.right:
key = x.key
yield key, self.D[key].item
x = x.right

def test():
K = KeyedList()
K.append('one','hello')
K.append('two','hello')
K.append('four','hello')
K.insertafter('two','three','hello')
for x in K.iteritems():
print x

if __name__ == '__main__':
test()
--
http://mail.python.org/mailman/listinfo/python-list


Python alternatives to Text::SimpleTable?

2009-02-28 Thread Ray Van Dolson
So I'm looking for an easy (read: lazy) way to generate output in nice
ASCII tables like the Text::SimpleTable[1] module in perl.  I've come
across two so far in the Python world that look promising[2][3] but I'm
wondering if anyone else out there has some recommendations for me.

Thanks,
Ray

[1] http://search.cpan.org/dist/Text-SimpleTable/lib/Text/SimpleTable.pm
[2] http://pypi.python.org/pypi/text_table/0.02
[3] http://jefke.free.fr/stuff/python/texttable/
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's so wrong about execfile?

2009-02-28 Thread James Matthews
It is considered one of the big holes in PHP (Remote file include...)
However in Python things can be done securely

On Sat, Feb 28, 2009 at 7:15 AM, Carl Banks wrote:

> On Feb 27, 7:21 pm, Sammo  wrote:
> > Given that execfile has been removed in py3k, I want to understand
> > exactly why.
> >
> > Okay, I get that execfile is bad from the following thread:
> >
> > On Jul 29 2007, 2:39 pm, Steven D'Aprano
> >
> >
> >
> >  wrote:
> > > (1) Don't use eval, exec or execfile.
> >
> > > (2) If you're an expert, don't use eval, exec or execfile.
> >
> > > (3) If you're an expert, and are fully aware of the security risks,
> don't
> > > use eval, exec or execfile.
> >
> > > (4) If you're an expert, and are fully aware of the security risks, and
> > > have a task that can only be solved by using eval, exec or execfile,
> find
> > > another solution.
> >
> > > (5) If there really is no other solution, you haven't looked hard
> enough.
> >
> > > (6) If you've looked REALLY hard, and can't find another solution, AND
> > > you're an expert and are fully aware of the security risks, THEN you
> can
> > > think about using eval, exec or execfile.
> >
> > What are some of the reasons why execfile should not be used?
> >
> > What are some examples of cases where execfile is the correct way of
> > doing something?
>
> You didn't quote the context of Steven's reply, so I don't know if he
> was talking in general, or for a particular situation.  I suspect it
> was the latter, though.
>
> Anyway, there is one generally valid use case for these three: when
> it's your deliberate intention to give the user the power to run
> arbitrary Python code.  If you really want to give the user this
> power, and the user is trusted on whatever machine they are running it
> on, go ahead and use it.  No apology necessary.
>
> [For instance, the package I use to generate my web site uses exec and
> eval, because it processes templates with embedded Python code.  It's
> all generated statically, on my own desktop, and I author all the
> pages myself, so there is no security risk.  If I were to distribute
> this package (and I do, though not many people use it, because
> everyone just writes their own HTML templates), there would be no risk
> because the user is expected to be able to run Python, and if they can
> be trusted to run Python on their own system, they can be trusted to
> run my program, which execs templates that they write themselves.]
>
> I would suggest, however, that even if that is your intention that you
> consider leveraging Python's built-in import infrastructure.  Instead
> of execfile, you could have your program simply import a module the
> user writes (after adding a user-specific directory to sys.path).
>
>
> Now, here are a few situations where you should follow Steven's advice
> above (i.e., don't, ever):
>
> - Don't ever use exec or eval to construct a variable name
> dynamically.  Don't ever do this, for instance:
>
> x = eval("self","%s%d" % (name,index))
>
> This is unforgiveable.  Python has better and safer ways to do this
> (use getattr, setattr, globals, and locals built-ins).  And if you
> find yourself using them a lot, it's a red flag that you should be
> using dicts instead.
>
> - Don't ever pass any data to exec or eval that you didn't either
> write, or thoroughly inspect, yourself.  Especially don't pass it any
> data you received over the network.  You have to be the super extreme
> expert that Steven described, and own a lot of liability insurance,
> befor you can do that.
>
>
> Carl Banks
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/

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


Re: OTish: convince the team to drop VBScript

2009-02-28 Thread Christian Heimes
Christian R. schrieb:
> Hello,
> 
> Brand new to this list, I've not found a quick way to search the
> archives, and this is not a technical question.
> 
> I've just been hired at a digital signage company. They use VBScript
> for simple-to-medium scripting. I've abandoned it about 8 years ago. I
> want to convince the manager and the two programmers to switch to
> Python. My main arguments for Python:
>   - Faster
>   - More powerful
>   - Simpler syntax
>   - More up-to-date, evolving
>   - Modularity
>   - Lots of open source modules
>   - Better for development of "tools" (a goal stated by the mgr)

- Heavily used by lots of large companies and major players like Google,
NASA, CERN ... Check out http://www.python.org/about/success/

> Not so sure:
>   - Easier to integrate/translate with/into C#, which is what is used
> there for complex development. Am I right?

Well, there are IronPython and PythonDotNET. The former ist a full blown
implementation of Python in .NET sponsored by Microsoft and part of the
next release of Visual Studio. The later is a bridge between .NET and
CPython.

Christian

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


Re: ANN: updates to Python-by-example

2009-02-28 Thread James Matthews
Thanks for adding this. I needed to show someone some examples...

On Fri, Feb 27, 2009 at 5:35 PM, steven.oldner wrote:

> On Feb 27, 8:40 am, pyt...@bdurham.com wrote:
> > Rainy,
> >
> > Great stuff! Thanks for your examples with the community!!
> >
> > Regards,
> > Malcolm
>
> Let me add my thanks!  I using it now...
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: Creating Zip file like java jar file

2009-02-28 Thread zaheer . agadi
On Feb 28, 11:33 pm, Lie Ryan  wrote:
> zaheer.ag...@gmail.com wrote:
> > On Feb 28, 11:15 pm, "Gabriel Genellina" 
> > wrote:
> >> En Sat, 28 Feb 2009 14:34:15 -0200,  escribió:
>
> >>> I want to create zip file equivalent to java jar file,I created a zip
> >>> file of my sources and added some __main__.py
> >>> it says __Main__.py not found in Copyproject.zip..?
> >> __main__.py must exist in the root directory.
>
> >> --
> >> Gabriel Genellina
>
> > What do you mean by root directory..?What is this directory in
> > Windows..?You mean the top level folder of the project?in my case
> > copyproject folder..?
>
> root directory is the topmost directory (imagine a tree, the root is
> where all the branches branched from), in this case the root directory
> is your copyproject main folder.



I wonder, I do have the __main__.py  in the root directory,but still
getting
python.exe cannot find __main__.py in CopyProject.zip

I used the following command
python Copyproject.zip -m __main__.py --uploadFile and also tried with
python Copyproject.zip --uploadFile
both give me the same error , I can see the sys.path contains the
project folder.
--
http://mail.python.org/mailman/listinfo/python-list


OTish: convince the team to drop VBScript

2009-02-28 Thread Christian R.
Hello,

Brand new to this list, I've not found a quick way to search the
archives, and this is not a technical question.

I've just been hired at a digital signage company. They use VBScript
for simple-to-medium scripting. I've abandoned it about 8 years ago. I
want to convince the manager and the two programmers to switch to
Python. My main arguments for Python:
- Faster
- More powerful
- Simpler syntax
- More up-to-date, evolving
- Modularity
- Lots of open source modules
- Better for development of "tools" (a goal stated by the mgr)

Not so sure:
- Easier to integrate/translate with/into C#, which is what is used
there for complex development. Am I right?

The company does use Python on rare occasions. It all comes down to
the prejudices and habits of one of the programmers. His only argument
I can't counter -because I don't see the problem- is that "Python
modules cause problems for updates to customer's installations".

My major points will be:
- Easier for all three of us
- Stay up-to-date with industry. VBScript soon obsolescent.
- Better for the company (state-of-the-art skills, think about the
future, assets re-use etc.)

Any details or added arguments are welcome. In advance, thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How best to test functions which use date.today

2009-02-28 Thread Christian Heimes
Lie Ryan wrote:
>> But this fails with:
>>
>> TypeError: can't set attributes of built-in/extension type
>> 'datetime.date'
> 
> This is because today is an attribute. In python, we can override
> attribute access to become a function call. I don't have python right
> now, but try this:
> 
> del date.today
> date.today = mytoday

It won't work. The datetime module is written in C. You can't modify a C
 extension.

Christian

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


Re: Creating Zip file like java jar file

2009-02-28 Thread Lie Ryan
zaheer.ag...@gmail.com wrote:
> On Feb 28, 11:15 pm, "Gabriel Genellina" 
> wrote:
>> En Sat, 28 Feb 2009 14:34:15 -0200,  escribió:
>>
>>> I want to create zip file equivalent to java jar file,I created a zip
>>> file of my sources and added some __main__.py
>>> it says __Main__.py not found in Copyproject.zip..?
>> __main__.py must exist in the root directory.
>>
>> --
>> Gabriel Genellina
> 
> What do you mean by root directory..?What is this directory in
> Windows..?You mean the top level folder of the project?in my case
> copyproject folder..?

root directory is the topmost directory (imagine a tree, the root is
where all the branches branched from), in this case the root directory
is your copyproject main folder.

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


Re: Creating Zip file like java jar file

2009-02-28 Thread zaheer . agadi
On Feb 28, 11:15 pm, "Gabriel Genellina" 
wrote:
> En Sat, 28 Feb 2009 14:34:15 -0200,  escribió:
>
> > I want to create zip file equivalent to java jar file,I created a zip
> > file of my sources and added some __main__.py
> > it says __Main__.py not found in Copyproject.zip..?
>
> __main__.py must exist in the root directory.
>
> --
> Gabriel Genellina

What do you mean by root directory..?What is this directory in
Windows..?You mean the top level folder of the project?in my case
copyproject folder..?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating Zip file like java jar file

2009-02-28 Thread Gabriel Genellina

En Sat, 28 Feb 2009 14:34:15 -0200,  escribió:


I want to create zip file equivalent to java jar file,I created a zip
file of my sources and added some __main__.py
it says __Main__.py not found in Copyproject.zip..?


__main__.py must exist in the root directory.

--
Gabriel Genellina

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


Re: How best to test functions which use date.today

2009-02-28 Thread Lie Ryan

Yuan HOng wrote:

HI,

In my project I have several date related methods which I want tested for
correctness. The functions use date.today() in several places. Since this
could change every time I run the test, I hope to find someway to fake a
date.today.

For illustration lets say I have a function:


from datetime import date
def today_is_2009():
return date.today().year == 2009

To test this I would like to write test function like:

def test_today_is_2009():
set_today(date(2008, 12, 31))
assert today_is_2009() == False
set_today(date(2009,1,1))
assert today_is_2009() == True

The first approach of achieving this purpose is to monkey patch the
date.today like:

date.today = mytoday

But this fails with:

TypeError: can't set attributes of built-in/extension type 'datetime.date'


This is because today is an attribute. In python, we can override 
attribute access to become a function call. I don't have python right 
now, but try this:


del date.today
date.today = mytoday


A second possibility would be to change the system date (I am running
Linux). However the standard Python module doesn't provide a method for this
purpose. I could use os.system to issue a date command. But I am not very
comfortable with this since changing the system time could break something
undesirably. Also I will then have to have root privilege to run my test.
Besides, I will have to stop the ntp daemon so it will not inadvertently
correct the system clock during the test period.

Is there any suggestion from the community on how best to test such
functions?


It is a very bad idea to change the system date.

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


Re: c.Win32_OperatingSystem question.

2009-02-28 Thread bryan rasmussen
oh I noticed the problem with the
BuildNumber = et.SubElement(oper.BuildNumber)
instead of
BuildNumber = str(oper.BuildNumber)

and fixed it. No improvement in results however.

Best Regards,
Bryan Rasmussen

On Sat, Feb 28, 2009 at 6:38 PM, bryan rasmussen
 wrote:
> Maybe there's a more specific list I should ask this question on but I
> don't know what it is. I'm using Tim Golden's wmi stuff, and putting
> my output into an XML document.
>
> I have the following bit of code
>
>
>  root = et.Element("locations")
>        ComputerInfo = et.SubElement(root, "ComputerInfo")
>        ComputerName = et.SubElement(ComputerInfo,"ComputerName")
>        ComputerDomain = et.SubElement(ComputerInfo,"Domain")
>
>        location = et.SubElement(root, "location")
>        locationpath = et.SubElement(location, "locationpath")
>        locationtype = et.SubElement(location, "locationtype")
>        currenttime = et.SubElement(location,"time")
>
>        currenttimeZone = et.SubElement(ComputerInfo,"timeZone")
>        BootDevice = et.SubElement(ComputerInfo,"BootDevice")
>        BuildNumber = et.SubElement(ComputerInfo,"BuildNumber")
>        BuildType = et.SubElement(ComputerInfo,"BuildType")
>        Caption = et.SubElement(ComputerInfo,"Caption")
>        CodeSet = et.SubElement(ComputerInfo,"CodeSet")
>        CountryCode = et.SubElement(ComputerInfo,"CountryCode")
>        Description = et.SubElement(ComputerInfo,"ComputerDescription")
>        FreePhysicalMemory = et.SubElement(ComputerInfo,"FreeMemory")
>        LocalDateTime = et.SubElement(ComputerInfo,"LocalDateTime")
>        Locale = et.SubElement(ComputerInfo,"Locale")
>        Manufacturer = et.SubElement(ComputerInfo,"Manufacturer")
>        Organization = et.SubElement(ComputerInfo,"ComputerOrganization")
>
>
>        OSType = et.SubElement(ComputerInfo,"OperatingSystem")
>        WindowsDirectory = et.SubElement(ComputerInfo,"WindowsDirectory")
>
>        # print  "ok"
>        # time.sleep(3)
>
>
>        for oper in c.Win32_OperatingSystem():
>          # print "here"
>          # time.sleep(3)
>          ComputerName.text = str(oper.Name)
>          ComputerDomain.text = str(oper.Domain)
>          currenttimeZone.text = str(oper.CurrentTimeZone)
>          try:
>            currenttime.text = str(datetime.datetime.utcnow())
>            BootDevice.text = str(oper.BootDevice)
>            BuildNumber = et.SubElement(oper.BuildNumber)
>            BuildType.text = str(oper.BuildType)
>            Caption.text = str(oper.Caption)
>            CodeSet.text = str(oper.CodeSet)
>            CountryCode.text = str(oper.CountryCode)
>            Description.text = str(oper.ComputerDescription)
>            FreePhysicalMemory.text = str(oper.FreeMemory)
>            LocalDateTime.text = str(oper.LocalDateTime)
>            Locale.text = str(oper.Locale)
>            Manufacturer.text = str(oper.Manufacturer)
>            Organization.text = str(oper.ComputerOrganization)
>
>
>            OSType.text = str(oper.OperatingSystem)
>            WindowsDirectory.text = str(oper.WindowsDirectory)
>
>
> At the end of that thhe only text node thaht comes out is
> ComputerName, WMI is running - Am I using the wrong names for things
> here? When I try to get the same values using WScript and WQL to
> extract from Win32_OperatingSystem I get all the values.
>
> Best Regards,
> Bryan Rasmussen
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Delete all items in the list

2009-02-28 Thread Terry Reedy

Steven D'Aprano wrote:


Big Oh notation is good for estimating asymptotic behaviour, which means it
is good for predicting how an algorithm will scale as the size of the input
increases. It is useless for predicting how fast that algorithm will run,
since the actual speed depends on those constant factors that Big Oh
neglects. That's not a criticism of Big Oh -- predicting execution speed is
not what it is for.

For what it's worth, for very small lists, the while...remove algorithm is
actually faster that using a list comprehension, despite being O(M*N)
versus O(N), at least according to my tests. It's *trivially* faster, but
if you're interested in (premature) micro-optimisation, you might save one
or two microseconds by using a while loop for short lists (say, around
N<=12 or so according to my tests), and swapping to a list comp only for
larger input.

Now, this sounds silly, and in fact it is silly for the specific problem
we're discussing, but as a general technique it is very powerful. For
instance, until Python 2.3, list.sort() used a low-overhead but O(N**2)
insertion sort for small lists, only kicking off a high-overhead but O(N)


O(NlogN)


sample sort above a certain size. The current timsort does something
similar, only faster and more complicated. If I understand correctly, it
uses insertion sort to make up short runs of increasing or decreasing
values, and then efficiently merges them.


It uses binary insertion sort to make runs of 64 (determined by 
empirical testing).  The 'binary' part means that it uses O(logN) binary 
search rather than O(n) linear search to find the insertion point for 
each of N items, so that finding insertion points uses only O(NlogN) 
comparisions (which are relatively expensive).  Each of the N insertions 
is done with a single memmove() call, which typically is relatively 
fast.  So although binary insertion sort is still O(N*N), the 
coefficient of the N*N term in the time formula is relatively small.


The other advantages of timsort are that it exploits existing order in a 
list while preserving the order of items that compare equal.


Terry Jan Reedy


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


c.Win32_OperatingSystem question.

2009-02-28 Thread bryan rasmussen
Maybe there's a more specific list I should ask this question on but I
don't know what it is. I'm using Tim Golden's wmi stuff, and putting
my output into an XML document.

I have the following bit of code


  root = et.Element("locations")
ComputerInfo = et.SubElement(root, "ComputerInfo")
ComputerName = et.SubElement(ComputerInfo,"ComputerName")
ComputerDomain = et.SubElement(ComputerInfo,"Domain")

location = et.SubElement(root, "location")
locationpath = et.SubElement(location, "locationpath")
locationtype = et.SubElement(location, "locationtype")
currenttime = et.SubElement(location,"time")

currenttimeZone = et.SubElement(ComputerInfo,"timeZone")
BootDevice = et.SubElement(ComputerInfo,"BootDevice")
BuildNumber = et.SubElement(ComputerInfo,"BuildNumber")
BuildType = et.SubElement(ComputerInfo,"BuildType")
Caption = et.SubElement(ComputerInfo,"Caption")
CodeSet = et.SubElement(ComputerInfo,"CodeSet")
CountryCode = et.SubElement(ComputerInfo,"CountryCode")
Description = et.SubElement(ComputerInfo,"ComputerDescription")
FreePhysicalMemory = et.SubElement(ComputerInfo,"FreeMemory")
LocalDateTime = et.SubElement(ComputerInfo,"LocalDateTime")
Locale = et.SubElement(ComputerInfo,"Locale")
Manufacturer = et.SubElement(ComputerInfo,"Manufacturer")
Organization = et.SubElement(ComputerInfo,"ComputerOrganization")


OSType = et.SubElement(ComputerInfo,"OperatingSystem")
WindowsDirectory = et.SubElement(ComputerInfo,"WindowsDirectory")

# print  "ok"
# time.sleep(3)


for oper in c.Win32_OperatingSystem():
  # print "here"
  # time.sleep(3)
  ComputerName.text = str(oper.Name)
  ComputerDomain.text = str(oper.Domain)
  currenttimeZone.text = str(oper.CurrentTimeZone)
  try:
currenttime.text = str(datetime.datetime.utcnow())
BootDevice.text = str(oper.BootDevice)
BuildNumber = et.SubElement(oper.BuildNumber)
BuildType.text = str(oper.BuildType)
Caption.text = str(oper.Caption)
CodeSet.text = str(oper.CodeSet)
CountryCode.text = str(oper.CountryCode)
Description.text = str(oper.ComputerDescription)
FreePhysicalMemory.text = str(oper.FreeMemory)
LocalDateTime.text = str(oper.LocalDateTime)
Locale.text = str(oper.Locale)
Manufacturer.text = str(oper.Manufacturer)
Organization.text = str(oper.ComputerOrganization)


OSType.text = str(oper.OperatingSystem)
WindowsDirectory.text = str(oper.WindowsDirectory)


At the end of that thhe only text node thaht comes out is
ComputerName, WMI is running - Am I using the wrong names for things
here? When I try to get the same values using WScript and WQL to
extract from Win32_OperatingSystem I get all the values.

Best Regards,
Bryan Rasmussen
--
http://mail.python.org/mailman/listinfo/python-list


How best to test functions which use date.today

2009-02-28 Thread Yuan HOng
HI,

In my project I have several date related methods which I want tested for
correctness. The functions use date.today() in several places. Since this
could change every time I run the test, I hope to find someway to fake a
date.today.

For illustration lets say I have a function:


from datetime import date
def today_is_2009():
return date.today().year == 2009

To test this I would like to write test function like:

def test_today_is_2009():
set_today(date(2008, 12, 31))
assert today_is_2009() == False
set_today(date(2009,1,1))
assert today_is_2009() == True

The first approach of achieving this purpose is to monkey patch the
date.today like:

date.today = mytoday

But this fails with:

TypeError: can't set attributes of built-in/extension type 'datetime.date'

A second possibility would be to change the system date (I am running
Linux). However the standard Python module doesn't provide a method for this
purpose. I could use os.system to issue a date command. But I am not very
comfortable with this since changing the system time could break something
undesirably. Also I will then have to have root privilege to run my test.
Besides, I will have to stop the ntp daemon so it will not inadvertently
correct the system clock during the test period.

Is there any suggestion from the community on how best to test such
functions?

-- 
Hong Yuan

大管家网上建材超市
装修装潢建材一站式购物
http://www.homemaster.cn
--
http://mail.python.org/mailman/listinfo/python-list


TypeErrors

2009-02-28 Thread Sean Novick
I'm having issues with a phone-number database. 
Here is a code snippet:
 def menu():
    
    print '''Please make a selection from the following options:
    To add an Employee - enter: 1
    
    For a complete listing of Employees - enter: 2
    To see the 'test page' and exit the database - enter: 3'''
    print
    return input(":")
#Start of Program
    foo = phonedb()
    loop = 1
    choice = 0
    while loop == 1:
    choice = menu()
    if choice == 1:
    print "Enter the Employee's full name: "
    n = raw_input(':')
    print "Enter the Employee's full telephone number: "
    p = raw_input(':')
    print "Enter the telephone number type:(0 = UNKNOWN, 1 = HOME, 2 = 
WORK, 3 = FAX, 4 = CELL)"
    t = raw_input(':')
    if t == '0':
    foo.add(n, p, UNKNOWN)
    if t == '1':
    foo.add(n, p, HOME)
    if t == '2':
    foo.add(n, p, WORK)
    if t == '3':
    foo.add(n, p, FAX)
    if t == '4':
    foo.add(n, p, CELL)
    print t
    
    elif choice == 2:
    print(list)
    
    loop = 0
It works until I enter "t", then this is what I get:
"Please make a selection from the following options:
    To add an Employee - enter: 1
    
    For a complete listing of Employees - enter: 2
    To see the 'test page' and exit the database - enter: 3"
:1
Enter the Employee's full name: 
:john
Enter the Employee's full telephone number: 
:123-456-7890
Enter the telephone number type:(0 = UNKNOWN, 1 = HOME, 2 = WORK, 3 = FAX, 4 = 
CELL)
:1
First lookup:
Traceback (most recent call last):
  File "F:\CSC113 Module 4 CA\sample database.py", line 72, in 
    class phonedb:
  File "F:\CSC113 Module 4 CA\sample database.py", line 146, in phonedb
    for entry in foo.lookup('reifsch'):
  File "F:\CSC113 Module 4 CA\sample database.py", line 101, in lookup
    if cmp(e, string) == 0:
TypeError: comparison did not return an int
>>> 
I do not know what this error means. I tried to look it up in help, but to no 
avail. If someone could please help or tell me where I could find an answer. 
Thanks.


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


Creating Zip file like java jar file

2009-02-28 Thread zaheer . agadi
Hi,
I want to create zip file equivalent to java jar file,I created a zip
file of my sources and added some __main__.py
some how I am getting an error saying __main.py does not exist in the
zip file

  Copyproject(main folder)
  |
  |_src(folder)
  |  |
  |  |__Nertworkpackage
  |   ||
  |   ||__Storepackage
  |   |   |
  |   |__FtpPackage |__module1.py
  |   |__module2.py
  | tests  |__ module3.py

Copyproject(main folder) | |_src(folder) | | | |__Nertworkpackage
| | | | | |__Storepackage | | | | |__FtpPackage |__module1.py | |
__module2.py | tests |__ module3.py

Module1 takes some commandline parameters that will do some operation
Like If I say
" module1.py --uploadFile  " A file should get uploaded
(this works)
Now I want to do
Copyproject.zip --uploadFile  to upload the file

How should I do this, I tried to put __main__ parallel to src folder
it says __Main__.py not found in Copyproject.zip..?

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


Re: Proposed implementation for an Ordered Dictionary

2009-02-28 Thread Steven D'Aprano
Colin J. Williams wrote:

> Sometimes, it's useful to be able to
> obtain the data in the sorted sequence.
> 
> You might consider adding functionality
> like:
> 
> def seqItems(self):
> '''To return the items, sorted
> by key. '''
> return [self[k] for k in
> self.seqKeys()]

Amazingly, the Python time-machine provides such functionality! Using just a
handful of pre-existing pieces, you can do this:

sorted(mydict.items())
sorted(mydict.keys())
[mydict[x] for x in sorted(mydict.keys)]

and any other sequence you might need. That's the beauty of a general
purpose programming language. You don't need everything to be a built-in
*wink*



-- 
Steven

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


Re: Data Coding suggestions

2009-02-28 Thread steven.oldner
On Feb 27, 2:04 pm, Rick Dooling  wrote:
> On Feb 27, 6:42 am, "steven.oldner"  wrote:
>
> > Just learning Python and have a project to create a weekly menu and a
> > shopping list from the menu.  
> > Question:  How should I set up the data?  I'm looking at maybe 70 menu
> > items and maybe 1000 items for the shopping list.  I need to be able
> > to maintain each item also.
>
> I agree with Mr. Holden. It's a perfect exercise for using Python with
> sqlite3.
>
> And the nice thing about this documentation is it has plenty of good
> examples:
>
> http://docs.python.org/library/sqlite3.html
>
> Good luck,
>
> RD

Thanks guys.  While shopping today I've thought of a few more columns
for my data so my first item will be building the 3 DB tables and a
way to populate them.  Since this was intended to automate what I do
on a weekly basis, I didn't think about adding recipes since I know
what I need for the family, but that's a good touch.

Item 1. Build 3 db tables
Item 2. Build app to populate tables.
Item 3. Build app to read tables and print lists.

Anything else?

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


Re: Delete all items in the list

2009-02-28 Thread Steven D'Aprano
Chris Rebert wrote:

> Obviously that equivalence is true, but in this case I'm emphasizing
> that it's even worse than that when constant factors are taken into
> account. Big-O is nice in the abstract, but in the real-world those
> constant factors can matter.
> 
> In pure big-O, it is indeed O(M*N) vs. O(N)
> Including constant factors, the performance is roughly 2*M*N*X [X =
> overhead of remove()] vs. N, which makes the badness of the algorithm
> all the more apparent.


So, what you're saying is that if you include a constant factor on one side
of the comparison, and neglect the constant factors on the other, the side
with the constant factor is worse. Well, duh :)

I forget which specific O(N) algorithm you're referring to, but I think it
was probably a list comp:

L[:] = [x for x in L if x != 'a']

As a wise man once said *wink*, "Big-O is nice in the abstract, but in the
real-world those constant factors can matter". This is very true... in this
case, the list comp requires creating a new list, potentially resizing it
an arbitrary number of times, then possibly garbage collecting the previous
contents of L. These operations are not free, and for truly huge lists
requiring paging, it could get very expensive.

Big Oh notation is good for estimating asymptotic behaviour, which means it
is good for predicting how an algorithm will scale as the size of the input
increases. It is useless for predicting how fast that algorithm will run,
since the actual speed depends on those constant factors that Big Oh
neglects. That's not a criticism of Big Oh -- predicting execution speed is
not what it is for.

For what it's worth, for very small lists, the while...remove algorithm is
actually faster that using a list comprehension, despite being O(M*N)
versus O(N), at least according to my tests. It's *trivially* faster, but
if you're interested in (premature) micro-optimisation, you might save one
or two microseconds by using a while loop for short lists (say, around
N<=12 or so according to my tests), and swapping to a list comp only for
larger input.

Now, this sounds silly, and in fact it is silly for the specific problem
we're discussing, but as a general technique it is very powerful. For
instance, until Python 2.3, list.sort() used a low-overhead but O(N**2)
insertion sort for small lists, only kicking off a high-overhead but O(N)
sample sort above a certain size. The current timsort does something
similar, only faster and more complicated. If I understand correctly, it
uses insertion sort to make up short runs of increasing or decreasing
values, and then efficiently merges them.


-- 
Steven

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


Re: Proposed implementation for an Ordered Dictionary

2009-02-28 Thread Colin J. Williams

Raymond Hettinger wrote:

[Paul Rubin]

Ehh, I guess I'm not surprised at the slowdown and extra complexity
from the second dict.  Oh well.  If the module really turns out to be
really used a lot, another (messy) approach would be to write a C
extension that uses a doubly linked list some day.


That seems like an ideal implementation to me.

  O(1): appending, popping, searching, and deletion
  O(n): traversal

Raymond


Sometimes, it's useful to be able to 
obtain the data in the sorted sequence.


You might consider adding functionality 
like:


def seqItems(self):
'''To return the items, sorted 
by key. '''
return [self[k] for k in 
self.seqKeys()]


def seqKeys(self):
''' To return the keys sorted.  '''
k= self.keys()
k.sort()
return k

def seqValues(self):
''' To return the values, with 
their keys, sorted by value. '''
v= [(it[1], it[0]) for it in 
self.items()]

v.sort()
return v

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


Re: Queries

2009-02-28 Thread mmcclaf
So basically you are complaining that groups don't pick up post by
GMail users?

As for the SQL thing, you still don't see how I am linking this to
SQL? I have to make in your terms: a textual representation of the
statements I'd make in SQL. The statement I made with the bold SELECT,
etc, replace those with the relational algebra symbols, hence needing
to make a relational algebra expression.

>> So in short of the responses given, I need to study further: GROUP BY,
>> HAVING, AS, COUNT, and subselect queries, right?

>Since it's homework, we (this group) won't be giving direct SQL 
> statements...

I never said I wanted direct SQL statements, moreso guidance as to
what direction I should be heading for each of the queries. I just
wanted to make sure that there might not be other things I might want
to study as  well that might be required for the queries. Try not to
interpret what isn't there... I'm looking for help, not direct answers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-02-28 Thread Mark Wooding
Ethan Furman  writes:

> Mark Wooding wrote:
>> Here's what I think is the defining property of pass-by-value [...]:
>>
>>   The callee's parameters are /new variables/, initialized /as if by
>>   assignment/ from the values of caller's argument expressions.
>>
>> My soundbite definition for pass-by-reference is this:
>>
>>   The callee's parameters are merely /new names/ for the caller's
>>   argument variables -- as far as that makes sense.
>
> Greetings, Mark!

You posted to the whole group -- probably using a wide-reply option
while reading the mailing list.  Still, I'll give an answer here in
order to help any other readers of the list or newsgroup.  However, as
far as I'm concerned, this discussion is basically at an end and I'm not
really interested in starting it up all over again.  To that end, I've
set followups to `poster'.  I shall continue reply to private email
which seems interested in a sensible discussion.

> I was hoping you might be able to clarify those last two sound bites
> for me -- I think I understand what you are saying, but I'm confused
> about how they relate to Python...
>
> Specifically, how is a new name (pbr) different, in Python, from a new
> name initialized as if by assignment (pbv)?  It seems to me than you
> end up with the same thing in either case (in Python, at least),
> making the distinction non-existent.

You've missed a level of indirection.  In particular, `names' aren't
things that you initialize.  They're things that you /bind/ to
variables.  The crucial difference is that, in pass-by-value, new
variables are created as an intrinsic part of the process, whereas in
pass-by-reference, new variables are not (usually) created, and instead
the formal parameter names are bound to the caller's pre-existing
argument variables.

It's worth noting that I use the terms `name' and `binding' in different
ways from most of the Python community.  This is unfortunate.  The
discrepancy is actually because the Python meanings of these words are
not the same as the meanings in the wider computer science and
mathematical communities.  For example, many Python users seem to use
`binding' to mean `assignment', which is a shame because it leaves the
concept that is usually called `binding' without a name.  So I'll stick
with the wider meanings.

A while ago, I posted an essay -- to this group -- which may help
explain the concepts:

Message-ID: <8763k14nc6.fsf@metalzone.distorted.org.uk>
http://groups.google.com/group/comp.lang.python/msg/f6f1a321f819d02b

On with the question.

> def func(bar):
> bar.pop()
>
> Pass-by-reference:
>   foo = ['Ethan','Furman']
>   func(foo)   # bar = foo
>
> Pass-by-value:
>   foo = ['Python','Rocks!']
>   func(foo)   # bar is new name for foo
>   # is this any different from above?
>
> If I have this right, in both cases foo will be reduced to a
> single-item list after func.  

You're correct.  So: we can conclude that the above test is not
sufficient to distinguish the two cases.

> Any further explanation you care to provide will be greatly
> appreciated!

This test is sufficient to distinguish:

def test(x):
  x = 'clobbered'

y = 'virgin'
test(y)
print y

If it prints `virgin' then you have call-by-value.  If it prints
`clobbered' then you have call-by-reference.

Let's examine the two cases, as I did in the essay I cited above.  I'll
do call-by-value first.  First, we define a function `test'.  Then, we
initialize `y'.  It's worth examining this process in detail.  The name
`y' is initially unbound. so it is implicitly bound to a fresh
variable.  Then, (a reference to) the string object 'virgin' is stored
in this variable.  We can show this diagrammatically as follows.

y (in global env.)  >  [VAR]  ---> 'virgin'

(In the diagrams, ===> denotes a binding relationship, between names and
variables; and ---> denotes a reference relationship, between variables
and values.)

Next, we call the `test' function.  Call-by-value says that we must
evaluate the argument expressions.  There's only one: `x'.  The value of
a name is obtained by (a) finding which variable is bound to the name,
and (b) extracting the value from this variable.  Well, the variable is
the one we just bound, and the value stored is (the reference to) the
string 'virgin'.  So the result of evaluating the argument expressions
is simply (the reference to) that string.

The function has one parameter, `y'.  A new environment is constructed
by extending the global environment.  In this new environment, the name
`y' is bound to a fresh variable -- distinct from all others, and
especially from the variable bound to `x' -- and in that variable we
store the value of the corresponding argument expression.  Result: the
function body is executed in an environment which is like the global
environment except that `y' is bound to a fresh variable containing
'virg

Re: Proposed implementation for an Ordered Dictionary

2009-02-28 Thread python

>> A sort of premature pessimization, then.

QOTW!

+1

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


Re: Using xreadlines

2009-02-28 Thread Nick Craig-Wood
bearophileh...@lycos.com  wrote:
>  Brett Hedges:
> > My question is how do I go to a previous line in the file? xreadlines has a 
> > file.next() statement that gives the next line, and I need a statement that 
> > gives me the previous line.<
> 
>  In modern versions of Python you usually don't need xreadlines,
>  because files are iterable.
> 
>  If your files are small, you can just read all the lines in a list
>  with open(...).readlines(), and then just use the item of the list
>  with the n-1 index.

There is also the linecache module

  http://docs.python.org/library/linecache.html

Which may be useful...

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


Re: Delete all items in the list

2009-02-28 Thread Clarendon
Thank you very much for all your replies. I actually used the while
loop as the data is not large. But I was looking for a simpler, built
in command, something like L.remove('a', all) or L.removeall('a').
Python has re.findall function, but why not removeall, so users have
to make up long lines of expression?
--
http://mail.python.org/mailman/listinfo/python-list


Re: what does this mean....?

2009-02-28 Thread zaheer . agadi
On Feb 28, 1:50 pm, Ben Finney 
wrote:
> "Gabriel Genellina"  writes:
> > En Sat, 28 Feb 2009 04:44:28 -0200,  escribió:
>
> > > One question off the topic.,
>
> > Usually it's better to post a separate message.
>
> More specifically (and I only say this because many people seem not to
> observe the distinction), when starting an entirely new topic of
> discussion, you should not reply to an existing message since it's
> then confusingly related with the same thread; instead, compose a
> *new* message with the appropriate subject.
>
> --
>  \   “Either he's dead or my watch has stopped.” —Groucho Marx |
>   `\   |
> _o__)  |
> Ben Finney

I agree I should have posted a new topic, Point taken..
Thanks Gabriel ,I will try this if  could not get this to work will
post a new thread.
--
http://mail.python.org/mailman/listinfo/python-list


Re: what does this mean....?

2009-02-28 Thread Ben Finney
"Gabriel Genellina"  writes:

> En Sat, 28 Feb 2009 04:44:28 -0200,  escribió:
> 
> > One question off the topic.,
> 
> Usually it's better to post a separate message.

More specifically (and I only say this because many people seem not to
observe the distinction), when starting an entirely new topic of
discussion, you should not reply to an existing message since it's
then confusingly related with the same thread; instead, compose a
*new* message with the appropriate subject.

-- 
 \   “Either he's dead or my watch has stopped.” —Groucho Marx |
  `\   |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Issues using SOAP/WSDL with HTTPS

2009-02-28 Thread Good Z
Hello all, 
I am new to SOAP/WebServices and getting error when using HTTPS with it. Any  
help is appreciated. here is what i am doing:


import xml 
import fpconst 
import SOAPpy 
from SOAPpy import WSDL 
wsdlFile = 'https://..com/webService.wsdl' 
server = WSDL.Proxy(wsdlFile) 


It seems the WSDL file has been read but when it tried to GET the XSD file that 
is there in WSDL file, we get following error. 


  File "", line 1, in 
  File "/var/lib/python-support/python2.5/SOAPpy/WSDL.py", line 62, in __init__
self.wsdl = reader.loadFromStream(stream, wsdlsource)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/WSDLTools.py", line 
34, in loadFromStream
wsdl.load(document)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/WSDLTools.py", line 
260, in load
schema = reader.loadFromNode(WSDLToolsAdapter(self), item)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 
80, in loadFromNode
schema.load(reader)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 
1088, in load
self.addImportSchema(tp.getSchema())
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 
1205, in getSchema
self._schema = reader.loadFromURL(url)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 
111, in loadFromURL
reader.loadFromURL(url)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 
266, in loadFromURL
self.__node = DOM.loadFromURL(url)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/Utility.py", line 614, 
in loadFromURL
file = urlopen(url)
  File "/var/lib/python-support/python2.5/SOAPpy/wstools/Utility.py", line 155, 
in urlopen
response = conn.getresponse()
  File "/usr/lib/python2.5/httplib.py", line 931, in getresponse
response.begin()
  File "/usr/lib/python2.5/httplib.py", line 388, in begin
version, status, reason = self._read_status()
  File "/usr/lib/python2.5/httplib.py", line 352, in _read_status
raise BadStatusLine(line)


Regards,
Mike



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


Re: what does this mean....?

2009-02-28 Thread Gabriel Genellina

En Sat, 28 Feb 2009 04:44:28 -0200,  escribió:


One question off the topic.,


Usually it's better to post a separate message.


How to create a .pyz file. I have python project that has some modules
in it , I want to create a zip file so that I can use it as we use
java jar file
Like I want to do a
mypyFiles.pyz --sendFile C:\\testFile
I currently have a module that does this when run as single python
module, but I want to do same this using a zip file which will  have
some other modules within it.


Just put all your modules inside the zip, and create a __main__.py file.  
Execute it using:


python foo.zip

See http://docs.python.org/using/cmdline.html#command-line

--
Gabriel Genellina

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