TypeError: can only concatenate list (not "tuple") to list

2010-01-03 Thread Gabriel Genellina

This
py> [1,2,3] + (4,5)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate list (not "tuple") to list


--
Gabriel Genellina

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


python mechanize proxy support question

2010-01-03 Thread elca

Hello All

Happy New Year!

i have some question about python mechanize 's proxy support.

im making some web client script, and i would like to insert proxy support

function into my script.

for example ,if i have such like following some script.

how can i add proxy support into my mechanize script?

i was look for some reference , but not so much good hint from google.

params = urllib.urlencode({'id':id, 'passwd':pw})
rq = mechanize.Request("http://www.example.com"; params) 
rs = mechanize.urlopen(rq)

whenever i open this 'www.example.com' website , i would like open go
through proxy.

Thanks in advance!
-- 
View this message in context: 
http://old.nabble.com/python-mechanize-proxy-support-question-tp27009696p27009696.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Question about an application

2010-01-03 Thread r0g
rieh25 wrote:
> Thanks, I had forgotten about it. I'll investigate if there are ways to
> automate using it to run programs in several computers at the same time.
> 
> 
> Rodrick Brown wrote:
>> Take a look at ssh
>>


There are. Take a look at paramiko if you want to interface with SSH
within python. Depending on what you need to do it may well be easier to
use bash scripts / batch files or simply the CLI instead e.g.

ssh account_n...@192.168.x.x 'ls /' > root_folder_listing.txt

This line...
  starts ssh
  logs into account on machine 192.168.x.x
  executes ls
  pipes the data back to
  a file on your local machine

Easy peasy :)

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


Re: Significant whitespace

2010-01-03 Thread Steven D'Aprano
On Sun, 03 Jan 2010 23:42:44 -0500, David Robinow wrote:

> On Sun, Jan 3, 2010 at 10:42 PM, Roy Smith  wrote:
>> In article ,
>>  David Robinow  wrote:
>>
>>> On Sun, Jan 3, 2010 at 8:09 PM, Tim Roberts  wrote:
>>> > More than "not required", it was "not relevant".  This led to one of
>>> > the most infamous programming blunders in the early days of the
>>> > space program, when one programmer accidentially typed a period
>>> > instead of a comma resulting in the loss of a satellite:
>>> Interesting story. Did you make it up?
>>
>> It's a fairly well known story.
>>
>> http://catless.ncl.ac.uk/Risks/5.64.html#subj4.2
>  Sure. But the question is, "Who made it up?"
> http://en.wikiquote.org/wiki/Fortran
> 
> Computer folklore has incorrectly attributed the loss of the Mariner 1
> space probe to a syntax error in a Fortran program. For example, "Recall
> the first American space probe to Venus, reportedly lost because Fortran
> cannot recognize a missing comma in a DO statement…"[


What makes you believe it is incorrect?



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


Re: Exception as the primary error handling mechanism?

2010-01-03 Thread Steven D'Aprano
On Sun, 03 Jan 2010 22:36:44 -0500, Roy Smith wrote:

> In article ,
>  Steven D'Aprano  wrote:
> 
>> This last one can be *very* problematic. In the early 1990s, I was
>> programming using a callback API that could only return an integer. The
>> standard way of indicating an error was to return -1. But what happens
>> if -1 is a legitimate return value, e.g. for a maths function?
> 
> One of the truly nice features of Python is the universally
> distinguished value, None.


What happens if you need to return None as a legitimate value?


Here's a good example: iterating over a list. Python generates an 
exception when you hit the end of the list. If instead, Python returned 
None when the index is out of bounds, you couldn't store None in a list 
without breaking code.

So we produce a special sentinel object EndOfSequence. Now we can't do 
this:

for obj in ["", 12, None, EndOfSequence, [], {}]:
print dir(obj)  # or some other useful operation

The fundamental flaw of using magic values is that, there will always be 
some application where you want to use the magic value as a non-special 
value, and then you're screwed.

This is why, for instance, it's difficult for C strings to contain a null 
byte, and there are problems with text files on DOS and CP/M (and Windows 
under some circumstances) that contain a ^Z byte.



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


Re: Significant whitespace

2010-01-03 Thread r0g
David Robinow wrote:
> On Sun, Jan 3, 2010 at 10:42 PM, Roy Smith  wrote:
>> In article ,
>>  David Robinow  wrote:
>>
>>> On Sun, Jan 3, 2010 at 8:09 PM, Tim Roberts  wrote:
 More than "not required", it was "not relevant".  This led to one of the
 most infamous programming blunders in the early days of the space program,
 when one programmer accidentially typed a period instead of a comma
 resulting in the loss of a satellite:
>>> Interesting story. Did you make it up?
>> It's a fairly well known story.
>>
>> http://catless.ncl.ac.uk/Risks/5.64.html#subj4.2
>  Sure. But the question is, "Who made it up?"
> http://en.wikiquote.org/wiki/Fortran
> 
> Computer folklore has incorrectly attributed the loss of the Mariner 1
> space probe to a syntax error in a Fortran program. For example,
> "Recall the first American space probe to Venus, reportedly lost
> because Fortran cannot recognize a missing comma in a DO statement…"[



Wow you're totally right! It was a missing UNDERSCORE not a DOT being
typed instead of a COMMA! We've been lied to ALL ALONG! What kind of
sickos would do this? Let's find this Tim character, flay him alive and
then go crown you the KING OF EVERYTHING for rescuing us from that
deadly nugget of misinformation!

Honestly I might have believed those dot/comma LIES if it wasn't for
your noble selfless efforts to uncover the SHOCKING TRUTH. Imagine what
might have happened! The character in question being an UNDERSCORE
COMPLETELY CHANGES the meaning and point of the story. As for it being
LEFT OUT rather than TRANSPOSED, well, anyone can see how that TURNS THE
WHOLE STORY UPSIDE DOWN.

Of course there are the naysayers who might claim absolute accuracy is
no big deal in stories that are essentially parables but they do not
understand the HARM that can come from not remembering really tiny,
almost inconsequential details. For what it's worth I DO NOT consider
you a tiresome pedant and I think your taunting, patronising style is
completely appropriate and proportional to Tim's sickening crimes
against fact.

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


Re: twenty years ago Guido created Python

2010-01-03 Thread Chris Jones
On Sun, Jan 03, 2010 at 10:18:18PM EST, Ben Finney wrote:
> Chris Jones  writes:

[..]

> > Sorry you missed my point.
> 
> I didn't, since I attempted to bring it back on topic by expunging the
> off-topic part of your message. 

Er.. what's 'off-topic' about mentioning that a couple of trolls on this
list often seem to attract far more interest than a genuine testimonial
to Guido's achievement? 

> Sorry I failed to salvage the thread.

Man with a Mission, hehe.. 

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


Re: Question about an application

2010-01-03 Thread rieh25

Thanks, I had forgotten about it. I'll investigate if there are ways to
automate using it to run programs in several computers at the same time.


Rodrick Brown wrote:
> 
> Take a look at ssh
> 
> Sent from my iPhone 3GS.
> 
> On Jan 4, 2010, at 12:50 AM, rieh25  wrote:
> 
>>
>> I am thinking of installing a python webserver I coded in every  
>> computer at
>> my work. This would allow me to run specific tasks in them, like  
>> creating
>> backups, installing things, etc. Is there another way to run  
>> programs in
>> remote computers? Thanks for your opinions.
>> -- 
>> View this message in context:
>> http://old.nabble.com/Question-about-an-application-tp27009118p27009118.html
>> Sent from the Python - python-list mailing list archive at Nabble.com.
>>
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Question-about-an-application-tp27009118p27009252.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: twenty years ago Guido created Python

2010-01-03 Thread r0g
n00m wrote:
> Ok, let me evolve a bit my thought.
> Guido is Eropean Culture.
> Now say what was invented by Japanese, by Chinese?
> Nothing.
> Barbaric cultures, they are animals inborn animals.
> Russian Sikorsky built choppers for Eisenhower.
> Look at letter "S" on them -- its his name
> What you know about his destiny?
> You know knothing. Yuou don't know that only the
> greatest Russian composer Rakhmaninov helped him, in America.
> Literally -- by money, the composer gave him all his fortune ~$1500
> Be not this help -- no choppers in America



Announcement: You can download the latest version of this cutting edge
bot from here...

http://www.illiteratexenophobicrantingracistsimulator.ru/usenet_spambot.py

Plugins available here...

http://www.illiteratexenophobicrantingracistsimulator.ru/terrible_spelling.py
http://www.illiteratexenophobicrantingracistsimulator.ru/inconsequential_facts.py
http://www.illiteratexenophobicrantingracistsimulator.ru/rabid_nationalism.py

Happy new year everybody!

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


Re: Question about an application

2010-01-03 Thread rodrick brown

Take a look at ssh

Sent from my iPhone 3GS.

On Jan 4, 2010, at 12:50 AM, rieh25  wrote:



I am thinking of installing a python webserver I coded in every  
computer at
my work. This would allow me to run specific tasks in them, like  
creating
backups, installing things, etc. Is there another way to run  
programs in

remote computers? Thanks for your opinions.
--
View this message in context: 
http://old.nabble.com/Question-about-an-application-tp27009118p27009118.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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

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


Question about an application

2010-01-03 Thread rieh25

I am thinking of installing a python webserver I coded in every computer at
my work. This would allow me to run specific tasks in them, like creating
backups, installing things, etc. Is there another way to run programs in
remote computers? Thanks for your opinions.
-- 
View this message in context: 
http://old.nabble.com/Question-about-an-application-tp27009118p27009118.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: twenty years ago Guido created Python

2010-01-03 Thread n00m
Now tell me:
what ahat this mobs of yellow, africans, asiats, are doing in
Stockholm?
Do you think your govs let me in just to vist England, Norway? Never.
Its all conditionally. But the fact is. IS.
You roll our world into abyss of stupidity

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


Re: Significant whitespace

