Re: Pyfora, a place for python

2009-11-07 Thread Saketh
On Nov 4, 5:28 pm, Alan Franzoni 
wrote:
> On 11/2/09 3:44 PM, Diez B. Roggisch wrote:
>
> > Being from germany, I can say that we *have* this fragmentation, and
> > frankly: I don't like it. I prefer my communication via NNTP/ML, and not
> > with those visually rather noisy and IMHO suboptimal forums. E.g. it
>
> That's right... forums, although more "accessible" to all the people who
> can't/doesn't want to use specific email or nntp clients, are quite slow
> to use.
>
> But I think Ubuntu forums support threads and are kind of "channeled"
> between ML and webinterface... something like Google Groups; I think
> THAT would be a good idea. What about trying to "channel"
> comp.lang.python and a forum?
>
> --
> Alan Franzoni
> contact me at pub...@[mysurname].eu

Hi everyone,

My small effort to create a place for discussing Python seems to have
sparked a larger discussion than I had anticipated. My intent in
creating Pyfora is not to splinter the community or encroach upon
comp.lang.python users, but to create an alternative location where
users can discuss Python. If this offends or irritates anyone, please
accept my humble apologies.

I understand that forums can be degenerate and uncivil, but my hope is
that with Pyfora, beginners will have a place to freely ask questions
in a genial environment. A large part of my computer upbringing was on
forums, and I wanted to share that experience with new Python users.

Sincerely,
Saketh
-- 
http://mail.python.org/mailman/listinfo/python-list


extracting info from media files

2009-11-07 Thread Michele Simionato
I would like to extract some simple info from media files, such as
size, resolution, duration, codec. What's the simplest way to do it?
Once in a time there was pymedia but I see the latest release is of
February 2006. The solution should work on Linux and provide support
for a large set of video formats.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Editing PDF files usig Python

2009-11-07 Thread David Williams
Maybe try ReportLab, its pretty much the most advanced Python PDF toolkit
I know of:

http://www.reportlab.org/

> Hi All,
>
> Greetings,
>
> I am a newbie in Python, i have a requirement to develop a component in
> python that can "text" water mark the PDF file both digitallly and
> visibly.
> I have already devloped this kind of a component in .Net using iTextSharp
> library. So i know a thing or 2 about water marking :-)
> i also need to able to read back the water mark text that was put in to
> the
> PDF (both digital and visible).
>
> I looked around on google and found that pyPDF, win32Client etc which may
> be
> the one i will have to use. using neither of them i could put a text and
> hidden text in to the pdf files. Any light thrown in this direction will
> be
> of great help to me. Appcreciate your help with this.
>
> Thanks
> Subrah
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: imputil.py, is this a bug ?

2009-11-07 Thread Stef Mientki

Gabriel Genellina wrote:
En Fri, 06 Nov 2009 18:33:37 -0300, Stef Mientki 
 escribió:


I get an error compiling with pyjamas, in the standard module 
imputil, _import_top_module


Note that imputil is undocumented in 2.5, deprecated in 2.6 and 
definitively gone in 3.0



AttributeError: 'unicode' object has no attribute 'import_top'

def _import_top_module(self, name):
# scan sys.path looking for a location in the filesystem that 
contains

# the module, or an Importer object that can import the module.
for item in sys.path:
if isinstance(item, _StringType):
module = self.fs_imp.import_from_dir(item, name)
else:
module = item.import_top(name)
if module:
return module
return None

It seems that elements of sys.path can be of the type unicode
so by adding the next 2 lines, everything works ok.
elif isinstance ( item, basestring ) :
module = self.fs_imp.import_from_dir ( str(item), name)

is this a bug ?
(I'm using Python 2.5.2 on Windows )


Yes, seems to be a bug. But given the current status of imputil, it's 
not likely to be fixed; certainly not in 2.5 which only gets security 
fixes now.


I cannot test it at this moment, but I'd use the unicode item directly 
(that is, self.fs_imp.import_from_dir(item, name)). Or perhaps 
item.encode(sys.getdefaultfilesystemencoding()). str(item) 
definitively won't work with directory names containing non-ascii 
characters.


Why are you using imputil in the first place?


thanks Gabriel,
well PyJamas is using (a copy) of it and I bumped into problems using 
PyJamas.

I'll send this message to the PyJamas developers,
because this stuff is far beyond my knowledge.

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: imputil.py, is this a bug ?

2009-11-07 Thread lkcl
On Nov 7, 2:20 am, "Gabriel Genellina"  wrote:
> Yes, seems to be a bug. But given the current status of imputil, it's not
> likely to be fixed; certainly not in 2.5 which only gets security fixes
> now.

 well, that bug's not the only one.  the other one that i found, which
i have been specifically ordered not to report (that or _any_ python
bugs, of which there have been several discovered in the past eight
months), will have to wait until the python developers rescind that
order.

if the python community is lucky, by the time that decision is made, i
will not have forgotten what those bugs are.


> (that is, self.fs_imp.import_from_dir(item, name)). Or perhaps
> item.encode(sys.getdefaultfilesystemencoding()). str(item) definitively
> won't work with directory names containing non-ascii characters.
>
> Why are you using imputil in the first place?

 it's an absolutely necessary and integral part of pyjamas-desktop
"platform overrides".

 it's absolutely essential to track, in exactly the same manner in
which python "normally" performs importing, and to give the platform-
specific "overrides" a chance to get in there, first.

 so, it is absolutely essential to have a correct working version of
imputil.py - and due to the bugs present, and the unwillingness of the
python team to fix those bugs, pyjamas-desktop is forced to maintain a
copy of imputil.py

 the "platform" is set to e.g. hulahop, pywebkitgtk or mshtml,
depending on the decision made by the user or the developer to use a
particular browser engine.  the platform name is stored in
pyjd.platform in exactly the same way that the system name is stored
in sys.platform.

 the way that the platform-specific overrides works is to perform AST
translation of the module, and then to look for the exact same module
but in platform/{modulename}{platformname}.py and perform AST
translation of _that_ module as well.

 then, at the top level, any global functions in the platform-specific
AST tree *replace* those in the "main" AST.  likewise, a node-walk
along all methods in all classes of the platform-specific AST tree.

 in this way, god-awful messy code like this:

 Widget.py
 class Widget:
 def do_something(self):
if platform == 'mshtml':
# do something terrible and ugly
elif platform == 'pywebkitgtk':
# do something only marginally better
else:
# do the default W3C standards-compliant thing

 def a_standard_function(self):
# do something normal that all the browser engines get right

 can be replaced by three files, each of which encodes *only* the
logic associated with the god-awful ugliness of each browser:

 Widget.py
 class Widget:
 def do_something(self):
# do the default W3C standards-compliant thing

 def a_standard_function(self):
# do something normal that all the browser engines get right

 platform/Widgetpywebkitgtk.py
 class Widget:
 def do_something(self):
# do something only marginally better

 platform/Widgetmshtml.py
 class Widget:
 def do_something(self):
   # do something terrible and ugly


 a similar trick could in fact be deployed to drastically simplify the
layout of e.g. distutils, _espeeecially_ the compiler and linker
modules, by using sys.platform as the "override", or, given that
that's not entirely the whole decision-making process, as i noted when
doing the mingw32 port of python, it would be better to set something
like distutils.platform and to use that.

 however, although the technique could be used in the distutils/
ccompiler.py case, the level of complexity of the code (the size of
each "override"), and the small number of actual modules, means that
there isn't actually that much benefit in deploying this AST-
overriding technique.

 in the pyjamas API, however, with over 75 user-interface modules, and
over 1200 functions, any one of which could be over-ridden by _eight_
separate platforms, each with their own quirks that can usually be
handled with one or two lines of code, the AST-merging idea that james
tauber came up with is an absolute god-send.

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


Re: Using logging module for conditional nested logs

2009-11-07 Thread Vinay Sajip
On Nov 4, 11:14 pm, Reckoner  wrote:

> Thanks again.

You're welcome. You asked (on a Logging 101 blog comment) for a
tutorial on how to use Filters. I can point you this Stack Overflow
question:

http://stackoverflow.com/questions/1383254/logging-streamhandler-and-standard-streams

The answer is perhaps the tutorial you asked for. Another example is
given in this test script:

http://opensolaris.org/sc/src/xen-gate/xvm-3.3+xen.hg/tools/python/logging/logging-0.4.9.2/test/log_test18.py

Hope it helps.

Regards,

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


What is the correct way to port codecs.open to python 3.1?

2009-11-07 Thread Baptiste Lepilleur
After applying 2to3.py to port a 2.6 script to 3.1, I get the following
error when running my script:
  File "purekeyworddbtest.py", line 143, in __init__
f = codecs.open(EXCLUDED_KEYWORDS_FILE, 'rt', 'utf-8')
  File "c:\Python31\lib\codecs.py", line 870, in open
file = builtins.open(filename, mode, buffering)
ValueError: can't have text and binary mode at once

I skimmed through python 3.0 release notes, and I haven't seen anything
indicating that codecs.open behaviour has changed in incompatible way (just
that it is no longer useful). Have I missed something?

Do I need to replace all codecs.open with the built-in open function? If so,
why does codecs.open still exist?
-- 
http://mail.python.org/mailman/listinfo/python-list


ErrorHandler 1.1.0 Released!

2009-11-07 Thread Chris Withers

I'm pleased to announce a new release of ErrorHandler.

This is a handler for the python standard logging framework that can
be used to tell whether messages have been logged at or above a
certain level.

The only change for this release is that there is now a full set of 
documentation available courtesy of Sphinx:


http://packages.python.org/errorhandler/

For more information, please see:
http://www.simplistix.co.uk/software/python/errorhandler

cheers,

Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk



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


Nov 7 TODAY & Nov 22 - Join Global FreeSW Python GNU(Linux) HW Culture meeting via VOIP - BerkeleyTIP GlobalTIP - For Forwarding

2009-11-07 Thread john_re
Guido Van Rossum SciPy talk this month!


CONTENTS: Meeting days/times & Howto - Mark your calendar's dates;
Videos; Hot topics; Opportunities; Announcement Flyers; New webpages

=
Come join in with the Global Free SW HW & Culture community at the
BerkeleyTIP/GlobalTIP meeting, via VOIP.

Two meetings this month:
Sat Nov 7,  12Noon - 3PM Pacific Time (=UTC-8)
Sun Nov 22, 12Noon - 3PM Pacific Time (=UTC-8)
Mark your calendars, 1st Sat, 3rd Sun every month.
  {Note: 4th Sunday this November, to give 2 week spacing.}

Join online #berkeleytip on irc.freenode.net
& we'll help you get your voip HW & SW working:
http://sites.google.com/site/berkeleytip/remote-attendance
Or come to the FreeSpeech Cafe at UC Berkeley in person meeting.

Join the global mailing list
http://groups.google.com/group/BerkTIPGlobal

I hope to see you there. :)


=  Talk Videos for November 2009:
Django Development  - Richard Kiss, Eddy Mulyono, Glen Jarvis, Simeon
Franklin; BayPiggies
Python for scientific research, discussion with Guido van Rossum;
UCBSciPy
Netbooks - Michael Gorven, Dave Mackie, and Jonathan Carter; CLUG
Japan Linux Symposium Keynote, Linus Torvalds & Jim Zemlin; Linux
Foundation

http://sites.google.com/site/berkeleytip/talk-videos
Download & watch them before the meetings, discuss at the meetings.

Thanks to all the Speakers, Videographers, & Groups! :)
[Record your local meeting! Put the video online, & email me for
inclusion for next month. :) ]

= Hot topics: Ubuntu 9.10 - Problems? Fixes? Upgrade? Install?
Freeswitch VOIP server - setup for BTIP
Flyers & outreach to UCBerkeley.
Outreach to other UC campuses next semester.


=  Opportunities - Learn new, or increase your job skills, &/or
volunteer & help the community:  Set up any of: a BTIP Mailing List, web
server/site, Freeswitch VOIP server, or Virtual Private Network & SSL


= Announcement Flyers:  Print & Post them in your community.  4/5
available - Freedom, Karmic Koala, Free Culture, SciPy, OLPC. See bottom
of page:  http://groups.google.com/group/BerkTIPGlobal


= New BTIP Webpages @ http://sites.google.com/site/berkeleytip/
UC Campus local groups; Free Hardware; System Administration;
Announcement Flyers; Opportunities


For Forwarding - You are invited to forward this announcement wherever
it would be appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the correct way to port codecs.open to python 3.1?

2009-11-07 Thread MRAB

Baptiste Lepilleur wrote:
After applying 2to3.py to port a 2.6 script to 3.1, I get the following 
error when running my script:

  File "purekeyworddbtest.py", line 143, in __init__
f = codecs.open(EXCLUDED_KEYWORDS_FILE, 'rt', 'utf-8')
  File "c:\Python31\lib\codecs.py", line 870, in open
file = builtins.open(filename, mode, buffering)
ValueError: can't have text and binary mode at once

I skimmed through python 3.0 release notes, and I haven't seen anything 
indicating that codecs.open behaviour has changed in incompatible way 
(just that it is no longer useful). Have I missed something?


Do I need to replace all codecs.open with the built-in open function? If 
so, why does codecs.open still exist?



The documentation says of codecs.open() that "Files are always opened in
binary mode, even if no binary mode was specified", but you've given the
mode as 'rt', so you're asking it to open the file both in text mode
_and_ binary mode. This is the same as in Python 2.6.

If it works in 2.6 but not in 3.1, perhaps it's just that in 2.6 it
ignores the 't' whereas in 3.1 it complains.
--
http://mail.python.org/mailman/listinfo/python-list


ANN: esky 0.2.1

