ipython prompt does not appear in windows

2011-05-17 Thread rusi
If I use ipython under emacs on linux it works (at least basic REPL)
ie I can type an expression and I get a result followed by a prompt

On windows ipython works at the shell.
Plain python works in emacs as well.

But inside emacs I dont see a prompt in ipython although I see it in
python.
I have to type an expression and then the prompt appears.

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


Re: indirect assignment question

2011-05-17 Thread Thomas Rachel

Am 17.05.2011 07:13 schrieb Andy Baxter:


self.window = self.wTree.get_widget("mainWindow")
self.outputToggleMenu = self.wTree.get_widget("menuitem_output_on")
self.outputToggleButton = self.wTree.get_widget("button_toggle_output")
self.logView = self.wTree.get_widget("textview_log")
self.logScrollWindow = self.wTree.get_widget("scrolledwindow_log")

and I would like (for tidiness / compactness's sake) to replace them
with something like this:
widgetDic = {
"mainWindow": self.window,
"menuitem_output_on": self.outputToggleMenu,
"button_toggle_output": self.outputToggleButton,
"textview_log": self.logView,
"scrolledwindow_log": self.logScrollWindow
}
for key in widgetDic:
... set the variable in dic[key] to point to self.wTree.get_widget(key)
somehow


assignmap = (
('mainWindow', 'window'),
('menuitem_output_on', 'outputToggleMenu'),
('button_toggle_output', 'outputToggleButton'),
('textview_log', 'logView'),
('scrolledwindow_log', 'logScrollWindow'),
)
for name, selfname in assignmap:
val = widgetDic[name] = self.wTree.get_widget(name)
setattr(self, selfname, val)


HTH,

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


Re: Deleting a file?

2011-05-17 Thread Algis Kabaila
On Tuesday 17 May 2011 07:23:33 garyr wrote:
> A file can be deleted by opening it with mode os.O_TEMPORARY
> and then closing it. How can a file be moved to the Recycle
> Bin, a la Windows?

Just highlight it, pess the "Del" key and select "move to 
Trash".  (With minor variation between different desktops, viz. 
KDE, gnome etc.

If you ask a genuine answer, the above are genuine answers.

HTH,

OldAl.

-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


How to select Python web frameworks and which one is the best framework ?

2011-05-17 Thread VGNU Linux
Hi all,

I am confused on which web framework to select for developing a small data
driven web application. Application will have features generally found in
now-a-days web application like security, database connectivity,
authentication etc. I found few web frameworks over the net like django,
zope 2/3, pylons, turbogears, web2py, grok etc. etc.
I just want to know that how developers/managers/organizations select a
framework which best suits their needs ? what are the parameters for
selection ?
also which is the best and widely used web framework for python ?

I apologize if this is a repeated question.

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


FW: help please

2011-05-17 Thread hamed azarkeshb



From: [email protected]
To: [email protected]
Subject: help please
Date: Tue, 17 May 2011 13:20:22 +0430








hi dearinwant to useautomation with catiaby python,but i dont know,how do we 
can creat catsafearrayvariant in python?please help me.i need urhelp by one 
example.thank u forany thing -- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert AWK regex to Python

2011-05-17 Thread J
Hello,

I have managed to get my script finished in the end by taking bits from 
everyone who answered.  Thank you so much.  the finished query string looks 
like this (still not the best but it gets the job done.  Once I learn to code 
more with Python I will probably go back to it and re-write it):-

# Log file to work on
filetoread = open("/tmp/pdu.log", "r")
# Perform filtering in the log file
text = filetoread.read()
text = text.replace("http://mail.python.org/mailman/listinfo/python-list


Datetime.timedelta

2011-05-17 Thread Tsolmon Narantsogt
Hi list

I'm using datetime.timedelta and i have a problem

delta = 1 day, 2:30:00
hours = delta.days * 8

how to add 8 + 2:30:00


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


cPickle -> invalid signature

2011-05-17 Thread Neal Becker
What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?

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


Re: Datetime.timedelta

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 07:44:08 -0300, Tsolmon Narantsogt   
escribió:



I'm using datetime.timedelta and i have a problem

delta = 1 day, 2:30:00
hours = delta.days * 8

how to add 8 + 2:30:00


Just operate with it as it were a number. The timedelta class implements  
all "sane" mathematical operations.


py> from datetime import *
py> def timedelta_from_dhms(days=0, hours=0, mins=0, secs=0):
...   return timedelta(days, hours*3600 + mins*60 + secs)
...
py> delta = timedelta_from_dhms(1, 2, 30)
py> delta
datetime.timedelta(1, 9000)
py> hours = delta.days * 8
py> delta + hours
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'datetime.timedelta' and  
'int'

py> hours = timedelta_from_dhms(0, delta.days * 8)
py> hours
datetime.timedelta(0, 28800)
py> delta + hours
datetime.timedelta(1, 37800)
py> def dhms_from_timedelta(td):
...   return td.days, td.seconds // 3600, (td.seconds % 3600) // 60,  
td.seconds % 60

...
py> dhms_from_timedelta(delta + hours)
(1, 10, 30, 0)

--
Gabriel Genellina

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


Re: FW: help please

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 06:43:51 -0300, hamed azarkeshb  
 escribió:


hi dearinwant to useautomation with catiaby python,but i dont know,how  
do we can creat catsafearrayvariant in python?please help me.i need  
urhelp by one example.thank u forany thing 		 	   		


There are two sides when you want to use automation with Python:

* learn how to do automation by itself, how COM works, how to invoke a COM  
server from Python. This is mostly application-independent. A good  
resource is "Python Programming in Win32" book by Mark Hammond. Chapter 5  
"Introduction to COM" is exactly what you need, and is available for  
preview in Google Books:  
http://books.google.com.ar/books?id=fzUCGtyg0MMC&lpg=PA65&pg=PA65#v=onepage&f=false


* learn how to use the actual objects exposed by the desired application.  
Usually, documentation is available for VBA or other languages, but can be  
easily translated into Python terms.


So I'd say you first read the book, then search the documentation about  
CATSafeArrayVariant and see how to create it, and then translate that into  
Python. Feel free to post any problem you encounter, a better place would  
be the python-win32 list:  
http://mail.python.org/mailman/listinfo/python-win32


Good luck!
--
Gabriel Genellina

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


Re: cPickle -> invalid signature

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 08:41:41 -0300, Neal Becker   
escribió:



What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic  
answer, make sure you open the file in binary mode, both when writing and  
reading.


--
Gabriel Genellina

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


where to find shared python script?

2011-05-17 Thread Yue Chao
Dear all,

I am new to python and thank you for your help!
the first question is, is there any resource online where we can find shared
python script (like reading a csv file for ready plot making, I know to use
csv module while I find it's not good enough) .

The second one is, is there a search function in the our mailing list
archive http://mail.python.org/pipermail/python-list/. ?

Best,

Chao

-- 
***
Chao YUE
Laboratoire des Sciences du Climat et de l'Environnement (LSCE-IPSL)
UMR 1572 CEA-CNRS-UVSQ
Batiment 712 - Pe 119
91191 GIF Sur YVETTE Cedex
Tel: (33) 01 69 08 77 30
Portable Phone (Mobil phone) : (33) 07 60 54  23 71

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


Re: where to find shared python script?

2011-05-17 Thread Tim Golden

On 17/05/2011 13:53, Yue Chao wrote:

I am new to python and thank you for your help!
the first question is, is there any resource online where we can find
shared python script (like reading a csv file for ready plot making, I
know to use csv module while I find it's not good enough) .


I don't know if that specific example is there, but the ActiveState
Python Cookbook is usually a good resource:

  http://code.activestate.com/recipes/langs/python/



The second one is, is there a search function in the our mailing list
archive http://mail.python.org/pipermail/python-list/. ?



http://www.google.com/search?q=site%3Amail.python.org+csv%20module&safe=active

There's also the corresponding Google Group:

  http://groups.google.com/group/comp.lang.python/topics?lnk

and MarkMail:

  http://python.markmail.org/

and GMane:

  http://news.gmane.org/gmane.comp.python.general

and quite a few others which republish the list as Web pages

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


Re: Convert AWK regex to Python

2011-05-17 Thread AlienBaby
On May 17, 11:07 am, J  wrote:
> Hello,
>
> I have managed to get my script finished in the end by taking bits from 
> everyone who answered.  Thank you so much.  the finished query string looks 
> like this (still not the best but it gets the job done.  Once I learn to code 
> more with Python I will probably go back to it and re-write it):-
>
> # Log file to work on
> filetoread = open("/tmp/pdu.log", "r")
> # Perform filtering in the log file
> text = filetoread.read()
> text = text.replace(" text = text.replace(".", " ")
> text = text.replace(r"(", " ")
> filetoread.close()
> # File to write output to
> filetowrite = file("/tmp/pdu_filtered.log", "w")
> # Write new log file
> filetowrite.write(text)
> filetowrite.close()
> # Read new log and get required fields from it
> filtered_log =  open("/tmp/pdu_filtered.log", "r")
> filtered_line = filtered_log.readlines()
> for line in filtered_line:
>         field = line.split(" ")
>         field5 = field[5].rsplit("_", 1)
>         print field5[0], field[14], field[22]
> print "Done"

You can also process the lines and write them out to the new logfile
as you read them in first time around, rather than: read them in,
process them, write them out, read them in, process them, write them
out;

log_file=open("old_log_file","r")
output_file=open("new_log_file","w")
for line in log_file:
 line=line.replace("http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-17 Thread D'Arcy J.M. Cain
On Tue, 17 May 2011 16:39:48 +1000
Chris Angelico  wrote:
> You have a point there. Although I can't guarantee that all my code is
> particularly *good*, certainly not what I'd want to hold up for a
> novice to learn from - partly because it dates back anywhere up to two
> decades, and partly because quite a few of the things I was working
> with are completely undocumented!

Sounds like a perfect reason to open source it.  If what you say is
true it could benefit you more than others, at least at the beginning.
Remember, open source is a two way street.

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


Re: Convert AWK regex to Python

2011-05-17 Thread harrismh777

J wrote:

Hello,


Hello, J,

   This is totally off-topic, but I was wondering why you are posting 
with double messages (triple) all over the place?


   Your reply-to is set to [email protected], and you 
cc to [email protected]...  and you're stuff is showing up in 
newsgroup comp.lang.python...


... did you know that all you need to do is use the newsgroup (use a 
client like sea monkey, or other... ) and your posts will show up in 
googlegroups, and will also be archived forever authomatically?


   Your messages are duplicating which is not only annoying on the 
surface, but also breaks the threads apart in a news client. What should 
appear (and does in googlegroups) as a single thread appears as many 
threads in the mail client; partly because of the RE: in the subject, 
and partly because of the reduplication.


   Just a heads up


kind regards,
m harris
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 vs Python 2.7 dilemma

2011-05-17 Thread Jorge Romero
I would recommend you going on the Python 2.x path.

Python 2.x is far from being deprecated. According to Wesley Chun (active
member of Python community and author of Core Python Programming) on a
Google I/O talk, everybody will be using Python 3 by 2018, so there's still
plenty of time. Besides, you can start with Python 2.7, which still is 2.x
but introduces 3.x features, and in some benchmarks seems to be more
efficient than latest 3.x.

3.x is said to be backwards incompatible, but that incompatibility is not
something that would bring you a limitation on porting your code later.

So, for the sake of web frameworks and runtime infrastructures, I'd stick to
2.x.

This is my IMHO, I'm sure you can get a more accurate answer from someone in
this list more experienced in the matter ;)

Have a good one.

On Tue, May 17, 2011 at 12:48 AM, Navkirat Singh wrote:

> Hi Guys,
>
> I have been trying to fight this issue for sometime now. I know that a
> large part of the python 3rd party software base has not been ported to
> python 3 yet. I am trying to build a web-based enterprise solution for my
> client. Most of reputed frameworks like Django and Turbo gears are yet in
> the 2.x stage. I know that these frameworks are extremely good. But I wanted
> to build my base with python 3 as that is what is going to prevail in the
> future.
>
> I have built my own little architecture using python3. Here is what I have
> accomplished till now:
>
> a) A multiprocessing webserver built directly using low level sockets for
> maximum control, conforming to RFC 2616 (not completely right now).
> b) A HTTP message parser  for parsing HTTP/1.1 requests and generating
> response messages
> c) A session control base using python multiprocessing dictionary manager
> d) A partially build MVC model, without a templating engine at the moment.
> I am planning to put Jinja 3 there.
>
> I have spent months of free time doing this. I have learnt a lot, but well
> I am not sure if the path I am on is the right one.
>
> My question to everyone is whether I should go ahead with this approach, or
> should I just use 2.x technology? I am not sure if I will be able to port
> all the code to python3 later.
>
> I will really appreciate any input.
>
> Thanks and regards,
> Navkirat
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


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


Newbie: Python 3.2, search for module dBase + Excel

2011-05-17 Thread Andreas Mosmann

Hi,

I am new to python and so I decided to use python 3.2
But, if I found out correctly, the are no working modules concerning 
Excel and dBase for this python version.
Did I only misunderstand anything or is this right? I tried to download 
and use pydbf and pyexcelerator but both gave me an syntax error inside 
the modules and I somewhere read, that both modules only exist for 
version 2.X


Is there a way for me to use them anyway or do I have to change to any 
2.X- Version? If last, which should I install?


Thanks in advance
Andreas

remark: My task is to compare 2 directories incl. subdirs containing 
dBase- Files and find out differencers in FileNames and FileStructures.
Up t now I devided it into 3 lists: OnlyInDir1, OnlyInDir2 and 
InBothDirs. Next step is to put it into an Excel- File with 3 
worksheets. If this would be impossible, so I could save this in any 
other way. But I really need a module that handles dBase- files to 
compare Structures of files with equal names.


My Code up to now is something like
import os
dirV1 = "C:\Path1"
dirV2 = "C:\Path2"

anzL1=0
listV1 = []
for root, dirs, files in os.walk(dirV1):
for file in files:
myFile=os.path.join(root[len(dirV1):], file)
listV1.append(myFile)
anzL1=anzL1+1
print(anzL1)
anzL2=0
anzLG=0
listV2 = []
listGem = []
for root, dirs, files in os.walk(dirV2):
for file in files:
myFile=os.path.join(root[len(dirV2):], file)
try:
listV1.index(myFile)
listV1.remove(myFile)
listGem.append(myFile)
anzL1=anzL1-1
anzLG=anzLG+1
except ValueError:
listV2.append(myFile)
anzL2=anzL2+1


print(anzL1)
print(anzLG)
print(anzL2)



--
wenn email, dann AndreasMosmann  web  de
--
http://mail.python.org/mailman/listinfo/python-list


Re: Deleting a file?

2011-05-17 Thread garyr
Jerry,

There was an error during the install but only required a minor change to an
__init__.py file to correct.

Works great. Just what I was looking for. Many thanks!

Gary

"Jerry Hill"  wrote in message
news:[email protected]...
> On Mon, May 16, 2011 at 5:23 PM, garyr  wrote:
>> A file can be deleted by opening it with mode os.O_TEMPORARY and then
>> closing it. How can a file be moved to the Recycle Bin, a la Windows?
>
> I see a send2trash module (http://hg.hardcoded.net/send2trash and
> http://www.hardcoded.net/articles/send-files-to-trash-on-all-platforms.htm)
>
> The source code looks pretty straightforward, but I don't think
> there's anything in the standard library that does that.
>
> -- 
> Jerry




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


portable multiprocessing code

2011-05-17 Thread Eric Frederich
I have written some code using Python 2.7 but I'd like these scripts
to be able to run on Red Hat 5's 2.4.3 version of Python which doesn't
have multiprocessing.
I can try to import multiprocessing and set a flag as to whether it is
available.  Then I can create a Queue.Queue instead of a
multiprocessing.Queue for the arg_queue and result_queue.
Without actually trying this yet it seems like things would work okay
except for the Worker class.  It seems I can conditionally replace
multiprocessing.Queue with Queue.Queue, but is there anything to
replace multiprocessing.Process with?

Are there any best practices for doing something like this?
Below is a dumb example that just counts lines in files.
What would be the best way to make this runnable in older (2.4.3)
versions of Python?


#!/usr/bin/env python

import sys
import os
import multiprocessing
import Queue

fnames = sys.argv[1:]

def SimpleWorker(func):
class SimpleWorker_wrapped(multiprocessing.Process):
def __init__(self, arg_queue, result_queue):
super(SimpleWorker_wrapped, self).__init__()
self.arg_queue= arg_queue
self.result_queue = result_queue
def run(self):
while True:
try:
args = self.arg_queue.get_nowait()
except Queue.Empty:
break
self.result_queue.put(func(*args))
return SimpleWorker_wrapped

@SimpleWorker
def line_counter(fname):
lc = len(open(fname).read().splitlines())
return fname, lc

arg_queue = multiprocessing.Queue()
result_queue = multiprocessing.Queue()
for fname in fnames:
arg_queue.put((fname,))

for i in range(multiprocessing.cpu_count()):
w = line_counter(arg_queue, result_queue)
w.start()

results = {}
for fname in sorted(fnames):
while fname not in results:
n, i = result_queue.get()
results[n] = i
print "%-40s %d" % (fname, results[fname])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: portable multiprocessing code

2011-05-17 Thread Benjamin Kaplan
On Tue, May 17, 2011 at 8:14 AM, Eric Frederich
 wrote:
> I have written some code using Python 2.7 but I'd like these scripts
> to be able to run on Red Hat 5's 2.4.3 version of Python which doesn't
> have multiprocessing.
> I can try to import multiprocessing and set a flag as to whether it is
> available.  Then I can create a Queue.Queue instead of a
> multiprocessing.Queue for the arg_queue and result_queue.
> Without actually trying this yet it seems like things would work okay
> except for the Worker class.  It seems I can conditionally replace
> multiprocessing.Queue with Queue.Queue, but is there anything to
> replace multiprocessing.Process with?
>
> Are there any best practices for doing something like this?
> Below is a dumb example that just counts lines in files.
> What would be the best way to make this runnable in older (2.4.3)
> versions of Python?
>

http://pypi.python.org/pypi/multiprocessing

Also, you may be able to find the processing package (what
multiprocessing was called back when it was 3rd party) in your package
manager.
-- 
http://mail.python.org/mailman/listinfo/python-list


Faster Recursive Fibonacci Numbers

2011-05-17 Thread RJB
I noticed some discussion of recursion. the trick is to find a
formula where the arguments are divided, not decremented.
I've had a "divide-and-conquer" recursion for the Fibonacci numbers
for a couple of years in C++ but just for fun rewrote it
in Python.  It was easy.  Enjoy.  And tell me how I can improve it!

def fibo(n):
"""A Faster recursive Fibonaci function
Use a formula from Knuth Vol 1 page 80, section 1.2.8:
   If F[n] is the n'th Fibonaci number then
   F[n+m] = F[m]*F[n+1] + F[m-1]*F[n].
  First set m = n+1
   F[ 2*n+1 ] = F[n+1]**2 + F[n]*2.

  Then put m = n in Knuth's formula,
   F[ 2*n ] = F[n]*F[n+1] + F[n-1]* F[n],
   and replace F[n+1] by F[n]+F[n-1],
   F[ 2*n ] = F[n]*(F[n] + 2*F[n-1]).
"""
if n<=0:
return 0
elif n<=2:
return 1
elif n%2==0:
half=n//2
f1=fibo(half)
f2=fibo(half-1)
return f1*(f1+2*f2)
else:
nearhalf=(n-1)//2
f1=fibo(nearhalf+1)
f2=fibo(nearhalf)
return f1*f1 + f2*f2


RJB the Lurker
http://www.csci.csusb.edu/dick/cs320/lab/10.html


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


Re: Python 3 vs Python 2.7 dilemma

2011-05-17 Thread Eric Snow
On Mon, May 16, 2011 at 10:48 PM, Navkirat Singh wrote:

> Hi Guys,
>
> I have been trying to fight this issue for sometime now. I know that a
> large part of the python 3rd party software base has not been ported to
> python 3 yet. I am trying to build a web-based enterprise solution for my
> client. Most of reputed frameworks like Django and Turbo gears are yet in
> the 2.x stage. I know that these frameworks are extremely good. But I wanted
> to build my base with python 3 as that is what is going to prevail in the
> future.
>
> I have built my own little architecture using python3. Here is what I have
> accomplished till now:
>
> a) A multiprocessing webserver built directly using low level sockets for
> maximum control, conforming to RFC 2616 (not completely right now).
> b) A HTTP message parser  for parsing HTTP/1.1 requests and generating
> response messages
> c) A session control base using python multiprocessing dictionary manager
> d) A partially build MVC model, without a templating engine at the moment.
> I am planning to put Jinja 3 there.
>
> I have spent months of free time doing this. I have learnt a lot, but well
> I am not sure if the path I am on is the right one.
>
> My question to everyone is whether I should go ahead with this approach, or
> should I just use 2.x technology? I am not sure if I will be able to port
> all the code to python3 later.
>
> I will really appreciate any input.
>
> Thanks and regards,
> Navkirat
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
I would say go Python 3, unless you have a dependency that prevents it.
 There was a lot of talk at pycon this year about how the rate of Python 3