2010-01-03 Thread David Robinow
On Sun, Jan 3, 2010 at 10:42 PM, Roy Smith  wrote:
> In article ,
>  David Robinow  wrote:
>
>> On Sun, Jan 3, 2010 at 8:09 PM, Tim Roberts  wrote:
>> > More than "not required", it was "not relevant".  This led to one of the
>> > most infamous programming blunders in the early days of the space program,
>> > when one programmer accidentially typed a period instead of a comma
>> > resulting in the loss of a satellite:
>> Interesting story. Did you make it up?
>
> It's a fairly well known story.
>
> http://catless.ncl.ac.uk/Risks/5.64.html#subj4.2
 Sure. But the question is, "Who made it up?"
http://en.wikiquote.org/wiki/Fortran

Computer folklore has incorrectly attributed the loss of the Mariner 1
space probe to a syntax error in a Fortran program. For example,
"Recall the first American space probe to Venus, reportedly lost
because Fortran cannot recognize a missing comma in a DO statement…"[
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Significant whitespace

2010-01-03 Thread Roy Smith
In article ,
 David Robinow  wrote:

> On Sun, Jan 3, 2010 at 8:09 PM, Tim Roberts  wrote:
> > More than "not required", it was "not relevant".  This led to one of the
> > most infamous programming blunders in the early days of the space program,
> > when one programmer accidentially typed a period instead of a comma
> > resulting in the loss of a satellite:
> Interesting story. Did you make it up?

It's a fairly well known story.

http://catless.ncl.ac.uk/Risks/5.64.html#subj4.2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-03 Thread Roy Smith
In article ,
 Steven D'Aprano  wrote:

> This last one can be *very* problematic. In the early 1990s, I was 
> programming using a callback API that could only return an integer. The 
> standard way of indicating an error was to return -1. But what happens if 
> -1 is a legitimate return value, e.g. for a maths function? 

One of the truly nice features of Python is the universally distinguished 
value, None.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-03 Thread Steven D'Aprano
On Sun, 03 Jan 2010 13:44:29 -0800, Michi wrote:


> The quoted sentence appears in a section of the article that deals with
> efficiency. I point out in that section that bad APIs often have a price
> not just in terms of usability and defect rate, but that they are often
> inefficient as well.

This is very true, but good APIs often trade-off increased usability and 
reduced defect rate against machine efficiency too. In fact, I would 
argue that this is a general design principle of programming languages: 
since correctness and programmer productivity are almost always more 
important than machine efficiency, the long-term trend across virtually 
all languages is to increase correctness and productivity even if doing 
so costs some extra CPU cycles.



> (For example, wrapper APIs often require additional
> memory allocations and/or data copies.) Incorrect use of exceptions also
> incurs an efficiency penalty.

And? *Correct* use of exceptions also incur a penalty. So does the use of 
functions. Does this imply that putting code in functions is a poor API? 
Certainly not.


> In many language implementations, exception handling is expensive;
> significantly more expensive than testing a return value.

And in some it is less expensive.

But no matter how much more expensive, there will always be a cut-off 
point where it is cheaper on average to suffer the cost of handling an 
exception than it is to make unnecessary tests.

In Python, for dictionary key access, that cut-off is approximately at 
one failure per ten or twenty attempts. So unless you expect more than 
one in ten attempts to lead to a failure, testing first is actually a 
pessimation, not an optimization.




> Consider the following:
> 
> int x;
> try {
> x = func();
> } catch (SomeException) {
>doSomething();
>return;
> }
> doSomethingElse();
> 
> Here is the alternative without exceptions. (func() returns SpecialValue
> instead of throwing.)
> 
> int x;
> x = func();
> if (x == SpecialValue) {
> doSomething();
> return;
> }
> doSomethingElse();


In some, limited, cases you might be able to use the magic return value 
strategy, but this invariably leads to lost programmer productivity, more 
complex code, lowered readability and usability, and more defects, 
because programmers will invariably neglect to test for the special value:

int x;
x = func();
doSomething(x);
return;

Or worse, they will write doSomething() so that it too needs to know 
about SpecialValue, and so do all the functions it calls. Instead of 
dealing with the failure in one place, you can end up having to deal with 
it in a dozen places.


But even worse is common case that SpecialValue is a legal value when 
passed to doSomething, and you end up with the error propagating deep 
into the application before being found. Or even worse, it is never found 
at all, and the application simply does the wrong thing.



 
> In many language implementations, the second version is considerably
> faster, especially when the exception may be thrown from deep in the
> bowels of func(), possibly many frames down the call tree.

This is a classic example of premature optimization. Unless such 
inefficiency can be demonstrated to actually matter, then you do nobody 
any favours by preferring the API that leads to more defects on the basis 
of *assumed* efficiency.

If your test for a special value is 100 times faster than handling the 
exception, and exceptions occur only one time in 1000, then using a 
strategy of testing for a special value is actually ten times slower on 
average than catching an exception.


 
> If func() throws an exception for something that routinely occurs in the
> normal use of the API, the extra cost can be noticeable. 

"Can be". But it also might not be noticeable at all.


[...]
> Here is an example of this:
> 
> KeyType k = ...;
> ValueType v;
> 
> try {
>v = collection.lookup(k);
> } catch (NotFoundException) {
>collection.add(k, defaultValue);
>v = defaultValue;
> }
> doSomethingWithValue(v);
> 
> The same code if collection doesn't throw when I look up something that
> isn't there:
> 
> KeyType k = ...;
> ValueType v;
> 
> v = collection.lookup(k);
> if (v == null) {
> collection.add(k, defaultValue);
> v = defaultValue;
> }
> doSomethingWithValue(v);
> 
> The problem is that, if I do something like this in a loop, and the loop
> is performance-critical, the exception version can cause a significant
> penalty.


No, the real problems are:

(1) The caller has to remember to check the return result for the magic 
value. Failure to do so leads to bugs, in some cases, serious and hard-to-
find bugs.

(2) If missing keys are rare enough, the cost of all those unnecessary 
tests will out-weigh the saving of avoiding catching the exception. "Rare 
enough" may still be very common: in the case of Python, the cross-over 
point is approximately 1 time in 15.

(3) Your collection now cannot use the magic value as a legiti

Re: Significant whitespace

2010-01-03 Thread David Robinow
On Sun, Jan 3, 2010 at 8:09 PM, Tim Roberts  wrote:
> More than "not required", it was "not relevant".  This led to one of the
> most infamous programming blunders in the early days of the space program,
> when one programmer accidentially typed a period instead of a comma
> resulting in the loss of a satellite:
Interesting story. Did you make it up?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any Swisses here?

2010-01-03 Thread n00m
What Imeant by what waht
try to solve e.g. http://acm.sgu.ru/problem.php?contest=0&problem=482
99% people here are 0 in this. They know this they know that, but they
can't nothing, they simply are sitting on this group and apraised
themselves But you can nothing
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: twenty years ago Guido created Python

2010-01-03 Thread Ben Finney
Chris Jones  writes:

> On Sun, Jan 03, 2010 at 04:19:02PM EST, Ben Finney wrote:
> > The entirety of ‘comp.lang.python’ is an ongoing response to Guido
> > van Rossum's achievements (and all the others that make Python
> > great). Mere week- or month-long threads are paltry by comparison.
>
> That I understand. But my remark was not really about Guido.. but
> rather in a roundabout way, more of a poke at [a troll], hopefully
> avoiding the troll-feeding trap.

You didn't avoid it, since you irrelevantly raised (twice, now)
discussion of a troll in a thread originally unrelated to that person.

> Sorry you missed my point.

I didn't, since I attempted to bring it back on topic by expunging the
off-topic part of your message. Sorry I failed to salvage the thread.