2009-11-07 Thread Ryan Kelly

I'm pleased to announce the latest release of esky, a tool for keeping
your frozen apps fresh:

  Downloads:http://pypi.python.org/pypi/esky/
  Latest Version:   0.2.1
  License:  BSD

Esky is an auto-update framework for frozen python apps, built on top of
bbfreeze.  It provides a simple API through which apps can find, fetch
and install updates, and a bootstrapping mechanism that keeps the app
safe in the face of failed or partial updates.

A frozen app that wants to auto-update itself might run the following in
a background thread:

if hasattr(sys,"frozen"):
app = esky.Esky(sys.executable,"http://myapp.com/downloads/";)
new_version = app.find_update()
if new_version is not None:
app.install_update(new_version)

The new version of the application is linked into the app directory in
the safest possible manner:  using a carefully-ordered sequence of
atomic renames on POSIX, using MoveFileTransacted on Windows Vista or
later, and using the "rename-and-pray" method on older versions of
Windows.  Failed or partial updates are detected and cleaned up
automatically.


 Enjoy!


 Ryan



-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au|  http://www.rfk.id.au/ramblings/gpg/ for details



signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


Serious Privileges Problem: Please Help

2009-11-07 Thread Victor Subervi
I have a serious privileges problem that is making it impossible to serve
python pages on a CentOS server. It appears that nobody on the CentOS
discussion list has a solution to this problem. I'm desperate and hoping
someone on this list can help.

[Fri Nov 06 11:50:40 2009] [error] [client 66.248.168.98] (2)No such file or
directory: exec of '/var/www/html/angrynates.com/global_solutions/index.py'
failed, referer: http://angrynates.com/global_solutions/
[Fri Nov 06 11:50:40 2009] [error] [client 66.248.168.98] Premature end of
script headers: index.py, referer: http://angrynates.com/global_solutions/

Now, the file does exist:

[r...@13gems global_solutions]# pwd
/var/www/html/angrynates.com/global_solutions
[r...@13gems global_solutions]# ls

-rwxr-xr-x 1 victor victor 275 Nov 6 07:05 index.py

and it serves just fine on another server, so there is no "premature end of
script headers".


Here's where it gets really weird. If I copy the code for index.py and
template.py which the former calls, and create files test.py and test2.py
and paste the code from the former files in those new files changing only
the import statement from "template" to "test2", the tests will resolve!!
Now, the ownership and mode are identical on all of them!!


[r...@13gems global_solutions]# ls -al | grep test.py
-rwxr-xr-x 1 root root 298 Nov 6 12:24 test.py
[r...@13gems global_solutions]# ls -al | grep test2.py
-rwxr-xr-x 1 root root 5716 Nov 6 12:25 test2.py
[r...@13gems global_solutions]# ls -al | grep index.py
-rwxr-xr-x 1 root root 316 Nov 6 07:05 index.py
[r...@13gems global_solutions]# ls -al | grep template.py
-rwxr-xr-x 1 root root 5806 Nov 6 07:06 template.py
-rwxr-xr-x 1 root root 6093 Nov 6 07:06 template.pyc

where test.py is identical to index.py (other than the necessary import) and
template is identical to test2.py


fixfiles relabel /var/www/html
# might just work
It didn't

touch /.autorelabel
# and then reboot will relabel all copied files to the correct contexts for
the location
I rebooted apache with no luck

or you could turn off SELinux and reboot
I did that and the following two solutions with no luck:
echo 0 >/selinux/enforce

[r...@13gems ~]# cd /etc/
[r...@13gems etc]# mv selinux/ selinux.BAK
[r...@13gems etc]# mkdir selinux
[r...@13gems etc]# echo 0>/selinux/enforce

...and the problem continues:
[r...@13gems etc]# tail /var/log/httpd/error_log
[Fri Nov 06 12:51:49 2009] [error] [client 66.248.168.98] Premature end of
script headers: index.py, referer: http://angrynates.com/global_solutions/
[Fri Nov 06 12:56:18 2009] [error] [client 66.248.168.98] (2)No such file or
directory: exec of '/var/www/html/angrynates.com/global_solutions/index.py'
failed, referer: http://angrynates.com/global_solutions/
[Fri Nov 06 12:56:18 2009] [error] [client 66.248.168.98] Premature end of
script headers: index.py, referer: http://angrynates.com/global_solutions/
[Fri Nov 06 12:56:20 2009] [error] [client 67.96.172.81] (2)No such file or
directory: exec of '/var/www/html/angrynates.com/global_solutions/index.py'
failed
[Fri Nov 06 12:56:20 2009] [error] [client 67.96.172.81] Premature end of
script headers: index.py
[Fri Nov 06 13:52:15 2009] [error] [client 66.249.67.153] File does not
exist: /var/www/html/angrynates.com/robots.txt
[Fri Nov 06 13:52:52 2009] [error] [client 208.84.198.58] (2)No such file or
directory: exec of '/var/www/html/angrynates.com/global_solutions/index.py'
failed, referer: http://angrynates.com/global_solutions/
[Fri Nov 06 13:52:52 2009] [error] [client 208.84.198.58] Premature end of
script headers: index.py, referer: http://angrynates.com/global_solutions/
[Fri Nov 06 13:52:52 2009] [error] [client 208.84.198.58] File does not
exist: /var/www/html/angrynates.com/favicon.ico
[Fri Nov 06 13:52:53 2009] [error] [client 208.84.198.58] File does not
exist: /var/www/html/angrynates.com/favicon.ico
[r...@13gems etc]#

Please help.
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the correct way to port codecs.open to python 3.1?

2009-11-07 Thread Baptiste Lepilleur
2009/11/7 MRAB 

> Baptiste Lepilleur wrote:
>
 [..]
>> Do I need to replace all codecs.open with the built-in open function? If
>> so, why does codecs.open still exist?
>>
>>  The documentation says of codecs.open() that "Files are always opened in
> binary mode, even if no binary mode was specified", but you've given the
> mode as 'rt', so you're asking it to open the file both in text mode
> _and_ binary mode. This is the same as in Python 2.6.
>
> If it works in 2.6 but not in 3.1, perhaps it's just that in 2.6 it
> ignores the 't' whereas in 3.1 it complains.
>

So I did miss something, but it was in 2.6. Thanks for the clarification.

Though, I think the documentation is somewhat confusing in 3.x as it says
that it opens the file in binary mode, but the opened file iterator returns
str not bytes...
-- 
http://mail.python.org/mailman/listinfo/python-list


Program to compute and print 1000th prime number

2009-11-07 Thread Ray Holt
I am taking the MIT online course Introduction to Computer Science and
Programming. I have a assignment to write a program to compute and print the
1000th. prime number. Can someone give me some leads on the correct code?
Thanks, Ray
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Program to compute and print 1000th prime number

2009-11-07 Thread sstein...@gmail.com


On Nov 7, 2009, at 9:44 AM, Ray Holt wrote:

I am taking the MIT online course Introduction to Computer Science  
and Programming. I have a assignment to write a program to compute  
and print the 1000th. prime number. Can someone give me some leads  
on the correct code? Thanks, Ray


Copying code != doing an assignment.  Try Knuth.

S


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


Re: What is the best way to delete strings in a string list that that match certain pattern?

2009-11-07 Thread Steven D'Aprano
On Fri, 06 Nov 2009 10:16:58 -0600, Peng Yu wrote:

> What is a list-comprehension?

Time for you to Read The Fine Manual.

http://docs.python.org/tutorial/index.html


> I tried the following code. The list 'l' will be ['a','b','c'] rather
> than ['b','c'], which is what I want. It seems 'remove' will disrupt the
> iterator, right? I am wondering how to make the code correct.
> 
> l = ['a', 'a', 'b', 'c']
> for x in l:
>   if x == 'a':
> l.remove(x)


Oh lordy, it's Shlemiel the Painter's algorithm. Please don't do that for 
lists with more than a handful of items. Better still, please don't do 
that.

http://www.joelonsoftware.com/articles/fog000319.html



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


Re: Docs Typo

2009-11-07 Thread Steven D'Aprano
On Sat, 07 Nov 2009 01:09:51 +1300, Lawrence D'Oliveiro wrote:

> In message <87eioghrsk@benfinney.id.au>, Ben Finney wrote:
> 
>> Lawrence D'Oliveiro  writes:
>> 
>>>  -- “ScrolledCavas” should
>>> be “ScrolledCanvas”.
>> 
>> Thanks for finding and describing a fault with the Python
>> documentation. This is not the right place for reporting it, though:
>> this is the Python user forum, not an appropriate place for reporting
>> faults.
>> 
>> If you would like the issue to be addressed, please report it to the
>> Python bug tracking system http://bugs.python.org/>.
> 
> What do you want, a bloody HTML patch? Just fix the damn typo, already!

I tried abusing strangers on the Internet, but the typo is still there. 
So I tried waving my hands in the air, but the typo is still there. Then 
I tried chanting magical incantations, but the typo is still there. I 
tried kicking the dog across the room, but the typo is still there. Next 
I'm going to try wishing really, really hard, and if that fails I'll try 
abusing strangers on the Internet again, and if that still fails, well, I 
guess that there just is no possible way to fix typos in the Python 
documentation.

Such a pity. If only there was, oh I don't know, a Python bug tracker or 
something, where one could report bugs and have them fixed.



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


Re: is None or == None ?

2009-11-07 Thread Steven D'Aprano
On Fri, 06 Nov 2009 16:51:18 +0100, Marco Mariani wrote:

> Using "x is y" with integers
> makes no sense and has no guaranteed behaviour AFAIK

Of course it makes sense. `x is y` means *exactly the same thing* for 
ints as it does with any other object: it tests for object identity. 
That's all it does, and it does it perfectly.

Python makes no promise whether x = 3; y = 3 will use the same object for 
both x and y or not. That's an implementation detail. That's not a 
problem with `is`, it is a problem with developers who make unjustified 
assumptions.


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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Steven D'Aprano
On Fri, 06 Nov 2009 18:46:33 -0800, gil_johnson wrote:

> I don't have the code with me, but for huge arrays, I have used
> something like:
> 
 arr[0] = initializer
 for i in range N:
  arr.extend(arr)
> 
> This doubles the array every time through the loop, and you can add the
> powers of 2 to get the desired result. Gil

Why is it better to grow the list piecemeal instead of just allocating a 
list the size you want in one go?

arr = [x]*size_wanted



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


Re: Defining re pattern for matching list of numbers

2009-11-07 Thread Steven D'Aprano
On Fri, 06 Nov 2009 10:16:31 -0800, Chris Rebert wrote:

> Your format seems so simple I have to ask why you're using regexes in
> the first place.

Raymond Hettinger has described some computing techniques as "code 
prions" -- programming advice or techniques which are sometimes useful 
but often actively harmful.

http://www.mail-archive.com/python-list%40python.org/msg262651.html

As useful as regexes are, I think they qualify as code prions too: people 
insist on using them in production code, even when a simple string method 
or function would do the job far more efficiently and readably.



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


Re: Program to compute and print 1000th prime number

2009-11-07 Thread Robert P. J. Day
On Sat, 7 Nov 2009, sstein...@gmail.com wrote:

>
> On Nov 7, 2009, at 9:44 AM, Ray Holt wrote:
>
>   I am taking the MIT online course Introduction to Computer Science and
>   Programming. I have a assignment to write a program to compute and print
>   the 1000th. prime number. Can someone give me some leads on the correct
>   code? Thanks, Ray
>
>
> Copying code != doing an assignment.  Try Knuth.

  i was going to say much the same, but it's also worth pointing out
that, using standard techniques, there is no straightforward way to
print the n'th prime number, given some initial value of n.

  the ubiquitous sieve of eratosthenes requires you to pre-specify
your maximum value, after which -- once the sieve completes -- all you
know is that you have all of the prime numbers up to n.  whether
you'll have 1000 of them isn't clear, which means that you might have
to start all over with a larger maximum value.  (being able to
directly determine the n'th prime number would solve a *lot* of prime
number problems. :-)

  and given that one can google and, in seconds, have the solution, i
feel no guilt in referring to
http://code.activestate.com/recipes/366178/.

rday
--


Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pyfora, a place for python

2009-11-07 Thread Aneesh Kulkarni
Imagine if no one ever created anything new out of fear of
"fragmenting the community".  Should we hurl the same accusation at
Guido for fragmenting the programmer community and creating Python,
when perfectly fine languages like Perl, Lisp & Smalltalk already
existed?

Creating new things is a part of the natural evolution of the web
ecosystem.  Some of them will succeed, like Python itself did, and
ultimately improve the ecosystem.  New places hardly fragment the
community, because at the early stages, they usually don't draw many
resources away from existing communities; by the time they do, they
can be valuable contributors to the larger community in their own
right.

Aneesh

On Nov 7, 2:58 am, Saketh  wrote:
> On Nov 4, 5:28 pm, Alan Franzoni 
> wrote:
>
>
>
>
>
> > On 11/2/09 3:44 PM, Diez B. Roggisch wrote:
>
> > > Being from germany, I can say that we *have* this fragmentation, and
> > > frankly: I don't like it. I prefer my communication via NNTP/ML, and not
> > > with those visually rather noisy and IMHO suboptimal forums. E.g. it
>
> > That's right... forums, although more "accessible" to all the people who
> > can't/doesn't want to use specific email or nntp clients, are quite slow
> > to use.
>
> > But I think Ubuntu forums support threads and are kind of "channeled"
> > between ML and webinterface... something like Google Groups; I think
> > THAT would be a good idea. What about trying to "channel"
> > comp.lang.python and a forum?
>
> > --
> > Alan Franzoni
> > contact me at pub...@[mysurname].eu
>
> Hi everyone,
>
> My small effort to create a place for discussing Python seems to have
> sparked a larger discussion than I had anticipated. My intent in
> creatingPyforais not to splinter the community or encroach upon
> comp.lang.python users, but to create an alternative location where
> users can discuss Python. If this offends or irritates anyone, please
> accept my humble apologies.
>
> I understand that forums can be degenerate and uncivil, but my hope is
> that withPyfora, beginners will have a place to freely ask questions
> in a genial environment. A large part of my computer upbringing was on
> forums, and I wanted to share that experience with new Python users.
>
> Sincerely,
> Saketh

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