transition is drastically increasing.   Many of the large projects (as well
as pypy, ironpython, and jython) talked about their transition plans for
Python 3 in the next year or two.

The expectation is that this year will see a switch across many projects.
 It is a snowball effect, as more dependencies transition the remaining ones
have less reason to stay on Python 2.  The anticipation was to see everyone
on Python 3 by 5 years after its release.  It was released  just over 2.5
years ago.

Here are some references that you might find helpful:

http://wiki.python.org/moin/Python2orPython3
http://py3ksupport.appspot.com/
http://dev.pocoo.org/~gbrandl/py3pkgs.png

Cheers,

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


Re: pyjamas 0.8alpha1 release

2011-05-17 Thread lkcl
On May 4, 7:37 pm, Terry Reedy  wrote:
> On 5/4/2011 10:06 AM, Luke Kenneth Casson Leighton wrote:
>
> > after a long delay thepyjamasproject -http://pyjs.org- has begun the
> > 0.8 series of releases, beginning with alpha1:
>
> >https://sourceforge.net/projects/pyjamas/files/pyjamas/0.8/
>
> >pyjamasis a suite of projects, including a python-to-javascript
> > compiler
>
> As you well know, there is no such thing as 'python' when it comes to
> compiling actual code. So please specify both in announcements here and
> on the project homepagehttp://sourceforge.net/projects/pyjamas/
> which versions are supported. I do not really want to have to download
> and experiment to determine whether to bother downloading.
>
> If you do not yet support 3.x, I request and recommend that you do so,

 with the situation as it is, there is not a snowball in hell's chance
that's going to happen.

 allow me to explain.

 the python translator in pyjamas is heavily dependent on the
"compiler" module (which is written in c) and is in turn, as you are
no doubt aware, specifically dependent on the grammar file.  the
python translator for pyjamas 0.3 was 1,200 lines of code.  thanks to
some brilliant and dedicated work by kees bos, over something like a 6
month virtually full-time period, it's now somewhere around 5,000
lines of heavily-dense code in which very specific javascript
optimisations have been encoded.

 then, on top of that, it is necessary to implement the data types
that are supported in python 3.x, along with several built-ins
(exceptions etc.).  the basic implementation - pyjslib.py - is 6,700
lines of python code with in-built hand-optimised javascript, and it
would be necessary to reimplement / re-work... and then support...
that reimplementation.

 then, on top of that, there are a number of python-based