-- 
 \  “If sharing a thing in no way diminishes it, it is not rightly |
  `\  owned if it is not shared.” —Augustine of Hippo (354–430 CE) |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: twenty years ago Guido created Python

2010-01-03 Thread n00m
i'm sobered up
Yes of course Guido and his lang is both superb things
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Significant whitespace

2010-01-03 Thread Roy Smith
In article ,
 Tim Roberts  wrote:

> Roy Smith  wrote:
> >
> >2) Whitespace was not required in many places.  For example, the following 
> >two statements (this will only make sense in a fixed-width font) are 
> >identical:
> >
> >   DO 10 I = 1, 10
> >   DO10I=1,10
> 
> More than "not required", it was "not relevant".  This led to one of the
> most infamous programming blunders in the early days of the space program,
> when one programmer accidentially typed a period instead of a comma
> resulting in the loss of a satellite:
> 
>DO 10 I = 1. 10
> 
> What this actually does is store the floating point value "1.1" in a new
> variable called "DO10I".

1.1 or 1.01?  There were some places where a blank was equivalent to a zero 
in a number. I don't remember if this was one of them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2010-01-03 Thread prakash jp
*#How to use setup.py file with py2exe:*
**
python daniesetup.py py2exe --bundle 1

*#Also the data files have to taken care off in the options* list

*#Here is a sample setup.py:*
*#*
from distutils.core import setup
import py2exe
import sys

# no arguments
if len(sys.argv) == 1:
sys.argv.append("py2exe")
# creates a standalone .exe file, no zip files
setup( options = {"py2exe": {"compressed": 1, "optimize": 2, "ascii": 1,
"bundle_files": 1}},
   zipfile = None,
   # replace test.py with your own code filename here ...
   console = [{"script": 'test.py'}] )
Regards
Prakash
-- 
http://mail.python.org/mailman/listinfo/python-list


python xmlrpc client with ssl client certificates and standard modules

2010-01-03 Thread News123
Hi,

I was googling fot quite some time and was not really succesfull.

I found one solution, which I will try soon.
It is
http://www.cs.technion.ac.il/~danken/xmlrpc-ssl.html
(found in
http://hamakor.org.il/pipermail/python-il/2008-February/29.html )

This will probably work, but it requires the module M2Crypto.

In order to avoid installing M2Crypto an all hosts that want to run the
script I wondered, whether there is no other solution.

I can do xmlrpc over ssl WITHOUT certificates with following code:

import xmlrpclib
server_url = 'https://myserver'
server = xmlrpclib.Server(server_url);


and I can perform a https get request WITH certificates with below snippet:

import httplib
conn = httplib.HTTPSConnection(
HOSTNAME,
key_file = KEYFILE,
cert_file = CERTFILE
)
conn.putrequest('GET', '/')
conn.endheaders()
response = conn.getresponse()
print response.read()


I'm just lost of how to 'combine' both.


Thanks in advance for any suggestions / hints




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


Re: Safe file I/O to shared file (or SQLite) from multi-threaded web server

2010-01-03 Thread Steve Holden
Lawrence D'Oliveiro wrote:
> In message , Steve 
> Holden wrote:
> 
>> Yes, but not to MySQL, please. Particularly since there is a sword of
>> Damocles hanging over its head while the Oracle takeover of Sun is
>> pending.
> 
> Ah, I see the FUDsters are crawling out of the woodwork here, as well. I’ve 
> got news for you: MySQL is an open-source product. And you can’t kill Open 
> Source. So go crawling back to your proprietary world, if that’s the only 
> world you understand.

I have no objection to you attempting to inform me about things I
already understand, but I would appreciate at least some attempt on your
part to maintain civility in your discourse. There is no need to be so
obnoxious, or so ill-informed: I didn't get to chair the Python Software
Foundation by "crawling [around in a] proprietary world", so kindly mind
your manners.

MySQL has always been technically inferior to other choices of open
source database. The current state of affairs was entirely predictable,
and appears to be more to do with Monty Widenius' wish to continue
exploiting a brand that he sold toSun two years ago than it has to do
with technical issues, as I pointed out yesterday.

http://holdenweb.blogspot.com/2010/01/wht-save-mysql-now.html

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Safe file I/O to shared file (or SQLite) from multi-threaded web server

2010-01-03 Thread Lawrence D'Oliveiro
In message , Steve 
Holden wrote:

> Yes, but not to MySQL, please. Particularly since there is a sword of
> Damocles hanging over its head while the Oracle takeover of Sun is
> pending.

Ah, I see the FUDsters are crawling out of the woodwork here, as well. I’ve 
got news for you: MySQL is an open-source product. And you can’t kill Open 
Source. So go crawling back to your proprietary world, if that’s the only 
world you understand.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DST and datetime

2010-01-03 Thread Lawrence D'Oliveiro
In message <874on82oan@benfinney.id.au>, Ben Finney wrote:

> Or you could use the ready-made wheel maintained by others:
> 
> tzinfo Objects
> http://docs.python.org/library/datetime.html#tzinfo-objects>

But that’s only an abstract base class, which means it doesn’t actually 
implement any reading of actual timezone info.

> World timezone definitions, modern and historical
> http://pypi.python.org/pypi/pytz>

Shame that they maintain their own duplicate of the Olson database, instead 
of reading the original directly from /usr/share/zoneinfo 
.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Significant whitespace

2010-01-03 Thread Tim Roberts
Roy Smith  wrote:
>
>2) Whitespace was not required in many places.  For example, the following 
>two statements (this will only make sense in a fixed-width font) are 
>identical:
>
>   DO 10 I = 1, 10
>   DO10I=1,10

More than "not required", it was "not relevant".  This led to one of the
most infamous programming blunders in the early days of the space program,
when one programmer accidentially typed a period instead of a comma
resulting in the loss of a satellite:

   DO 10 I = 1. 10

What this actually does is store the floating point value "1.1" in a new
variable called "DO10I".
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-03 Thread Cameron Simpson
On 03Jan2010 15:56, cassiope  wrote:
| Strace confirms the uid and gid == "lesser user".  Changing the
| directory
| permissions to 775 changes nothing.  Clearly get EACCES error on the
| attempted
| file creation.
| 
| The only other thing is that as part of the python interpreter call, I
| provide
| a "reduced environment", just UID,GID,TMP,PWD,USER, and HOME.  Is
| anything
| else needed?

Should be irrelevant.

Ok: does the file to be created already exist? If so, what are its
permissions? If the file exists and isn't writable you may get this
error.

Also, did you eyeball the actual open() call to ensure the file pathname
is correct, and doesn't use a bogus (non-existent) directory name?
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

"GOD IS MY SOURCE"  - Bumper sticker, Chapel Hill, NC
I'll have to remember that one for the next code review meeting.
- ajvan...@ingr.com (Alain van der Heide)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-03 Thread cassiope
On Jan 3, 3:00 pm, Cameron Simpson  wrote:
> On 03Jan2010 14:20, cassiope  wrote:
> | On Jan 2, 8:02 pm, Cameron Simpson  wrote:
> | > Can you show us:
> | >   - the directory user and group ownership and permissions
> | >   - the daemon's user and group values?
> |
> | Directory permissions: 774
>
> That's unusual - why the "4"? Directories with read but no search (1)
> are of limited use. (Not none - it's only unusual, not insane).
>
> | Directory ownership: "lesser user", "special group" where /etc/group
> | has "special group" members including the "lesser user", as well as
> | those who are expected to use the daemon, but not root.
> | Script ownership: "lesser user"; permissions 755
> | Daemon ownership: root; permissions: 755 (always started by root).
>
> And the script/daemon _runs_ as the "lesser user"?
>
> If so, superficially the permissions look like they should work.
> --
> Cameron Simpson  DoD#743http://www.cskk.ezoshosting.com/cs/
>
> I couldn't think of anything else to do with it, so I put it on the web.

Strace confirms the uid and gid == "lesser user".  Changing the
directory
permissions to 775 changes nothing.  Clearly get EACCES error on the
attempted
file creation.

The only other thing is that as part of the python interpreter call, I
provide
a "reduced environment", just UID,GID,TMP,PWD,USER, and HOME.  Is
anything
else needed?

Thanks again, Cameron!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-03 Thread MRAB

Michi wrote:

On Jan 1, 2:47 pm, Peng Yu  wrote:

In the article API Design Matters by Michi Henning

Communications of the ACM
Vol. 52 No. 5, Pages 46-56
10.1145/1506409.1506424http://cacm.acm.org/magazines/2009/5/24646-api-design-matters/fulltext

It says "Another popular design flaw—namely, throwing exceptions for
expected outcomes—also causes inefficiencies because catching and
handling exceptions is almost always slower than testing a return
value."

My observation is contradicted to the above statement by Henning. If
my observation is wrong, please just ignore my question below.


Seeing that quite a few people have put their own interpretation on
what I wrote, I figured I'll post a clarification.

The quoted sentence appears in a section of the article that deals
with efficiency. I point out in that section that bad APIs often have
a price not just in terms of usability and defect rate, but that they
are often inefficient as well. (For example, wrapper APIs often
require additional memory allocations and/or data copies.) Incorrect
use of exceptions also incurs an efficiency penalty.

In many language implementations, exception handling is expensive;
significantly more expensive than testing a return value. Consider the
following:

int x;
try {
x = func();
} catch (SomeException) {
   doSomething();
   return;
}
doSomethingElse();

Here is the alternative without exceptions. (func() returns
SpecialValue instead of throwing.)

int x;
x = func();
if (x == SpecialValue) {
doSomething();
return;
}
doSomethingElse();

In many language implementations, the second version is considerably
faster, especially when the exception may be thrown from deep in the
bowels of func(), possibly many frames down the call tree.

If func() throws an exception for something that routinely occurs in
the normal use of the API, the extra cost can be noticeable. Note that
I am not advocating not to use exceptions. I *am* advocating to not
throw exceptions for conditions that are not exceptional.

The classic example of this are lookup functions that, for example,
retrieve the value of an environment variable, do a table lookup, or
similar. Many such APIs throw an exception when the lookup fails
because the key isn't the table. However, very often, looking for
something that isn't there is a common case, such as when looking for
a value and, if the value isn't present already, adding it. Here is an
example of this:

KeyType k = ...;
ValueType v;

try {
   v = collection.lookup(k);
} catch (NotFoundException) {
   collection.add(k, defaultValue);
   v = defaultValue;
}
doSomethingWithValue(v);

The same code if collection doesn't throw when I look up something
that isn't there:

KeyType k = ...;
ValueType v;

v = collection.lookup(k);
if (v == null) {
collection.add(k, defaultValue);
v = defaultValue;
}
doSomethingWithValue(v);

The problem is that, if I do something like this in a loop, and the
loop is performance-critical, the exception version can cause a
significant penalty.


In Python, of course, there's a method for this: setdefault.


As the API designer, when I make the choice between returning a
special value to indicate some condition, or throwing an exception, I
should consider the following questions:

 * Is the special condition such that, under most conceivable
circumstances, the caller will treat the condition as an unexpected
error?

 * Is it appropriate to force the caller to deal with the condition in
a catch-handler?

 * If the caller fails to explicitly deal with the condition, is it
appropriate to terminate the program?

Only if the answer to these questions is "yes" is it appropriate to
throw an exception. Note the third question, which is often forgotten.
By throwing an exception, I not only force the caller to handle the
exception with a catch-handler (as opposed to leaving the choice to
the caller), I also force the caller to *always* handle the exception:
if the caller wants to ignore the condition, he/she still has to write
a catch-handler and failure to do so terminates the program.

Apart from the potential performance penalty, throwing exceptions for
expected outcomes is bad also because it forces a try-catch block on
the caller. One example of this is the .NET socket API: if I do non-
blocking I/O on a socket, I get an exception if no data is ready for
reading (which is the common and expected case), and I get a zero
return value if the connection was lost (which is the uncommon and
unexpected case).

In other words, the .NET API gets this completely the wrong way round.
Code that needs to do non-blocking reads from a socket turns into a
proper mess as a result because the outcome of a read() call is tri-
state:

 * Data was available and returned: no exception

 * No data available: exception

 * Connection lost: no exception

Because such code normally lives in a loop that decrements a byte
count until the expected number of bytes have been read, the control
flow because real

Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-03 Thread Cameron Simpson
On 03Jan2010 14:20, cassiope  wrote:
| On Jan 2, 8:02 pm, Cameron Simpson  wrote:
| > Can you show us:
| >   - the directory user and group ownership and permissions
| >   - the daemon's user and group values?
| 
| Directory permissions: 774

That's unusual - why the "4"? Directories with read but no search (1)
are of limited use. (Not none - it's only unusual, not insane).

| Directory ownership: "lesser user", "special group" where /etc/group
| has "special group" members including the "lesser user", as well as
| those who are expected to use the daemon, but not root.
| Script ownership: "lesser user"; permissions 755
| Daemon ownership: root; permissions: 755 (always started by root).

And the script/daemon _runs_ as the "lesser user"?

If so, superficially the permissions look like they should work.
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

I couldn't think of anything else to do with it, so I put it on the web.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-03 Thread cassiope
On Jan 2, 8:02 pm, Cameron Simpson  wrote:
> On 02Jan2010 15:21, cassiope  wrote:
> | [...]  I want
> | to save a copy of the email in a particular directory which is
> | accessible to the Windows clients via samba.
> |
> | The strange thing is that even with the right user-id, I cannot seem
> | to write to the directory, getting an IOError exception.  Changing the
> | directory to world-writable fixes this.  I can confirm the uid and gid
> | for the script by having the script print these values just before
> | trying to create/write the file.  Becoming the same lesser user, I
> | have no problem writing a file to the same directory.
>
> Can you show us:
>   - the directory user and group ownership and permissions
>   - the daemon's user and group values?

Directory permissions: 774
Directory ownership: "lesser user", "special group" where /etc/group
has
   "special group" members including the "lesser user", as well as
those
   who are expected to use the daemon, but not root.
Script ownership: "lesser user"; permissions 755
Daemon ownership: root; permissions: 755 (always started by root).

The script also has to connect to a postgresql database for part of
its
work - that part works,
> You can also strace your daemon:
>
>   strace -f -e trace=file your-daemon your-daemon-args... 2>strace.out
>
> and then examine the log for the precise UNIX-level failure.
>
> Cheers,
> --
> Cameron Simpson  DoD#743http://www.cskk.ezoshosting.com/cs/
>
> Money won't buy happiness, but it will pay the salary of a large research
> staff to study the problem. - Bill Vaughan

Thanks, Cameron (and Steve and Christian).  My first shot with strace
(it's
been awhile since I've used that - I think your syntax may be a tiny
bit off
- but it's probably the tool I need to use.  Will explore further...


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


Re: twenty years ago Guido created Python

2010-01-03 Thread Chris Jones
On Sun, Jan 03, 2010 at 04:19:02PM EST, Ben Finney wrote:
> Chris Jones  writes:

> > Interesting to note that Guido's achievements prompt much less
> > response, and get much less coverage […]
> 
> The entirety of ‘comp.lang.python’ is an ongoing response to Guido van
> Rossum's achievements (and all the others that make Python great).
> Mere week- or month-long threads are paltry by comparison.

That I understand. But my remark was not really about Guido.. but rather
in a roundabout way, more of a poke at Xah Lee, hopefully avoiding the
troll-feeding trap. Sorry you missed my point.

Come to think of it, since I have nothing much to say about python, but
nevertheless enjoy reading most of the material on this list, this was
mostly an excuse to wish everyone here a Happy New Year.

CJ

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


Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-03 Thread Steve Holden
cassiope wrote:
> On Jan 2, 6:40 pm, Christian Heimes  wrote:
>> cassiope wrote:
>>> The strange thing is that even with the right user-id, I cannot seem
>>> to write to the directory, getting an IOError exception.  Changing the
>>> directory to world-writable fixes this.  I can confirm the uid and gid
>>> for the script by having the script print these values just before
>>> trying to create/write the file.  Becoming the same lesser user, I
>>> have no problem writing a file to the same directory.
>> Are you able to write to the directory with the user id when you tried
>> to create a file manually?
> 
> Yes.  Sorry that wasn't clear.
> 
>> How are you changing the uid and gid of your script? IIRC you have to
>> set the effective user id with os.seteuid() and os.setegid().
> 
> I'm changing the uid and gid in the daemon (which runs with root
> permissions
> until the fork and uid/gid change).  The uid and gid are confirmed by
> printing os.getuid() and os.getgid() in the script.
> 
And what do os.geteuid() and os.getegid() report? I suppose it's
possible there's some bizarre difference between the effective and
actual process parameters. IS the filestore a local file system, or an
NFS mount?

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Set variables based on dictionary

2010-01-03 Thread Peter Otten
Joan Miller wrote:

> How to set local variables based on dictionary contents?

>>> def f(**d):
... for k, v in d.iteritems(): exec "%s = v" % k
... return locals()
...
>>> f(a=42, b="yadda")
{'a': 42, 'k': 'b', 'b': 'yadda', 'd': {'a': 42, 'b': 'yadda'}, 'v': 
'yadda'}
>>> f(**{"print 'warning: this can execute arbitrary code'; a":42})
warning: this can execute arbitrary code
{'a': 42, 'k': "print 'warning: this can execute arbitrary code'; a", 'd': 
{"print 'warning: this can execute arbitrary code'; a": 42}, 'v': 42}

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


Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-03 Thread cassiope
On Jan 2, 6:40 pm, Christian Heimes  wrote:
> cassiope wrote:
> > The strange thing is that even with the right user-id, I cannot seem
> > to write to the directory, getting an IOError exception.  Changing the
> > directory to world-writable fixes this.  I can confirm the uid and gid
> > for the script by having the script print these values just before
> > trying to create/write the file.  Becoming the same lesser user, I
> > have no problem writing a file to the same directory.
>
> Are you able to write to the directory with the user id when you tried
> to create a file manually?

Yes.  Sorry that wasn't clear.

> How are you changing the uid and gid of your script? IIRC you have to
> set the effective user id with os.seteuid() and os.setegid().

I'm changing the uid and gid in the daemon (which runs with root
permissions
until the fork and uid/gid change).  The uid and gid are confirmed by
printing os.getuid() and os.getgid() in the script.

> Christian

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


Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-03 Thread cassiope
On Jan 2, 3:46 pm, Steve Holden  wrote:
> cassiope wrote:
> > I have a daemon on a Linux system that supports a number of Windows
> > clients.  Among the functions is to send e-mails, which is
> > sufficiently complicated that I fork() a separate process which gets
> > setuid to a lesser user, and calls a python script which does the
> > actual formatting and emailing (the daemon is written in C).  I want
> > to save a copy of the email in a particular directory which is
> > accessible to the Windows clients via samba.
>
> > The strange thing is that even with the right user-id, I cannot seem
> > to write to the directory, getting an IOError exception.  Changing the
> > directory to world-writable fixes this.  I can confirm the uid and gid
> > for the script by having the script print these values just before
> > trying to create/write the file.  Becoming the same lesser user, I
> > have no problem writing a file to the same directory.
>
> Have you looked at the IOError's errno attribute to find out exactly why
> the Python subprocess is unable to write to the directory?

It's errno=13 ... "permission denied".

> > Is there anything that I can do to diagnose why this script is
> > failing?  For various reasons I don't want to make the directory world-
> > writable.
>
> I'd concur on that decision.
>
> > This is on a Debian "squeeze" system, with python 2.5.
>
> > Thanks for any insights!
>
> Take a closer look at the exception, that might stimulate a thought or two.
>
> regards
>  Steve
> --
> Steve Holden           +1 571 484 6266   +1 800 494 3119
> PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
> Holden Web LLC                http://www.holdenweb.com/
> UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

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


Re: Exception as the primary error handling mechanism?

2010-01-03 Thread Michi
On Jan 1, 2:47 pm, Peng Yu  wrote:
>
> In the article API Design Matters by Michi Henning
>
> Communications of the ACM
> Vol. 52 No. 5, Pages 46-56
> 10.1145/1506409.1506424http://cacm.acm.org/magazines/2009/5/24646-api-design-matters/fulltext
>
> It says "Another popular design flaw—namely, throwing exceptions for
> expected outcomes—also causes inefficiencies because catching and
> handling exceptions is almost always slower than testing a return
> value."
>
> My observation is contradicted to the above statement by Henning. If
> my observation is wrong, please just ignore my question below.

Seeing that quite a few people have put their own interpretation on
what I wrote, I figured I'll post a clarification.

The quoted sentence appears in a section of the article that deals
with efficiency. I point out in that section that bad APIs often have
a price not just in terms of usability and defect rate, but that they
are often inefficient as well. (For example, wrapper APIs often
require additional memory allocations and/or data copies.) Incorrect
use of exceptions also incurs an efficiency penalty.

In many language implementations, exception handling is expensive;
significantly more expensive than testing a return value. Consider the
following:

int x;
try {
x = func();
} catch (SomeException) {
   doSomething();
   return;
}
doSomethingElse();

Here is the alternative without exceptions. (func() returns
SpecialValue instead of throwing.)

int x;
x = func();
if (x == SpecialValue) {
doSomething();
return;
}
doSomethingElse();

In many language implementations, the second version is considerably
faster, especially when the exception may be thrown from deep in the
bowels of func(), possibly many frames down the call tree.

If func() throws an exception for something that routinely occurs in
the normal use of the API, the extra cost can be noticeable. Note that
I am not advocating not to use exceptions. I *am* advocating to not
throw exceptions for conditions that are not exceptional.

The classic example of this are lookup functions that, for example,
retrieve the value of an environment variable, do a table lookup, or
similar. Many such APIs throw an exception when the lookup fails
because the key isn't the table. However, very often, looking for
something that isn't there is a common case, such as when looking for
a value and, if the value isn't present already, adding it. Here is an
example of this:

KeyType k = ...;
ValueType v;

try {
   v = collection.lookup(k);
} catch (NotFoundException) {
   collection.add(k, defaultValue);
   v = defaultValue;
}
doSomethingWithValue(v);

The same code if collection doesn't throw when I look up something
that isn't there:

KeyType k = ...;
ValueType v;

v = collection.lookup(k);
if (v == null) {
collection.add(k, defaultValue);
v = defaultValue;
}
doSomethingWithValue(v);

The problem is that, if I do something like this in a loop, and the
loop is performance-critical, the exception version can cause a
significant penalty.

As the API designer, when I make the choice between returning a
special value to indicate some condition, or throwing an exception, I
should consider the following questions:

 * Is the special condition such that, under most conceivable
circumstances, the caller will treat the condition as an unexpected
error?

 * Is it appropriate to force the caller to deal with the condition in
a catch-handler?

 * If the caller fails to explicitly deal with the condition, is it
appropriate to terminate the program?

Only if the answer to these questions is "yes" is it appropriate to
throw an exception. Note the third question, which is often forgotten.
By throwing an exception, I not only force the caller to handle the
exception with a catch-handler (as opposed to leaving the choice to
the caller), I also force the caller to *always* handle the exception:
if the caller wants to ignore the condition, he/she still has to write
a catch-handler and failure to do so terminates the program.

Apart from the potential performance penalty, throwing exceptions for
expected outcomes is bad also because it forces a try-catch block on
the caller. One example of this is the .NET socket API: if I do non-
blocking I/O on a socket, I get an exception if no data is ready for
reading (which is the common and expected case), and I get a zero
return value if the connection was lost (which is the uncommon and
unexpected case).

In other words, the .NET API gets this completely the wrong way round.
Code that needs to do non-blocking reads from a socket turns into a
proper mess as a result because the outcome of a read() call is tri-
state:

 * Data was available and returned: no exception

 * No data available: exception

 * Connection lost: no exception

Because such code normally lives in a loop that decrements a byte
count until the expected number of bytes have been read, the control
flow because really awkward because the successful case must be dealt
wit

Re: What is the best data structure for a very simple spreadsheet?

2010-01-03 Thread mdipierro
Perhaps this can be useful:
http://www.web2py.com/examples/spreadsheet

The code is in a single file with not dependencies and it does not
require web2py to run:
http://code.google.com/p/web2py/source/browse/gluon/contrib/spreadsheet.py

Here is a sample controller that shows you how to embed the
spreadsheet in web page:
http://code.google.com/p/web2py/source/browse/applications/examples/controllers/spreadsheet.py

Massimo



On Jan 3, 5:27 am, vsoler  wrote:
> Hi,
>
> Not sure this is the best group to post, but I cannot think of any
> other.
>
> My application would contain a limited set of "cells" represented by
> the instances of a Cell class:
>
> class Cell:
> ...
>
> A1=Cell(7)
> A2=Cell(2*A1)
> A3=Cell(3*A1+A2)
> A4=Cell(A3*4)
>
> Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140
>
> Now, I somehow want to be able to show a dependency tree
>
> 1 level dependency trees
>   A1: None
>   A2: A1
>   A3: A1, A2
>   A4: A3
>
> All levels dependency trees
>
>   A1: None
>   A2: A1
>   A3: A1, A2
>   A4: A3, A2, A1
>
> Leaf + values dependency trees:
>
>   A1: 7
>   A2: A1=7, 2
>   A3: 3, A1=7, 2
>   A4: 3, A1=7, 2, 4
>
> What I'd like to know is:
>
> 1) what are, in your opinion, the basic elements of the Cell class?
> 2) Do I need a parser to evaluate the formulas like “3*A1+A2”? Can you
> recommend one library that already contains one?
> 3) Do I need a tree data structure to represent my data? would the
> tree be an attribute of the class instance?
>
> I imagine a lot can be said on these questions. What I am looking for
> is some hints that help me get out of where I am now.
>
> Any help is highly appreciated.
>
> Vicente Soler

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


Re: HAppy New Year

2010-01-03 Thread D'Arcy J.M. Cain
On Sun, 3 Jan 2010 21:18:38 +0200
Dotan Cohen  wrote:
> Wow, I just love Windows users. Sending this to the Python list? Paste

I was going to ask him if his mommy and daddy knew that he was playing
with the grown-ups' computer.

-- 
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: twenty years ago Guido created Python

2010-01-03 Thread Ben Finney
Chris Jones  writes:

> Interesting to note that Guido's achievements prompt much less
> response, and get much less coverage […]

The entirety of ‘comp.lang.python’ is an ongoing response to Guido van
Rossum's achievements (and all the others that make Python great). Mere
week- or month-long threads are paltry by comparison.

-- 
 \“If this is your first visit to the USSR, you are welcome to |
  `\  it.” —hotel room, Moscow |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