Re: PyQt processEvents not processing

2009-11-07 Thread David Boddie
On Saturday 07 November 2009 05:12, DarkBlue wrote:

> qt 4.5.3
> pyqt 4.6.1
> python 2.6
> 
> I have this QtTable widget which I want to refresh once about every 2
> seconds with new data.
> 
> so I do :
> 
>  def updateSchedule(self):
>  for j in range(0,10):
>   doUpdate()
>   QtCore.processEvents()
>   sleep(2)
> 
>  unfortunately QT appears to wait until the for loop finishes
>  and only then paints the QtTable widget on the screen showing
>  only the latest updated result.

It's difficult to know exactly why this is without more context. Calling
the application's processEvents() method should give the user interface the
chance to update itself, but perhaps you need to explicitly call update()
on the QTableView or QTableWidget instance to ensure that it is refreshed.

An alternative way to do this is to use a timer to update the table every
two seconds.

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


Re: What is the best way to delete strings in a string list that that match certain pattern?

2009-11-07 Thread Peng Yu
On Sat, Nov 7, 2009 at 8:54 AM, Steven D'Aprano
 wrote:
> On Fri, 06 Nov 2009 10:16:58 -0600, Peng Yu wrote:
>
>> What is a list-comprehension?
>
> Time for you to Read The Fine Manual.
>
> http://docs.python.org/tutorial/index.html
>
>
>> I tried the following code. The list 'l' will be ['a','b','c'] rather
>> than ['b','c'], which is what I want. It seems 'remove' will disrupt the
>> iterator, right? I am wondering how to make the code correct.
>>
>> l = ['a', 'a', 'b', 'c']
>> for x in l:
>>   if x == 'a':
>>     l.remove(x)
>
>
> Oh lordy, it's Shlemiel the Painter's algorithm. Please don't do that for
> lists with more than a handful of items. Better still, please don't do
> that.
>
> http://www.joelonsoftware.com/articles/fog000319.html

I understand what is Shlemiel the Painter's algorithm. But if the
iterator can be intelligently adjusted in my code upon 'remove()', is
my code Shlemiel the Painter's algorithm?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best way to delete strings in a string list that that match certain pattern?

2009-11-07 Thread Peng Yu
On Fri, Nov 6, 2009 at 5:57 PM, Dave Angel  wrote:
>
>
> Peng Yu wrote:
>>
>> On Fri, Nov 6, 2009 at 10:42 AM, Robert P. J. Day 
>> wrote:
>>
>>>
>>> On Fri, 6 Nov 2009, Peng Yu wrote:
>>>
>>>

 On Fri, Nov 6, 2009 at 3:05 AM, Diez B. Roggisch 
 wrote:

>
> Peng Yu schrieb:
>
>>
>> Suppose I have a list of strings, A. I want to compute the list (call
>> it B) of strings that are elements of A but doesn't match a regex. I
>> could use a for loop to do so. In a functional language, there is way
>> to do so without using the for loop.
>>
>
> Nonsense. For processing over each element, you have to loop over them,
> either with or without growing a call-stack at the same time.
>
> FP languages can optimize away the stack-frame-growth (tail recursion)
> - but
> this isn't reducing complexity in any way.
>
> So use a loop, either directly, or using a list-comprehension.
>

 What is a list-comprehension?

 I tried the following code. The list 'l' will be ['a','b','c'] rather
 than ['b','c'], which is what I want. It seems 'remove' will disrupt
 the iterator, right? I am wondering how to make the code correct.

 l ='a', 'a', 'b', 'c']
 for x in l:
  if x ='a':
    l.remove(x)

 print l

>>>
>>>  list comprehension seems to be what you want:
>>>
>>>  l =i for i in l if i != 'a']
>>>
>>
>> My problem comes from the context of using os.walk(). Please see the
>> description of the following webpage. Somehow I have to modify the
>> list inplace. I have already tried 'dirs =i for i in l if dirs !'a']'. But
>> it seems that it doesn't "prune the search". So I need the
>> inplace modification of list.
>>
>> http://docs.python.org/library/os.html
>>
>> When topdown is True, the caller can modify the dirnames list in-place
>> (perhaps using del or slice assignment), and walk() will only recurse
>> into the subdirectories whose names remain in dirnames; this can be
>> used to prune the search, impose a specific order of visiting, or even
>> to inform walk() about directories the caller creates or renames
>> before it resumes walk() again. Modifying dirnames when topdown is
>> False is ineffective, because in bottom-up mode the directories in
>> dirnames are generated before dirpath itself is generated.
>>
>>
>
> The context is quite important in this case.  The os.walk() iterator gives
> you a tuple of three values, and one of them is a list.  You do indeed want
> to modify that list, but you usually don't want to do it "in-place."   I'll
> show you the in-place version first, then show you the slice approach.
>
> If all you wanted to do was to remove one or two specific items from the
> list, then the remove method would be good.  So in your example, you don' t
> need a loop.  Just say:
>   if 'a' in dirs:
>        dirs.remove('a')
>
> But if you have an expression you want to match each dir against, the list
> comprehension is the best answer.  And the trick to stuffing that new list
> into the original list object is to use slicing on the left side.  The [:]
> notation is a default slice that means the whole list.
>
>   dirs[:] = [ item for item in dirs if     bool_expression_on_item ]

I suggest to add this example to the document of os.walk() to make
other users' life easier.
-- 
http://mail.python.org/mailman/listinfo/python-list


Can't Find Module

2009-11-07 Thread Victor Subervi
Hi;
I'm getting this error:

Mod_python error: "PythonHandler mod_python.publisher"

Traceback (most recent call last):

  File "/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 299,
in HandlerDispatch
result = object(req)

  File "/usr/lib64/python2.4/site-packages/mod_python/publisher.py", line
204, in handler
module = page_cache[req]

  File "/usr/lib64/python2.4/site-packages/mod_python/cache.py", line 82, in
__getitem__
return self._checkitem(name)[2]

  File "/usr/lib64/python2.4/site-packages/mod_python/cache.py", line 124,
in _checkitem
value = self.build(key, name, opened, entry)

  File "/usr/lib64/python2.4/site-packages/mod_python/publisher.py", line
77, in build
return ModuleCache.build(self, key, req, opened, entry)

  File "/usr/lib64/python2.4/site-packages/mod_python/cache.py", line 371,
in build
exec opened in module.__dict__

  File "/var/www/html/angrynates.com/global_solutions/index.py", line 8, in
?
from template import template

ImportError: No module named template


Here's the code:

#!/usr/bin/python

import string
import cgitb; cgitb.enable()
import cgi
import sys,os
sys.path.append(os.getcwd())
from template import template

ourFile = string.split(__file__, "/")
page = ourFile[len(ourFile) - 1][:-3]

form = cgi.FieldStorage()
w = form.getfirst('w', '1024')

print page

template(page, w)


I can import this just fine from the python command prompt. So, what gives?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Program to compute and print 1000th prime number

2009-11-07 Thread Raymond Hettinger
> > On Nov 7, 2009, at 9:44 AM, Ray Holt wrote:
>
> >       I am taking the MIT online course Introduction to Computer Science and
> >       Programming. I have a assignment to write a program to compute and 
> > print
> >       the 1000th. prime number. Can someone give me some leads on the 
> > correct
> >       code? Thanks, Ray

Tongue in cheek solution:

import urllib2

url = 'http://primes.utm.edu/lists/small/1.txt'
primes = []
for line in urllib2.urlopen(url).read().splitlines():
values = line.split()
if len(values) == 10:
primes.extend(values)
print primes[1000-1]


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


Re: Program to compute and print 1000th prime number

2009-11-07 Thread Robert P. J. Day
On Sat, 7 Nov 2009, Raymond Hettinger wrote:

> > > On Nov 7, 2009, at 9:44 AM, Ray Holt wrote:
> >
> > >       I am taking the MIT online course Introduction to Computer
> > > Science and       Programming. I have a assignment to write a
> > > program to compute and print       the 1000th. prime number. Can
> > > someone give me some leads on the correct       code? Thanks,
> > > Ray
>
> Tongue in cheek solution:
>
> import urllib2
>
> url = 'http://primes.utm.edu/lists/small/1.txt'
> primes = []
> for line in urllib2.urlopen(url).read().splitlines():
> values = line.split()
> if len(values) == 10:
> primes.extend(values)
> print primes[1000-1]

  reminds me of a variation of an old joke:  using nothing but this
barometer, determine the height of that building.

  answer:  go to the building manager and say, "i'll give you this
really neat barometer if you tell me how tall this building is."

rday
--


Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Program to compute and print 1000th prime number

2009-11-07 Thread Xavier Ho
On Sun, Nov 8, 2009 at 12:44 AM, Ray Holt  wrote:

>  I have a assignment to write a program to compute and print the 1000th.
> prime number. Can someone give me some leads on the correct code?
>

Ray, if you really want an answer out of this list, you'll have to at least
show us what efforts you've put into solving this problem. Perhaps if you
post your code that doesn't quite work, we can make suggestions on how to
improve/fix it. Other than that, it's generally considered bad karma to give
any kind of code, and we need to know where you are.

my 2c,
Xavier
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extracting info from media files

2009-11-07 Thread Sean DiZazzo
MediaInfo is your best bet.  http://mediainfo.sourceforge.net/en

~Sean

On Nov 6, 11:59 pm, Michele Simionato 
wrote:
> I would like to extract some simple info from media files, such as
> size, resolution, duration, codec. What's the simplest way to do it?
> Once in a time there was pymedia but I see the latest release is of
> February 2006. The solution should work on Linux and provide support
> for a large set of video formats.

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


Re: Program to compute and print 1000th prime number

2009-11-07 Thread Mensanator
On Nov 7, 11:23 am, Raymond Hettinger  wrote:
> > > On Nov 7, 2009, at 9:44 AM, Ray Holt wrote:
>
> > >       I am taking the MIT online course Introduction to Computer Science 
> > > and
> > >       Programming. I have a assignment to write a program to compute and 
> > > print
> > >       the 1000th. prime number. Can someone give me some leads on the 
> > > correct
> > >       code? Thanks, Ray
>
> Tongue in cheek solution:
>
> import urllib2
>
> url = 'http://primes.utm.edu/lists/small/1.txt'
> primes = []
> for line in urllib2.urlopen(url).read().splitlines():
>     values = line.split()
>     if len(values) == 10:
>         primes.extend(values)
> print primes[1000-1]

Nice, but you can do better.

>>> import gmpy
>>> n = 1
>>> for i in xrange(1000):
n = gmpy.next_prime(n)
>>> print n
7919

>
> Raymond

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


exception due to NoneType

2009-11-07 Thread asit
In my program I want to catch exception which is caused by accessing
NoneType object.

Can anyone suggest me how this can be done ??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the correct way to port codecs.open to python 3.1?

2009-11-07 Thread Antoine Pitrou
Le Sat, 07 Nov 2009 12:56:54 +0100, Baptiste Lepilleur a écrit :
> 
> After applying 2to3.py to port a 2.6 script to 3.1, I get the following
> error when running my script:
>   File "purekeyworddbtest.py", line 143, in __init__
> f = codecs.open(EXCLUDED_KEYWORDS_FILE, 'rt', 'utf-8')
>   File "c:\Python31\lib\codecs.py", line 870, in open
> file = builtins.open(filename, mode, buffering)
> ValueError: can't have text and binary mode at once

I would suggest not using codecs.open() in 3.x, since the built-in open() 
will do the same thing, but faster.

So just write:
f = open(EXCLUDED_KEYWORDS_FILE, 'r', encoding='utf-8')
and you'll get a fast file object giving you str (unicode) objects after 
an implicit utf-8 decoding of file data.

Regards

Antoine.

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


how to display the return type of an os method?

2009-11-07 Thread Robert P. J. Day

  once again, a thoroughly newbie question but what's the quickest way
to display the return type of, say, os.stat()?  i can obviously do
this in two steps:

>>> x=os.stat('/etc/passwd')
>>> type(x)

>>>

  i'd just like to see that os.stat() returns a posix.stat_result
object in one line.  how dumb a question is that?

rday
--


Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday

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


Re: Program to compute and print 1000th prime number

2009-11-07 Thread John Posner

Robert P. J. Day said:

  the ubiquitous sieve of eratosthenes requires you to pre-specify
your maximum value, after which -- once the sieve completes -- all you
know is that you have all of the prime numbers up to n.  whether
you'll have 1000 of them isn't clear, which means that you might have
to start all over with a larger maximum value.  (being able to
directly determine the n'th prime number would solve a *lot* of prime
number problems. :-)

  
In April of this year, members of this forum helped me to devise a 
prime-number iterator [1]. So here's a simple solution for the OP:


#---
from itertools import ifilter, count

# create iterator
prime_iter = ifilter(
   lambda n, P=[]: all(n%p for p in P) and not P.append(n),
   count(2))

# throw away lots of primes
for i in range(999):   
   prime_iter.next()
  
# here's the one we want

print prime_iter.next()  #7919
#---

I don't think this is a solution that a course instructor would expect, 
though!