reimplementations of various python modules, such as md5.py, re.py,
string.py and so on, each of which would have to be double-checked for
compatibility with their python 3.x counterparts.  do they exist, have
they been rewritten, modified etc.`

 then, on top of that, it is necessary to run the pyjamas UI code,
which is some 15,000 lines of code, along with the other libraries
such as GChart, through lib2to3, and then to double-check them.

 then, on top of that, it is necessary to run the examples - of which
there are 70 - again through lib2to3.  i've just done a "wc" on the
examples source code: it comes to a whopping total of 60,000 lines of
code.

 so you have to do all this work, and really it's impossible to begin
realistically checking that it works until you get to the LibTest
example (which is the main test suite, comprising some 3,000 or so
regression tests), and once you've done all that work you now need a
userbase and also some maintainers.

 and, when it comes to doing a release, you need to test all 70
examples in a matrix of 14 browsers plus 4 desktop runtime engines,
and the browsers you need to recompile three times - with -O
(optimised), --strict (python-compliant) and there's one more, i
forget its name, it's designed to minimise the amount of javascript
generated.

 to support 3.x therefore requires a complete and utter rewrite, and
then a hell of a lot of work on top of that.  it's basically
supporting a totally separate language, and so is basically a
completely new project.  i know you mean well, but... you've
drastically underestimated quite how much effort has gone into the
pyjamas project - just look at the ohloh statistics for goodness sake!
it's listed as having had 31 man-years gone into it! 
http://www.ohloh.net/p/pyjamas

 so if you can find the money to get people paid to create a python
3.x to javascript compiler, which will require approximately twelve to
fifteen man-months of full-time dedicated programming effort, please
do speak up!

 otherwise please - really: just saying "give me support for python
3.x or else" is ... honestly - it's a free software project, _not_ a
paid-up corporate google/nokia/ibm/redhat/etc. funded project: you
know the score, and you know the drill.

 now.

 leaving _that_ aside, there happens to be absolutely no really good
compelling reason to support python 3.x in the first place.  "python 3
is the future of python" gimme a break!! [so why is archlinux the only
linux distribution that's converted over to run everything off of
python 3.x?]

 the thing is: there aren't really any major dependencies to "get in
the way" in pyjs.  as in: it's entirely self-sufficient [it has to
be].  even the installation has its own sandbox system.  the only
dependency *is* python 2.N, and when daniel kluev completes his
GSoC2011 project, that'll be a "bootstrap" into javascript, including
the translator itself being compiled into javascript, and then not
even python 2.N will be a dependency!

 the bottom line is this: somewhere in the next 8 to 10 years, python
2.N will be deprecated in all but the most die-hard places.  at *that*
time, it will have been worthwhile 

Re: FW: help please

2011-05-17 Thread Littlefield, Tyler
Not to be pedantic or anything, and I may not be able to help 
regardless, but it looks like your space key is fixed, and I don't 
really care to pick through and try to play hangman with your message.

On 5/17/2011 3:43 AM, hamed azarkeshb wrote:



From: [email protected]
To: [email protected]
Subject: help please
Date: Tue, 17 May 2011 13:20:22 +0430

hi dear
inwant to useautomation with catiaby python,but i dont know,h*ow do we 
can creat catsafearrayvariant in python?*

please help me.i need urhelp by one example.
thank u forany thing



--

Take care,
Ty
my website:
http://tds-solutions.net
my blog:
http://tds-solutions.net/blog
skype: st8amnd127
“Programmers are in a race with the Universe to create bigger and better 
idiot-proof programs, while the Universe is trying to create bigger and better
idiots.  So far the Universe is winning.”
“If Java had true garbage collection, most programs would delete themselves 
upon execution.”

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


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 9:50 AM, RJB  wrote:
> I noticed some discussion of recursion. the trick is to find a
> formula where the arguments are divided, not decremented.
> I've had a "divide-and-conquer" recursion for the Fibonacci numbers
> for a couple of years in C++ but just for fun rewrote it
> in Python.  It was easy.  Enjoy.  And tell me how I can improve it!
>
> def fibo(n):
>        """A Faster recursive Fibonaci function
> Use a formula from Knuth Vol 1 page 80, section 1.2.8:
>           If F[n] is the n'th Fibonaci number then
>                   F[n+m] = F[m]*F[n+1] + F[m-1]*F[n].
>  First set m = n+1
>   F[ 2*n+1 ] = F[n+1]**2 + F[n]*2.
>
>  Then put m = n in Knuth's formula,
>           F[ 2*n ] = F[n]*F[n+1] + F[n-1]* F[n],
>   and replace F[n+1] by F[n]+F[n-1],
>           F[ 2*n ] = F[n]*(F[n] + 2*F[n-1]).
> """
>        if n<=0:
>                return 0
>        elif n<=2:
>                return 1
>        elif n%2==0:
>                half=n//2
>                f1=fibo(half)
>                f2=fibo(half-1)
>                return f1*(f1+2*f2)
>        else:
>                nearhalf=(n-1)//2
>                f1=fibo(nearhalf+1)
>                f2=fibo(nearhalf)
>                return f1*f1 + f2*f2

Thanks for posting!  Actually, it looks like this is the same O(n)
algorithm that rusi posted.  There was also a O(log n) algorithm
discussed that is based on vector math.  You might want to take a
look.

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


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread rusi
On May 17, 8:50 pm, RJB  wrote:
> I noticed some discussion of recursion. the trick is to find a
> formula where the arguments are divided, not decremented.
> I've had a "divide-and-conquer" recursion for the Fibonacci numbers
> for a couple of years in C++ but just for fun rewrote it
> in Python.  It was easy.  Enjoy.  And tell me how I can improve it!
>
> def fibo(n):
>         """A Faster recursive Fibonaci function
> Use a formula from Knuth Vol 1 page 80, section 1.2.8:
>            If F[n] is the n'th Fibonaci number then
>                    F[n+m] = F[m]*F[n+1] + F[m-1]*F[n].
>   First set m = n+1
>    F[ 2*n+1 ] = F[n+1]**2 + F[n]*2.
>
>   Then put m = n in Knuth's formula,
>            F[ 2*n ] = F[n]*F[n+1] + F[n-1]* F[n],
>    and replace F[n+1] by F[n]+F[n-1],
>            F[ 2*n ] = F[n]*(F[n] + 2*F[n-1]).
> """
>         if n<=0:
>                 return 0
>         elif n<=2:
>                 return 1
>         elif n%2==0:
>                 half=n//2
>                 f1=fibo(half)
>                 f2=fibo(half-1)
>                 return f1*(f1+2*f2)
>         else:
>                 nearhalf=(n-1)//2
>                 f1=fibo(nearhalf+1)
>                 f2=fibo(nearhalf)
>                 return f1*f1 + f2*f2
>
> RJB the Lurkerhttp://www.csci.csusb.edu/dick/cs320/lab/10.html

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


Re: Python enabled gdb on Windows and relocation

2011-05-17 Thread Ruben Van Boxem
2011/5/15 Ruben Van Boxem :
> 2011/5/15 Ruben Van Boxem :
>> 2011/5/15 Ruben Van Boxem :
>>> 2011/5/14 Doug Evans :
 On Sat, May 14, 2011 at 2:09 AM, Ruben Van Boxem
  wrote:
> 2011/5/14 Doug Evans :
>> On Thu, May 12, 2011 at 9:19 AM, Ruben Van Boxem
>>  wrote:
>>> (now in plain-text as required by gdb mailing list)
>>>
>>> Hi,
>>>
>>> I am currently trying to integrate Python support into my toolchain
>>> build (including GDB of course). It is a sysrooted
>>> binutils+GCC+GDB+mingw-w64 toolchain.
>>>
>>> I currently have the basic setup working: I can link gdb with my
>>> manually generated import lib to the python dll from the official
>>> Windows install. If there is anything I am missing or a very easy
>>> solution to the problems decsribed below, please just say so. I am
>>> only suggesting what I would like to happen.
>>>
>>> Now on to the problems I'd like to discuss:
>>>
>>> 1. gdb.exe won't start without me having set PYTHONPATH manually.
>>
>> In a properly configured/built gdb on linux this isn't necessary, even
>> if python is installed in some random place.
>> I'm not sure about windows though.
>> Did you specify --with-python when you configured gdb, and if so did
>> you specify a value?
>> e.g., --with-python=SOME_VALUE
>
> I was cross-compiling a mingw toolchain+gdb from Linux, so I used
> --with-python without a value (because gdb configure tries to find the
> Python executabe), and I added -I"/path/to/python/includes" to CFLAGS
> and -L"/path/to/pythondll/importlib" to LDFLAGS, which built as it
> should. This is hacky though, and gdb configure should provide
> --with-python-libs and --with-python-include to make it more
> streamlined with any other build prerequisite (like
> gmp/mpfr/mpc/cloog/ppl in GCC for example).

 Ah.
 Cross-compiling gdb with python is in need of improvement.
 Alas python hasn't been designed with cross-compilation in mind (e.g.
 build on linux, run on windows).
 AIUI, the way to get the parameters required for compiling with
 libpython is to get them from python's "distutils": kinda hard to do
 in a cross-compile.  Done correctly there's no need to run python.

 I haven't done anything more to support python in gdb's configure.ac
 because it's not clear to me what the right thing to do is: distutils
 provides more than just --libs and --includes (btw, we don't use
 --libs though, we use --ldflags which includes all of: the directory
 in which to find libpython, the -l for libpython, and the -l's for all
 the other libraries python needs). [Which isn't to say that someone
 else isn't free to tackle this.]

 In the meantime, what I've been doing is a hack: write a script that
 responds to:
 --includes
 --ldflags
 --exec-prefix
 and pass that as --with-python.

 E.g.
 bash$ cat $HOME/my-python-for-config
 #! /bin/sh

 if [ $# -ne 2 ]
 then
        echo "Bad # args.  Blech!" >&2
        exit 1
 fi

 # The first argument is the path to python-config.py, ignore it.

 case "$2" in
 --includes) echo "-I/usr/include/python2.6 -I/usr/include/python2.6" ;;
 --ldflags) echo "-L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm
 -lpython2.6" ;;
 --exec-prefix) echo "/usr" ;;
 *) echo "Bad arg $2.  Blech!" >&2 ; exit 1 ;;
 esac

 exit 0
 bash$ ./configure --with-python=$HOME/my-python-for-config [...]
 [...]


 Note that --exec-prefix is the runtime location of python.
 GCC uses this to tell libpython where to find its support files.
 [grep for Py_SetProgramName in gdb/python/python.c]
>>>
>>> OK, I tried your script in a couple of variations. It gets rid of the
>>> traceback I had before, but still doesn't help the PYTHONPATH problem.
>>> My directory structure is as follows (this is not in root, "/" is just
>>> my main build directory, there are several levels below it):
>>>
>>> /gdb <-- gdb build dir
>>> /gdb/gdb <-- where the python configuration is done
>>> /python <-- temporary install dir for python files for build,
>>> extracted from the official Windows installer, also location of
>>> libpython2.7.a import library
>>> /python/include/python27 <-- python headers, found by gdb in both cases
>>> /mingw64 <-- toolchain sysroot prefix
>>> /mingw64/bin <-- install location of gdb and python27.dll
>>> /mingw64/lib/python27 <-- install location of all python scripts
>>>
>>> First variant:
>>> --includes) echo "-I../../python/include" ;;
>>> --ldflags) echo "-L../../python -lpython2.7" ;;
>>> --exec-prefix) echo "../../mingw64/lib/python27" ;;
>>>
>>> Here exec-prefix would be the relative path from where "configure"
>>> does its magic to the final location of the scripts on the build
>>> system.
>>>
>>> Second variant:
>

Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread rusi
On May 17, 8:50 pm, RJB  wrote:
> I noticed some discussion of recursion. the trick is to find a
> formula where the arguments are divided, not decremented.
> I've had a "divide-and-conquer" recursion for the Fibonacci numbers
> for a couple of years in C++ but just for fun rewrote it
> in Python.  It was easy.  Enjoy.  And tell me how I can improve it!
>
> def fibo(n):
>         """A Faster recursive Fibonaci function
> Use a formula from Knuth Vol 1 page 80, section 1.2.8:
>            If F[n] is the n'th Fibonaci number then
>                    F[n+m] = F[m]*F[n+1] + F[m-1]*F[n].
>   First set m = n+1
>    F[ 2*n+1 ] = F[n+1]**2 + F[n]*2.
>
>   Then put m = n in Knuth's formula,
>            F[ 2*n ] = F[n]*F[n+1] + F[n-1]* F[n],
>    and replace F[n+1] by F[n]+F[n-1],
>            F[ 2*n ] = F[n]*(F[n] + 2*F[n-1]).
> """
>         if n<=0:
>                 return 0
>         elif n<=2:
>                 return 1
>         elif n%2==0:
>                 half=n//2
>                 f1=fibo(half)
>                 f2=fibo(half-1)
>                 return f1*(f1+2*f2)
>         else:
>                 nearhalf=(n-1)//2
>                 f1=fibo(nearhalf+1)
>                 f2=fibo(nearhalf)
>                 return f1*f1 + f2*f2
>
> RJB the Lurkerhttp://www.csci.csusb.edu/dick/cs320/lab/10.html

-
Its an interesting problem and you are 75% there.
You see the halving gives you logarithmic behavior and the double
calls give exponential behavior.

So how to get rid of double calls?  Its quite simple: Just define your
function in terms of return pairs of adjacent pairs ie (fib(n), fib(n
+1)) for some n rather then a single number fib(n)

Here's a straightforward linear function:

def fp(n):  #fibpair
if n==1:
return (1,1)
else:
a,b = fp(n-1)
return (b, a+b)

def fib(n):
a,b = fp(n)
return a

---
Now use this (pairing) idea with your (halving) identities and you
should get a logarithmic algo.

[If you cant do it ask again but yes its fun to work out so do
try :-) ]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ann] pyjamas 0.8alpha1 release

2011-05-17 Thread harrismh777

Terry Reedy wrote:

Like it or not, Python 3 is the future of Python. It is the Python that
many Python newcomers learn first, and perhaps ever will.


Yes, no doubt, and I'm genuine about that...

... but there is something else to consider, as I'm sure you are aware. 
At some point Python is going to have to standardize in order to 
survive. And by survive I'm not talking about the Python 'community,' as 
much as I'm talking about the acceptance and wide-spread use of Python 
by people who just want to get work done and solve problems.


If there is another major jump like  2.x --> 3.x  in the future, Python 
will die. I hope you guys are aware of this. The user base might accept 
this thing once, but they're not going do it again...


Like it or not, Python 2.x has millions of lines of code running out 
there, and they're not going to get morphed into 3.x coding. So, 2x is 
going to be around for many years to come.


On the other hand, I'm teaching 3x, coding 3x, and porting to 3x... and 
also encouraging others to do the same... but there is a limit to that 
also. My system has 2.4, 2.5, 2.6, 2.7 and 3.2...   and that's the 
trouble with an interpreter. Different versions of the source code (.py 
files) require a matching 'interpreter,' where-as in other languages a 
new compiler version does not require recompiling source, but if source 
is recompiled everything still works... not so in Python. The fact that 
Python is free to morph gleely from PEP to PEP without responsibility or 
accountability with the user base is what may kill Python, unless the 
Python community gets a grip on this concept.



kind regards,
m harris

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


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread geremy condra
On Tue, May 17, 2011 at 9:36 AM, rusi  wrote:
> On May 17, 8:50 pm, RJB  wrote:
>> I noticed some discussion of recursion. the trick is to find a
>> formula where the arguments are divided, not decremented.
>> I've had a "divide-and-conquer" recursion for the Fibonacci numbers
>> for a couple of years in C++ but just for fun rewrote it
>> in Python.  It was easy.  Enjoy.  And tell me how I can improve it!
>>
>> def fibo(n):
>>         """A Faster recursive Fibonaci function
>> Use a formula from Knuth Vol 1 page 80, section 1.2.8:
>>            If F[n] is the n'th Fibonaci number then
>>                    F[n+m] = F[m]*F[n+1] + F[m-1]*F[n].
>>   First set m = n+1
>>    F[ 2*n+1 ] = F[n+1]**2 + F[n]*2.
>>
>>   Then put m = n in Knuth's formula,
>>            F[ 2*n ] = F[n]*F[n+1] + F[n-1]* F[n],
>>    and replace F[n+1] by F[n]+F[n-1],
>>            F[ 2*n ] = F[n]*(F[n] + 2*F[n-1]).
>> """
>>         if n<=0:
>>                 return 0
>>         elif n<=2:
>>                 return 1
>>         elif n%2==0:
>>                 half=n//2
>>                 f1=fibo(half)
>>                 f2=fibo(half-1)
>>                 return f1*(f1+2*f2)
>>         else:
>>                 nearhalf=(n-1)//2
>>                 f1=fibo(nearhalf+1)
>>                 f2=fibo(nearhalf)
>>                 return f1*f1 + f2*f2
>>
>> RJB the Lurkerhttp://www.csci.csusb.edu/dick/cs320/lab/10.html
>
> -
> Its an interesting problem and you are 75% there.
> You see the halving gives you logarithmic behavior and the double
> calls give exponential behavior.
>
> So how to get rid of double calls?  Its quite simple: Just define your
> function in terms of return pairs of adjacent pairs ie (fib(n), fib(n
> +1)) for some n rather then a single number fib(n)
>
> Here's a straightforward linear function:
>
> def fp(n):  #fibpair
>    if n==1:
>        return (1,1)
>    else:
>        a,b = fp(n-1)
>        return (b, a+b)
>
> def fib(n):
>    a,b = fp(n)
>    return a
>
> ---
> Now use this (pairing) idea with your (halving) identities and you
> should get a logarithmic algo.
>
> [If you cant do it ask again but yes its fun to work out so do
> try :-) ]
> --
> http://mail.python.org/mailman/listinfo/python-list
>

or O(1):

φ = (1 + sqrt(5)) / 2
def fib(n):
numerator = (φ**n) - (1 - φ)**n
denominator = sqrt(5)
return round(numerator/denominator)

Testing indicates that it's faster somewhere around 7 or so.

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


in search of graceful co-routines

2011-05-17 Thread Chris Withers

Hi All,

I'm looking for a graceful pattern for the situation where I have a 
provider of a sequence, the consumer of a sequence and code to moderate 
the two, and where I'd like to consumer to be able to signal to the 
provider that it hasn't succeeded in processing one element in the queue.


So, I'd want the controlling code to look a lot like:

for item in provider:
  try:
consumer.handleItem(self)
  except:
 provider.failed(item)

Now, since the sequence is long, and comes from a file, I wanted the 
provider to be an iterator, so it occurred to me I could try and use the 
new 2-way generator communication to solve the "communicate back with 
the provider", with something like:


for item in provider:
  try:
consumer.handleItem(self)
  except:
 provider.send('fail')
  else:
 provider.send('succeed')

..but of course, this won't work, as 'send' causes the provider 
iteration to continue and then returns a value itself. That feels weird 
and wrong to me, but I guess my use case might not be what was intended 
for the send method.


Anyway, I wonder how other people would write this?
(I'm particularly interested in a sane way to use the two way 
communication that PEP 342 introduced)


cheers,

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


groupby - summing multiple columns in a list of lists

2011-05-17 Thread Jackson
I'm currently using a function pasted in below. This allows me to sum
a column (index) in a list of lists.

So if mylist = [[1, 2, 3], [1, 3, 4], [2, 3, 4], [2, 4, 5]]
group_results(mylist,[0],1)

Returns:
[(1, 5), (2, 7)]

What I would like to do is allow a tuple/list of index values, rather
than a single index value to be summed up, so you could say
group_results(mylist,[0],[1,2]) would return [(1, 5,7), (2, 7,9)] but
I'm struggling to do so, any thoughts? Cheers

from itertools import groupby as gb
from operator import itemgetter as ig

def group_results(table,keys,value):
res = []
nkey = ig(*keys)
value = ig(value)
for k, group in gb(sorted(table,key=ig(*keys)),nkey):
res.append((k,sum(value(row) for row in group)))
return res
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread Jussi Piitulainen
geremy condra writes:

> or O(1):
> 
> φ = (1 + sqrt(5)) / 2
> def fib(n):
> numerator = (φ**n) - (1 - φ)**n
> denominator = sqrt(5)
> return round(numerator/denominator)
> 
> Testing indicates that it's faster somewhere around 7 or so.

And increasingly inaccurate from 71 on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: in search of graceful co-routines

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 11:04 AM, Chris Withers  wrote:
> Now, since the sequence is long, and comes from a file, I wanted the
> provider to be an iterator, so it occurred to me I could try and use the new
> 2-way generator communication to solve the "communicate back with the
> provider", with something like:
>
> for item in provider:
>  try:
>    consumer.handleItem(self)
>  except:
>     provider.send('fail')
>  else:
>     provider.send('succeed')
>
> ..but of course, this won't work, as 'send' causes the provider iteration to
> continue and then returns a value itself. That feels weird and wrong to me,
> but I guess my use case might not be what was intended for the send method.
>
> Anyway, I wonder how other people would write this?
> (I'm particularly interested in a sane way to use the two way communication
> that PEP 342 introduced)

You can use send the way you're wanting to.  It will look something like this:

def provider():
  result = None
  while True:
if result is None:
  if has_more_items():
next_item = get_next_item()
  else:
break
elif result == 'fail':
  process_fail()
  next_item = None
elif result == 'succeed':
  process_succeed()
  next_item = None
else:
  raise ValueError('unknown result %s' % result)
result = (yield next_item)

Whenever you call provider().next() or provider().send(None), you
simply get the next item.  If you call provider().send('succeed') or
provider().send('fail'), then the corresponding code is run and the
yielded value is None, without consuming anything from the sequence.

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


Re: in search of graceful co-routines

2011-05-17 Thread Carl Banks
On Tuesday, May 17, 2011 10:04:25 AM UTC-7, Chris Withers wrote:
> Now, since the sequence is long, and comes from a file, I wanted the 
> provider to be an iterator, so it occurred to me I could try and use the 
> new 2-way generator communication to solve the "communicate back with 
> the provider", with something like:
> 
> for item in provider:
>try:
>  consumer.handleItem(self)
>except:
>   provider.send('fail')
>else:
>   provider.send('succeed')
> 
> ..but of course, this won't work, as 'send' causes the provider 
> iteration to continue and then returns a value itself. That feels weird 
> and wrong to me, but I guess my use case might not be what was intended 
> for the send method.

You just have to call send() in a loop yourself.  Note that you should usually 
catch StopIteration whenever calling send() or next() by hand.  Untested:

result = None
while True:
try:
item = provider.send(result)
except StopIteration:
break
try:
consumer.handleItem(item)
except:
result = 'failure'
else:
result = 'success'


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


if statement on lenght of a list

2011-05-17 Thread Joe Leonardo
Hey all,

Totally baffled by this...maybe I need a nap. Writing a small function to 
reject input that is not a list of 19 fields.

def breakLine(value):
if value.__class__() != [] and value.__len__() != 19:
print 'You must pass a list that contains 19 fields.'
else:
print 'YAY!'

If I pass:
breakLine([])

I get:
YAY!

I expect:
You must pass a list that contains 19 fields.

If I print len(value) I get: 0

What is going on here?

Thanks!




[cid:[email protected]]

Joe Leonardo | Business Intelligence Analyst | 
DataLogix
303.327.1730 d | 415.812.5244 c | 
[email protected]

Better Marketing through Data(tm)


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


best way to extract sentence from txt file

2011-05-17 Thread Robert Pazur
Hi all,
my question is maybe quite simple:
What is the best (and shortest) way to extract sentence from .txt file?
Thanks in advance,
Robert Pazur
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: groupby - summing multiple columns in a list of lists

2011-05-17 Thread Peter Otten
Jackson wrote:

> I'm currently using a function pasted in below. This allows me to sum
> a column (index) in a list of lists.
> 
> So if mylist = [[1, 2, 3], [1, 3, 4], [2, 3, 4], [2, 4, 5]]
> group_results(mylist,[0],1)
> 
> Returns:
> [(1, 5), (2, 7)]
> 
> What I would like to do is allow a tuple/list of index values, rather
> than a single index value to be summed up, so you could say
> group_results(mylist,[0],[1,2]) would return [(1, 5,7), (2, 7,9)] but
> I'm struggling to do so, any thoughts? Cheers
> 
> from itertools import groupby as gb
> from operator import itemgetter as ig
> 
> def group_results(table,keys,value):
> res = []
> nkey = ig(*keys)
> value = ig(value)
> for k, group in gb(sorted(table,key=ig(*keys)),nkey):
> res.append((k,sum(value(row) for row in group)))
> return res

You could write a version of sum() that can cope with tuples:

from itertools import groupby, imap

def itemgetter(keys, rowtype=tuple):
def getitem(value):
return rowtype(value[key] for key in keys)
return getitem

def sum_all(rows):
rows = iter(rows)
sigma = next(rows)
rowtype = type(sigma)
sigma = list(sigma)
for row in rows:
for i, x in enumerate(row):
sigma[i] += x
return rowtype(sigma)

def group_results(table, key, value):
get_key = itemgetter(key)
get_value = itemgetter(value)
table = sorted(table, key=get_key)
for keyvalue, group in groupby(table, get_key):
yield keyvalue + sum_all(imap(get_value, group))

but I'd probably use a dict-based approach:

def group_results(table, key, value):
get_key = itemgetter(key)
get_value = itemgetter(value)
grouped = {}
for row in table:
key = get_key(row)
value = get_value(row)
if key in grouped:
grouped[key] = tuple(a + b for a, b in zip(grouped[key], value))
else:
grouped[key] = value
return [k + v for k, v in sorted(grouped.iteritems())]

if __name__ == "__main__":
items = [(1, 2, 3), (1, 3, 4), (2, 3, 4), (2, 4, 5)]
print list(group_results(items, [0], [1, 2]))

Note that the function built with my version of itemgetter() will always 
return a tuple.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cPickle -> invalid signature

2011-05-17 Thread Neal Becker
Gabriel Genellina wrote:

> En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 
> escribió:
> 
>> What does it mean when cPickle.load says:
>> RuntimeError: invalid signature
>>
>> Is binary format not portable?
> 
> Are you sure that's the actual error message?
> I cannot find such message anywhere in the sources.
> The pickle format is quite portable, even cross-version. As a generic
> answer, make sure you open the file in binary mode, both when writing and
> reading.
> 

Yes, that's the message.

Part of what is pickled is a numpy array.  I am writing on a 32-bit linux 
system 
and reading on a 64-bit system.  Reading on the 64-bit system is no problem.

Maybe the message comes from numpy's unpickling?

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


Re: if statement on lenght of a list

2011-05-17 Thread Jerry Hill
On Tue, May 17, 2011 at 2:02 PM, Joe Leonardo wrote:

> Hey all,
>
>
>
> Totally baffled by this…maybe I need a nap. Writing a small function to
> reject input that is not a list of 19 fields.
>
>
>
> def breakLine(value):
>
> if value.__class__() != [] and value.__len__() != 19:
>
>
This should use an "or" test, not "and".  And is probably better written as:
if not isinstance(value, list) or len(value) != 19:

That would allow for subclasses of list, assuming that would be okay.

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


Re: if statement on lenght of a list

2011-05-17 Thread Chris Rebert
On Tue, May 17, 2011 at 11:02 AM, Joe Leonardo
 wrote:
>
> Hey all,
>
> Totally baffled by this…maybe I need a nap. Writing a small function to 
> reject input that is not a list of 19 fields.
>
> def breakLine(value):
>     if value.__class__() != [] and value.__len__() != 19:
>     print 'You must pass a list that contains 19 fields.'
>     else:
>     print 'YAY!'
>
> If I pass:
> breakLine([])
>
> I get:
> YAY!
>
> I expect:
> You must pass a list that contains 19 fields.

Your test should use `or` as opposed to `and`. Since you're indeed
passing in a list, the first part of your condition is False; since
you used `and`, this makes the entire condition False. Therefore, the
else clause ("YAY!") gets executed.

Also, your test is written quite strangely. One would more normally
and straightforwardly write it as:
if not isinstance(value, list) or len(value) != 19:

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


Re: if statement on lenght of a list

2011-05-17 Thread MRAB

On 17/05/2011 19:02, Joe Leonardo wrote:

Hey all,

Totally baffled by this…maybe I need a nap. Writing a small function to
reject input that is not a list of 19 fields.

def breakLine(value):
if value.__class__() != [] and value.__len__() != 19:
print 'You must pass a list that contains 19 fields.'
else:
print 'YAY!'

If I pass:

breakLine([])

I get:

YAY!

I expect:

You must pass a list that contains 19 fields.

If I print len(value) I get: 0

What is going on here?


If value is [], then value.__class__() is [], so value.__class__() !=
[] is False.

What you meant was:

if value.__class__() != [] or value.__len__() != 19:
print 'You must pass a list that contains 19 fields.'
else:
print 'YAY!'

although the Pythonic way to write it would be:

if not isinstance(value, list) or len(value) != 19:
print 'You must pass a list that contains 19 fields.'
else:
print 'YAY!'

or, even better:

if isinstance(value, list) and len(value) == 19:
print 'YAY!'
else:
print 'You must pass a list that contains 19 fields.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: if statement on lenght of a list

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 12:02 PM, Joe Leonardo
wrote:

> Hey all,
>
>
>
> Totally baffled by this…maybe I need a nap. Writing a small function to
> reject input that is not a list of 19 fields.
>
>
>
> def breakLine(value):
>
> if value.__class__() != [] and value.__len__() != 19:
>
> print 'You must pass a list that contains 19 fields.'
>
> else:
>
> print 'YAY!'
>
>
>
> If I pass:
>
> breakLine([])
>
>
>
> I get:
>
> YAY!
>
>
>
> I expect:
>
> You must pass a list that contains 19 fields.
>
>
>
> If I print len(value) I get: 0
>
>
>
> What is going on here?
>
>
Evaluating the conditions, the first line reduces to "if False and True"
which further reduces to "if False".  You probably meant to write "or"
instead of "and".

A few other comments:

"value.__len__()" is better written as "len(value)".

"value.__class__() != []" would be better written as "type(value) is list".

Better yet would be to not worry so much about the particular type of
sequence passed in by the caller.  To allow any sequence you could just do
this:

def break_line(value):
  if len(value) != 19:
raise ValueError('value must contain 19 items')

If value is not a sequence, then it will just raise a TypeError, which is
typically what you would want in that situation anyway.  Or if value
absolutely must be a list due to the way your function works, you can do
this:

def break_line(value):
  value = list(value)
  if len(value) != 19:
raise ValueError('value must contain 19 items')

Again that will just raise a TypeError if the value can't be converted to a
list.  One of the niceties about this version is that value can be any
iterable, not just a sequence.

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


Python 3.x and bytes

2011-05-17 Thread Ethan Furman

In Python 3 one can say

--> huh = bytes(5)

Since the bytes type is actually a list of integers, I would have 
expected this to have huh being a bytestring with one element -- the 
integer 5.  Actually, what you get is:


--> huh
b'\x00\x00\x00\x00\x00'

or five null bytes.  Note that this is an immutable type, so you cannot 
go in later and say


--> huh[3] = 9
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'bytes' object does not support item assignment


So, out of curiosity, does anyone actually use this, um, feature?

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


[RELEASED] Python 3.2.1 rc 1

2011-05-17 Thread Georg Brandl
On behalf of the Python development team, I am pleased to announce the
first release candidate of Python 3.2.1.

Python 3.2.1 will the first bugfix release for Python 3.2, fixing over 120
bugs and regressions in Python 3.2.

For an extensive list of changes and features in the 3.2 line, see

http://docs.python.org/3.2/whatsnew/3.2.html

To download Python 3.2.1 visit:

http://www.python.org/download/releases/3.2.1/

This is a testing release: Please consider trying Python 3.2.1 with your code
and reporting any bugs you may notice to:

http://bugs.python.org/


Enjoy!

-- 
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.2's contributors)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to extract sentence from txt file

2011-05-17 Thread Michiel Overtoom

On May 17, 2011, at 20:22, Robert Pazur wrote:

> my question is maybe quite simple:
> What is the best (and shortest) way to extract sentence from .txt file?

Well, open("filename.txt").readlines() gives you a list of all the lines in a 
txt file, which might not be sentences, depending on the text file is 
structured.  If you really want to interpret the text file as a collection of 
sentences, some parsing might be involved. What is a sentence? A sequence of 
words ending with a dot? With a question mark? How do quotes play a role in 
this?

Did you have a specific sentence (or line) in thought? The first line? The last 
line? A random line somewhere in between?

Until then we have to guess, and my E.S.P. is notoriously bad.

Greetings,

-- 
"Learn to value yourself, which means: fight for your happiness."  - Ayn Rand   
   

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


Re: if statement on lenght of a list

2011-05-17 Thread Ethan Furman

Joe Leonardo wrote:


Totally baffled by this…maybe I need a nap. Writing a small function to 
reject input that is not a list of 19 fields.


def breakLine(value):
if value.__class__() != [] and value.__len__() != 19:
print 'You must pass a list that contains 19 fields.'
else:
print 'YAY!'

If I pass:

breakLine([])

I get:

YAY!


Change your 'and' to an 'or'.

Also, change your 'value.__len__()' to 'len(value)'.

Finally, if you absolutely don't want any iterable that might work (such 
as a tuple), change 'value.__class__() != []' to either 'type(value) != 
list' or, if subclasses are okay (and they probably should be) 'not 
isinstance(value, list)'.


Incorporating these suggestions looks like this:

def breakLine(value):
if not isinstance(value, list) or len(value) != 19:
print 'You must pass a list that contains 19 fields.'
else:
print 'YAY!'


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


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread geremy condra
On Tue, May 17, 2011 at 10:19 AM, Jussi Piitulainen
 wrote:
> geremy condra writes:
>
>> or O(1):
>>
>> φ = (1 + sqrt(5)) / 2
>> def fib(n):
>>     numerator = (φ**n) - (1 - φ)**n
>>     denominator = sqrt(5)
>>     return round(numerator/denominator)
>>
>> Testing indicates that it's faster somewhere around 7 or so.
>
> And increasingly inaccurate from 71 on.

Yup. That's floating point for you. For larger values you could just
add a linear search at the bottom using the 5f**2 +/- 4 rule, which
would still be quite fast out to about 10 times that. The decimal
module gets you a tiny bit further, and after that it's time to just
use Dijkstra's, like rusi suggested. In any event, I still think this
formulation is the most fun ;).

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


Re: best way to extract sentence from txt file

2011-05-17 Thread Miki Tebeka
http://nltk.googlecode.com/svn/trunk/doc/api/nltk.tokenize-module.html ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 12:47 PM, Ethan Furman  wrote:
> In Python 3 one can say
>
> --> huh = bytes(5)
>
> Since the bytes type is actually a list of integers, I would have expected
> this to have huh being a bytestring with one element -- the integer 5.
>  Actually, what you get is:
>
> --> huh
> b'\x00\x00\x00\x00\x00'
>
> or five null bytes.  Note that this is an immutable type, so you cannot go
> in later and say
>
> --> huh[3] = 9
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: 'bytes' object does not support item assignment
>
>
> So, out of curiosity, does anyone actually use this, um, feature?

I suppose it's for interoperability with the mutable bytearray type,
which takes the same parameters in the constructor.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Felipe Bastos Nunes
They accept .replace(b"00", b"12") for example. Documentation about
it.

2011/5/17 Ethan Furman 

> In Python 3 one can say
>
> --> huh = bytes(5)
>
> Since the bytes type is actually a list of integers, I would have expected
> this to have huh being a bytestring with one element -- the integer 5.
>  Actually, what you get is:
>
> --> huh
> b'\x00\x00\x00\x00\x00'
>
> or five null bytes.  Note that this is an immutable type, so you cannot go
> in later and say
>
> --> huh[3] = 9
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: 'bytes' object does not support item assignment
>
>
> So, out of curiosity, does anyone actually use this, um, feature?
>
> ~Ethan~
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Felipe Bastos Nunes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 1:20 PM, Ian Kelly  wrote:
> I suppose it's for interoperability with the mutable bytearray type,
> which takes the same parameters in the constructor.

http://www.python.org/dev/peps/pep-3137/#constructors
-- 
http://mail.python.org/mailman/listinfo/python-list


Cartoonify Myself

2011-05-17 Thread Chris M. Bartos

Hi,

Is there a Python module that can "cartoonify" a picture of myself? 
There's got to be an algorithm out there somewhere, right? If there is a 
way to cartoon a single picture, could you cartoonify a video, too?


Thanks for your help.


Chris

--
Christopher M. Bartos
[email protected]
330-324-0018

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


Re: problem with GKT module?

2011-05-17 Thread Alister Ware
On Mon, 16 May 2011 14:56:38 -0500, harrismh777 wrote:

> alister ware wrote:
>>  def callback(self,widget,data=None):
>>  print widget  #gives reference to radio 
button ok print
>>  widget.name #widget name on windoze, None on 
linux
> 
> Well, you're obviously using Python 2.x ...
> 
> ... have you tried this in Python 3.x ?
> 
> 
> Neither here nor there...  you need to know who/what is generating
> 'widget'.  Is widget buried in gtk where you can't see how it works, or
> is widget a Python class (or wrapper) where you can see what its doing?
> 
> The fact that widget.name returns None on the linux platform tells me
> that widget is a Python class (or wrapper) ... so you probably have a
> widget.py file somewhere... or some other module that widget is a class
> definition in... who knows... (at this point).
> 
> It seems to me that the 'builder' is behaving differently on the two
> platforms (rather than Python is behaving differently on the two
> platforms).
> 
> What happens if you change the data=None pair?
> 
> What happens if you omit data=None pair?
> 
> Do you see this difference with *all* widgets, or just radio buttons?
> 
> 
> 
> kind regards,
> m harris

It seems it was introduced in pygtk 2.1.7 as a side effect of correcting 
something to do with widget id's and the fact that widget names do not 
have to be unique (although glade insists that they are).

looks like i have to modify my code & use gtk.buildable.get_name(widget) 
instead, not really a big change but may break someone else's code 



-- 
If you're not careful, you're going to catch something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread MRAB

On 17/05/2011 19:47, Ethan Furman wrote:

In Python 3 one can say

--> huh = bytes(5)

Since the bytes type is actually a list of integers, I would have
expected this to have huh being a bytestring with one element -- the
integer 5. Actually, what you get is:

--> huh
b'\x00\x00\x00\x00\x00'

or five null bytes. Note that this is an immutable type, so you cannot
go in later and say

--> huh[3] = 9
Traceback (most recent call last):
File "", line 1, in 
TypeError: 'bytes' object does not support item assignment


So, out of curiosity, does anyone actually use this, um, feature?


I suppose it follows the example of 'list' and 'tuple' in accepting an
iterable.

Producing a bytestring of zero bytes might have its uses, but because
Python lets me do coding at a high level (lists, dicts, etc), I've
never used that feature.

BTW, help(bytes) doesn't seem to mention it!
--
http://mail.python.org/mailman/listinfo/python-list


Re: FW: help please

2011-05-17 Thread Albert Hopkins
On Tue, 2011-05-17 at 10:18 -0600, Littlefield, Tyler wrote:
> Not to be pedantic or anything, and I may not be able to help 
> regardless, but it looks like your space key is fixed, and I don't 
> really care to pick through and try to play hangman with your message.

I actually, at first glance, thought it was spam, ignored it, and was
wondering why people were replying to it :|

-a


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


Re: Python 3.x and bytes

2011-05-17 Thread Corey Richardson
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 05/17/2011 02:47 PM, Ethan Furman wrote:
> In Python 3 one can say
> 
> --> huh = bytes(5)
> 
> Since the bytes type is actually a list of integers, I would have 
> expected this to have huh being a bytestring with one element -- the 
> integer 5.  Actually, what you get is:
> 
> --> huh
> b'\x00\x00\x00\x00\x00'
> 
> or five null bytes.  Note that this is an immutable type, so you cannot 
> go in later and say

For the bytes to actually be a 'list of integers', you need to pass it
an iterable, ex:
>>> bytes([5, 6, 1, 3])
b'\x05\x06\x01\x03'

- From help(bytes):
 |  bytes(iterable_of_ints) -> bytes
 |  bytes(string, encoding[, errors]) -> bytes
 |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
 |  bytes(memory_view) -> bytes

Looks like you're using the fourth when you want the first, possibly?

- -- 
Corey Richardson
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.17 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJN0tF1AAoJEAFAbo/KNFvp41AH/1l2zR6XVOJ0xM7s2P+PDYZX
OAhmi19hFEP0zQoWiW3TiMEVPlaqgtipPCp1t+jTeNNN3F+H4NG2DHJJZ3dPDr2J
CpABQKyS4MJQTUxhCIlXqAaA2I1pejzAv6fwsF66/zPFmyaTAJLDP+3WMQvCUUoZ
5A3qHgHNp6vBHXd13RNdQStLeprfQptA+z6XdiJPos348ecRj/u9id7v28dwxxsm
d9WA6oYwJ+Y/NcG2OP0Flyp3Zc3hymVsv5vhmhG2+EiIrxMn95k8ImsKLEhvUW3a
72CxlE6EaOMD4MuWyeGMS33c0vHwtAvEIE7M56R2FAl8EsUFwP2swaij0tEiemg=
=8MRV
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ipython prompt does not appear in windows

2011-05-17 Thread Dan Stromberg
Try running ipython in a cmd.exe.  If that works, it almost certainly means
that the I/O is going directly to video RAM instead of through a disciplined
API.

On Tue, May 17, 2011 at 12:00 AM, rusi  wrote:

> If I use ipython under emacs on linux it works (at least basic REPL)
> ie I can type an expression and I get a result followed by a prompt
>
> On windows ipython works at the shell.
> Plain python works in emacs as well.
>
> But inside emacs I dont see a prompt in ipython although I see it in
> python.
> I have to type an expression and then the prompt appears.
>
> Any clues?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Ethan Furman

Felipe Bastos Nunes wrote:

2011/5/17 Ethan Furman wrote:


In Python 3 one can say

--> huh = bytes(5)

Since the bytes type is actually a list of integers, I would have
expected this to have huh being a bytestring with one element -- the
integer 5.  Actually, what you get is:

--> huh
b'\x00\x00\x00\x00\x00'

or five null bytes.  Note that this is an immutable type, so you
cannot go in later and say

--> huh[3] = 9
Traceback (most recent call last):
 File "", line 1, in 
TypeError: 'bytes' object does not support item assignment


So, out of curiosity, does anyone actually use this, um, feature?

>

They accept .replace(b"00", b"12") for example.


So they do.  Although that particular example doesn't work since b'0' is 
the integer 48...


--> huh.replace(b'00',b'12')
b'\x00\x00\x00\x00\x00'


The big question, though, is would you do it this way:

some_var = bytes(23).replace(b'\x00', b'a')

or this way?

some_var = bytes(b'a' * 23)

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


Re: portable multiprocessing code

2011-05-17 Thread Michael Kent
You could also install Python 2.7 on that RedHat machine.  It can be done 
without interfering with the 2.5 that RedHat depends on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Felipe Bastos Nunes
This piece of code works fine for me:

> >>> somevar = bytes()
> >>> somevar
> ''
> >>> somevar.replace(b'', b'10')
> '10'
> >>> somevar
> ''
> >>> somevar = somevar.replace(b'', b'10')
> >>> somevar
> '10'
> >>> somevar2 = bytes(b'10'*2)
> >>> somevar2
> '1010'
> >>> somevar2 = somevar2.replace(b'01', b'57'*3)
> >>> somevar2
> '15757570'
>
> They're unmutable, but replace deals with it.
2011/5/17 Ethan Furman 

> Felipe Bastos Nunes wrote:
>
>  2011/5/17 Ethan Furman wrote:
>>
>>>
>>> In Python 3 one can say
>>>
>>> --> huh = bytes(5)
>>>
>>> Since the bytes type is actually a list of integers, I would have
>>>expected this to have huh being a bytestring with one element -- the
>>> integer 5.  Actually, what you get is:
>>>
>>> --> huh
>>> b'\x00\x00\x00\x00\x00'
>>>
>>> or five null bytes.  Note that this is an immutable type, so you
>>> cannot go in later and say
>>>
>>> --> huh[3] = 9
>>> Traceback (most recent call last):
>>>  File "", line 1, in 
>>> TypeError: 'bytes' object does not support item assignment
>>>
>>>
>>> So, out of curiosity, does anyone actually use this, um, feature?
>>>
>> >
>
>> They accept .replace(b"00", b"12") for example.
>>
>
> So they do.  Although that particular example doesn't work since b'0' is
> the integer 48...
>
> --> huh.replace(b'00',b'12')
>
> b'\x00\x00\x00\x00\x00'
>
>
> The big question, though, is would you do it this way:
>
> some_var = bytes(23).replace(b'\x00', b'a')
>
> or this way?
>
> some_var = bytes(b'a' * 23)
>
> ~Ethan~
>



-- 
Felipe Bastos Nunes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cartoonify Myself

2011-05-17 Thread andy baxter

On 17/05/11 20:26, Chris M. Bartos wrote:

Hi,

Is there a Python module that can "cartoonify" a picture of myself? 
There's got to be an algorithm out there somewhere, right? If there is 
a way to cartoon a single picture, could you cartoonify a video, too?


Thanks for your help.


Chris



You could have a look at the python automation module for the gimp (a 
free software image editor). See e.g.:


http://starryalley.homelinux.net/blog/index.php?/archives/1248-Star-Trail-Automation-script-using-python-gimp.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand html.parser.HTMLParser

2011-05-17 Thread Karim

On 05/17/2011 03:05 AM, Andrew Berg wrote:

On 2011.05.16 02:26 AM, Karim wrote:

Use regular expression for bad HTLM or beautifulSoup (google it), below
a exemple to extract all html links:

linksList = re.findall('.*?',htmlSource)
for link in linksList:
  print link

I was afraid I might have to use regexes (mostly because I could never
understand them).
Even the BeautifulSoup website itself admits it's awful with Python 3 -
only the admittedly broken 3.1.0 will work with Python 3 at all.
ElementTree doesn't seem to have been updated in a long time, so I'll
assume it won't work with Python 3.
lxml looks promising, but it doesn't say anywhere whether it'll work on
Python 3 or not, which is puzzling since the latest release was only a
couple months ago.

Actually, if I'm going to use regex, I might as well try to implement
Versions* in Python.

Thanks for the answers!

*http://en.totalcmd.pl/download/wfx/net/Versions (original, made for
Total Commander) and
https://addons.mozilla.org/en-US/firefox/addon/versions-wfx_versions/
(clone implemented as a Firefox add-on; it's so wonderful, I even wrote
the docs for it!)


Andrew,

I wrote a class with HMLTParser to get only one link for a given 
project, cf below:


  73 class ResultsLinkParser(HTMLParser.HTMLParser):
  74 """Class ResultsLinkParser inherits form HTMLParser to extract
  75 the original 'Submission date' of the a bug.
  76 This customized parser will deals with the 'View Defect' HTML
  77 page from Clear DDTS.
  78 """
  79 def __init__(self):
  80 HTMLParser.HTMLParser.__init__(self)
  81 self._link = None
  82
  83 def handle_starttag(self, tag, attrs):
  84 """Implement standard class HTMLParser customizing method."""
  85 if tag == 'frame':
  86 try:
  87 attributes = dict(attrs)
  88 if attributes['name'] == 'indexframe':
  89 self._link = attributes['src']
  90 except KeyError, e:
  91 print("""WARNING: Attribute '{keyname}' from frame tag
  92   in QueryResult page does not 
exist!""".format(keyname=e))

  93
  94 def link(self):
  95 """Return the html link of the query results page."""
  96 return self._link

You can use it and just modified it to get the latest just add some code 
(and change the tag 'name' of my example) to compare revision number 
with max and keep the max to compare it to the next value. I let you add 
this little code just create self._revision = None in the __init__(self) 
which hold the current max revision. After parser.feed() you can get the 
value by parser._revision or a public parser.revision() method to get 
the value.


Cheers
Karim


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


Re: Python enabled gdb on Windows and relocation

2011-05-17 Thread Doug Evans
On Sun, May 15, 2011 at 6:26 AM, Ruben Van Boxem
 wrote:
> Wow, I think I have a partial solution. Delving into the Python docs,
> for example here:
> http://docs.python.org/using/windows.html#finding-modules, you can see
> that PYTHONPATH is used first, then the Windows registry, then
> PYTHONHOME, then some default relative paths. I placed the python
> scripts all in the directory structure like so:
>
> /bin/gdb
> /bin/Lib/
> /bin/python27.dll
>
> This works, even without any manual PYTHONPATH intervention. Problem
> is though, that as soon as someone has a PYTHONPATH environment
> variable from a (incompatible) Python installation (think different
> bitness or version 3.x instead of 2.7.1), I cannot predict what will
> go wrong. This problem originates in Python's way of filling in the
> search path (sys.path). A true solution in the GDB case to prevent
> this collision of an incompatible PYTHONPATH would be that GDB sets an
> internal PYTHONPATH as directed by configure, uses that to load its
> Python internals, and allows the GDB child processes (apps being
> debugged) to use the environment PYTHONPATH. For now, I have a
> functional installation, but it will break as soon as someone installs
> Python on their system.

What if the user *wants* gdb's python to use $PYTHONPATH from his/her
environment?
To handle *this* case, *and* the case of an incompatible python
installation using $PYTHONPATH, there is the $GDB_PYTHONPATH proposal
(see earlier email for details).  It feels problematic to decide at
configure time whether there will or will not be an incompatible
python at runtime.

[I realize you have subsequent messages.
Just replying in sequence.]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Ethan Furman

Corey Richardson wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 05/17/2011 02:47 PM, Ethan Furman wrote:

In Python 3 one can say

--> huh = bytes(5)

Since the bytes type is actually a list of integers, I would have 
expected this to have huh being a bytestring with one element -- the 
integer 5.  Actually, what you get is:


--> huh
b'\x00\x00\x00\x00\x00'

or five null bytes.  Note that this is an immutable type, so you cannot 
go in later and say


For the bytes to actually be a 'list of integers', you need to pass it
an iterable, ex:

bytes([5, 6, 1, 3])

b'\x05\x06\x01\x03'


Not so.

--> huh = b'abcedfg'
--> huh[3]
101

It's a list of int's.


- From help(bytes):
 |  bytes(iterable_of_ints) -> bytes
 |  bytes(string, encoding[, errors]) -> bytes
 |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
 |  bytes(memory_view) -> bytes

Looks like you're using the fourth when you want the first, possibly?


Nope.  Apparently, it's not well documented.  If you check PEP 358 
you'll find it.


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


Re: Python 3.x and bytes

2011-05-17 Thread Felipe Bastos Nunes
Mine bytes constructor when useing Corey's advice give's me a string instead
of a b''...

2011/5/17 Corey Richardson 

> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On 05/17/2011 02:47 PM, Ethan Furman wrote:
> > In Python 3 one can say
> >
> > --> huh = bytes(5)
> >
> > Since the bytes type is actually a list of integers, I would have
> > expected this to have huh being a bytestring with one element -- the
> > integer 5.  Actually, what you get is:
> >
> > --> huh
> > b'\x00\x00\x00\x00\x00'
> >
> > or five null bytes.  Note that this is an immutable type, so you cannot
> > go in later and say
>
> For the bytes to actually be a 'list of integers', you need to pass it
> an iterable, ex:
> >>> bytes([5, 6, 1, 3])
> b'\x05\x06\x01\x03'
>
> - From help(bytes):
>  |  bytes(iterable_of_ints) -> bytes
>  |  bytes(string, encoding[, errors]) -> bytes
>  |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
>  |  bytes(memory_view) -> bytes
>
> Looks like you're using the fourth when you want the first, possibly?
>
> - --
> Corey Richardson
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2.0.17 (GNU/Linux)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
>
> iQEcBAEBAgAGBQJN0tF1AAoJEAFAbo/KNFvp41AH/1l2zR6XVOJ0xM7s2P+PDYZX
> OAhmi19hFEP0zQoWiW3TiMEVPlaqgtipPCp1t+jTeNNN3F+H4NG2DHJJZ3dPDr2J
> CpABQKyS4MJQTUxhCIlXqAaA2I1pejzAv6fwsF66/zPFmyaTAJLDP+3WMQvCUUoZ
> 5A3qHgHNp6vBHXd13RNdQStLeprfQptA+z6XdiJPos348ecRj/u9id7v28dwxxsm
> d9WA6oYwJ+Y/NcG2OP0Flyp3Zc3hymVsv5vhmhG2+EiIrxMn95k8ImsKLEhvUW3a
> 72CxlE6EaOMD4MuWyeGMS33c0vHwtAvEIE7M56R2FAl8EsUFwP2swaij0tEiemg=
> =8MRV
> -END PGP SIGNATURE-
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Felipe Bastos Nunes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 1:50 PM, Corey Richardson  wrote:
> - From help(bytes):
>  |  bytes(iterable_of_ints) -> bytes
>  |  bytes(string, encoding[, errors]) -> bytes
>  |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
>  |  bytes(memory_view) -> bytes
>
> Looks like you're using the fourth when you want the first, possibly?

Nope, he's using the fifth form, bytes(int), which is listed in the
PEP but not in the help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python enabled gdb on Windows and relocation

2011-05-17 Thread Doug Evans
On Sun, May 15, 2011 at 9:11 AM, Ruben Van Boxem
 wrote:
> I am sorry for the repeated messages that no one cares about, but I
> may have discovered GDB in its current form already allows what I
> want: I tried to figure out what exact paths the snake in gdb was
> using to search for its modules, and came up with this:
> (gdb) python import sys
> (gdb) python print sys.path
> ['m:\\development\\mingw64\\share\\gdb/python',
> 'M:\\Development\\mingw64\\bin\\python27.zip',
> 'M:\\Development\\mingw64\\bin\\DLLs',
> 'M:\\Development\\mingw64\\bin\\lib',
> 'M:\\Development\\mingw64\\bin\\lib\\plat-win',
> 'M:\\Development\\mingw64\\bin\\lib\\lib-tk',
> 'M:\\Development\\mingw64\\bin',
> 'M:\\Development\\mingw64\\bin\\lib\\site-packages']
>
> This means that every python command within gdb searches
> /share/gdb/python FIRST (even before an environment's
> PYTHONPATH), alleviating any concerns or problems I or anyone would
> have with another python installation, as this apparently built-in
> path comes up first. All I, or anyone interested in doing this kind of
> thing, have to do is copy all the python scripts from the Windows
> installation's Lib directory to the /share/gdb/python
> directory.
>
> I don't know where this path comes from, but it is quite handy, and
> makes this whole discussion  moot for Python people. Only "issue" that
> I'll have to work around is the --with-python-includes and
> --with-python-libs that are missing, using either manual
> CFLAGS/LDFLAGS or a variant of your script.

IMO *if* gdb wanted to support people adding files to *its*
/share/gdb directory, more thought is needed - e.g. maybe
document a "site" directory for such files.  Dunno.  IMO we certainly
don't want to formally allow folks to willy-nilly put anything there -
no guarantees a future release might add something that collides with
something the user put there.
If and until then, you're probably pretty safe if you put everything
in a subdirectory with a unique enough name, if you really wanted to
go this route.

Btw, there is the system.gdbinit file which sites *are* free to customize.

E.g., configure --with-system-gdbinit=/share/gdb/system.gdbinit.

You can put whatever you want in that file.
E.g., you could add a directory to python's sys.path.

[Technically speaking, the path /share/gdb/system.gdbinit
goes against what I just said, but IMO this name is safe.]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 2:20 PM, Ethan Furman  wrote:
> The big question, though, is would you do it this way:
>
> some_var = bytes(23).replace(b'\x00', b'a')
>
> or this way?
>
> some_var = bytes(b'a' * 23)

Actually, I would just do it this way:

some_var = b'a' * 23

That's already a bytes object.  Passing it into the constructor is redundant.
-- 
http://mail.python.org/mailman/listinfo/python-list


python logging

2011-05-17 Thread Fei
where is default logging file on Mac? I saw lots of app just import
logging, and begins to logging.info(...) etc.  I'm not sure where to
look at the logging configuration to figure out the log location.

I just get in touch of python about 1month ago, and I appreciate your
help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread Wolfram Hinderer
On 17 Mai, 20:56, geremy condra  wrote:
> On Tue, May 17, 2011 at 10:19 AM, Jussi Piitulainen
>
>  wrote:
> > geremy condra writes:
>
> >> or O(1):
>
> >> ö = (1 + sqrt(5)) / 2
> >> def fib(n):
> >>     numerator = (ö**n) - (1 - ö)**n
> >>     denominator = sqrt(5)
> >>     return round(numerator/denominator)
>
> >> Testing indicates that it's faster somewhere around 7 or so.
>
> > And increasingly inaccurate from 71 on.
>
> Yup. That's floating point for you. For larger values you could just
> add a linear search at the bottom using the 5f**2 +/- 4 rule, which
> would still be quite fast out to about 10 times that. The decimal
> module gets you a tiny bit further, and after that it's time to just
> use Dijkstra's, like rusi suggested. In any event, I still think this
> formulation is the most fun ;).

I think you can write it even more funny

def fib(n):
return round(((.5 + .5 * 5 ** .5) ** n -  (.5 - .5 * 5 ** .5) **
n) * 5 ** -.5)

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


Re: portable multiprocessing code

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 9:14 AM, Eric Frederich
 wrote:
> I have written some code using Python 2.7 but I'd like these scripts
> to be able to run on Red Hat 5's 2.4.3 version of Python which doesn't
> have multiprocessing.
> I can try to import multiprocessing and set a flag as to whether it is
> available.  Then I can create a Queue.Queue instead of a
> multiprocessing.Queue for the arg_queue and result_queue.
> Without actually trying this yet it seems like things would work okay
> except for the Worker class.  It seems I can conditionally replace
> multiprocessing.Queue with Queue.Queue, but is there anything to
> replace multiprocessing.Process with?

Yes, threading.Thread.

Pro: Since the multiprocessing module is designed to be a drop-in
replacement for the threading module, it should also be pretty
straight-forward to go in the reverse direction.

Con: You won't have true concurrency because of the GIL.

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


test_argparse.py FAILED (failures=6)

2011-05-17 Thread nirinA raseliarison


==
FAIL: test_failures_many_groups_listargs (__main__.TestFileTypeW)
--
Traceback (most recent call last):
  File "Lib/test/test_argparse.py", line 216, in wrapper
test_func(self)
  File "Lib/test/test_argparse.py", line 235, in test_failures
raises(ArgumentParserError, parser.parse_args, args)
AssertionError: ArgumentParserError not raised by parse_args

==
FAIL: test_failures_many_groups_sysargs (__main__.TestFileTypeW)
--
Traceback (most recent call last):
  File "Lib/test/test_argparse.py", line 216, in wrapper
test_func(self)
  File "Lib/test/test_argparse.py", line 235, in test_failures
raises(ArgumentParserError, parser.parse_args, args)
AssertionError: ArgumentParserError not raised by parse_args

==
FAIL: test_failures_no_groups_listargs (__main__.TestFileTypeW)
--
Traceback (most recent call last):
  File "Lib/test/test_argparse.py", line 216, in wrapper
test_func(self)
  File "Lib/test/test_argparse.py", line 235, in test_failures
raises(ArgumentParserError, parser.parse_args, args)
AssertionError: ArgumentParserError not raised by parse_args

==
FAIL: test_failures_no_groups_sysargs (__main__.TestFileTypeW)
--
Traceback (most recent call last):
  File "Lib/test/test_argparse.py", line 216, in wrapper
test_func(self)
  File "Lib/test/test_argparse.py", line 235, in test_failures
raises(ArgumentParserError, parser.parse_args, args)
AssertionError: ArgumentParserError not raised by parse_args

==
FAIL: test_failures_one_group_listargs (__main__.TestFileTypeW)
--
Traceback (most recent call last):
  File "Lib/test/test_argparse.py", line 216, in wrapper
test_func(self)
  File "Lib/test/test_argparse.py", line 235, in test_failures
raises(ArgumentParserError, parser.parse_args, args)
AssertionError: ArgumentParserError not raised by parse_args

==
FAIL: test_failures_one_group_sysargs (__main__.TestFileTypeW)
--
Traceback (most recent call last):
  File "Lib/test/test_argparse.py", line 216, in wrapper
test_func(self)
  File "Lib/test/test_argparse.py", line 235, in test_failures
raises(ArgumentParserError, parser.parse_args, args)
AssertionError: ArgumentParserError not raised by parse_args

--
Ran 1599 tests in 6.298s

FAILED (failures=6)

Traceback (most recent call last):
  File "Lib/test/test_argparse.py", line 4681, in 
test_main()
  File "Lib/test/test_argparse.py", line 4673, in test_main
support.run_unittest(__name__)
  File "/mnt/sda14/pack_build/Python-3.2.1rc1/Lib/test/support.py", line  
1184, in run_unittest

_run_suite(suite)
  File "/mnt/sda14/pack_build/Python-3.2.1rc1/Lib/test/support.py", line  
1167, in _run_suite

raise TestFailed(err)
test.support.TestFailed: multiple errors occurred


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


test_ftplib.py failed with segmentation fault,gcc4.6.0,glibc-2.13

2011-05-17 Thread nirinA raseliarison

hi all,

i can't get connected to bugs.python.org
so here my make test results.

make test aborted when running test_ftplib.

and running 

# ./python Lib/test/test_ftplib.py
Segmentation fault

with this kernel message:
[ 2166.927138] python[12142]: segfault at 1d81 ip 7f7e733a09c2 sp
7f7e701038a0 error 4 in libc-2.13.so[7f7e73328000+19b000]

however, i just tested using ftplib without tls and it worked fine.

below the error log


== CPython 3.2.1rc1 (default, May 17 2011, 22:01:34) [GCC 4.6.0]
==
Linux-2.6.38.wmodem-x86_64-Intel-R-_Pentium-R-_Dual__CPU__E2180__@_2.00GHz-with-slackware-12.2.0
little-endian
==   /mnt/sda14/pack_build/Python-3.2.1rc1/build/test_python_12247
Testing with flags: sys.flags(debug=0, division_warning=0, inspect=0,
interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0,
no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=0)



test_abort (__main__.TestFTPClass) ... ok
test_acct (__main__.TestFTPClass) ... ok
test_all_errors (__main__.TestFTPClass) ... ok
test_delete (__main__.TestFTPClass) ... ok
test_dir (__main__.TestFTPClass) ... ok
test_exceptions (__main__.TestFTPClass) ... ok
test_getwelcome (__main__.TestFTPClass) ... ok
test_login (__main__.TestFTPClass) ... ok
test_makepasv (__main__.TestFTPClass) ... ok
test_makeport (__main__.TestFTPClass) ... ok
test_mkd (__main__.TestFTPClass) ... ok
test_nlst (__main__.TestFTPClass) ... ok
test_parse257 (__main__.TestFTPClass) ... ok
test_pwd (__main__.TestFTPClass) ... ok
test_quit (__main__.TestFTPClass) ... ok
test_rename (__main__.TestFTPClass) ... ok
test_retrbinary (__main__.TestFTPClass) ... ok
test_retrbinary_rest (__main__.TestFTPClass) ... ok
test_retrlines (__main__.TestFTPClass) ... ok
test_rmd (__main__.TestFTPClass) ... ok
test_sanitize (__main__.TestFTPClass) ... ok
test_set_pasv (__main__.TestFTPClass) ... ok
test_size (__main__.TestFTPClass) ... ok
test_storbinary (__main__.TestFTPClass) ... ok
test_storbinary_rest (__main__.TestFTPClass) ... ok
test_storlines (__main__.TestFTPClass) ... ok
test_voidcmd (__main__.TestFTPClass) ... ok
test_with_statement (__main__.TestFTPClass) ... ok
testTimeoutConnect (__main__.TestTimeouts) ... ok
testTimeoutDefault (__main__.TestTimeouts) ... ok
testTimeoutDifferentOrder (__main__.TestTimeouts) ... ok
testTimeoutDirectAccess (__main__.TestTimeouts) ... ok
testTimeoutNone (__main__.TestTimeouts) ... ok
testTimeoutValue (__main__.TestTimeouts) ... ok
test_abort (__main__.TestTLS_FTPClassMixin) ...

*** glibc detected *** ./python: free(): invalid next size (normal):
0x7f38f0018cf0 ***
=== Backtrace: =
/lib64/libc.so.6(+0x78f85)[0x7f38fa1e7f85]
/lib64/libc.so.6(cfree+0x73)[0x7f38fa1ebd93]
/mnt/sda14/pack_build/Python-3.2.1rc1/build/lib.linux-x86_64-3.2/_ssl.cpython-32m.so(CRYPTO_free+0x3d)[0x7f38f940b3aa]
/mnt/sda14/pack_build/Python-3.2.1rc1/build/lib.linux-x86_64-3.2/_ssl.cpython-32m.so(+0x12f407)[0x7f38f9492407]
/mnt/sda14/pack_build/Python-3.2.1rc1/build/lib.linux-x86_64-3.2/_ssl.cpython-32m.so(RSA_private_decrypt+0x45)[0x7f38f9429979]
/mnt/sda14/pack_build/Python-3.2.1rc1/build/lib.linux-x86_64-3.2/_ssl.cpython-32m.so(ssl3_get_client_key_exchange+0x2a4)[0x7f38f93e7060]
/mnt/sda14/pack_build/Python-3.2.1rc1/build/lib.linux-x86_64-3.2/_ssl.cpython-32m.so(ssl3_accept+0xa0b)[0x7f38f93e40d2]
/mnt/sda14/pack_build/Python-3.2.1rc1/build/lib.linux-x86_64-3.2/_ssl.cpython-32m.so(SSL_do_handshake+0x98)[0x7f38f9400021]
/mnt/sda14/pack_build/Python-3.2.1rc1/build/lib.linux-x86_64-3.2/_ssl.cpython-32m.so(+0x77f69)[0x7f38f93daf69]
./python(PyEval_EvalFrameEx+0x709c)[0x45d4ec]
./python(PyEval_EvalCodeEx+0x696)[0x456186]
./python(PyEval_EvalFrameEx+0x6d83)[0x45d1d3]
./python(PyEval_EvalFrameEx+0x6e9e)[0x45d2ee]
./python(PyEval_EvalCodeEx+0x696)[0x456186]
./python(PyEval_EvalFrameEx+0x6d83)[0x45d1d3]
./python(PyEval_EvalFrameEx+0x6e9e)[0x45d2ee]
./python(PyEval_EvalCodeEx+0x696)[0x456186]
./python(PyEval_EvalFrameEx+0x6d83)[0x45d1d3]
./python(PyEval_EvalCodeEx+0x696)[0x456186]
./python(PyEval_EvalFrameEx+0x6d83)[0x45d1d3]
./python(PyEval_EvalFrameEx+0x6e9e)[0x45d2ee]
=== Memory map: 
0040-00586000 r-xp  08:0e 54225
/mnt/sda14/pack_build/Python-3.2.1rc1/python
00786000-007cf000 rw-p 00186000 08:0e 54225
/mnt/sda14/pack_build/Python-3.2.1rc1/python
007cf000-007ed000 rw-p  00:00 0
00b9c000-0111a000 rw-p  00:00 0
[heap]
7f38f000-7f38f0022000 rw-p  00:00 0
7f38f0022000-7f38f400 ---p  00:00 0
7f38f6537000-7f38f654c000 r-xp  08:0b 224
/usr/lib64/libgcc_s.so.1
7f38f654c000-7f38f674b000 ---p 00015000 08:0b 224
/usr/lib64/libgcc_s.so.1
7f38f674b000-7f38f674c000 rw-p 00014000 08:0b 224
/usr/lib64/libgcc_s.so.1
7f38f674c000-7f38f674d000 ---p  00:00 0
7f38f674d000-7f38f6f4d000 rw-p  00:00 0
7f38f6f4d000-7f38f6f64000 r-xp  08:0b 117661
/lib64/libresolv-2.13.so
7f38f6f64000-7f38f7164000 ---p 00017000 08:0b 117661

smtplib is broken when using TLS

2011-05-17 Thread nirinA raseliarison

i think this has the same origin as the ftplib test failure.

Python 3.2.1rc1 (default, May 17 2011, 22:01:34)
[GCC 4.6.0] on linux2
Type "copyright", "credits" or "license()" for more information.
 RESTART  





send: 'ehlo [127.0.0.1]\r\n'
reply: b'250-mx.google.com at your service, [41.188.13.184]\r\n'
reply: b'250-SIZE 35882577\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-STARTTLS\r\n'
reply: b'250 ENHANCEDSTATUSCODES\r\n'
reply: retcode (250); Msg: b'mx.google.com at your service,
[41.188.13.184]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES'
send: 'STARTTLS\r\n'
reply: b'220 2.0.0 Ready to start TLS\r\n'
reply: retcode (220); Msg: b'2.0.0 Ready to start TLS'
Traceback (most recent call last):
File "/root/template_mail_text.py", line 49, in 
  server.starttls()
File "/usr/local/lib/python3.2/smtplib.py", line 649, in starttls
  self.sock = ssl.wrap_socket(self.sock, keyfile, certfile)
File "/usr/local/lib/python3.2/ssl.py", line 509, in wrap_socket
  ciphers=ciphers)
File "/usr/local/lib/python3.2/ssl.py", line 266, in __init__
  raise x
File "/usr/local/lib/python3.2/ssl.py", line 262, in __init__
  self.do_handshake()
File "/usr/local/lib/python3.2/ssl.py", line 441, in do_handshake
  self._sslobj.do_handshake()
ssl.SSLError: [Errno 1] _ssl.c:392: error:140943FC:SSL
routines:SSL3_READ_BYTES:sslv3 alert bad record mac


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


Re: Python 3.x and bytes

2011-05-17 Thread Corey Richardson
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 05/17/2011 04:55 PM, Ethan Furman wrote:
> Apparently, it's not well documented.  If you check PEP 358 
> you'll find it.
> 
> ~Ethan~

Agreed, it looks like it should be mentioned in bytes.__doc__ about the
single-integer argument.

- -- 
Corey Richardson
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.17 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJN0ugoAAoJEAFAbo/KNFvphIsH/3LOzN8+D98D0+nm6m8sfCUC
f+KfgTLITAmecYOuOBym1snl6qj2JnZkGYRW6M2O5NV8arNJ1dHty3dPbwMeKdfH
67m2a0UgHcwqv5M5VGNQQYTQ03Mzqy+A84MMvBKWUQ0nxZRCkPMtdxm2T4/UEVLx
uelDPOdOWB1PDmc3sNUDPovXeOFlTKmcQ5yfolyrdLFU/KmbamgRSltpBFEbyInO
4KI3hoGka4PVaaBLf9QPjFC6tBu4QdQ4UTnWD3sy78LA3KPsa5MEpXFXctwJkJ+O
q2Y7SWOPJDz19V+MT87Aeu69YpzxWwkp4fBflNxYaQUoJqNlzIfRkavUzZ0zfMQ=
=E2qm
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Having a problem getting python working...

2011-05-17 Thread Ned Deily
In article <[email protected]>,
 Chris Paton  wrote:
> Not sure if this is the right place to put this (forgive me for my ignorance, 
> I'm looking everywhere!). I'm having a problem getting IDLE working. I'm 
> working off Mac OSX 10.6.7 with Python 3.2 installed and I installed 
> Activetcl 8.5.9 as recommended. IDLE is still crashing at random moments - 
> loading, saving, typing, compiling... I tried to do a simple 'hello world' 
> but it kept crashing. There's no official report; I just get the spinning 
> beach ball then have to force quit. I'm quite new to all of this so any help 
> would be extremely appreciated. Need to get into this ASAP as I need to do 
> some stuff for my thesis project! 

Sorry for the late response but if you can document how to reproduce the 
crashes or have a crash report that would be great.  But, first, are you 
sure you were using IDLE 3.2 and not the Apple-supplied IDLE 2.6 in OS X 
10.6?  The latter will definitely exhibit that behavior.  If you are 
installed Python 3.2 from one of the python.org installers, IDLE 3.2 
will be available in /Applications/Python 3.2/ or as 
/usr/local/bin/idle3.2.

-- 
 Ned Deily,
 [email protected]

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


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread geremy condra
On Tue, May 17, 2011 at 2:04 PM, Wolfram Hinderer
 wrote:
> On 17 Mai, 20:56, geremy condra  wrote:
>> On Tue, May 17, 2011 at 10:19 AM, Jussi Piitulainen
>>
>>  wrote:
>> > geremy condra writes:
>>
>> >> or O(1):
>>
>> >> ö = (1 + sqrt(5)) / 2
>> >> def fib(n):
>> >>     numerator = (ö**n) - (1 - ö)**n
>> >>     denominator = sqrt(5)
>> >>     return round(numerator/denominator)
>>
>> >> Testing indicates that it's faster somewhere around 7 or so.
>>
>> > And increasingly inaccurate from 71 on.
>>
>> Yup. That's floating point for you. For larger values you could just
>> add a linear search at the bottom using the 5f**2 +/- 4 rule, which
>> would still be quite fast out to about 10 times that. The decimal
>> module gets you a tiny bit further, and after that it's time to just
>> use Dijkstra's, like rusi suggested. In any event, I still think this
>> formulation is the most fun ;).
>
> I think you can write it even more funny
>
> def fib(n):
>    return round(((.5 + .5 * 5 ** .5) ** n -  (.5 - .5 * 5 ** .5) **
> n) * 5 ** -.5)
>
> ;-)

Ok, that's amusing. It does hide the interaction with the golden ratio
though, which is what I find so fascinating about the earlier one.

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


Re: python logging

2011-05-17 Thread Rafael Durán Castañeda

On 17/05/11 22:55, Fei wrote:

where is default logging file on Mac? I saw lots of app just import
logging, and begins to logging.info(...) etc.  I'm not sure where to
look at the logging configuration to figure out the log location.

I just get in touch of python about 1month ago, and I appreciate your
help.

Looking at python docs you will find:

http://docs.python.org/howto/logging.html#logging-basic-tutorial

First example explains what you are asking.

P.S.: Next time you may try to look for the info you need before asking
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.x and bytes

2011-05-17 Thread Ethan Furman

Ian Kelly wrote:

On Tue, May 17, 2011 at 2:20 PM, Ethan Furman  wrote:

The big question, though, is would you do it this way:

some_var = bytes(23).replace(b'\x00', b'a')

or this way?

some_var = bytes(b'a' * 23)


Actually, I would just do it this way:

some_var = b'a' * 23

That's already a bytes object.  Passing it into the constructor is redundant.


Heh, good point.

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


English Idiom in Unix: Directory Recursively

2011-05-17 Thread Xah Lee
might be of interest.

〈English Idiom in Unix: Directory Recursively〉
http://xahlee.org/comp/idiom_directory_recursively.html

--
English Idiom in Unix: Directory Recursively

Xah Lee, 2011-05-17

Today, let's discuss something in the category of lingustics.

You know how in unix tools, when you want to delete the whole
directory and all sub-directories and files in it, it's referred as
“recursive”?

For example, when you want to delete the whole dir in emacs, it
prompts this message: “Recursive delete of xx? (y or n) ”. (Note: to
be able to delete whole dir in emacs in dired, you'll first need to
turn it on. See: emacs dired tutorial.)

Here's another example. A quote from “rsync” man page:

 …
 This would recursively transfer all files from the directory …
 -r, --recursive recurse into directories
 This tells rsync to copy directories recursively.  See also --
dirs (-d).
 …

Here's a quote from “cp”'s man page:

 -R, -r, --recursive
  copy directories recursively

and lots of other tools has a “-r” option, and they all refer to it as
“recursive”.

Though, if you think about it, it's not exactly a correct description.
“Recursive”, or “recursion”, refers to a particular type of algorithm,
or a implementation using that algorithm. Obviously, to process all
directory's content does not necessarily mean it must be done by a
recursive algorithm. A iteration can do it as well and it's easy to
have the full behavior and properties in the result as a recursive
approach, such as specifying depth order, level to dive into, etc.
(because, dir is a tree, and recursive algorithm is useful for walking
the tree data structure but is not necessary, because a tree can be
laid out flat. Any path order taken by a recursive approach can be
done by just enumerating the nodes in sequence. In fact, iteration
approach can be faster and simpler in many aspects. (i wrote a article
about this some 10 years ago, see: Trees and Indexes.) Note: this
thought about tree and its nodes as a set of node addresses can be
applied to any tree data structure, such as lisp's nested syntax, XML.
See: Programing Language: Fundamental Problems of Lisp.)

If you look at Windows or Mac OS X world, i don't think they ever
refer to dealing with whole dir as “recursive” in user interface. For
example, in Windows Vista, while changing properties of a folder, it
has this message:

Apply changes to this folder only.
Apply changes to this folder, subfolders and files.

Note the second choice. In unix, it would say “Apply changes to this
folder recursively.”

So, the word “recursive” used in unixes may be technically incorrect,
but more so, it's just not the right phrase. Because, we want to
communicate whether the whole content of a directory are processed,
not about certain algorithm or how it is implemented. A simple “all
the dir's branches/contents” or similar would be more apt.

Recently i was chatting in Second Life with someone (Sleeves). She's
typing, while i'm on voice. In part of our conversation, i said “you
sounded fine”. Note that it's technically incorrect, because she's
typing, not on voice. So she didn't actually make any “sound”. But to
say “you typed fine”, or “you chatted fine”, won't get the message
across.

That's idiom. When you interpret a idiom logically, it doesn't make
much sense, but people understand the particular phrase better anyway.
I suspect the “directory recursively” is also a idiom. It seems so
natural and really gets the point across, without any ill effects.
Even if the implementation actually used a iteration, it doesn't seems
to matter.

So the interesting question is, why this idiom works? Or, how it
developed?

I think, among programers (which all unix users are in the 1970s),
every one knows the concept of recursion, and many unix tools on dir
probably are implemented with a recursive algorithm. When you say “…
recursively”, the point gets across, because we all understand it,
even when we are not actually talking about implementation. The phrase
“… directory recursively” is short and memorable, while “… directory
and all its contents” or “… directory and all its branches” or “…
directory and all its sub-directories and files” are wordy and
unwieldy.
✍

Idiocy Of Unix Copy Command
Emacs Lisp Suggestion: Function to Copy/Delete a Directory
Recursively
How to rsync, unison, wget, curl
Hunspell Tutorial
Mac OS X Resource Fork and Command Line Tips
ImageMagick Tutorial
Making System Calls in Perl and Python
Unix And Literary Correlation
The Unix Pestilence
To An Or Not To An
On “I” versus “i” (capitalization of first person pronoun)
On the Postposition of Conjunction in Penultimate Position of a
Sequence
What's Passive Voice? What's Aggressive Voice?
Why You Should Avoid The Jargon “Tail Recursion”
Why You should Not Use The Jargon Lisp1 and Lisp2
Jargons of Inf

Re: ipython prompt does not appear in windows

2011-05-17 Thread Ori L.
See here for a workaround: https://bugs.launchpad.net/ipython/+bug/290228

First result on Google for the query "ipython emacs windows", BTW.

On May 17, 3:00 am, rusi  wrote:
> If I use ipython under emacs on linux it works (at least basic REPL)
> ie I can type an expression and I get a result followed by a prompt
>
> On windows ipython works at the shell.
> Plain python works in emacs as well.
>
> But inside emacs I dont see a prompt in ipython although I see it in
> python.
> I have to type an expression and then the prompt appears.
>
> Any clues?

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


Re: python logging

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 2:55 PM, Fei  wrote:
> where is default logging file on Mac? I saw lots of app just import
> logging, and begins to logging.info(...) etc.  I'm not sure where to
> look at the logging configuration to figure out the log location.

There is no default log file.  You're seeing that because logging only
needs to be configured by the program once, not on a per-module basis.
 Thus most modules will just do import logging on the assumption that
the configuration has already been performed somewhere else.

If no logging configuration is done at all, then the logging
statements will have no effect.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-17 Thread Ian Kelly
On Tue, May 17, 2011 at 4:26 PM, Xah Lee  wrote:
> Though, if you think about it, it's not exactly a correct description.
> “Recursive”, or “recursion”, refers to a particular type of algorithm,
> or a implementation using that algorithm.

Only when used as programming jargon.  In mathematics, "recursive
function" does *not* mean "a function implemented using a recursive
algorithm".  It's just a formal definition of a specific class of
mathematical functions.

As it turns out, "recursive" also has a non-technical definition,
which again has nothing to do with algorithms except in the broadest
sense:

recursiveadj.
1. pertaining to or using a rule or procedure that can be applied repeatedly
(from dictionary.com)

This definition fits the Unix usage perfectly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to extract sentence from txt file

2011-05-17 Thread Chris Angelico
On Wed, May 18, 2011 at 4:40 AM, Michiel Overtoom  wrote:
> Until then we have to guess, and my E.S.P. is notoriously bad.

Roll d20 and add your ESP skill and your Wisdom modifier. The DC for
this test is 20 if you're familiar with D&D, or 25 if you are not.

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


Re: English Idiom in Unix: Directory Recursively

2011-05-17 Thread Chris Angelico
On Wed, May 18, 2011 at 8:26 AM, Xah Lee  wrote:
>      Apply changes to this folder only.
>        Apply changes to this folder, subfolders and files.
>
> Note the second choice. In unix, it would say “Apply changes to this
> folder recursively.”

I think this is more about the Windows and Mac philosophy to dumb
things down at the expense of verbosity, than about Unix jargon.
Archiving and compressing files using Phil Katz's PKZip utility uses
the -r option to include all subdirectories; it's documented as
"recurse subudirectories", which makes plenty of sense. (There's an
equivalent utility from Info-ZIP in a lot of Linux distros, and it has
the same option, listed as "recurse into directories".) Can you think
of any other single word that clearly describes the action of tracing
into all subdirectories? Even if it's not algorithmically accurate, it
carries the meaning. The "mind-space" requirement is quite compact;
you can ignore the "into subdirectories" part and just think "-r means
recurse", whereas the alternative is "-r means files in this directory
and all its subdirectories".

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


Re: FW: help please

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 16:48:29 -0300, Albert Hopkins
 escribió:

On Tue, 2011-05-17 at 10:18 -0600, Littlefield, Tyler wrote:



Not to be pedantic or anything, and I may not be able to help
regardless, but it looks like your space key is fixed, and I don't
really care to pick through and try to play hangman with your message.


I actually, at first glance, thought it was spam, ignored it, and was
wondering why people were replying to it :|


I can't remember exactly in which release 'perfect English skills' were
added to Python runtime requirements, could you please refresh my memory?

--
Gabriel Genellina

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


Re: cPickle -> invalid signature

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 15:26:53 -0300, Neal Becker 
escribió:


Gabriel Genellina wrote:


En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 
escribió:


What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic
answer, make sure you open the file in binary mode, both when writing  
and

reading.



Yes, that's the message.

Part of what is pickled is a numpy array.  I am writing on a 32-bit  
linux system
and reading on a 64-bit system.  Reading on the 64-bit system is no  
problem.


Maybe the message comes from numpy's unpickling?


Maybe, at least 'invalid signature' makes sense in Numpy. In that case, a
better place to ask would be a numpy specific list, see
http://www.scipy.org/Mailing_Lists


--
Gabriel Genellina

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


Re: FW: help please

2011-05-17 Thread Littlefield, Tyler

>I can't remember exactly in which release 'perfect English skills' were
>added to Python runtime requirements, could you please refresh my memory?
the one that requires people use the space key and check over their 
messages before they hit the enter key. Not so bad a request, I don't 
think. I am using a screen reader--it takes the text and puts it in 
speech. It uses the space as it's separation between words, as we all 
do, so wheniseetextlikethis it just jumbles it altogether. The point was 
to request that the OP try to formulate a good request, or get the space 
key fixed, both of which would've helped.

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


Ed hardy, (tshirt$13, swim strunk$25, jean$30, handbag$34, cap$13, sunglass$12, shoes$25), Nike shoes:$32, Handbag:$35, NFL:$20, jean:$30, air force one shoes, lv, gucci, D&G, bbc, coachUGG boot:$50

2011-05-17 Thread john kode
Get Nike Shoes at Super Cheap Prices
Discount Ed hardy tshirt  (www.dmuch.com)
Discount Ed hardy swimming suit (www.dmuch.com)
Discount Ed hardy jean  (www.dmuch.com)
Discount Ed hardy shoes  (www.dmuch.com)
Discount Ed hardy handbag  (www.dmuch.com)
Discount Ed hardy other porduct  (www.dmuch.com)
Discount Nike air jordans  (www.dmuch.com)
Discount Nike Air Max 90 Sneakers  (www.dmuch.com)
Discount Nike Air Max 91 Supplier  (www.dmuch.com)
Discount Nike Air Max 95 Shoes Supplier  (www.dmuch.com)
Discount Nike Air Max 97 Trainers  (www.dmuch.com)
Discount Nike Air Max 2003 Wholesale  (www.dmuch.com)
Discount Nike Air Max 2004 Shoes Wholesale
(www.dmuch.com)
Discount Nike Air Max 2005 Shop  (www.dmuch.com)
Discount Nike Air Max 2006 Shoes Shop  (www.dmuch.com)
Discount Nike Air Max 360 Catalogs  (www.dmuch.com)
Discount Nike Air Max Ltd Shoes Catalogs  (www.dmuch.com)
Discount Nike Air Max Tn Men's Shoes  (www.dmuch.com)
Discount Nike Air Max Tn 2 Women's Shoes  (www.dmuch.com)
Discount Nike Air Max Tn 3 Customize  (www.dmuch.com)
Discount Nike Air Max Tn 4 Shoes Customize
( www.dmuch.com)
Discount Nike Air Max Tn 6 Supply  (www.dmuch.com)
Discount Nike Shox NZ Shoes Supply  (www.dmuch.com)
Discount Nike Shox OZ Sale  (www.dmuch.com)
Discount Nike Shox TL Store  (www.dmuch.com)
Discount Nike Shox TL 2 Shoes Store (www.dmuch.com)
Discount Nike Shox TL 3 Distributor (www.dmuch.com)
Discount Nike Shox Bmw Shoes Distributor  (www.dmuch.com)
Discount Nike Shox Elite Shoes Manufacturer
(www.dmuch.com)
Discount Nike Shox Monster Manufacturer  (www.dmuch.com)
Discount Nike Shox R4 Running Shoes  (www.dmuch.com)
Discount Nike Shox R5 Mens Shoes  (www.dmuch.com)
Discount Nike Shox Ride Womens Shoes (www.dmuch.com)
Discount Nike Shox Rival Shoes Wholesaler  (www.dmuch.com)
Discount Nike Shox Energia Wholesaler  (www.dmuch.com)
Discount Nike Shox LV Sneaker  (www.dmuch.com)
Discount Nike Shox Turbo Suppliers  (www.dmuch.com)
Discount Nike Shox Classic Shoes Suppliers
(www.dmuch.com)
Discount Nike Shox Dendara Trainer  (www.dmuch.com)
Discount Nike Air Jordan 1 Seller  (www.dmuch.com)
Discount Nike Air Jordan 2 Shoes Seller  (www.dmuch.com)
Discount Nike Air Jordan 3 Collection  (www.dmuch.com)
Discount Nike Air Jordan 4 Shoes Collection
(www.dmuch.com)
Discount Nike Air Jordan 5 Chaussure Shoes
(www.dmuch.com)
Discount Nike Air Jordan 6 Catalog  (www.dmuch.com)
Discount Nike Air Jordan 7 Shoes Catalog  (www.dmuch.com)
Discount Nike Air Jordan 8 Customized  (www.dmuch.com)
Discount Nike Air Jordan 9 Shoes Customized
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cPickle -> invalid signature

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 15:26:53 -0300, Neal Becker 
escribió:


Gabriel Genellina wrote:


En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 
escribió:


What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic
answer, make sure you open the file in binary mode, both when writing  
and

reading.



Yes, that's the message.

Part of what is pickled is a numpy array.  I am writing on a 32-bit  
linux system
and reading on a 64-bit system.  Reading on the 64-bit system is no  
problem.


Maybe the message comes from numpy's unpickling?


Maybe, at least 'invalid signature' makes sense in Numpy. In that case, a
better place to ask would be a numpy specific list, see
http://www.scipy.org/Mailing_Lists


--
Gabriel Genellina

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


basic bytecode to machine code compiler (part 2)

2011-05-17 Thread Rouslan Korneychuk
I mentioned before that I had a proof of concept to convert Python 
bytecode to native machine code.


It's available at https://github.com/Rouslan/nativecompile

Now that I have a substantial number of the bytecode instructions 
implemented, I thought I would share some benchmark results.



The first test performs a quicksort on a list of 100 numbers, 5000 
times. The second calculates all the prime numbers up to 1000. Each 
test is run three times in a row, first with the interpreter, then with 
the compiled code.


 SCRIPT ONE 

import time
import random
import nativecompile

bcode = compile('''
def quicksort(array):
if len(array) <= 1:
return array
pindex = len(array)//2
pivot = array[pindex]
less = []
greater = []
for i,x in enumerate(array):
if i != pindex:
(less if x <= pivot else greater).append(x)
return quicksort(less) + [pivot] + quicksort(greater)

in_ = list(range(100))
random.seed(346097)
random.shuffle(in_)

t = time.clock()
for x in range(5000):
out = quicksort(in_)
t = time.clock()-t

assert out == sorted(in_)

print('execution time: {}'.format(round(t,10)))
''','','exec')

mcode = nativecompile.compile(bcode)

print('byte code')
for x in range(3): eval(bcode)
print()

print('machine code')
for x in range(3): mcode()
print()

 OUTPUT 

byte code
execution time: 1.77
execution time: 1.76
execution time: 1.77

machine code
execution time: 1.42
execution time: 1.42
execution time: 1.42


 SCRIPT TWO 

import time
import math
import nativecompile

bcode = compile('''
def primes_list(upto):
nums = [True] * (upto//2-1)

for i in range(3,math.floor(math.sqrt(upto))+1,2):
if nums[i//2-1]:
for j in range(i*3,upto,i*2):
nums[j//2-1] = False

primes = []
for i,n in enumerate(nums):
if n: primes.append((i+1)*2+1)

return primes

t = time.clock()
primes = primes_list(1000)
t = time.clock()-t

print(primes[-1])
print('execution time: {}'.format(round(t,10)))
''','','exec')

mcode = nativecompile.compile(bcode)

print('byte code')
for x in range(3): eval(bcode)
print()

print('machine code')
for x in range(3): mcode()
print()

 OUTPUT 

byte code
991
execution time: 3.47
991
execution time: 3.38
991
execution time: 3.36

machine code
991
execution time: 2.95
991
execution time: 2.96
991
execution time: 2.95



The results are not terribly impressive, but it's something.

Also, although I wasn't intending on doing anything more complicated 
than getting rid of the interpreter loop, I'm starting to notice little 
ways the code can be optimized without needing run-time analysis. The 
most obvious is looping over a range object. I could do away with the 
iterator and just use a native integer (and have the program fall back 
to the iterator interface if 'range' didn't refer to the built-in range 
object after all).

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


Re: python logging

2011-05-17 Thread Fei
On May 17, 6:55 pm, Ian Kelly  wrote:
> On Tue, May 17, 2011 at 2:55 PM, Fei  wrote:
> > where is default logging file on Mac? I saw lots of app just import
> > logging, and begins to logging.info(...) etc.  I'm not sure where to
> > look at the logging configuration to figure out the log location.
>
> There is no default log file.  You're seeing that because logging only
> needs to be configured by the program once, not on a per-module basis.
>  Thus most modules will just do import logging on the assumption that
> the configuration has already been performed somewhere else.
>
> If no logging configuration is done at all, then the logging
> statements will have no effect.

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


Re: English Idiom in Unix: Directory Recursively

2011-05-17 Thread Steven W. Orr

On 5/17/2011 6:26 PM, Xah Lee wrote:

might be of interest.

〈English Idiom in Unix: Directory Recursively〉
http://xahlee.org/comp/idiom_directory_recursively.html


The answer is from compute science 101. From any standard data structures 
course, you learn the algorithm for how to walk a tree. To make it simple, the 
example is to use a binary tree which means that any non-leaf node of a tree may 
only have two child nodes, which are designated as Left and Right. There are 
only three things that are possible: Visit, Go Left, or Go Right. This means 
that a tree traversal program can only be written three ways:

A PreOrder Traversal will Visit, Go Left, Go Right.
An InOrder Traversal will Go Left, Visit, Go Right.
A PostOrder Traversal will Go Left, Go Right, Visit.

So, the Visit function is the function that does whatever you want to have 
happen at that node. Selection of whether you want to do things like copy, print 
or delete are designated by what kind of traversal you perform. And, since the 
Traversal function calls itself, it is, by definition, recursive.


QED.

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyjamas 0.8alpha1 release

2011-05-17 Thread Terry Reedy

On 5/17/2011 12:07 PM, lkcl wrote:

On May 4, 7:37 pm, Terry Reedy  wrote:

On 5/4/2011 10:06 AM, Luke Kenneth Casson Leighton wrote:

pyjamasis a suite of projects, including a python-to-javascript
compiler



As you well know, there is no such thing as 'python' when it comes to
compiling actual code. So please specify both in announcements here and
on the project homepagehttp://sourceforge.net/projects/pyjamas/
which versions are supported.


> [no response]

I would still like to know. Do you fully support 2.7? It has many of the 
same changes that are in 3.1 and even 3.2 so I can imagine it would be 
difficult.



If you do not yet support 3.x, I request and recommend that you do so,


with the situation as it is, there is not a snowball in hell's chance
that's going to happen. allow me to explain.


Thank you for the explanation. You are right that I probably 
underestimated the work, though you have or will do some of what is 
needed to fully support 2.7.


...

  otherwise please - really: just saying "give me support for python
3.x or else" is ...


And I did not say that. I first learned Python with 1.3 and could again 
write 2.x code if motivated.


...

  leaving _that_ aside, there happens to be absolutely no really good
compelling reason to support python 3.x in the first place.


Depend on who *you* want to target as users. *Your* choice, of course.


"python 3 is the future of python" gimme a break!!


Let's discuss that in a couple of years.


[so why is archlinux the only linux distribution that's converted

> over to run everything off of python 3.x?]

Because being first is their thing.

--
Terry Jan Reedy

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


Finding the local directory of a file in the python path

2011-05-17 Thread are Dogue
Hi there,

I have a problem that I can't seem to solve after quite a bit of
searching, probably because I can't find the right terms to search
for.

Basically, here's the situation. Let's say I have a file at ~/foo/bin/
foo.py that imports a script that at ~/bar/bin/bar.py. The imported
file needs to load something from '~/bar/bin/data/', but I cannot hard
code the full path. Instead, what I need is to have something in
bar.py like

dir =  # Not sure what this line should be
datadir = dir + '/data/'

If I use sys.path[0] or os.getcwd(), then when I import the file from
~/foo/bin/, I get that dir is '~/foo/bin' rather than '~/bar/bin'

I hope this explanation makes sense. If you have any insights, I would
be most appreciative.

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


Re: [ann] pyjamas 0.8alpha1 release

2011-05-17 Thread Terry Reedy

On 5/17/2011 12:38 PM, harrismh777 wrote:

Terry Reedy wrote:

Like it or not, Python 3 is the future of Python. It is the Python that
many Python newcomers learn first, and perhaps ever will.


Yes, no doubt, and I'm genuine about that...

... but there is something else to consider, as I'm sure you are aware.
At some point Python is going to have to standardize in order to
survive. And by survive I'm not talking about the Python 'community,' as
much as I'm talking about the acceptance and wide-spread use of Python
by people who just want to get work done and solve problems.

If there is another major jump like 2.x --> 3.x in the future,


There can't be, in that the essence of the jump was elimination of 
original flaws in 1.0 or 1.1 by elimination of old ways in favor of new 
ways that are already present in 2.7 or before.



Python will die. I hope you guys are aware of this.


No, because I think you are exaggerating.  That said, I think core 
Python is pretty close to 'complete' and I would not mind further syntax 
freezes like the one for 3.2.



Like it or not, Python 2.x has millions of lines of code running out
there, and they're not going to get morphed into 3.x coding.


Except for public libraries, I do not think it should be.


So, 2x is going to be around for many years to come.


For as long the existing binaries can run or a long as the code can be 
compiled.



with an interpreter. Different versions of the source code (.py files)
require a matching 'interpreter,'


Most 2.x code is forward compatible with newer 2.x versions.


where-as in other languages a new
compiler version does not require recompiling source, but if source is
recompiled everything still works...


Unless the new compiler is for a newer version of the language. I 
believe C89 compilers had problems with some K&R + extensions C. I do 
not know if C89 code is completely C99 compatible. I know the reverse is 
not true, CPython is still C89 code since that apparently still makes it 
available on more machines.


--
Terry Jan Reedy

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


Re: Finding the local directory of a file in the python path

2011-05-17 Thread are Dogue
Nevermind...
os.path.dirname (__file__)


On May 17, 9:44 pm, are Dogue  wrote:
> Hi there,
>
> I have a problem that I can't seem to solve after quite a bit of
> searching, probably because I can't find the right terms to search
> for.
>
> Basically, here's the situation. Let's say I have a file at ~/foo/bin/
> foo.py that imports a script that at ~/bar/bin/bar.py. The imported
> file needs to load something from '~/bar/bin/data/', but I cannot hard
> code the full path. Instead, what I need is to have something in
> bar.py like
>
> dir =  # Not sure what this line should be
> datadir = dir + '/data/'
>
> If I use sys.path[0] or os.getcwd(), then when I import the file from
> ~/foo/bin/, I get that dir is '~/foo/bin' rather than '~/bar/bin'
>
> I hope this explanation makes sense. If you have any insights, I would
> be most appreciative.
>
> Thanks
> Are

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


Re: in search of graceful co-routines

2011-05-17 Thread Terry Reedy

On 5/17/2011 1:04 PM, Chris Withers wrote:

Hi All,

I'm looking for a graceful pattern for the situation where I have a
provider of a sequence, the consumer of a sequence and code to moderate
the two, and where I'd like to consumer to be able to signal to the
provider that it hasn't succeeded in processing one element in the queue.

So, I'd want the controlling code to look a lot like:

for item in provider:
try:
consumer.handleItem(self)
except:
provider.failed(item)

Now, since the sequence is long, and comes from a file, I wanted the
provider to be an iterator, so it occurred to me I could try and use the
new 2-way generator communication to solve the "communicate back with
the provider", with something like:

for item in provider:
try:
consumer.handleItem(self)
except:
provider.send('fail')
else:
provider.send('succeed')

..but of course, this won't work, as 'send' causes the provider
iteration to continue and then returns a value itself. That feels weird
and wrong to me, but I guess my use case might not be what was intended
for the send method.

Anyway, I wonder how other people would write this?
(I'm particularly interested in a sane way to use the two way
communication that PEP 342 introduced)


By default, Python iterators operate in pull mode -- consumers request a 
new item when they want one. I believe .send was mostly intended to 
reverse that, to operate in push mode where producers .send() a item to 
a consumer when they are ready to. That is certainly true of examples I 
have seen.


Using .send for feedback to a provider is trickier, as the two other 
posts have shown. Another option is to write an iterator class instead 
of generator function. You can then give the provider a message receive 
method (.send or whatever) that is decoupled from the send-next method. 
Your example above then *would* work, as 'send' would not cause anything 
in the provider except what you want it to cause.


Standard generator functions abbreviate standard iterator classes. When 
one moves beyond standard iterator behavior, the equivalence tends to 
break down.


--
Terry Jan Reedy

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


  1   2   >