[gtk+thread] Why worker thread never wakes from time.sleep()?

2010-01-03 Thread Dmitry Teslenko
Hello!
I have simple gui gtk app. It has worker thread that populates list
with strings and gtk window with main loop which pops strings
from this list and shows them in TreeView.

Thread runs get_data_from_pcap to populate list with strings.
Gtk app calls update_store() with gobject.timeout_add every second.

If I comment time.sleep() in update_store(),
worker thread never wakes up after his time.sleep().
Why?

Here's runnable example:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import pygtk
pygtk.require('2.0')
import gtk
import gobject

import pcap

import sys
import threading
import time

CONSOLE_ENCODING = 'utf-8'
if sys.platform == 'win32':
CONSOLE_ENCODING = 'cp866'

global_pcap_queue = []
global_pcap_lock = threading.Lock()
global_pcap_stop_event = threading.Event()

class CityGame:
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect('delete_event', self.delete_event)
window.connect('destroy', self.destroy)

store = gtk.ListStore(gobject.TYPE_STRING)

view = gtk.TreeView(store)

#name
col = gtk.TreeViewColumn('Data')
cell = gtk.CellRendererText()
view.append_column(col)
col.pack_start(cell, True)
col.add_attribute(cell, 'text', 0)

vb = gtk.VBox()
vb.pack_start(view)