As mentioned in [1], optimizations of this algorithm (using 
itertools.takewhile() and/or caching previously-computed squares) are 
still at cl1p.net [2].


-John

[1]  http://mail.python.org/pipermail/python-list/2009-April/177415.html

[2]  http://www.cl1p.net/python_prime_generators






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


Re: What is the best way to delete strings in a string list that that match certain pattern?

2009-11-07 Thread Robert P. J. Day
On Sat, 7 Nov 2009, Peng Yu wrote:

> On Fri, Nov 6, 2009 at 5:57 PM, Dave Angel  wrote:

> > But if you have an expression you want to match each dir against,
> > the list comprehension is the best answer.  And the trick to
> > stuffing that new list into the original list object is to use
> > slicing on the left side.  The [:] notation is a default slice
> > that means the whole list.
> >
> >   dirs[:] = [ item for item in dirs if     bool_expression_on_item ]
>
> I suggest to add this example to the document of os.walk() to make
> other users' life easier.

  huh?  why do you need the slice notation on the left?  why can't you
just assign to "dirs" as opposed to "dirs[:]"?  using the former seems
to work just fine.  is this some kind of python optimization or idiom?

rday
--



Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to display the return type of an os method?

2009-11-07 Thread Bruno Desthuilliers
Robert P. J. Day a écrit :
>   once again, a thoroughly newbie question but what's the quickest way
> to display the return type of, say, os.stat()?  i can obviously do
> this in two steps:
> 
 x=os.stat('/etc/passwd')
 type(x)
> 
> 
>   i'd just like to see that os.stat() returns a posix.stat_result
> object in one line. 

=> type(os.stat('/etc/passwd'))

But reading the doc might help too:

=> help(os.stat)

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


Re: exception due to NoneType

2009-11-07 Thread Bruno Desthuilliers
asit a écrit :
> In my program I want to catch exception which is caused by accessing
> NoneType object.
> 
> Can anyone suggest me how this can be done ??

Not without the minimal working code exposing your problem, or the full
traceback you got. Merely "accessing NoneType object" doesn't by itself
raise any exception... I suspect you get the None object where you
expected something else and try to access an attribute of this
'something else', and ends up getting an AttributeError, but there are
other possible scenarii that might fit your (very poor) description of
the problem, so no way too help you without more informations. As a
general rule, remember that the traceback is actually meant to *help*
finding out what went wring.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Program to compute and print 1000th prime number

2009-11-07 Thread Andre Engels
On Sat, Nov 7, 2009 at 6:40 PM, Mensanator  wrote:

>> Tongue in cheek solution:
>>
>> import urllib2
>>
>> url = 'http://primes.utm.edu/lists/small/1.txt'
>> primes = []
>> for line in urllib2.urlopen(url).read().splitlines():
>>     values = line.split()
>>     if len(values) == 10:
>>         primes.extend(values)
>> print primes[1000-1]
>
> Nice, but you can do better.
>
 import gmpy
 n = 1
 for i in xrange(1000):
>        n = gmpy.next_prime(n)
 print n
> 7919

With the help of the solutions given so far, I can do even better than that:

n = 7919
print n


-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft research on code quality

2009-11-07 Thread Bruno Desthuilliers
Aahz a écrit :
> http://research.microsoft.com/en-us/news/features/nagappan-100609.aspx

An interesting reading. Thanks for the link.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best way to delete strings in a string list that that match certain pattern?

2009-11-07 Thread Peter Otten
Robert P. J. Day wrote:

> On Sat, 7 Nov 2009, Peng Yu wrote:
> 
>> On Fri, Nov 6, 2009 at 5:57 PM, Dave Angel  wrote:
> 
>> > But if you have an expression you want to match each dir against,
>> > the list comprehension is the best answer.  And the trick to
>> > stuffing that new list into the original list object is to use
>> > slicing on the left side.  The [:] notation is a default slice
>> > that means the whole list.
>> >
>> > dirs[:] = [ item for item in dirs if bool_expression_on_item ]
>>
>> I suggest to add this example to the document of os.walk() to make
>> other users' life easier.
> 
>   huh?  why do you need the slice notation on the left?  why can't you
> just assign to "dirs" as opposed to "dirs[:]"?  using the former seems
> to work just fine.  is this some kind of python optimization or idiom?

dirs = [...]

rebinds the name "dirs" while

dirs[:] = [...]

updates the contents of the list currently bound to the "dirs" name. The 
latter is necessary in the context of os.walk() because it yields a list of 
subdirectories, gives the user a chance to update it and than uses this 
potentially updated list to decide which subdirectories to descend into.
A simplified example:

>>> def f():
... items = ["a", "b", "c"]
... yield items
... print items
...
>>> for items in f():
... items = ["x", "y"]
...
['a', 'b', 'c']
>>> for items in f():
... items[:] = ["x", "y"]
...
['x', 'y']

Peter

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


Re: how to display the return type of an os method?

2009-11-07 Thread Robert P. J. Day
On Sat, 7 Nov 2009, Bruno Desthuilliers wrote:

> Robert P. J. Day a écrit :
> >   once again, a thoroughly newbie question but what's the quickest way
> > to display the return type of, say, os.stat()?  i can obviously do
> > this in two steps:
> >
>  x=os.stat('/etc/passwd')
>  type(x)
> > 
> >
> >   i'd just like to see that os.stat() returns a posix.stat_result
> > object in one line.
>
> => type(os.stat('/etc/passwd'))
>
> But reading the doc might help too:
>
> => help(os.stat)

  never mind, i realize now it was a dumb question since the return
type is based on the routine logic, of course.  argh.  carry on.

rday
--


Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Bruno Desthuilliers
kj a écrit :
> 
> As I said, this is considered an optimization, at least in Perl,
> because it lets the interpreter allocate all the required memory
> in one fell swoop, instead of having to reallocate it repeatedly
> as the array grows.

IIRC, CPython has it's own way to optimize list growth.