window.add(vb)
window.set_size_request(400, 300)
window.show_all()

self.__store = store


def main(self):
gobject.timeout_add(1000, self.update_store)
gtk.main()

def update_store(self):
data = None

global_pcap_lock.acquire()
if len(global_pcap_queue):
data = global_pcap_queue.pop(0)
print 'Update'
global_pcap_lock.release()

time.sleep(0.01)

if data:
self.__store.append([data])

return True

def delete_event(self, widget, event, data = None):
dlg = gtk.MessageDialog(flags = gtk.DIALOG_MODAL, type =
gtk.MESSAGE_QUESTION,
buttons = gtk.BUTTONS_YES_NO,
message_format = 'Are you sure you want to quit?')
dlg.set_title('CityGame')
result = dlg.run()
dlg.destroy()
return (result != gtk.RESPONSE_YES)

def destroy(self, widget, data = None):
gtk.main_quit()

def main(args):
cg = CityGame()
cg.main()

def get_data_from_pcap():
#while True:
while not global_pcap_stop_event.isSet():
global_pcap_lock.acquire()
global_pcap_queue.append(str(time.time()))
print 'Thread'
global_pcap_lock.release()
time.sleep(0.01)
return

if __name__ == '__main__':
global_pcap_stop_event.clear()
pcap_thread = threading.Thread(target = get_data_from_pcap)
pcap_thread.start()
main(sys.argv[1:])
global_pcap_stop_event.set()
pcap_thread.join()

-- 
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing in e-mail?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HAppy New Year

2010-01-03 Thread Dotan Cohen
> What I want to know is why didn't he just write
>
> """\
> ... original long string ...
> """.replace("6", "_")
>

Uf! Why didn't I think of that?!


> But watch that snarkiness ... I'm a Windows user too!
>

That's fine, I know that fresh air has to get into the basement somehow !

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HAppy New Year

2010-01-03 Thread Steve Holden
Dotan Cohen wrote:
> 2010/1/2 baboucarr sanneh :
>> Hi guys,
>>
>> Jus want to wish you a happy new year to u all..
>>
>> 1.Copy the content below and Paste it on a Notepad.
>> 2 . Use replace all (Ctrl + H)
>> 3. Type in ‘6’ in the ‘find what’ column
>>
>> 4.   Type in _ (underscore) in the ‘replace with’ column
>>
>> 5.   Click on replace all.
>>
> 
> Wow, I just love Windows users. Sending this to the Python list? Paste
> "on a notepad"?!? The "Replace All" function in "a notepad" is
> Ctrl-H?!?? What does H stand for?!?!? Explicit instructions how to
> :%s/6/_/g in "a notepad"?!?!?
> 
> Happy new year!
> 
What I want to know is why didn't he just write

"""\
... original long string ...
""".replace("6", "_")

But watch that snarkiness ... I'm a Windows user too!

regards
 Steve

-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: HAppy New Year

2010-01-03 Thread Dotan Cohen
2010/1/2 baboucarr sanneh :
> Hi guys,
>
> Jus want to wish you a happy new year to u all..
>
> 1.Copy the content below and Paste it on a Notepad.
> 2 . Use replace all (Ctrl + H)
> 3. Type in ‘6’ in the ‘find what’ column
>
> 4.   Type in _ (underscore) in the ‘replace with’ column
>
> 5.   Click on replace all.
>

Wow, I just love Windows users. Sending this to the Python list? Paste
"on a notepad"?!? The "Replace All" function in "a notepad" is
Ctrl-H?!?? What does H stand for?!?!? Explicit instructions how to
:%s/6/_/g in "a notepad"?!?!?

Happy new year!

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best data structure for a very simple spreadsheet?

2010-01-03 Thread MRAB

vsoler wrote:

Hi,

Not sure this is the best group to post, but I cannot think of any
other.

My application would contain a limited set of "cells" represented by
the instances of a Cell class:

class Cell:
...

A1=Cell(7)
A2=Cell(2*A1)
A3=Cell(3*A1+A2)
A4=Cell(A3*4)

Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140

Now, I somehow want to be able to show a dependency tree

1 level dependency trees
  A1: None
  A2: A1
  A3: A1, A2
  A4: A3

All levels dependency trees

  A1: None
  A2: A1
  A3: A1, A2
  A4: A3, A2, A1

Leaf + values dependency trees:

  A1: 7
  A2: A1=7, 2
  A3: 3, A1=7, 2
  A4: 3, A1=7, 2, 4

What I'd like to know is:

1) what are, in your opinion, the basic elements of the Cell class?
2) Do I need a parser to evaluate the formulas like “3*A1+A2”? Can you
recommend one library that already contains one?
3) Do I need a tree data structure to represent my data? would the
tree be an attribute of the class instance?

I imagine a lot can be said on these questions. What I am looking for
is some hints that help me get out of where I am now.

Any help is highly appreciated.


As well as considering the other replies, you don't necessarily need to
parse the expressions yourself.

If A1 is a cell then 2*A1 tries to call the __rmul__ method of A1 (and
A1*2 tries to call the __mul__ method of A1), so you could have it
return a formula object that will multiply and return the numeric value
of self (A1) by 2 when its own numeric value is requested. This means
that a cell could be initialised with either a number or a formula.
--
http://mail.python.org/mailman/listinfo/python-list


Re: twenty years ago Guido created Python

2010-01-03 Thread Chris Jones
On Thu, Dec 31, 2009 at 05:06:24PM EST, Steve Howell wrote:

> FYI:
> 
> http://twitter.com/gvanrossum
> 
> Python is a truly awesome programming language.  Not only is Guido a
> genius language designer, but he is also a great project leader.  What
> an accomplishment.  Congratulations to everybody who has contributed
> to Python in the last two decades!

Interesting to note that Guido's achievements prompt much less response,
and get much less coverage, than Xah Lee's :-)

I guess Guido's not one to care much about beauty contests anyway.

HNY,

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


Re: Any Swisses here?

2010-01-03 Thread Jack Diederich
On Sat, Jan 2, 2010 at 10:38 PM, n00m  wrote:
> On Jan 3, 5:30 am, Steve Holden  wrote:
>> Zhu Sha Zang wrote:
>> >> [stuff and nonsense from a third party]
>> > WTF?
>>
>> We do get the occasional bigot dropping in from time to time. Best to
>> ignore them 'til they go away.
>>
> And who are YOU?
> What you achieved in the life?
> For me you is nothing I recall only Kipling, Dickens, Newton
> its your background. My backgroung is the best rockets


Don't be so dismissive Steve.  What we have here is clearly a
struggling young AI trying to extrapolate the average content of an
alt.group to the comp.lang community.  The fact that it passed the
gmail spam filters is a sign of progress.

So hello new friend, and your backgroung is the best rockets!

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


Re: What is the best data structure for a very simple spreadsheet?

2010-01-03 Thread Jon Clements
On Jan 3, 2:58 pm, Lie Ryan  wrote:
> On 1/3/2010 10:27 PM, vsoler wrote:
>
> > 1) what are, in your opinion, the basic elements of the Cell class?
>
> The "user-entered formula" and "effective value". A Cell containing a
> formula "abc" has a value of "abc"; a cell containing the formula "=1+5"
> has a value of "6". You could use the 'property' decorator for the
> "effective value" attribute.
>
> > 2) Do I need a parser to evaluate the formulas like 3*A1+A2 ? Can you
> > recommend one library that already contains one?
>
> Yes you do. PyParsing, regex, write your own parser; choose your own
> poison depending on the expected complexity of the formulaes.
>
> > 3) Do I need a tree data structure to represent my data?
>
> There are two main options for your "primary data structure":
> - table (2x2 list) -- if you expect most of your cells to be filled,
> this is simple, but uses lots of memory
> - sparse table (list/dicts of cells) -- if you have a large table that
> is mostly empty cells
>
> The Dependency Tree is the "side data structure"; a "Cell" is a "Node";
> a Cell's "dependencies" is the Node's "children"; a Cell's "dependant"
> is the Node's "parent". Cells maintains a list of dependencies (or
> dynamically generates them when requested) by analyzing the "formula"
> attribute for references to other cells.
>
> PS: Strictly speaking, this "side data structure" is not a "Tree" as
> there are multiple root nodes. I think it's called "Directed Acyclic
> Graph". However, it's true that, given a cell as a root, the cell's
> dependencies is a proper tree.
>
> > would the
> > tree be an attribute of the class instance?
>
> you could use 'property' decorator and make the dependency tree a
> "computed attribute" of the cell; many people recommended against a
> 'property' that is heavy to compute though and calculating dependencies
> may be quite heavy depending on the complexity of the spreadsheet.
>
> > I imagine a lot can be said on these questions. What I am looking for
> > is some hints that help me get out of where I am now.
>
> > Any help is highly appreciated.
>
> > Vicente Soler
>
>

As well as what Steven & Lie have mentioned, maybe you could get
inspiration from http://pyspread.sourceforge.net/

Although I've not looked at it, my gut feeling is the author would've
had to address these issues (take that as a disclaimer of some
sort :) )

>From not having to had a need for this sort of thing, I'd probably go
for a sparse representation as a graph.

But again, depends why you're segmenting the "spreadsheet" from "need
to tell dependencies".

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


Re: What is the best data structure for a very simple spreadsheet?

2010-01-03 Thread Lie Ryan

On 1/3/2010 10:27 PM, vsoler wrote:


1) what are, in your opinion, the basic elements of the Cell class?


The "user-entered formula" and "effective value". A Cell containing a 
formula "abc" has a value of "abc"; a cell containing the formula "=1+5" 
has a value of "6". You could use the 'property' decorator for the 
"effective value" attribute.



2) Do I need a parser to evaluate the formulas like “3*A1+A2”? Can you
recommend one library that already contains one?


Yes you do. PyParsing, regex, write your own parser; choose your own 
poison depending on the expected complexity of the formulaes.



3) Do I need a tree data structure to represent my data?


There are two main options for your "primary data structure":
- table (2x2 list) -- if you expect most of your cells to be filled, 
this is simple, but uses lots of memory
- sparse table (list/dicts of cells) -- if you have a large table that 
is mostly empty cells


The Dependency Tree is the "side data structure"; a "Cell" is a "Node"; 
a Cell's "dependencies" is the Node's "children"; a Cell's "dependant" 
is the Node's "parent". Cells maintains a list of dependencies (or 
dynamically generates them when requested) by analyzing the "formula" 
attribute for references to other cells.


PS: Strictly speaking, this "side data structure" is not a "Tree" as 
there are multiple root nodes. I think it's called "Directed Acyclic 
Graph". However, it's true that, given a cell as a root, the cell's 
dependencies is a proper tree.



would the
tree be an attribute of the class instance?


you could use 'property' decorator and make the dependency tree a 
"computed attribute" of the cell; many people recommended against a 
'property' that is heavy to compute though and calculating dependencies 
may be quite heavy depending on the complexity of the spreadsheet.



I imagine a lot can be said on these questions. What I am looking for
is some hints that help me get out of where I am now.

Any help is highly appreciated.

Vicente Soler


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


Re: Safe file I/O to shared file (or SQLite) from multi-threaded web server

2010-01-03 Thread Steve Holden
John Nagle wrote:
> pyt...@bdurham.com wrote:
>> I'm looking for the best practice way for a multi-threaded python web
>> server application to read/write to a shared file or a SQLite database.
>>
>> What do I need to do (if anything) to make sure my writes to a regular
>> file on disk or to a SQLite database are atomic in nature when multiple
>> clients post data to my application simultaneously?
> 
>SQLite can do that correctly, but SQLite isn't intended for use
> as a database engine for a busy database being used by many
> concurrent operations.  Especially if those operations involve
> updates.  Any update in SQLite locks all tables involved for the duration
> of the operation.  When SQLite hits a lock, it returns an error code, and
> the caller should retry after a delay.  If this occurs frequently in
> your application, you've hit the limits of SQLite.  Then it's
> time to move up to MySQL.
> 
Or PostgreSQL, which has superior SQL standards conformance and
excellent high-volume data performance.

>   If you have enough traffic that you need a multi-threaded web server,
> it's probably time to move up.
> 
Yes, but not to MySQL, please. Particularly since there is a sword of
Damocles hanging over its head while the Oracle takeover of Sun is pending.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2010-01-03 Thread Lie Ryan

On 12/30/2009 11:25 PM, Roald de Vries wrote:

Actually, performance is not much if an issue for what I want to do;
it's mainly interest in 'how should I do this in general'. I'll just
leave in all the code, and if it becomes a real issue, I'll separate the
code over an interactive and a non-interactive script. Thanks for your
inputs.



XP summarizes it as: You ain't gonna need it 
(http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it )

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


International Journal of Electronics, Information and Systems (IJEIS) Call for Paper

2010-01-03 Thread ijeiseditor
The International Journal of Electronics, Information and Systems
(IJEIS) publish original papers on all subjects relevant to
electronics, computer science, communication network, and information
systems. The highest priority will be given to those contributions
concerned with a discussion of the background of a practical problem,
the establishment of an appropriate model, the determination of a
solution, approximate or exact, analytical or numerical, and a
discussion of the relevance of the results when applied to the real-
life problem. Paper submissions are invited in the area of electronics
and computer science, in particular the technological advances and
research results in the fields of theoretical, experimental, and
applied electronics, computer science and Information technology.

Topics of interest include but are not limited to the following:

Electronics:

Analogue and digital circuit design,  Microwave circuits and systems,
Optoelectronic circuits, Semiconductor devices, Sensor technology,
Transport in electronic materials, VLSI technology and device
processing, Analogue Circuits and Signal Processing, Digital Circuits
and Signal Processing, RF and Wireless Circuits & Systems, Biomedical
Circuits & Systems, System Architectures and Applications, System
Integration,  SoC and Mixed-Signal disign, Design Automation of
Electronics & Systems, Assembly and Packaging, Sensing and Sensor
Networks, Photonic and Optoelectronic Circuits, Test and Reliability,
Neural Network Circuits & Systems, Heterogeneous Structures, Advanced
Technologies, Telecommunications and Multimedia, Electronic Materials,
Electronic Devices, Integrated Electronic-Circuits, Optoelectronics
&Quantum Electronics, Biomedical Engineering, Electronics
Applications, Sensing Systems, Communication and Networks, Electronic
Commerce, All topics related Electronics

Computer Science:

Parallel Processing and Distributed Computing, Foundations of High-
performance Computing, Graph Theory and Analysis of Algorithms,
Artificial Intelligences and Pattern/Image Recognitions, Neural
Networks and Biomedical Simulations, Virtual Visions and Virtual
Simulations, Data Mining, Web Image Mining and Applications, Data Base
Management and Information Retrievals Adaptive Systems, Bifurcation,
Biocybernetics, Bioinformatics, Bio-Inspired Networks, Blind Systems,
Cellular Neural Networks, Chaos, Chaos Neural Networks, Circuit
Simulation, Circuit Theory, Communication Systems, Complex Systems,
Control Systems, Cryptosystems, Data Compression, Data Mining,
Detection, Echo Canceller, Estimation, Evolutional Computation,
Filter, Filter Bank, Fractal, Fuzzy Systems, Image Processing, Image
Recognition, Internet Security, Medical Applications, Modeling,
Optimization, Speech Processing, Speech Synthesis, Speech Recognition,
Synchronization, Video Signal Processing, Watermarking, Wavelet
Transform, All topics related Computer Science
Communication Network:

Ad-Hoc, Mobile, Wireless Networks and Mobile Computing, Quantum
Computing, Coding, and Error Controls
Agent Computing and Multi-Agents Systems, Defining Spectrum Rights and
Open Spectrum Solutions, Quality of Services and Communication
Protocols, Satellite and Optical Communication Systems, 3G/4G Network
Evolutions, CDMA/GSM Communication Protocols, Mobile Computing for e-
Commerce,Transmission/Switching/Distribution
technologies,Communication Theory,Signal Processing for
Communications,Wireless Communications,Wireless & Mobile
Networking,Optical Networks and Systems,Next-Generation Networking and
Internet,Communication QoS, Reliability and Modelling,Ad-hoc, Sensor
and Mesh Networking,Multimedia Services, Communication Software and
Services,Communication and Information System Security, System
control, network/service management, Network and Internet protocols
and standards,Client-server, distributed and Web-based communication
systems, Broadband and multimedia systems and applications, Trials of
advanced systems and services, Any topics related Communication
Network

Information and Systems:

Cryptography and Foundation of Computer Security, Authentication/
Authorization Issues, IDS/Firewall, Anti-Spam mail, Anti-virus issues,
Wireless Access Security, Network Security Applications, Biometric
authentication and algorithms, Fingerprint /Hand/Biometrics
Recognitions and Technologies, IC-card Security, OTP and Key
Management Issues, E-commerce, Ubiquitous and RFID Applications,
Metadata and Meta Modeling, XML and Data Management, Knowledge
Management, Web Security and Privacy, Cyber Threats, Web Services and
Web Engineering, Web Intelligence, Wireless Applications, Protocols
and Standards, Network Systems, Proxies and Servers, Multimedia
Applications using Web Services, Ontology and the Semantic Web, B2B,
B2C and C2C, e-Business System Design and Development, e-Payment,
Portal Strategies, Social Networks and Information Systems, Social and
Legal Issues, Digital Ecology, e-Governance, e-Learning and Virtual
Cl

Re: Significant whitespace

2010-01-03 Thread Mensanator
On Jan 1, 4:02�pm, Dan Stromberg  wrote:
> I put together a page about significant whitespace (and the lack thereof).

The real problem is your use of proportional spaced fonts.

>
> You're invited to check it out:
>
> http://stromberg.dnsalias.org/~dstromberg/significant-whitespace.html

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


Re: Significant whitespace

2010-01-03 Thread John Machin
On Jan 2, 10:29 am, Roy Smith  wrote:

>
> To address your question more directly, here's a couple of ways Fortran
> treated whitespace which would surprise the current crop of
> Java/PHP/Python/Ruby programmers:
>
> 1) Line numbers (i.e. the things you could GOTO to) were in column 2-7
> (column 1 was reserved for a comment indicator).  This is not quite
> significant whitespace, it's more like significant indentation.

That would also surprise former FORTRAN programmers (who rarely
referred to the language as "Fortran"). A comment was signified by a C
in col 1. Otherwise cols 1-5 were used for statement labels (the
things you could GOTO), col 6 for a statement continuation indicator,
cols 7-72 for statement text, and cols 73-80 for card sequence numbers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing?

2010-01-03 Thread garyrob
One thing I'm not clear on regarding Klauss' patch. He says it's
applicable where the data is primarily non-numeric. In trying to
understand why that would be the case, I'm thinking that the increased
per-object memory overhead for reference-counting would outweigh the
space gains from the shared memory.

Klauss's test code stores a large number of dictionaries which each
contain just 3 items. The stored items are strings, but short ones...
it looks like they take up less space than double floats(?).

So my understanding is that the point is that the overhead for the
dictionaries is big enough that the patch is very helpful even though
the stored items are small. And that the patch would be less and less
effective as the number of items stored in each dictionary became
greater and greater, until eventually the patch might do more use more
space for reference counting than it saved by shared memory.

Is this understanding correct? (I'm hoping not, because for some
applications, I'd like to be able to use it for large dictionaries
containing lots of numbers.)

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


Re: Bare Excepts

2010-01-03 Thread myle
Why we should prefer ``if: ...'' over  a ``try: ... except something:
pass'' block?
In 
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#InitializingDictionaryElements
it is stated that a try catch block is faster if more often no
exception occurs.

Happy new year,
Dimitris Leventeas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dangerous behavior of list(generator)

2010-01-03 Thread Steven D'Aprano
On Wed, 30 Dec 2009 23:20:06 -0500, Benjamin Kaplan wrote:

>>> I used to have that a lot in cases where not finding at least one
>>> valid foo is an actual fatal error.
>>
>> What's wrong with the obvious solution?
>>
>> if not any(foo for foo in foos if foo.bar):
>>    raise ValueError('need at least one valid foo')
> 
> That would require 2 iterations through foos- once in the test, once for
> the assignment if successful. 

Remember though that any is a lazy test: it returns as soon as it gets a 
result. In the case of an empty list, it returns immediately with False, 
and in the case of a non-empty list, it returns immediately it reaches a 
true item. It doesn't matter if there are twenty thousand items, it will 
only look at the first so long as it is true.

Which of course answers my own question... what's wrong with using any is 
that it fails if the objects are all considered false in a boolean 
context, or if they might be. That means it will work for some objects 
(e.g. the re module's MatchObject instances which are always true), but 
not for arbitrary objects which may be false.



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


Re: Dynamic text color

2010-01-03 Thread Cousin Stanley

> John Posner wrote  
> 
> I've posted a complete solution 
>   
>   http://cl1p.net/jjp_dynamic_text_color/.

  John  

Thanks for posting your solution to Dave McCormick's query
about colorizing text  

I was not familiar with the re.finditer method
for searching strings or with using tags in 
Tkinter Text widgets to change text attributes  

Instead of binding the Text widget to  events
to call the colorizer on each key-stroke, I used a button
callback   

   http://cl1p.net/cs_static_text_color

This provides a static one-shot colorization after all
of the text is entered and should save a few cpu cycles 
although it's not as nifty as the dynamic process  

I used a dictionary instead of a list for position data
and also added a  { term : color }  dictionary so that 
words other than color names can be hi-lighted 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


HAppy New Year

2010-01-03 Thread baboucarr sanneh

Hi guys,

Jus want to wish you a happy new year to u all..

1.Copy the content below and Paste 
it on a Notepad.2 
. Use replace all (Ctrl + H)3. 
Type in ‘6’ in the ‘find what’ column
4.   Type in _ 
(underscore) in the ‘replace with’ column
5.   Click on 
replace all.

666
6669969966996666996996669966996666999966966
666996996699666699699999966666999969996
6669969966996699996996996699999966999999699
66699669669966996666966699996699996669966699666
6669969996996699666696669966999966999966966
666666999966996996669966999966999969996
6669996669996699666699699666996666999999699
6669969966996666996996669966666669966699666
666
666
666
66996996966666996699996996666996996
66996999996666699996999996666996996
669969966699699666999966999999669966666996699996996
6696699666996666666699699669966669966966996
66969666669999669969966669969996996
6699699999999666999999666669966
6699699666996996669999999999966669996669996
669969966996669966999999996996666996996
666
666
666
666996699666969996666699966
99996669996999999999966
69966999969969966699996699699966699999996669966
666669966699666996699696699999969669966
66699666969966699669699999966969966
6669966996699999699699699666999999966699966
666996666699699666996699666999999999966
6669966669966699669999666666666
66

Regards,
Baboucarr.


  
_
Windows Live: Friends get your Flickr, Yelp, and Digg updates when they e-mail 
you.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_3:092010-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to run a sudo command from script

2010-01-03 Thread Kent Tenney
On Fri, Jan 1, 2010 at 5:08 PM, Diez B. Roggisch  wrote:
> Kent Tenney schrieb:
>>
>> Howdy,
>>
>> A script running as a regular user sometimes wants
>> to run sudo commands.
>>
>> It gets the password with getpass.
>> pw = getpass.getpass()
>>
>> I've fiddled a bunch with stuff like
>> proc = subprocess.Popen('sudo touch /etc/foo'.split(),
>> stdin=subprocess.PIPE)
>> proc.communicate(input=pw)
>>
>> getting assorted errors with all variations I try.
>>
>> Googling says use pexpect, but I'd prefer a stdlib solution.
>
> pexpect is pure python, and it's needed. There is no easy way around the
> issue, so if you insist on not using pexpect, you re-invent the wheel and
> write the exact same code - just more error-prone, because of
> wheel-reinvention

Indeed, the requirements of this are way more complex than I guessed.
The following seems to work well, took some fiddling with EOF.

def sudo(command, password=None, prompt="Enter password "):

import pexpect

if not password:
import getpass
password = getpass.getpass(prompt)

command = "sudo " + command
child = pexpect.spawn(command)
child.expect(['ssword', pexpect.EOF])
child.sendline(password)
child.expect(pexpect.EOF)
# is this necessary?
child.close()

Thanks,
Kent

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


Re: What is the best data structure for a very simple spreadsheet?

2010-01-03 Thread vsoler
On Jan 3, 1:28 pm, Steven D'Aprano  wrote:
> On Sun, 03 Jan 2010 03:27:46 -0800, vsoler wrote:
> > My application would contain a limited set of "cells" represented by the
> > instances of a Cell class:
>
> > class Cell:
> > ...
>
> > A1=Cell(7)
> > A2=Cell(2*A1)
> > A3=Cell(3*A1+A2)
> > A4=Cell(A3*4)
>
> > Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140
>
> > Now, I somehow want to be able to show a dependency tree
>
> > 1 level dependency trees
> >   A1: None
> >   A2: A1
> >   A3: A1, A2
> >   A4: A3
>
> > All levels dependency trees
>
> >   A1: None
> >   A2: A1
> >   A3: A1, A2
> >   A4: A3, A2, A1
>
> > Leaf + values dependency trees:
>
> >   A1: 7
> >   A2: A1=7, 2
> >   A3: 3, A1=7, 2
> >   A4: 3, A1=7, 2, 4
>
> > What I'd like to know is:
>
> > 1) what are, in your opinion, the basic elements of the Cell class?
>
> def Cell(object):
>     def __init__(self, payload):
>         self.payload = payload
>     def __str__(self):
>         return str(self.payload)
>     def __float__(self):
>         return float(self.payload)
>     def dependency(self):
>         try:
>             return self.payload.dependency()
>         except AttributeError:
>             return ['None']
>
> Cells can contain one of three things: a number, a string, or a formula.
> The first two can be supported by providing a built-in Python object
> (float or str) as payload. You can support formulae two ways that I can
> think of:
>
> (1) Provide a formula as a string, with a leading '='. Then, whenever you
> want to evaluate such a cell, you fetch the string from the cell, parse
> it, generate an arithmetic expression, and calculate it.
>
> (2) Instead of parsing the formula on every single spreadsheet refresh,
> use a couple of helper classes:
>
> class Indirect(object):
>     def __init__(self, ref, sheet=None):
>         if sheet is None:
>             self.sheet = default_sheet()
>         else:
>             self.sheet = sheet
>         self.ref = ref
>     def __str__(self):
>         return str(self.sheet[self.ref])
>     def float(self):
>         return float(self.sheet[self.ref])
>     def dependency(self):
>         return [self.ref]
>
> class Formula(object):
>     def __init__(self, x, y, op):
>         self.x = x
>         self.y = y
>         self.op = op
>     def eval(self):
>         return self.op(float(x), float(y))
>     def dependency(self):
>         return self.x.dependency(level) + self.y.dependency(level)
>
> Then do something like this:
>
> sheet = {}
> sheet['A1'] = Cell(7)
> sheet['A2'] = Cell(Formula(2, Indirect('A1'), operator.mul))
> sheet['A3'] = Cell(
>   Formula(
>     Formula(3, Indirect('A1'), operator.mul),
>     Indirect('A2'),
>     operator.add
>     ))
> sheet['A4'] = Cell(Formula(Indirect('A3'), 4, operator.mul))
>
> Then you only need to parse each human-readable formula like '=2*A1' once.
>
> > 2) Do I need a parser to evaluate the formulas like “3*A1+A2”?
>
> Yes.
>
> > Can you recommend one library that already contains one?
>
> Try PyParsing.
>
> > 3) Do I need a tree
> > data structure to represent my data? would the tree be an attribute of
> > the class instance?
>
> I suspect a dict will be faster.
>
> To get the dependencies of each cell:
>
> for key, value in sheet.items():
>     print key, value.dependency()
>
> Keep in mind I haven't tested ANY of this -- it is entirely stream of
> consciousness. I've never actually done this, so I have no idea whether
> it is a good approach or not, but it seems to me that it might be.
>
> --
> Steven

WOW!!!
After lunch I am going to read your post thoroughly, but I can already
see that you've put into it a lot of time and expertise.

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


Re: What is the best data structure for a very simple spreadsheet?

2010-01-03 Thread Steven D'Aprano
On Sun, 03 Jan 2010 03:27:46 -0800, vsoler wrote:

> My application would contain a limited set of "cells" represented by the
> instances of a Cell class:
> 
> class Cell:
> ...
> 
> A1=Cell(7)
> A2=Cell(2*A1)
> A3=Cell(3*A1+A2)
> A4=Cell(A3*4)
> 
> Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140
> 
> Now, I somehow want to be able to show a dependency tree
> 
> 1 level dependency trees
>   A1: None
>   A2: A1
>   A3: A1, A2
>   A4: A3
> 
> All levels dependency trees
> 
>   A1: None
>   A2: A1
>   A3: A1, A2
>   A4: A3, A2, A1
> 
> Leaf + values dependency trees:
> 
>   A1: 7
>   A2: A1=7, 2
>   A3: 3, A1=7, 2
>   A4: 3, A1=7, 2, 4
> 
> What I'd like to know is:
> 
> 1) what are, in your opinion, the basic elements of the Cell class?

def Cell(object):
def __init__(self, payload):
self.payload = payload
def __str__(self):
return str(self.payload)
def __float__(self):
return float(self.payload)
def dependency(self):
try:
return self.payload.dependency()
except AttributeError:
return ['None']


Cells can contain one of three things: a number, a string, or a formula.
The first two can be supported by providing a built-in Python object 
(float or str) as payload. You can support formulae two ways that I can 
think of:

(1) Provide a formula as a string, with a leading '='. Then, whenever you 
want to evaluate such a cell, you fetch the string from the cell, parse 
it, generate an arithmetic expression, and calculate it.

(2) Instead of parsing the formula on every single spreadsheet refresh, 
use a couple of helper classes: 

class Indirect(object):
def __init__(self, ref, sheet=None):
if sheet is None:
self.sheet = default_sheet()
else:
self.sheet = sheet
self.ref = ref
def __str__(self):
return str(self.sheet[self.ref])
def float(self):
return float(self.sheet[self.ref])
def dependency(self):
return [self.ref]

class Formula(object):
def __init__(self, x, y, op):
self.x = x
self.y = y
self.op = op
def eval(self):
return self.op(float(x), float(y))
def dependency(self):
return self.x.dependency(level) + self.y.dependency(level)



Then do something like this:

sheet = {}
sheet['A1'] = Cell(7)
sheet['A2'] = Cell(Formula(2, Indirect('A1'), operator.mul))
sheet['A3'] = Cell(
  Formula(
Formula(3, Indirect('A1'), operator.mul), 
Indirect('A2'), 
operator.add
))
sheet['A4'] = Cell(Formula(Indirect('A3'), 4, operator.mul))


Then you only need to parse each human-readable formula like '=2*A1' once.


> 2) Do I need a parser to evaluate the formulas like “3*A1+A2”? 

Yes.

> Can you recommend one library that already contains one? 

Try PyParsing.


> 3) Do I need a tree
> data structure to represent my data? would the tree be an attribute of
> the class instance?

I suspect a dict will be faster.


To get the dependencies of each cell:

for key, value in sheet.items():
print key, value.dependency()


Keep in mind I haven't tested ANY of this -- it is entirely stream of 
consciousness. I've never actually done this, so I have no idea whether 
it is a good approach or not, but it seems to me that it might be.



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


Re: Windows 7 : any problems installing or running Python ?

2010-01-03 Thread python
David,

Try disabling your firewall software momentarily to see if that
makes a difference. IDLE uses a local port for inter-process
communication - you may need to configure your firewall to allow
IDLE's port usage.

To test whether Python itself has been properly installed, open
up a cmd prompt, change your current directory to the folder
where you installed Python, create the short, 1 line script that
follows, and then run it. If this works, then Python has been
successfully installed on your workstation and the problem you're
having is specific to IDLE.

1 line script (place in hello.py)

print "Hello world"

Command line to run above script:

python hello.py

You might also try installing an alternate Python build, eg. if
you installed from python.org, then try one of the setups from
ActiveState. Or vice-versa.

We're running Python 2.6.4 on Windows XP (32-bit), Windows Vista
(32 and 64-bit), and Windows 7 (32 and 64-bit) without problem.

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


What is the best data structure for a very simple spreadsheet?

2010-01-03 Thread vsoler
Hi,

Not sure this is the best group to post, but I cannot think of any
other.

My application would contain a limited set of "cells" represented by
the instances of a Cell class:

class Cell:
...

A1=Cell(7)
A2=Cell(2*A1)
A3=Cell(3*A1+A2)
A4=Cell(A3*4)

Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140

Now, I somehow want to be able to show a dependency tree

1 level dependency trees
  A1: None
  A2: A1
  A3: A1, A2
  A4: A3

All levels dependency trees

  A1: None
  A2: A1
  A3: A1, A2
  A4: A3, A2, A1

Leaf + values dependency trees:

  A1: 7
  A2: A1=7, 2
  A3: 3, A1=7, 2
  A4: 3, A1=7, 2, 4

What I'd like to know is:

1) what are, in your opinion, the basic elements of the Cell class?
2) Do I need a parser to evaluate the formulas like “3*A1+A2”? Can you
recommend one library that already contains one?
3) Do I need a tree data structure to represent my data? would the
tree be an attribute of the class instance?

I imagine a lot can be said on these questions. What I am looking for
is some hints that help me get out of where I am now.

Any help is highly appreciated.

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


Re: Dynamic text color

2010-01-03 Thread Dave McCormick

John,
Interesting and confusing...
I tested my code on Ubuntu 8.04, Win XP and 7, and WinMob before I 
called it "good".  And of course your modifications work on all too.


"""
* rename get_position() to get_complete_text()
* replace new_Rword(), new_Bword(), and new_Gword() with a single 
function that has an extra parameter, "color".

"""
The first easy, the second is going to take some thinking
Keep at it I will.  I am hooked!!!  Being able to write once and run on 
all of the above platforms is amazing!!!


Thanks again!!!
Dave

John Posner wrote:

On Sat, Jan 2, 2010 at 1:47 PM, Dave McCormick wrote:


WooHoo!!!
I got it!!! Yup, I am sure it can be optimized but it works!!!


Dave, please ignore a couple of my bogus complaints in the previous 
message:


   ... you call function new_Rword() before you define it

   ... this version also has the advantage of defining each function 
just once, instead of multiple times on each keystroke



But I stand by my overall statement that the program didn't work for 
me, and that rearranging the lines produces a working program.


-John

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