>  (Of course, like with all optimizations,
> whether it's worth the bother is another question.)

My very humble opinion is that unless you spot a bottleneck (that is,
you have real performance issues AND the profiler identified list growth
as the culprit), the answer is a clear and obvious NO.

> Another situation where one may want to do this is if one needs to
> initialize a non-sparse array in a non-sequential order,

Then use a dict.

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


Re: exception due to NoneType

2009-11-07 Thread asit
On Nov 7, 10:36 pm, Bruno Desthuilliers
 wrote:
> asit a écrit :
>
> > In my program I want to catch exception which is caused by accessing
> > NoneType object.
>
> > Can anyone suggest me how this can be done ??
>
> Not without the minimal working code exposing your problem, or the full
> traceback you got. Merely "accessing NoneType object" doesn't by itself
> raise any exception... I suspect you get the None object where you
> expected something else and try to access an attribute of this
> 'something else', and ends up getting an AttributeError, but there are
> other possible scenarii that might fit your (very poor) description of
> the problem, so no way too help you without more informations. As a
> general rule, remember that the traceback is actually meant to *help*
> finding out what went wring.

I could have described the error, but the problem is that it's
dependent of a third party library..

Let me write the code here...

import twitter

api = twitter.Api('asitdhal','swordfish')
users = api.GetFriends()
for s in users:
print
print "##"
try:
print "user id : " + str(s.id)
print "user name : " + s.name
print "user location : " + s.location
print "user description : " + s.description
print "user profile image url : " + s.profile_image_url
print "user url : " + s.url
print "user status : " + str(s.status)
except TypeError:
pass


look at the except TypeError. This is supposed to catch only exception
thrown by NoneType.

please help me.
-- 
http://mail.python.org/mailman/listinfo/python-list


database handling

2009-11-07 Thread asit
I need some tutorial about python-mysql connectivity(database
handling).

Somebody please help me !!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Luis Alberto Zarrabeitia Gomez

Quoting Bruno Desthuilliers :

> > Another situation where one may want to do this is if one needs to
> > initialize a non-sparse array in a non-sequential order,
> 
> Then use a dict.

Ok, he has a dict.

Now what? He needs a non-sparse array.

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Andre Engels
On Sat, Nov 7, 2009 at 8:25 PM, Luis Alberto Zarrabeitia Gomez
 wrote:
>
> Quoting Bruno Desthuilliers :
>
>> > Another situation where one may want to do this is if one needs to
>> > initialize a non-sparse array in a non-sequential order,
>>
>> Then use a dict.
>
> Ok, he has a dict.
>
> Now what? He needs a non-sparse array.

Let d be your dict.

Call the zeroeth place in your array d[0], the first d[1], the 1th
d[10].


-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is None or == None ?

2009-11-07 Thread Terry Reedy

Steven D'Aprano wrote:

On Fri, 06 Nov 2009 16:51:18 +0100, Marco Mariani wrote:


Using "x is y" with integers
makes no sense and has no guaranteed behaviour AFAIK


Of course it makes sense. `x is y` means *exactly the same thing* for 
ints as it does with any other object: it tests for object identity. 
That's all it does, and it does it perfectly.


Python makes no promise whether x = 3; y = 3 will use the same object for 
both x and y or not. That's an implementation detail. That's not a 
problem with `is`, it is a problem with developers who make unjustified 
assumptions.


Which is to say, it normally makes no sense to write 'm is n' for m, n ints.

The *exception* is when one is exploring implementation details, either 
to discover them or to test that they are as intended. So, last I 
looked, the test suite for ints makes such tests. If the implementation 
changes, the test should change also.


The problem comes when newbies use 'is' without realizing that they are 
doing black-box exploration of otherwise irrelevant internals. 
(White-box exploration would be reading the code, which makes it plain 
what is going on ;-).


Terry Jan Reedy


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


Re: Pyfora, a place for python

2009-11-07 Thread Terry Reedy

Saketh wrote:

On Nov 4, 5:28 pm, Alan Franzoni 



My small effort to create a place for discussing Python seems to have
sparked a larger discussion than I had anticipated. My intent in
creating Pyfora is not to splinter the community or encroach upon
comp.lang.python users, but to create an alternative location where
users can discuss Python. If this offends or irritates anyone, please
accept my humble apologies.

I understand that forums can be degenerate and uncivil, but my hope is
that with Pyfora, beginners will have a place to freely ask questions
in a genial environment. A large part of my computer upbringing was on
forums, and I wanted to share that experience with new Python users.


I have no problem with efforts to create something new and different. I 
am curious whether you were or have become aware of


http://www.python-forum.org/pythonforum/index.php

It seems to already do what you intended to do, so if you want to 
continue, you might think of how to differentiate PyFora.


Terry Jan Reedy

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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Luis Alberto Zarrabeitia Gomez

Quoting Andre Engels :

> On Sat, Nov 7, 2009 at 8:25 PM, Luis Alberto Zarrabeitia Gomez
>  wrote:
> >
> > Ok, he has a dict.
> >
> > Now what? He needs a non-sparse array.
> 
> Let d be your dict.
> 
> Call the zeroeth place in your array d[0], the first d[1], the 1th
> d[10].

Following that reasoning, we could get rid of lists and arrays altogether.

Here's why that wouldn't work:

for x,y in zip(d,other):
... do something ...

Yes, we could also ignore zip and just use range/xrange to iterate for the
indices... 

Lists and dictionaries have different semantics. One thing is to argue that you
shouldn't be thinking on pre-growing a list for performance reasons before being
sure that it is a bottleneck, and a very different one is to argue that because
one operation (__setitem__) is the same with both structures, we should not use
lists for what may need, depending on the problem, list semantics. 

¿Have you ever tried to read list/matrix that you know it is not sparse, but you
don't know the size, and it may not be in order? A "grow-able" array would just
be the right thing to use - currently I have to settle with either hacking
together my own grow-able array, or preloading the data into a dict, growing a
list with the [0]*size trick, and updating that list. Not hard, not worthy of a
PEP, but certainly not so easy to dismiss.

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

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


Re: database handling

2009-11-07 Thread Nick Touran
The mysqldb module works well for me. It's available on sourceforge. Find
some examples in the documentation here:

http://mysql-python.sourceforge.net/MySQLdb.html#some-mysql-examples

-Nick

On Sat, Nov 7, 2009 at 11:24 AM, asit  wrote:

> I need some tutorial about python-mysql connectivity(database
> handling).
>
> Somebody please help me !!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: imputil.py, is this a bug ?

2009-11-07 Thread Terry Reedy

Stef Mientki wrote:

Gabriel Genellina wrote:
En Fri, 06 Nov 2009 18:33:37 -0300, Stef Mientki 
 escribió:


I get an error compiling with pyjamas, in the standard module 
imputil, _import_top_module


Note that imputil is undocumented in 2.5, deprecated in 2.6 and 
definitively gone in 3.0


It was deprecated because it is buggy and unmaintainable.

In 3.1 it has been replaced with the new written-in-Python importlib. 
That has also been added to the upcoming 2.7.


Anyone using imputil and having problems with it should try the 2.7 
version of importlib and see if it runs well-enough on earlier versions.


Terry Jan Reedy

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


Re: Serious Privileges Problem: Please Help

2009-11-07 Thread Rami Chowdhury
On Saturday 07 November 2009 06:13:11 Victor Subervi wrote:
> I have a serious privileges problem that is making it impossible to serve
> python pages on a CentOS server. It appears that nobody on the CentOS
> discussion list has a solution to this problem. I'm desperate and hoping
> someone on this list can help.
> 
> [Fri Nov 06 11:50:40 2009] [error] [client 66.248.168.98] (2)No such file
>  or directory: exec of
>  '/var/www/html/angrynates.com/global_solutions/index.py' failed, referer:
>  http://angrynates.com/global_solutions/
> [Fri Nov 06 11:50:40 2009] [error] [client 66.248.168.98] Premature end of
> script headers: index.py, referer: http://angrynates.com/global_solutions/
> 
> Now, the file does exist:
> 
> [r...@13gems global_solutions]# pwd
> /var/www/html/angrynates.com/global_solutions
> [r...@13gems global_solutions]# ls
> 
> -rwxr-xr-x 1 victor victor 275 Nov 6 07:05 index.py
> 
> and it serves just fine on another server, so there is no "premature end of
> script headers".
> 
> 
> Here's where it gets really weird. If I copy the code for index.py and
> template.py which the former calls, and create files test.py and test2.py
> and paste the code from the former files in those new files changing only
> the import statement from "template" to "test2", the tests will resolve!!
> Now, the ownership and mode are identical on all of them!!
> 
> 
> [r...@13gems global_solutions]# ls -al | grep test.py
> -rwxr-xr-x 1 root root 298 Nov 6 12:24 test.py
> [r...@13gems global_solutions]# ls -al | grep test2.py
> -rwxr-xr-x 1 root root 5716 Nov 6 12:25 test2.py
> [r...@13gems global_solutions]# ls -al | grep index.py
> -rwxr-xr-x 1 root root 316 Nov 6 07:05 index.py
> [r...@13gems global_solutions]# ls -al | grep template.py
> -rwxr-xr-x 1 root root 5806 Nov 6 07:06 template.py
> -rwxr-xr-x 1 root root 6093 Nov 6 07:06 template.pyc
> 
> where test.py is identical to index.py (other than the necessary import)
>  and template is identical to test2.py
> 
> 
> fixfiles relabel /var/www/html
> # might just work
> It didn't
> 
> touch /.autorelabel
> # and then reboot will relabel all copied files to the correct contexts for
> the location
> I rebooted apache with no luck
> 
> or you could turn off SELinux and reboot
> I did that and the following two solutions with no luck:
> echo 0 >/selinux/enforce
> 
> [r...@13gems ~]# cd /etc/
> [r...@13gems etc]# mv selinux/ selinux.BAK
> [r...@13gems etc]# mkdir selinux
> [r...@13gems etc]# echo 0>/selinux/enforce
> 
> ...and the problem continues:
> [r...@13gems etc]# tail /var/log/httpd/error_log
> [Fri Nov 06 12:51:49 2009] [error] [client 66.248.168.98] Premature end of
> script headers: index.py, referer: http://angrynates.com/global_solutions/
> [Fri Nov 06 12:56:18 2009] [error] [client 66.248.168.98] (2)No such file
>  or directory: exec of
>  '/var/www/html/angrynates.com/global_solutions/index.py' failed, referer:
>  http://angrynates.com/global_solutions/
> [Fri Nov 06 12:56:18 2009] [error] [client 66.248.168.98] Premature end of
> script headers: index.py, referer: http://angrynates.com/global_solutions/
> [Fri Nov 06 12:56:20 2009] [error] [client 67.96.172.81] (2)No such file or
> directory: exec of '/var/www/html/angrynates.com/global_solutions/index.py'
> failed
> [Fri Nov 06 12:56:20 2009] [error] [client 67.96.172.81] Premature end of
> script headers: index.py
> [Fri Nov 06 13:52:15 2009] [error] [client 66.249.67.153] File does not
> exist: /var/www/html/angrynates.com/robots.txt
> [Fri Nov 06 13:52:52 2009] [error] [client 208.84.198.58] (2)No such file
>  or directory: exec of
>  '/var/www/html/angrynates.com/global_solutions/index.py' failed, referer:
>  http://angrynates.com/global_solutions/
> [Fri Nov 06 13:52:52 2009] [error] [client 208.84.198.58] Premature end of
> script headers: index.py, referer: http://angrynates.com/global_solutions/
> [Fri Nov 06 13:52:52 2009] [error] [client 208.84.198.58] File does not
> exist: /var/www/html/angrynates.com/favicon.ico
> [Fri Nov 06 13:52:53 2009] [error] [client 208.84.198.58] File does not
> exist: /var/www/html/angrynates.com/favicon.ico
> [r...@13gems etc]#
> 
> Please help.
> Victor
> 

Can we see the output of 'ls -lZ' and 'fixfiles check' on those directories, 
and see what the Apache (httpd.conf or .htaccess) configuration is for them?


Rami Chowdhury
"Passion is inversely proportional to the amount of real information 
available." -- Benford's Law of Controversy
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: imputil.py, is this a bug ?

2009-11-07 Thread Terry Reedy

lkcl wrote:

On Nov 7, 2:20 am, "Gabriel Genellina"  wrote:

Yes, seems to be a bug. But given the current status of imputil, it's not
likely to be fixed; certainly not in 2.5 which only gets security fixes
now.


 well, that bug's not the only one.  the other one that i found, which
i have been specifically ordered not to report


Imputil has been deprecated and has in 3.1 and will-be in 2.7 replaced 
by importlib, written in Python. So reporting more bugs in imputil is 
rather useless noise. So either use your patched version or try shifting 
to the 2.7 importlib and see if it runs well enough on earlier versions.


>(that or _any_ python bugs, of which there have been several 
discovered in the past eight

months), will have to wait until the python developers rescind that
order.


Without seeing documentary proof, I am dubious that you have been 
ordered to not properly report bugs in supported, not deprecated, 
modules. If really so, post reports here and interested parties can try 
to verify and possibly report them themselves. I, for instance, would be 
interested in 3.1 bugs that do not require outside resources to verify.


Terry Jan Reedy

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


My own accounting python euler problem

2009-11-07 Thread vsoler
In the accounting department I am working for we are from time to time
confronted to the following problem:

A customer sends us a check for a given amount, but without specifying
what invoices it cancels. It is up to us to find out which ones the
payment corresponds to.

For example, say that the customer has the following outstanding
invoices:  $300, $200, $50; and say that the check is for $250. This
time it is clear, the customer is paying bills $200 and $50.

However, let's now say that the outstanding invoices are $300, $200,
$100 and that the check is for $300. In this case there are already
two possibilities. The customer is paying the $300 invoice or the $200
and $100. In other words, there is more than one solution to the
problem.

My first question is:
1. given a list of invoives I=[500, 400, 450, 200, 600, 700] and a
check Ch=600
how can I print all the different combinations of invoices that the
check is possibly cancelling

1.a. first approach using "brute force", that is, exploring all
different combinations: every single invoice, all of 2-element tuples,
3-element tuples, etc...

1.b can all the solutions be found without exploring all possible
combinations? some problems can be solved by discarding some invoices,
for example those whose amounts are greater than the amount of the
check. Any ideas?

My second question is:
2. this time there are also credit notes outstanding, that is,
invoices with negative amounts. For example,  I=[500, 400, -100, 450,
200, 600, -200, 700] and a check Ch=600

2.a  is the "brute force" method used in 1.a still applicable now that
"I" contains negative values?

2.b  same as 1.b.  However, this time I can imagen that the number of
invoices that can be discarded is a lot more reduced.

I am a fan of Python, which I find very elegant, powerful and easy to
develop with. I would like to find answers to the problems described
above, partially because I am still learning python, and I would like
to make use of it.

Can anybody help?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My own accounting python euler problem

2009-11-07 Thread Jack Diederich
On Sat, Nov 7, 2009 at 4:39 PM, vsoler  wrote:
> In the accounting department I am working for we are from time to time
> confronted to the following problem:
[snip]
> For example, say that the customer has the following outstanding
> invoices:  $300, $200, $50; and say that the check is for $250. This
> time it is clear, the customer is paying bills $200 and $50.
[big snip]

http://en.wikipedia.org/wiki/Knapsack_problem

Unless your customers are giant defense contractors you should be able
to brute force a solution.  If they are so big that it doesn't take
micro seconds to brute force a solution then you probably have more
problems than just matching checks to invoices...

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


Re: My own accounting python euler problem

2009-11-07 Thread Robert P. J. Day
On Sat, 7 Nov 2009, vsoler wrote:

> In the accounting department I am working for we are from time to
> time confronted to the following problem:
>
> A customer sends us a check for a given amount, but without
> specifying what invoices it cancels. It is up to us to find out
> which ones the payment corresponds to.
>
> For example, say that the customer has the following outstanding
> invoices:  $300, $200, $50; and say that the check is for $250. This
> time it is clear, the customer is paying bills $200 and $50.
>
> However, let's now say that the outstanding invoices are $300, $200,
> $100 and that the check is for $300. In this case there are already
> two possibilities. The customer is paying the $300 invoice or the
> $200 and $100. In other words, there is more than one solution to
> the problem.
>
> My first question is: 1. given a list of invoives I=[500, 400, 450,
> 200, 600, 700] and a check Ch=600 how can I print all the different
> combinations of invoices that the check is possibly cancelling

  that sounds like the classic knapsack problem:

http://www.itl.nist.gov/div897/sqg/dads/HTML/knapsackProblem.html

it's NP-complete.

rday
--


Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday

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


Re: Serious Privileges Problem: Please Help

2009-11-07 Thread Victor Subervi
httpd.conf:


ServerAdmin m...@creative.vi
DocumentRoot /var/www/html/angrynates.com
ServerName angrynates.com
Options +ExecCGI -IncludesNoExec

 Options +ExecCGI
 AllowOverride Options
 AllowOverride FileInfo
 #AddHandler mod_python .py
 #PythonHandler mod_python.publisher
 #PythonDebug On





#ls -lZ
drwxr-xr-x  root root  1024
drwxr-xr-x  root root  1132
drwxr-xr-x  root root  1255
-rwxr-xr-x  root root  About_Us_frame.py
-rwxr-xr-x  root root  About_Us.py
-rwxr-xr-x  root root  ajax.cgi.txt
-rwxr-xr-x  root root  ajax.html
-rwxr-xr-x  root root  Catalog_frame.py
-rwxr-xr-x  root root  Catalog.py
-rwxr-xr-x  root root  cats_edit2.py
-rwxr-xr-x  root root  cats_edit.py
-rwxr-xr-x  root root  client2.py
-rwxr-xr-x  root root  client_delete2.py
-rwxr-xr-x  root root  client_delete.py
-rwxr-xr-x  root root  client_edit2.py
-rwxr-xr-x  root root  client_edit3.py
-rwxr-xr-x  root root  client_edit.py
-rwxr-xr-x  root root  client.py
-rwxr-xr-x  root root  Contact_Us_frame.py
-rwxr-xr-x  root root  Contact_Us.py
-rwxr-xr-x  root root  credit_app.doc
-rwxr-xr-x  root root  Credit Application DP
Dist .doc
-rwxr-xr-x  root root
 Customer_Templates_frame.py
-rwxr-xr-x  root root  Customer_Templates.py
-rwxr-xr-x  root root
 display_spreadsheet2.py
-rwxr-xr-x  root root
 display_spreadsheet.py
-rwxr-xr-x  root root
 EDDIE-Tool-1.0.0.tar.gz
-rwxr-xr-x  root root  email.py
-rwxr-xr-x  root root  error.log.0
-rwxr-xr-x  root root  favicon.gif
-rwxr-xr-x  root root  favicon.ico
-rwxr-xr-x  root root  Forms_frame.py
-rwxr-xr-x  root root  Forms.py
-rwxr-xr-x  root root  fw9.pdf
-rwxr-xr-x  root root  getResolution.py
-rw-r--r--  root root  hello.py
drwxr-xr-x  root root  images
drwxr-xr-x  root root  images1024
drwxr-xr-x  root root  images1132
drwxr-xr-x  root root  images1255
drwxr-xr-x  root root  images-old
-rwxr-xr-x  root root  index_frame.py
-rwxr-xr-x  root root  index.html
-rwxr-xr-x  root root  index.py
-rwxr-xr-x  root root  login.py
-rwxr-xr-x  root root  login.pyc
-rwxr-xr-x  root root
 Office_Supplies_frame.py
-rwxr-xr-x  root root  Office_Supplies.py
-rwxr-xr-x  root root
 Paper_Plastics_frame.py
-rwxr-xr-x  root root  Paper_Plastics.py
-rwxr-xr-x  root root  particulars.py
-rwxr-xr-x  root root  particulars.pyc
drwxr-xr-x  root root  pics
-rwxr-xr-x  root root  ping.py
-rwxr-xr-x  root root  products2.py
-rwxr-xr-x  root root  products3.py
-rwxr-xr-x  root root  products_cats.py
-rwxr-xr-x  root root  products_delete2.py
-rwxr-xr-x  root root  products_delete3.py
-rwxr-xr-x  root root  products_delete.py
-rwxr-xr-x  root root  products_edit2.py
-rwxr-xr-x  root root  products_edit3.py
-rwxr-xr-x  root root  products_edit.py
-rwxr-xr-x  root root  products_items.py
-rwxr-xr-x  root root  products_move2.py
-rwxr-xr-x  root root  products_move3.py
-rwxr-xr-x  root root  products_move.py
-rwxr-xr-x  root root  salesperson2.py
-rwxr-xr-x  root root
 salesperson_delete2.py
-rwxr-xr-x  root root  salesperson_delete.py
-rwxr-xr-x  roo

Re: My own accounting python euler problem

2009-11-07 Thread Robert P. J. Day
On Sat, 7 Nov 2009, vsoler wrote:

> In the accounting department I am working for we are from time to
> time confronted to the following problem:
>
> A customer sends us a check for a given amount, but without
> specifying what invoices it cancels. It is up to us to find out
> which ones the payment corresponds to.
>
> For example, say that the customer has the following outstanding
> invoices:  $300, $200, $50; and say that the check is for $250. This
> time it is clear, the customer is paying bills $200 and $50.
>
> However, let's now say that the outstanding invoices are $300, $200,
> $100 and that the check is for $300. In this case there are already
> two possibilities. The customer is paying the $300 invoice or the
> $200 and $100. In other words, there is more than one solution to
> the problem.
>
> My first question is:
> 1. given a list of invoives I=[500, 400, 450, 200, 600, 700] and a
> check Ch=600
> how can I print all the different combinations of invoices that the
> check is possibly cancelling

  by the way, there's a bit more to it than just seeing if you can
match the cheque amount exactly.  some python solutions are here:

  http://rosettacode.org/wiki/Knapsack_Problem

and a general solution allows you to place different "values" on which
items you pack into your knapsack.

  say a customer has outstanding invoices for 200, 400 and 600, and
you get a cheque for 600.  what do you apply that against?  the single
invoice for 600, or the two for 200 and 400?  that depends.

  if all invoices have the same "value", it won't matter.  but if the
invoice for 600 just went out, while the two others are just about to
become, say, overdue so that a penalty is about to be applied, your
customer would probably *really* appreciate it if you applied that
cheque to the older invoices.

  in general, then, you can not only see what matches exactly but,
for the sake of your customer, you can give higher value to paying off
older invoices.  that's how the general knapsack problem works.

rday
--


Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday

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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Terry Reedy

Steven D'Aprano wrote:

On Fri, 06 Nov 2009 18:46:33 -0800, gil_johnson wrote:


I don't have the code with me, but for huge arrays, I have used
something like:


arr[0] = initializer
for i in range N:
 arr.extend(arr)

This doubles the array every time through the loop, and you can add the
powers of 2 to get the desired result. Gil


Why is it better to grow the list piecemeal instead of just allocating a 
list the size you want in one go?


It isn't.


arr = [x]*size_wanted


Is what I would do.

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


Re: exception due to NoneType

2009-11-07 Thread Diez B. Roggisch

api = twitter.Api('asitdhal','swordfish')


You just gave the world the account-information to your twitter-account. 
 You'd rather change these asap, or somebody hijacks your account...


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


Re: is None or == None ?

2009-11-07 Thread sturlamolden
On 6 Nov, 14:35, "Alf P. Steinbach"  wrote:

> As I understand it, 'is' will always work and will always be efficient (it 
> just
> checks the variable's type), while '==' can depend on the implementation of
> equality checking for the other operand's class.

'==' checks for logical equality. 'is' checks for object identity.

None is a singleton of type NoneType. Since None evaluates to True
only when compared against itself, it is safe to use both operators.









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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Ivan Illarionov
On Nov 6, 3:12 pm, kj  wrote:
> The best I can come up with is this:
>
> arr = [None] * 100
>
> Is this the most efficient way to achieve this result?

It is the most efficient SAFE way to achieve this result.

In fact, there IS the more efficient way, but it's dangerous, unsafe,
unpythonic and plain evil:
>>> import ctypes
>>> ctypes.pythonapi.PyList_New.restype = ctypes.py_object
>>> ctypes.pythonapi.PyList_New(100)


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


Re: is None or == None ?

2009-11-07 Thread sturlamolden
On 6 Nov, 18:28, "Alf P. Steinbach"  wrote:

> Dynamic allocation isn't hare-brained, but doing it for every stored integer
> value outside a very small range is, because dynamic allocation is (relatively
> speaking, in the context of integer operations) very costly even with a
> (relatively speaking, in the context of general dynamic allocation) very
> efficient small-objects allocator - here talking order(s) of magnitude.

When it matters, we use NumPy and/or Cython.

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


Re: Command parsing... best module to use?

2009-11-07 Thread van Asselt
Hello Colin,

I have been using 'cmdloop.py' from Crutcher Dunnavant in a few programs
See http://py-cmdloop.googlecode.com/svn/trunk/cmdloop.py

Regards,
Henk

-

"Collin D"  wrote in message 
news:94dbc92b-0682-4995-b358-0c615c95a...@x6g2000prc.googlegroups.com...
> Hey everyone.
>
> I am writing a game in python, and it includes a text console somewhat
> like the one in WoW and Runescape. I want to be able to include "/"
> commands, like IRC, and was wondering what the best module would be to
> parse these.
>
> Thanks a lot,
> Collin D 


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


Re: Program to compute and print 1000th prime number

2009-11-07 Thread Wayne Brehaut
On Sat, 7 Nov 2009 19:34:47 +0100, Andre Engels
 wrote:

>On Sat, Nov 7, 2009 at 6:40 PM, Mensanator  wrote:
>
>>> Tongue in cheek solution:
>>>
>>> import urllib2
>>>
>>> url = 'http://primes.utm.edu/lists/small/1.txt'
>>> primes = []
>>> for line in urllib2.urlopen(url).read().splitlines():
>>>     values = line.split()
>>>     if len(values) == 10:
>>>         primes.extend(values)
>>> print primes[1000-1]
>>
>> Nice, but you can do better.
>>
> import gmpy
> n = 1
> for i in xrange(1000):
>>        n = gmpy.next_prime(n)
> print n
>> 7919
>
>With the help of the solutions given so far, I can do even better than that:
>
>n = 7919
>print n

>>> 7919
7919

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


Re: Serious Privileges Problem: Please Help

2009-11-07 Thread Rami Chowdhury

On Saturday 07 November 2009 13:51:06 Victor Subervi wrote:
> httpd.conf:
> 
> 
> ServerAdmin m...@creative.vi
> DocumentRoot /var/www/html/angrynates.com
> ServerName angrynates.com
> Options +ExecCGI -IncludesNoExec
> 

You may want to change this to:


If you want regular expression syntax, I would advise using the syntax

or 


> #ls -lZ
> drwxr-xr-x  root root  1024
> drwxr-xr-x  root root  1132
> drwxr-xr-x  root root  1255
[snip]

It looks like you don't have *any* SELinux context information; if SELinux is 
on, this will cause problems. Try using the 'restorecon' command to put the 
defaults in place, and consider using 'chcon' to change the security context 
to an appropriate one (I believe you want something like 
'unconfined_u:object_r:httpd_sys_content_t' for Apache content). 

> 
> On Sat, Nov 7, 2009 at 4:09 PM, Rami Chowdhury 
wrote:
> > On Saturday 07 November 2009 06:13:11 Victor Subervi wrote:
> > > I have a serious privileges problem that is making it impossible to
> > > serve python pages on a CentOS server. It appears that nobody on the
> > > CentOS discussion list has a solution to this problem. I'm desperate
> > > and hoping someone on this list can help.
> > >
> > > [Fri Nov 06 11:50:40 2009] [error] [client 66.248.168.98] (2)No such
> > > file or directory: exec of
> > >  '/var/www/html/angrynates.com/global_solutions/index.py' failed,
> >
> > referer:
> > >  http://angrynates.com/global_solutions/
> > > [Fri Nov 06 11:50:40 2009] [error] [client 66.248.168.98] Premature end
> >
> > of
> >
> > > script headers: index.py, referer:
> >
> > http://angrynates.com/global_solutions/
> >
> > > Now, the file does exist:
> > >
> > > [r...@13gems global_solutions]# pwd
> > > /var/www/html/angrynates.com/global_solutions
> > > [r...@13gems global_solutions]# ls
> > > 
> > > -rwxr-xr-x 1 victor victor 275 Nov 6 07:05 index.py
> > > 
> > > and it serves just fine on another server, so there is no "premature
> > > end
> >
> > of
> >
> > > script headers".
> > >
> > >
> > > Here's where it gets really weird. If I copy the code for index.py and
> > > template.py which the former calls, and create files test.py and
> > > test2.py and paste the code from the former files in those new files
> > > changing only the import statement from "template" to "test2", the
> > > tests will resolve!! Now, the ownership and mode are identical on all
> > > of them!!
> > >
> > >
> > > [r...@13gems global_solutions]# ls -al | grep test.py
> > > -rwxr-xr-x 1 root root 298 Nov 6 12:24 test.py
> > > [r...@13gems global_solutions]# ls -al | grep test2.py
> > > -rwxr-xr-x 1 root root 5716 Nov 6 12:25 test2.py
> > > [r...@13gems global_solutions]# ls -al | grep index.py
> > > -rwxr-xr-x 1 root root 316 Nov 6 07:05 index.py
> > > [r...@13gems global_solutions]# ls -al | grep template.py
> > > -rwxr-xr-x 1 root root 5806 Nov 6 07:06 template.py
> > > -rwxr-xr-x 1 root root 6093 Nov 6 07:06 template.pyc
> > >
> > > where test.py is identical to index.py (other than the necessary
> > > import) and template is identical to test2.py
> > >
> > >
> > > fixfiles relabel /var/www/html
> > > # might just work
> > > It didn't
> > >
> > > touch /.autorelabel
> > > # and then reboot will relabel all copied files to the correct contexts
> >
> > for
> >
> > > the location
> > > I rebooted apache with no luck
> > >
> > > or you could turn off SELinux and reboot
> > > I did that and the following two solutions with no luck:
> > > echo 0 >/selinux/enforce
> > >
> > > [r...@13gems ~]# cd /etc/
> > > [r...@13gems etc]# mv selinux/ selinux.BAK
> > > [r...@13gems etc]# mkdir selinux
> > > [r...@13gems etc]# echo 0>/selinux/enforce
> > >
> > > ...and the problem continues:
> > > [r...@13gems etc]# tail /var/log/httpd/error_log
> > > [Fri Nov 06 12:51:49 2009] [error] [client 66.248.168.98] Premature end
> >
> > of
> >
> > > script headers: index.py, referer:
> >
> > http://angrynates.com/global_solutions/
> >
> > > [Fri Nov 06 12:56:18 2009] [error] [client 66.248.168.98] (2)No such
> > > file or directory: exec of
> > >  '/var/www/html/angrynates.com/global_solutions/index.py' failed,
> >
> > referer:
> > >  http://angrynates.com/global_solutions/
> > > [Fri Nov 06 12:56:18 2009] [error] [client 66.248.168.98] Premature end
> >
> > of
> >
> > > script headers: index.py, referer:
> >
> > http://angrynates.com/global_solutions/
> >
> > > [Fri Nov 06 12:56:20 2009] [error] [client 67.96.172.81] (2)No such
> > > file
> >
> > or
> >
> > > directory: exec of '/var/www/html/
> >
> > angrynates.com/global_solutions/index.py'
> >
> > > failed
> > > [Fri Nov 06 12:56:20 2009] [error] [client 67.96.172.81] Premature end
> > > of script headers: index.py
> > > [Fri Nov 06 13:52:15 2009] [error] [client 66.249.67.153] File does not
> > > exist: /var/www/html/angrynates.com/robots.txt
> > > [Fri Nov 06 13:52:52 2009] [error] [clien

feedback on function introspection in argparse

2009-11-07 Thread Yuv
This was posted to the argparse mailing list by Steven Bethard and now
we'd like some feedback from comp.lang.python.

We now have a branch[5] of argparse that supports an ``argparse.run``
function[6] which does
some function introspection to build a command line parser from a
function definition:

-- prog.py --
import argparse

def func(foo, bar, baz):
   """A function that foo's a bar with a baz.
   foo - The foo
   bar - The bar to be foo'd
   baz - The baz with which to foo.
   """
   print foo, bar, baz

if __name__ == '__main__':
   argparse.run(func)
-- cmdline --
$ prog.py -h
usage: prog.py [-h] foo bar baz

A function that foo's a bar with a baz.

positional arguments:
 foo The foo
 bar The bar to be foo'd
 baz The baz with which to foo.

optional arguments:
 -h, --help  show this help message and exit
--

I'd love to hear some feedback on this. At the moment, the code can
introspect argument names, types from defaults, types from annotations
(in Python 3), help messages from docstrings, and knows how to convert
multiple functions into subcommands. The code's compatible and tested
on python 2.3 - 3.1. There are probably more things we could support
[7], but I'd like to get some feedback on what we have so
far. Some specific questions:

* Do you think this is worth including in argparse?
* Would you use the current ``argparse.run`` API in your own code?
* If you wouldn't use it as-is, what additional features/modifications
would you require?

--Steve and Yuv


PS: The authors of pyopt[1], opster[2], optfunc[3] and simpleopt[4]
were CC'd, in the hopes that we can converge to a common API, but they
didn't reply other than the pyopt guy (me) who wrote the patch.
[0] SVN branch at: 
http://argparse.googlecode.com/svn/branches/function-arguments/
[1] http://code.google.com/p/pyopt/
[2] http://hg.piranha.org.ua/opster/
[3] http://github.com/simonw/optfunc/
[4] http://pypi.python.org/pypi/simpleopt/
[5] http://argparse.googlecode.com/svn/branches/function-arguments/
[6] The branch also adds ``ArgumentParser.add_function_arguments``
which ``argparse.run`` is built on top of. This method allows you to
match function based arguments with other arguments as necessary,
e.g.::
   def items(n=10):
   return range(n)

   parser = argparse.ArgumentParser()
   parser.add_function_arguments(items)
   parser.add_argument('output_file')
   args = parser.parse_args()
   with open(args.output_file, 'w') as output_file:
   for item in args.items():
   output_file.write("%d\n" % item)

[7] I can imagine allowing the introspected values to be overridden
with decorators, though it may be out of the scope of this patch.
e.g.::
   @annotate(
   dirname=positional(help='...'),
   listen=optional('-l', default='localhost', help='ip to listen
on'),
   port=optional('-p', default=8000, help='port to listen on'),
   ...)
   def func(dirname, listen='localhost', port=8000, ...):
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is None or == None ?

2009-11-07 Thread sturlamolden
On 6 Nov, 17:54, "Alf P. Steinbach"  wrote:

> But wow. That's pretty hare-brained: dynamic allocation for every stored value
> outside the cache range, needless extra indirection for every operation.

First, integers are not used the same way in Python as they are in C+
+. E.g. you typically don't iterate over them in a for loop, but
rather iterate on the container itself. Second, if you need an array
of integers or floats, that is usually not done with a list: you would
use numpy.ndarray or array.array, and values are stored compactly.

A Python list is a list, it is not an array. If you were to put
integers in dynamic data structures in other languages (Java, C++),
you would use dynamic allocation as well. Yes a list is implemented as
an array of pointers, amortized to O(1) for appends, but that is an
implementation detail.

Python is not the only language that works like this. There are also
MATLAB and Lisp. I know you have a strong background in C++, but when
you are using Python you must unlearn that way of thinking.

Finally: if none of these helps, we can always resort to Cython.

In 99% of cases where integers are bottlenecks in Python, it is
indicative of bad style. We very often see this from people coming
form C++ and Java background, and subsequent claims that "Python is
slow". Python is not an untyped Java. If you use it as such, it will
hurt. Languages like Python, Perl, Common Lisp, and MATLAB require a
different mindset from the programmer.

















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


Re: exception due to NoneType

2009-11-07 Thread Bruno Desthuilliers
asit a écrit :
> On Nov 7, 10:36 pm, Bruno Desthuilliers
>  wrote:
>> asit a écrit :
>>
>>> In my program I want to catch exception which is caused by accessing
>>> NoneType object.
>>> Can anyone suggest me how this can be done ??
>> Not without the minimal working code exposing your problem, or the full
>> traceback you got. Merely "accessing NoneType object" doesn't by itself
>> raise any exception... I suspect you get the None object where you
>> expected something else and try to access an attribute of this
>> 'something else', and ends up getting an AttributeError, but there are
>> other possible scenarii that might fit your (very poor) description of
>> the problem, so no way too help you without more informations. As a
>> general rule, remember that the traceback is actually meant to *help*
>> finding out what went wring.
> 
> I could have described the error, but the problem is that it's
> dependent of a third party library..

This more often than not translates to "dependent of a wrong use of a
3rd part library".

> Let me write the code here...
> 
> import twitter
> 
> api = twitter.Api('asitdhal','swordfish')

I hope this is not your actual login.

> users = api.GetFriends()
> for s in users:
> print
> print "##"
> try:
> print "user id : " + str(s.id)

Please learn to use print and string formatting. Here are two ways to
get rid of the need to use str():

1/  print "user id : %s" % s.id
2/  print "user id : ", s.id


> print "user name : " + s.name
> print "user location : " + s.location
> print "user description : " + s.description
> print "user profile image url : " + s.profile_image_url
> print "user url : " + s.url
> print "user status : " + str(s.status)
> except TypeError:
> pass

Silently passing exception is 99.999 out of 100 a very stupid thing to do.

> 
> look at the except TypeError. 

Yes, I've seen it. It's stupid, and actually make debugging harder. Any
statement in this try block could raise a TypeError if the looked up
attribute of 's' is not a string. Python is NOT php, and will not
happily adds apples and parrots - you can only concatenate strings with
strings, not with ints or None or whatever...

> This is supposed to catch only exception
> thrown by NoneType.

Please get your facts straight.
1/ The NoneType doesn't "throw" (the appropriate python term is "raise")
 any exception by itself
2/ this except clause will catch any TypeError. Try this:

try:
   x = "aaa" + 42
except TypeError, e:
   print "This has nothing to do with NoneType"


> please help me.

Help yourself and read the FineManual. Then make appropriate use of
string formatting (your best friend for simple formatted outputs)
instead of useless string concatenations.

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


Re: database handling

2009-11-07 Thread Bruno Desthuilliers
asit a écrit :
> I need some tutorial about python-mysql connectivity(database
> handling).
> 
> Somebody please help me !!

You didn't search very far, did you ?

http://wiki.python.org/moin/DatabaseProgramming/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: feedback on function introspection in argparse

2009-11-07 Thread geremy condra
On Sat, Nov 7, 2009 at 5:45 PM, Yuv  wrote:
> This was posted to the argparse mailing list by Steven Bethard and now
> we'd like some feedback from comp.lang.python.
>
> We now have a branch[5] of argparse that supports an ``argparse.run``
> function[6] which does
> some function introspection to build a command line parser from a
> function definition:
>
> -- prog.py --
> import argparse
>
> def func(foo, bar, baz):
>   """A function that foo's a bar with a baz.
>   foo - The foo
>   bar - The bar to be foo'd
>   baz - The baz with which to foo.
>   """
>   print foo, bar, baz
>
> if __name__ == '__main__':
>   argparse.run(func)
> -- cmdline --
> $ prog.py -h
> usage: prog.py [-h] foo bar baz
>
> A function that foo's a bar with a baz.
>
> positional arguments:
>  foo         The foo
>  bar         The bar to be foo'd
>  baz         The baz with which to foo.
>
> optional arguments:
>  -h, --help  show this help message and exit
> --

Looks great! Very handy.

> I'd love to hear some feedback on this. At the moment, the code can
> introspect argument names, types from defaults, types from annotations
> (in Python 3), help messages from docstrings, and knows how to convert
> multiple functions into subcommands. The code's compatible and tested
> on python 2.3 - 3.1. There are probably more things we could support
> [7], but I'd like to get some feedback on what we have so
> far. Some specific questions:
>
> * Do you think this is worth including in argparse?
> * Would you use the current ``argparse.run`` API in your own code?

yes.

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


Re: is None or == None ?

2009-11-07 Thread Steven D'Aprano
On Sat, 07 Nov 2009 14:22:28 -0800, sturlamolden wrote:

> On 6 Nov, 14:35, "Alf P. Steinbach"  wrote:
> 
>> As I understand it, 'is' will always work and will always be efficient
>> (it just checks the variable's type), while '==' can depend on the
>> implementation of equality checking for the other operand's class.
> 
> '==' checks for logical equality. 'is' checks for object identity.

So far so good, although technically == merely calls __eq__, which can be 
over-ridden to do (nearly) anything you like:

>>> class Funny(object):
... def __eq__(self, other):
... return self.payload + other
...
>>> f = Funny()
>>> f.payload = 5
>>> f == 10
15


> None is a singleton of type NoneType. Since None evaluates to True only
> when compared against itself, 

That's wrong. None never evaluates to True, it always evaluates as None, 
in the same way that 42 evaluates as 42 and [1,2,3] evaluates as [1,2,3]. 
Python literals evaluate as themselves, always.

Perhaps you mean that *comparisons* of None evaluate to True only if both 
operands are None. That's incorrect too:

>>> None > None
False

You have to specify the comparison. It would be a pretty strange language 
if both None==None and None!=None returned True.



> it is safe to use both operators.

Only if you want unexpected results if somebody passes the wrong sort of 
object to your code.


>>> class NoneProxy:
... def __eq__(self, other):
... if other is None: return True
... return False
...
>>> o = NoneProxy()
>>> o is None
False
>>> o == None
True

You should use == *only* if you want to test for objects which are equal 
to None, *whatever that object may be*, and is if you want to test for 
None itself.



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


Re: exception due to NoneType

2009-11-07 Thread Ben Finney
asit  writes:

> for s in users:
> print
> print "##"
> try:
> print "user id : " + str(s.id)
> print "user name : " + s.name
> print "user location : " + s.location
> print "user description : " + s.description
> print "user profile image url : " + s.profile_image_url
> print "user url : " + s.url
> print "user status : " + str(s.status)
> except TypeError:
> pass

Why are you catching TypeError, only to discard it? Ignoring an error
doesn't make it go away.

The above code should rather use string formatting to interpolate the
values you want into a string for output::

import textwrap

for user in users:
print textwrap.dedent("""
##
user id: %(id)s
user name: %(name)s
user location: %(location)s
user description: %(description)s
user profile image url: %(profile_image_url)s
user url: %(url)s
user status: %(status)s
""") % vars(user)

-- 
 \   “My classmates would copulate with anything that moved, but I |
  `\   never saw any reason to limit myself.” —Emo Philips |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft research on code quality

2009-11-07 Thread Mensanator
On Nov 6, 3:15 pm, a...@pythoncraft.com (Aahz) wrote:
> http://research.microsoft.com/en-us/news/features/nagappan-100609.aspx
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> [on old computer technologies and programmers]  "Fancy tail fins on a
> brand new '59 Cadillac didn't mean throwing out a whole generation of
> mechanics who started with model As."  --Andrew Dalke

Microsoft has more to answer for for the fuckups they install
deliberately than for the bugs that get in accidentally.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: feedback on function introspection in argparse

2009-11-07 Thread Carl Banks
On Nov 7, 2:45 pm, Yuv  wrote:
> This was posted to the argparse mailing list by Steven Bethard and now
> we'd like some feedback from comp.lang.python.
>
> We now have a branch[5] of argparse that supports an ``argparse.run``
> function[6] which does
> some function introspection to build a command line parser from a
> function definition:
>
> -- prog.py --
> import argparse
>
> def func(foo, bar, baz):
>    """A function that foo's a bar with a baz.
>    foo - The foo
>    bar - The bar to be foo'd
>    baz - The baz with which to foo.
>    """
>    print foo, bar, baz
>
> if __name__ == '__main__':
>    argparse.run(func)
> -- cmdline --
> $ prog.py -h
> usage: prog.py [-h] foo bar baz
>
> A function that foo's a bar with a baz.
>
> positional arguments:
>  foo         The foo
>  bar         The bar to be foo'd
>  baz         The baz with which to foo.
>
> optional arguments:
>  -h, --help  show this help message and exit
> --
>
> I'd love to hear some feedback on this. At the moment, the code can
> introspect argument names, types from defaults, types from annotations
> (in Python 3), help messages from docstrings, and knows how to convert
> multiple functions into subcommands. The code's compatible and tested
> on python 2.3 - 3.1. There are probably more things we could support
> [7], but I'd like to get some feedback on what we have so
> far. Some specific questions:
>
> * Do you think this is worth including in argparse?
> * Would you use the current ``argparse.run`` API in your own code?
> * If you wouldn't use it as-is, what additional features/modifications
> would you require?

Looks quite useful.

I am not sure I like the name "run", seems to short and innocent for a
function this magical.

Is the docstring expected to be formatted according to some
convention?  I don't recognize a docstring convention in the example,
but then I don't bother with them much in my own code, that's why I
ask.


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


Re: feedback on function introspection in argparse

2009-11-07 Thread Yuv
On Nov 8, 1:33 am, Carl Banks  wrote:
> Is the docstring expected to be formatted according to some
> convention?

Yes it does, we parse the docstring as explained in argparse.py:
def _parse_docstring(function):
"""Parses a function's docstring for a description of the function
and for
help on the individual parameters.

The parsing algorithm currently looks for lines that start with a
parameter
name immediately followed by any amount of whitespace, hyphens or
colons.
The rest of the line following the colon/hyphen/whitespace is the
help.

Keyword Arguments:
function - the function whose docstring is parsed.

Returns a (description, help_dict) tuple:
description - all text before the first documented parameter
help_dict - a dictionary mapping parameter names to their help
strings
"""

We tried to comply to PEP 257 and we're open to suggestions on this.

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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread kj
In  Luis Alberto Zarrabeitia 
Gomez  writes:


>Quoting Andre Engels :

>> On Sat, Nov 7, 2009 at 8:25 PM, Luis Alberto Zarrabeitia Gomez
>>  wrote:
>> >
>> > Ok, he has a dict.
>> >
>> > Now what? He needs a non-sparse array.
>> 
>> Let d be your dict.
>> 
>> Call the zeroeth place in your array d[0], the first d[1], the 1th
>> d[10].

>Following that reasoning, we could get rid of lists and arrays altogether.

>Here's why that wouldn't work:

>for x,y in zip(d,other):
>... do something ...

>Yes, we could also ignore zip and just use range/xrange to iterate for the
>indices... 

>Lists and dictionaries have different semantics. One thing is to argue that you
>shouldn't be thinking on pre-growing a list for performance reasons before 
>being
>sure that it is a bottleneck, and a very different one is to argue that because
>one operation (__setitem__) is the same with both structures, we should not use
>lists for what may need, depending on the problem, list semantics. 

>¿Have you ever tried to read list/matrix that you know it is not sparse, but 
>you
>don't know the size, and it may not be in order? A "grow-able" array would just
>be the right thing to use - currently I have to settle with either hacking
>together my own grow-able array, or preloading the data into a dict, growing a
>list with the [0]*size trick, and updating that list. Not hard, not worthy of a
>PEP, but certainly not so easy to dismiss.

Thanks.  Well said.

Saludos,

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


Spam Bot, broken pipe

2009-11-07 Thread Someone Something
I have a irc spam bot (only testing on my channel :P ) whose main loop is
the following:

privc="PRIVMSG "+self.channel
while True:
 self.sock.send(privc=" :SPAM SPAM SPAM!");
 time.sleep(2);

And it gives an error "Broken Pipe".
How can I fix this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread sturlamolden
On 6 Nov, 13:12, kj  wrote:

>
> The best I can come up with is this:
>
> arr = [None] * 100
>
> Is this the most efficient way to achieve this result?

Yes, but why would you want to? Appending to a Python list has
amortized O(1) complexity. I am not sure about Perl, but in MATLAB
arrays are preallocated because resize has complexity O(n), instead of
amortized O(1). You don't need to worry about that in Python. Python
lists are resized with empty slots at the end, in proportion to the
size of the list. On average, this has the same complexity as pre-
allocation.












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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread sturlamolden
On 7 Nov, 03:46, gil_johnson  wrote:>

> I don't have the code with me, but for huge arrays, I have used
> something like:
>
> >>> arr[0] = initializer
> >>> for i in range N:
> >>>      arr.extend(arr)
>
> This doubles the array every time through the loop, and you can add
> the powers of 2 to get the desired result.
> Gil

You should really use append instead of extend. The above code is O
(N**2), with append it becomes O(N) on average.









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


Re: feedback on function introspection in argparse

2009-11-07 Thread Carl Banks
On Nov 7, 3:44 pm, Yuv  wrote:
> On Nov 8, 1:33 am, Carl Banks  wrote:
>
> > Is the docstring expected to be formatted according to some
> > convention?

[snippage]

> We tried to comply to PEP 257 and we're open to suggestions on this.


Ah, so we finally get to the answer: the convention is PEP 257.  :)


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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread sturlamolden
On 6 Nov, 22:03, kj  wrote:

> As I said, this is considered an optimization, at least in Perl,
> because it lets the interpreter allocate all the required memory
> in one fell swoop, instead of having to reallocate it repeatedly
> as the array grows.

Python does not need to reallocate repeatedly as a list grows. That is
why it's called a 'list' and not an array.

There will be empty slots at the end of a list you can append to,
without reallocating. When the list is resized, it is reallocated with
even more of these. Thus the need to reallocate becomes more and more
rare as the list grows, and on average the complexity of appending is
just O(1).




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


How convert string '1e7' to an integer?

2009-11-07 Thread Peng Yu
It seems that int() does not convert '1e7'. I'm wondering what
function to use to convert '1e7' to an integer?

>>> int('1e7')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '1e7'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread Carl Banks
On Nov 7, 5:05 pm, sturlamolden  wrote:
> On 7 Nov, 03:46, gil_johnson  wrote:>
>
> > I don't have the code with me, but for huge arrays, I have used
> > something like:
>
> > >>> arr[0] = initializer
> > >>> for i in range N:
> > >>>      arr.extend(arr)
>
> > This doubles the array every time through the loop, and you can add
> > the powers of 2 to get the desired result.
> > Gil
>
> You should really use append instead of extend. The above code is O
> (N**2), with append it becomes O(N) on average.

I think the top one is O(N log N), and I'm suspicious that it's even
possible to grow a list in less than O(N log N) time without knowing
the final size in advance.  Citation?  Futhermore why would it matter
to use extend instead of append; I'd assume extend uses the same
growth algorithm.  (Although in this case since the extend doubles the
size of the list it most likely reallocates after each call.)

[None]*N is linear time and is better than growing the list using
append or extend.


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


Re: Most efficient way to "pre-grow" a list?

2009-11-07 Thread exarkun

On 01:18 am, pavlovevide...@gmail.com wrote:

On Nov 7, 5:05�pm, sturlamolden  wrote:

On 7 Nov, 03:46, gil_johnson  wrote:>

> I don't have the code with me, but for huge arrays, I have used
> something like:

> >>> arr[0] = initializer
> >>> for i in range N:
> >>> � � �arr.extend(arr)

> This doubles the array every time through the loop, and you can add
> the powers of 2 to get the desired result.
> Gil

You should really use append instead of extend. The above code is O
(N**2), with append it becomes O(N) on average.


I think the top one is O(N log N), and I'm suspicious that it's even
possible to grow a list in less than O(N log N) time without knowing
the final size in advance.  Citation?  Futhermore why would it matter
to use extend instead of append; I'd assume extend uses the same
growth algorithm.  (Although in this case since the extend doubles the
size of the list it most likely reallocates after each call.)

[None]*N is linear time and is better than growing the list using
append or extend.


The wikipedia page for http://en.wikipedia.org/wiki/Amortized_analysis 
conveniently uses exactly this example to explain the concept of 
amortized costs.


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


Re: How convert string '1e7' to an integer?

2009-11-07 Thread Mensanator
On Nov 7, 7:17 pm, Peng Yu  wrote:
> It seems that int() does not convert '1e7'.

Because 'e' isn't a valid character in base 10.

> I'm wondering what
> function to use to convert '1e7' to an integer?
>
> >>> int('1e7')

>>> int(1e7)
1000


>
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: invalid literal for int() with base 10: '1e7'

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


Re: How convert string '1e7' to an integer?

2009-11-07 Thread Mick Krippendorf
Peng Yu wrote:
> It seems that int() does not convert '1e7'.
It seems it does, though:

>>> int('1e7', base=16)
487

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


Re: How convert string '1e7' to an integer?

2009-11-07 Thread MRAB

Peng Yu wrote:

It seems that int() does not convert '1e7'. I'm wondering what
function to use to convert '1e7' to an integer?


int('1e7')

Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '1e7'


In Python the e-form indicates a float, as does the presence of a
decimal point, but you can convert to float and then to int:

>>> int(float('1e7'))
1000
--
http://mail.python.org/mailman/listinfo/python-list


Re: How convert string '1e7' to an integer?

2009-11-07 Thread Ben Finney
Mick Krippendorf  writes:

> Peng Yu wrote:
> > It seems that int() does not convert '1e7'.
> It seems it does, though:
>
> >>> int('1e7', base=16)
> 487

Well played, sir.

-- 
 \   “It is wrong to think that the task of physics is to find out |
  `\ how nature *is*. Physics concerns what we can *say* about |
_o__) nature…” —Niels Bohr |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How convert string '1e7' to an integer?

2009-11-07 Thread Gary Herron

Mensanator wrote:

On Nov 7, 7:17 pm, Peng Yu  wrote:
  

It seems that int() does not convert '1e7'.



Because 'e' isn't a valid character in base 10.
  


But 1e7 is a valid float, so this works:

>>> int(float('1e7'))
1000

That has a problem though, if you surpass the ability of a float:

>>> int(float('1e20'))
1L
>>> int(float('1e30'))
119884624838656L


Gary Herron



  

I'm wondering what
function to use to convert '1e7' to an integer?



int('1e7')
  


  

int(1e7)


1000


  

Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '1e7'



  


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


Re: How convert string '1e7' to an integer?

2009-11-07 Thread Benjamin Kaplan
On Sat, Nov 7, 2009 at 8:17 PM, Peng Yu  wrote:
> It seems that int() does not convert '1e7'. I'm wondering what
> function to use to convert '1e7' to an integer?
>
 int('1e7')
> Traceback (most recent call last):
>  File "", line 1, in 
> ValueError: invalid literal for int() with base 10: '1e7'

Whenever you use that notation, you always get a float

>>> 1e7
1000.0

So to convert '1e7' to a number, you need to use float('1e7') which
you can then convert to an int
>>> int(float('1e7'))
1000



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


Re: How convert string '1e7' to an integer?

2009-11-07 Thread Christian Heimes
Peng Yu wrote:
> It seems that int() does not convert '1e7'. I'm wondering what
> function to use to convert '1e7' to an integer?

1e7 is a way to express a float in science and math. Try float("1e7")

Christian

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


Re: How convert string '1e7' to an integer?

2009-11-07 Thread Tim Chase

Mick Krippendorf wrote:

Peng Yu wrote:

It seems that int() does not convert '1e7'.

It seems it does, though:


int('1e7', base=16)

487


Bah...so narrow-minded ;-)

>>> print '\n'.join("Base %i: %i" % (base, int('1e7', 
base=base)) for base in range(15,37))

Base 15: 442
Base 16: 487
Base 17: 534
Base 18: 583
Base 19: 634
Base 20: 687
Base 21: 742
Base 22: 799
Base 23: 858
Base 24: 919
Base 25: 982
Base 26: 1047
Base 27: 1114
Base 28: 1183
Base 29: 1254
Base 30: 1327
Base 31: 1402
Base 32: 1479
Base 33: 1558
Base 34: 1639
Base 35: 1722
Base 36: 1807

I feel so dirty interpreting numbers in convenient ways...like an 
accountant.  ("whaddaya mean I can't file my tax-return in base 
17?!  There's nothing in the supporting documentation that 
mentions such draconian restrictions!")


-tkc




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


Spam Bot, broken pipe

2009-11-07 Thread Someone Something
I'm just testing it on my channel! I promise! Besides, I'm doing it to learn
about sockets! Please!


On Sat, Nov 7, 2009 at 8:07 PM, Krister Svanlund  wrote:

> On Sun, Nov 8, 2009 at 2:00 AM, Someone Something 
> wrote:
> > I have a irc spam bot (only testing on my channel :P ) whose main loop is
> > the following:
> >
> > privc="PRIVMSG "+self.channel
> > while True:
> >  self.sock.send(privc=" :SPAM SPAM SPAM!");
> >  time.sleep(2);
> >
> > And it gives an error "Broken Pipe".
> > How can I fix this?
>
> By doing it right... unfortunaly I don't approve of spam and can
> therefor not tell you how to do that.
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-11-07 Thread Alan Harris-Reid


mario ruggier wrote:

With respect to to original question regarding web frameworks +
database and Python 3, all the following have been available for
Python 3 since the day Python 3.0 was released:

QP, a Web Framework
http://pypi.python.org/pypi/qp/

Durus, a Python Object Database (the "default" in qp, for user
sessions, etc)
http://pypi.python.org/pypi/Durus/

Evoque, state-of-the-art templating engine
http://pypi.python.org/pypi/evoque/
(this one is available for py3.0 since a little later, 21-jan-2009)

All the above also runs on python 2.4 (thru to python 3)

For the record, you may see the list of all pypi packages availabe for
Python 3 at:
http://pypi.python.org/pypi?:action=browse&show=all&c=533

m.

Thanks for those links Mario - I'll check them out asap..

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


Re: is None or == None ?

2009-11-07 Thread Hrvoje Niksic
"Alf P. Steinbach"  writes:

> Speedup would likely be more realistic with normal implementation (not
> fiddling with bit-fields and stuff)

I'm not sure I understand this.  How would you implement tagged integers
without encoding type information in bits of the pointer value?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt processEvents not processing

2009-11-07 Thread DarkBlue
On Nov 8, 12:04 am, David Boddie  wrote:
> On Saturday 07 November 2009 05:12, DarkBlue wrote:
>
>
>
> > qt 4.5.3
> > pyqt 4.6.1
> > python 2.6
>
> > I have this QtTable widget which I want to refresh once about every 2
> > seconds with new data.
>
> > so I do :
>
> >  def updateSchedule(self):
> >          for j in range(0,10):
> >                       doUpdate()
> >                       QtCore.processEvents()
> >                       sleep(2)
>
> >  unfortunately QT appears to wait until the for loop finishes
> >  and only then paints the QtTable widget on the screen showing
> >  only the latest updated result.
>
> It's difficult to know exactly why this is without more context. Calling
> the application's processEvents() method should give the user interface the
> chance to update itself, but perhaps you need to explicitly call update()
> on the QTableView or QTableWidget instance to ensure that it is refreshed.
>
> An alternative way to do this is to use a timer to update the table every
> two seconds.
>
> David


As per your suggestion I added a timer to the init part and now the
update works as expected , even without calls to processEvents.

self.myTimer = QtCore.QTimer(self)
QtCore.QObject.connect(self.myTimer,QtCore.SIGNAL("timeout()"),
self.doUpdate)
self.timerTime = 0
self.myTimer.start(2000)

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


Re: Spam Bot, broken pipe

2009-11-07 Thread Someone Something
anyone?

On Sat, Nov 7, 2009 at 9:06 PM, Someone Something wrote:

>
>
> I'm just testing it on my channel! I promise! Besides, I'm doing it to
> learn about sockets! Please!
>
>
> On Sat, Nov 7, 2009 at 8:07 PM, Krister Svanlund <
> krister.svanl...@gmail.com> wrote:
>
>> On Sun, Nov 8, 2009 at 2:00 AM, Someone Something 
>> wrote:
>> > I have a irc spam bot (only testing on my channel :P ) whose main loop
>> is
>> > the following:
>> >
>> > privc="PRIVMSG "+self.channel
>> > while True:
>> >  self.sock.send(privc=" :SPAM SPAM SPAM!");
>> >  time.sleep(2);
>> >
>> > And it gives an error "Broken Pipe".
>> > How can I fix this?
>>
>> By doing it right... unfortunaly I don't approve of spam and can
>> therefor not tell you how to do that.
>>
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Cancelling a python thread (revisited...)

2009-11-07 Thread Sven Marnach
Hi,

the Python threading module does not seem to provide a means to cancel
a running thread.  There are many discussions on the web dealing with
this issue and many solutions are offered, but none of them seems to
be applicable to my situation, which is as follows:

I have a C library which does some very computationally intensive
stuff.  Some functions in this library might run for a long time, and
the code in the library is optimized for speed.  The library is used
in C programs and also from a PyGTK GUI program.  In the GUI, you can
choose the computation parameters and than start the computation.  It
is run in a separate thread, which calls a function in the C library
via ctypes.

Now it should be possible to cancel the computation from the GUI.  In
the C programs, I can just kill or cancel the thread (there is no
cleanup to be done -- the thread does not use any system resources
apart from CPU time).  In Python, this is not possible.  The solutions
for this problem I found on the web usually recommend to have the
thread regularly check some variable and exit if this variable
indicates to do so.  This would have to be included in the C library
and would include quite a bit of code refactoring.  The check cannot
be included in the inner loop because it would lead to significant
performance loss.  Furthermore, I just do not want to mess up an
elegant and efficient library design which works perfect when used
from C just to make up for shortcomings in Python.

So do I really have to refactor my C library just because Python
Thread objects lack a cancel method?  Is there really no other way?
And why on earth doesn't that cancel method exist?  There *are* good
reasons to cancel a thread, just google for "terminate a Python
thread" for tons of examples.

I would be grateful for any suggestions.

Greetings from Germany and have a nice day,
Sven
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >