Executing python script in non-interactive mode on cygwin (windows)

2006-01-23 Thread Pankaj
I am facing a very basic problem as any new bie would face.

I know perl and now i want to use python

In perl, it is very simple , just
 "perl scriptname.pl"
will execute the script.

But i think python is worse than perl

It takes to interactive mode , which i don;t want to use.

"python scriptname.py"
does not execute python script

It was, i don't know executing it or not.

1. I placed these contents in a file named "1.py"
a,b=0,1
n=5
while n<=0:
print b
a=b
b=a+b
n=n-1
print n

Then

2.
on "cygwin shell in windows"
i gave  "python 1.py"

hoping that  it will exeucte and give me output, but nothing was
printed

Does python not support teh non-interactive mode of execution

I have the manuals  and they dont' specify this thing anywhere.  they
tell use "python -c filename"


Please help.
A newbie's request.

Pankaj
i gav

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


Re: Executing python script in non-interactive mode on cygwin (windows)

2006-01-23 Thread Fredrik Lundh
"Pankaj" wrote:

> I know perl and now i want to use python
>
> In perl, it is very simple , just
>  "perl scriptname.pl"
> will execute the script.
>
> But i think python is worse than perl
>
> It takes to interactive mode , which i don;t want to use.
>
> "python scriptname.py"
> does not execute python script
>
> It was, i don't know executing it or not.
>
> 1. I placed these contents in a file named "1.py"
> a,b=0,1
> n=5
> while n<=0:
> print b
> a=b
> b=a+b
> n=n-1
> print n
>
> Then
>
> 2.
> on "cygwin shell in windows"
> i gave  "python 1.py"
>
> hoping that  it will exeucte and give me output, but nothing was
> printed
>
> Does python not support teh non-interactive mode of execution

> n=5
> while n<=0:

not sure about Perl, but in Python, five is not less than or equal
to zero.

maybe you meant to write:

n=5
while n >= 0:

?





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


Re: Executing python script in non-interactive mode on cygwin (windows)

2006-01-23 Thread Pankaj
Thanks  

it was my mistake

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


Re: Executing python script in non-interactive mode on cygwin (windows)

2006-01-23 Thread Sybren Stuvel
Pankaj enlightened us with:
> But i think python is worse than perl

No it isn't.

> It takes to interactive mode , which i don;t want to use.

Then don't use it.

> "python scriptname.py"
> does not execute python script

Yes it does.

> 1. I placed these contents in a file named "1.py"
> a,b=0,1
> n=5
> while n<=0:

Which is immediately false.

> on "cygwin shell in windows"
> i gave  "python 1.py"
>
> hoping that  it will exeucte and give me output, but nothing was
> printed

Which is correct for your program.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling python from C#...

2006-01-23 Thread Jens Theisen
There is IronPython which compiles to .NET. And there was another project  
bridging the .NET runtime with the standard Python interpreter of which I  
forgot the name.

Jens

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


Re: Decimal vs float

2006-01-23 Thread Bengt Richter
On Sat, 21 Jan 2006 14:28:20 +1100, Steven D'Aprano <[EMAIL PROTECTED]> wrote:

>On Fri, 20 Jan 2006 04:25:01 +, Bengt Richter wrote:
>
>> On Thu, 19 Jan 2006 12:16:22 +0100, =?ISO-8859-1?Q?Gerhard_H=E4ring?= 
>> <[EMAIL PROTECTED]> wrote:
>> [...]
>>>
>>>floating points are always imprecise, so you wouldn't want them as an 
>> Please, floating point is not "always imprecise." In a double there are
>> 64 bits, and most patterns represent exact rational values. Other than
>> infinities and NaNs, you can't pick a bit pattern that doesn't have
>> a precise, exact rational value. 
>
>Of course every float has a precise rational value.
>0.11 has a precise rational value:
>
>11/100
>
Good, I'm glad that part is clear ;-)

>But that's hardly what people are referring to. The question isn't whether
"people"?
>every float is an (ugly) rational, but whether every (tidy) rational is a
>float. And that is *not* the case, simple rationals like 1/10 cannot be
>written precisely as floats no matter how many bits you use. 
See the next statement below. What did you think I meant?
>
>> You can't represent all arbitarily chosen reals exactly as floats, that's 
>> true,
>> but that's not the same as saying that "floating points are always 
>> imprecise."
>
>"Always" is too strong, since (for example) 1/2 can be represented
>precisely as a float. But in general, for any "random" rational value N/M,
>the odds are that it cannot be represented precisely as a float. And
>that's what people mean when they say floats are imprecise.
That's what *you* mean, I take it ;-) I suspect what most people mean is that 
they don't
really understand how floating point works in detail, and they'd rather not 
think about it
if they can substitute a simple generalization that mostly keeps them out of 
trouble ;-)

Besides, "cannot be represented precisely" is a little more subtle than numbers 
of bits.
E.g., one could ask, how does the internal floating point bit pattern for 
0.10001
(which incidentally is not the actual exact decimal value of the IEEE 754 bit 
pattern --
0.155511151231257827021181583404541015625 is the exact value)
*not* "represent" 0.1 precisely? E.g., if all you are interested in is one 
decimal fractional
digit, any float whose exact rational value is f where .05 <= f < 0.15 could be 
viewed as one
in a (quite large) set of peculiar error-correcting codes that all map to the 
exact value you
want to represent. This is a matter of what you mean by "represent" vs what is 
represented.
Float representations are just codes made of bits. If what you want is for 
'%5.2f'%f to
produce two reliably exact decimal fractional digits, you have a lot of choices 
for f. Chances
are f = 0.1 won't make for a surprise, which in some sense means that the float 
bits behind float('.1')
"represented" .1 exactly, even though they did so by way of an unambiguously 
associated nearby
but different mathematically exact value.

BTW, equally important to precision of individual numbers IMO is what happens 
to the precision of
results of operations on inexactly represented values. How do errors accumulate 
and eventually
cause purportedly precise results to differ from mathematically exact results 
more than the advertised
precision would seem to allow? This kind of question leads to laws about when 
and how to round,
and definition of legal usage for factors e.g. converting from one currency to 
another, where
the inverse conversion factor is not a mathematical inverse.

Practicality is beating up on purity all over the place ;-)

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


Re: Who is www.python.org for? (was Re: New Python.org website ?)

2006-01-23 Thread Tim Parkin
Terry Hancock wrote:
> On 22 Jan 2006 14:18:18 -0800
> *I* don't want a "slick brochure" for Python as the website.
> 
> For all the commercial value in Python (and there is plenty,
> I am sure), it's not Java, and I don't want it to be.  I'm
> cool with suits loving it too, but I don't want to have to
> put on a suit to play. Python is an absolutely top-notch
> free software language for free software developers, not
> least of which are the amateurs, who program for love, not
> money.
> 
> I hesitate to express this opinion, because I don't want to
> seem intolerant (and I'm going to use whatever site there
> is), but if the suits can get their own place and leave me
> alone, I'm for that. ;-)
Cool!... I think thats exactly what we are after also. Only the home
page plus a handful of interior pages (in the about section) will be
targeted at businessmesn, developers and users. The rest of the site
will stay pretty much untouched (albeit cleaning up the html, ensuring
accessibility also adding consistent navigation to aid usability)


> 
> For me, the most important function of the python.org site
> is as a quick-reference to deeper documentation that I
> actually need in the process of writing Python code.
> 
All of these functions will still be in place.

> I don't really know if I'm the "market" for this site. I'm
> already sold on Python, after all, I just want something
> useful that I can use to stay up-to-date, and to find other
> Python resources if they move, get created, or if I just
> lose track of the URLs.
> 
you shouldn't have a problem at all then. Developers are the primary
marketing for the site. The home page is the only one that needs to
server multiple purposes and we're trying to balance those multiple
purposes between developers who come to the python site for the first
time and business people who come to python for the first time. The
homepage isn't very often used by people who are already developing or
using python, apart from to view news and to use the navigation to find
deeper content.

What I'd like is to add a 'developer homepage' that includes lots of rss
feeds from python related sites, cheeseshop announcements, etc, etc.
Then the majority of developers can bookmark a really useful page.

Tim

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


Re: Redirecting standard out in a single namespace

2006-01-23 Thread Bengt Richter
On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <[EMAIL PROTECTED]> wrote:

>Hello,
>
>I'm trying to redirect standard out in a single namespace.
>
>I can replace sys.stdout with a custom object - but that affects all
>namespaces.
>
>There will be code running simultaneously that could import sys
>afterwards - so I don't want to make the change in the sys module.
>
>I have an idea to redefine __import__ for the relevant namespace - so
>that an attempt to import sys will return a different module with a
>custom object for stdout. As sys is a builtin module this might not
>work for the print statement, which is what I want to redirect.
>
>I'm not in a position to test my idea until later :
>
>__import = __import__
>def __import__(name):
>if name == 'sys':
>return __import('newsys')
>else:
>return __import(name)
>
>import sys
>
>Is there another way to shadow the sys module from a single namespace ?
>
It wouldn't be shadowing, but I suppose you could replace sys.stdout with
a custom object whose methods check where they were called from.
Then you could give the object initialization parameters as to which namespace
you want to have the effect in, and/or methods to control the action or turn
it on or off etc. BTW, how about stderr?

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


Re: Read from Serial Port

2006-01-23 Thread Neil Benn
Casey Bralla wrote:

>I'd like to read ASCII data from a serial port, but (once again) I'm having
>trouble getting started.  (Can't seem to find the basic level of docs to
>get going )
>
>I'd like to use only standard "built-in" modules if possible.
>
>Could somebody offer a simple code-snippet to get me started reading from a
>serial port?
>
>Thanks!
>  
>
Here's some code which should help to get you started, I thought rather 
than leaving you in the hands of Google (which is not your friend, no 
more than MaccyDs is, as Flavour Flav said - 'Don;t believe the hype'), 
this may be helpful :

Here's a bit cut out from my own code using pySerial - some of the 
variables are not detailed but you can get the idea :

self.__objSerialPort = serial.Serial(self._dctConnectionParams
 ['ConnectionID'],
 self._dctConnectionParams
 ['BaudRate'],
 self._dctConnectionParams
 ['DataBits'],
 self._dctConnectionParams
 ['Parity'],
 self._dctConnectionParams
 ['StopBits'],
 1, #TimeOut
 
int(self._dctConnectionParams
 ['XONXOFF']),
 
int(self._dctConnectionParams
 ['RTSCTS']))

To send data with pyserial, you do this :

self.__objLock.acquire()
try:
try:
self.__objSerialPort.write(pStrMessage)
except StandardError:
self._objCurrentState = self._STATUS_CONSTS.ERROR
raise
else:
self._objCurrentState = self._STATUS_CONSTS.CONNECTED
finally:
self.__objLock.release()

The lock on this isn't needed for single threaded code but I would 
recommend making a class which deals with the communication in a 
thread-safe manner (the connection and disconnection as well - the above 
bit should be in a lock as well).

PySerial doesn't have the concept of Observer patterns to get 
message coming back in so you'll have to make a polling thread to 
observe the serial port when you want to read data, here's the checking 
bit - I'll leave the threading and observers up to you:

def __checkSerial(self):
"""
Checks serial port to see if anything is available to read
"""
self.__objLock.acquire()
try:
try:
intNoChars = self.__objSerialPort.inWaiting()
if intNoChars > 0:
strReceivedString = 
self.__objSerialPort.read(intNoChars)
self.fireNewMessage(strReceivedString)
except:
raise   
finally:
self.__objLock.release()

PySerial wraps all the platform specific stuff you, so you should 
really use that, it behaves fairly well - the only real problem is a 
lack of an observer interface but you can solve that as detailed above.  
One final thing, don;t forget that RS232 isn't  really a standard - it's 
more like a rumour :-).

Cheers,

Neil

-- 

Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 47
D-01307
Dresden
Germany

Tel : +49 (0)351 4173 154
e-mail : [EMAIL PROTECTED]
Cenix Website : http://www.cenix-bioscience.com

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


Re: OT: excellent book on information theory

2006-01-23 Thread Steven D'Aprano
On Sun, 22 Jan 2006 17:15:21 -0500, val bykoski wrote:

> The existing (formal) language, being helpful, was created 
> hundreds years ago and of course needs an update.

How does this follow? Why does something need to be updated *just* because
it was created hundreds of years ago? Isn't it more likely that having
passed the test of time, something that old is going to be better than
some untested, untried new invention?


-- 
Steven.

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


CFP: IAENG International Workshop on Software Engineering (in IMECS 2006)

2006-01-23 Thread imecs_2006
Call for Papers From:
International Association of Engineers (http://www.iaeng.org)
Journal Engineering Letters (http://www.engineeringletters.com)

The 2006 IAENG International Workshop on Software Engineering

(Part of The International MultiConference of Engineers and Computer
Scientists IMECS 2006)

IMECS 2006: 20-22 June, 2006, Hong Kong
http://www.iaeng.org/IMECS2006/IWSE2006.html


The IWSE'06 workshop is held as part of the International
MultiConference of Engineers and Computer Scientists 2006. The IMECS
2006 is organized by the International Association of Engineers
(IAENG), and serves as good platforms for the engineering community
members to meet with each other and to exchange ideas. Extended version
of the papers under this workshop can be included in the special issue
of our journal Engineering Letters. And, further extended version can
also be included in a book called "Current Trends in Software
Engineering " to be published by IAENG.

The IMECS 2006 multiconference has the focus on the frontier topics in
the theoretical and applied engineering and computer science subjects.
It consists of 14 workshops (see the details at IMECS website:
www.iaeng.org/IMECS2006). The multiconference serves as good platforms
for the engineering community members of different disciplines to meet
with each other and to exchange ideas. The current conference committee
of the IMECS 2006 includes over 140 workshop co-chairs and committee
members of mainly research center heads, department heads, professors,
research scientists from over 20 countries, while a few of the
committee members are also experienced software development directors
and engineers.

All submitted papers will be under peer review and accepted papers will
be published in the conference proceeding (ISBN: 988-98671-3-3). The
abstracts will be indexed and available at major academic databases.
The Technology Research Databases (TRD) of CSA (Cambridge Scientific
Abstracts), DBLP and Computer Science Bibliographies have promised to
index the print proceeding in advance of its publication. And after the
publication of the proceeding, print copies will also be sent to
databases like IEE INSPEC, Engineering Index (EI) and ISI Thomson
Scientific for indexing. The accepted papers will also be considered
for publication in the special issues of the journal Engineering
Letters. Some participants may also be invited to submit extended
version of their conference papers for considering as book chapters
(soon after the conference).


The topics of the workshop include, but not limited to, the following:

Software requirements engineering
Software architecture design
Software reusable components
Software testing and analysis
Software processes and workflows
Software safety, security and reliability
Software maintenance
Reverse engineering
Grid software
Software economics
Distribution systems
Programming languages
Embedded software systems
And their applications


=
Submission:

Prospective authors are invited to submit their draft paper in abstract
format (one page) or in full paper format to [EMAIL PROTECTED] by 12
March, 2006. The submitted file can be in MS Word format, PS format, or
PDF formats.

The first page of the draft paper should include:

· Title of the paper;
· Name, affiliation and e-mail address for each author;
· A maximum of 5 keywords of the paper;

Also, the name of the workshop session that the paper is being
submitted to should be stated in the email.


=
Important Dates:

Proposals for special conference sessions and tutorials deadline: 30
December, 2005
Draft Manuscript / Abstract submission deadline: 12 March, 2006
Camera-Ready papers & Pre-registration due: 2 April, 2006
IMECS 2006: 20-22 June, 2006


More details about the IWSE 2006 can be found at:
http://www.iaeng.org/IMECS2006/IWSE2006.html


IWSE Workshop Co-chairs and Committee Members:

Chin-Chen Chang
IEEE Fellow, IEE Fellow
Chair Professor in Department of Information Engineering and Computer
Science, Feng Chia University, Taiwan

Zonghua Gu (co-chair)
Assistant Professor
Dept. of Computer Science,
Hong Kong University of Science and Technology, HK

Pao-Ann Hsiung
Associate Professor, Institute of Computer Science and Information
Engineering
National Chung Cheng University, Taiwan

Quah Tong Seng (co-chair)
Professor of Information Communication Institute of Singapore (ICIS)
Nanyang Technological University, Singapore

Chen-Hua She (co-chair)
Assistant Professor, Department of Mechanical and Automation
Engineering
Da-Yeh University, Taiwan




It will be highly appreciated if you can circulate these calls for
papers to your colleagues.

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

Re: Some thougts on cartesian products

2006-01-23 Thread Bryan Olson
Christoph Zwerschke wrote:
[...]
> That may be the main problem to decide whether the cartesian product 
> should return a generator or a list.

The Cartesion product is a set.

[...]
> That's the other problem. The uses cases (like the password cracker 
> example) are very limited and in these cases you can either write nested 
> loops or write your own cartesian product.

Cartesian product is one of the essential operations of
relational algebra; in that context it's widely useful.
By itself, it's usually not what one wants.


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


CFP: IAENG International Workshop on Computer Science (in IMECS 2006)

2006-01-23 Thread imecs2006
Call for Papers From:
International Association of Engineers (http://www.iaeng.org)
Journal Engineering Letters (http://www.engineeringletters.com)


The 2006 IAENG International Workshop on Computer Science

(Part of The International MultiConference of Engineers and Computer
Scientists IMECS 2006)

IMECS 2006: 20-22 June, 2006, Hong Kong
http://www.iaeng.org/IMECS2006/IWCS2006.html


The IWCS'06 workshop is held as part of the International
MultiConference of Engineers and Computer Scientists 2006. The IMECS
2006 is organized by the International Association of Engineers
(IAENG), and serves as good platforms for the engineering community
members to meet with each other and to exchange ideas. Extended version
of the papers under this workshop can be included in the special issue
of our journal Engineering Letters. And, further extended version can
also be included in a book called "Current Trends in Computer Science"
to be published by IAENG.

The IMECS 2006 multiconference has the focus on the frontier topics in
the theoretical and applied engineering and computer science subjects.
It consists of 14 workshops (see the details at IMECS website:
www.iaeng.org/IMECS2006). The multiconference serves as good platforms
for the engineering community members of different disciplines to meet
with each other and to exchange ideas. The current conference committee
of the IMECS 2006 includes over 140 workshop co-chairs and committee
members of mainly research center heads, department heads, professors,
research scientists from over 20 countries, while a few of the
committee members are also experienced software development directors
and engineers.

All submitted papers will be under peer review and accepted papers will
be published in the conference proceeding (ISBN: 988-98671-3-3). The
abstracts will be indexed and available at major academic databases.
The Technology Research Databases (TRD) of CSA (Cambridge Scientific
Abstracts), DBLP and Computer Science Bibliographies have promised to
index the print proceeding in advance of its publication. And after the
publication of the proceeding, print copies will also be sent to
databases like IEE INSPEC, Engineering Index (EI) and ISI Thomson
Scientific for indexing. The accepted papers will also be considered
for publication in the special issues of the journal Engineering
Letters. Some participants may also be invited to submit extended
version of their conference papers for considering as book chapters
(soon after the conference).



The topics of the workshop include, but not limited to, the following:

Theoretical computer science:
Algorithmic information theory
Computability theory
Cryptography
Formal semantics
Theory of computation
Analysis of algorithms and problem complexity
Logics and meanings of programs
Mathematical logic and Formal languages
Type theory

Hardware:
Control structures and Microprogramming
Arithmetic and Logic structures
Memory structures
Input/output and Data communications
Logic Design
Integrated circuits
VLSI design
Performance and reliability

Computer systems organization:
Computer architecture
Computer networks
Distributed computing
Performance of systems
Computer system implementation

Computing methodologies:
Symbolic and Algebraic manipulation
Artificial intelligence
Computer graphics
Image processing and computer vision
Pattern recognition
Speech recognition
Simulation and Modeling
Document and text processing
Digital signal processing
   Computer applications:
Administrative data processing
Enterprise resource planning
Customer relationship management
Human Resource Management Systems
Mathematical software
Numerical analysis
Automated theorem proving
Computer algebra systems
Physical science and Engineering
Computational chemistry
Computational physics
Life and medical sciences
Bioinformatics
Computational biology
Medical informatics
Social and behavioral sciences
Computer-aided engineering
Robotics
Human-computer interaction
Speech synthesis
Usability engineering
Telecommunications
Queueing theory


=
Submission:

Prospective authors are invited to submit their draft paper in abstract
format (one page) or in full paper format to [EMAIL PROTECTED] by 12
March, 2006. The submitted file can be in MS Word format, PS format, or
PDF formats.

The first page of the draft paper should include:

· Title of the paper;
· Name, affiliation and e-mail address for each author;
· A maximum of 5 keywords of the paper;

Also, the name of the workshop session that the paper is being
submitted to should be stated in the email.


=
Important Dates:

Proposals for special conference sessions and tutorials deadline: 30
December, 2005
Draft Manuscript / Abstract submission deadline: 12 March, 2006
Camera-Ready papers & Pre-registration due: 2 April, 2006
IMECS 2006: 20-22 June, 2006


More details about the IWIWCS 2006 can be found at:
http://www.iaeng.org/IMECS2006/IWCS2006.html


IWCS Workshop Co-chairs and Committee Members:

Chin

Re: Python code written in 1998, how to improve/change it?

2006-01-23 Thread Bengt Richter
On Mon, 23 Jan 2006 08:53:59 +1300, Carl Cerecke <[EMAIL PROTECTED]> wrote:

>Bengt Richter wrote:
>> On Thu, 19 Jan 2006 23:16:57 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:
>
>> How about something like
>> 
>>  >>> actions = dict(
>>  ...a=compile('print "A"; state="b"','','exec'),
>>  ...b=compile('print "B"; state="c"','','exec'),
>>  ...c=compile('print "C"; state=None','','exec')
>>  ... )
>>  >>> state = 'a'
>>  >>> while state: eval(actions[state])
>>  ...
>>  A
>>  B
>>  C
>
>Good idea. But we can eliminate the dictionary lookup:
>
>a1 = compile('print "A"; state=b1','','exec')
>b1 = compile('print "B"; state=c1','','exec')
>c1 = compile('print "C"; state=None','','exec')
>
>state = a1
>while state:
> eval(state)
>
Cool. But unfortunately, neither version works inside a function's local 
namespace.
Using exec instead of eval seems to do it in either context though.
Now, how can we get optimized code (i.e., LOAD_FAST vs LOAD_NAME etc in a1 etc)
without byte code hackery?

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


Re: Arithmetic sequences in Python

2006-01-23 Thread Steven D'Aprano
On Sun, 22 Jan 2006 16:40:48 -0800, Paul Rubin wrote:

> Steve Holden <[EMAIL PROTECTED]> writes:
>> > The current list function is supposed to be something like a
>> > typecast:
>> >
>> list() isn't a function, it's a type.
> 
> I'm not sure what the distinction is supposed to be.  "list" is anyway
> callable, and lambda a:list(a) is certainly a function. 


class Parrot:
def __init__(self):
pass

Parrot is callable. Is it a function?


Types are types, classes are classes, functions are functions.

Admittedly I still confused between the various flavours of functions
(function, bound method, unbound method, class method, static method...)
*wink* but the difference between types and functions is fairly clear.

Just don't ask about the difference between type and class... *wink*



-- 
Steven.

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


Re: Some thougts on cartesian products

2006-01-23 Thread Steven D'Aprano
On Mon, 23 Jan 2006 01:25:36 +, Bryan Olson wrote:

>> Sometimes I was missing such a feature.
>> What I expect as the result is the "cartesian product" of the strings.
> 
> There's no such thing; you'd have to define it first. Are duplicates
> significant? Order?

Google "cartesian product" and hit "I'm feeling lucky".

Or go here: http://mathworld.wolfram.com/CartesianProduct.html

Still think there is no such thing?



-- 
Steven.

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


Re: Some thougts on cartesian products

2006-01-23 Thread Steven D'Aprano
On Mon, 23 Jan 2006 10:36:55 +, Bryan Olson wrote:

> Christoph Zwerschke wrote:
> [...]
>> That may be the main problem to decide whether the cartesian product 
>> should return a generator or a list.
> 
> The Cartesion product is a set.

And the generalization of mathematical sets in Python can be built-in
sets, lists or tuples, depending on what you need.

Given that cartesian products tend to be *extremely* large, some sort of
iterator is the only practical solution -- even if that's not
mathematically pure.


> [...]
>> That's the other problem. The uses cases (like the password cracker 
>> example) are very limited and in these cases you can either write nested 
>> loops or write your own cartesian product.
> 
> Cartesian product is one of the essential operations of
> relational algebra; in that context it's widely useful.
> By itself, it's usually not what one wants.

Google on "Cartesian product python" and you will find thousands of hits.
This is something that keeps coming up over and over again.

Personally, I think cartesian products, together with permutations and
combinations, belong in a module, not built-ins.



-- 
Steven.

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


Re: Redirecting standard out in a single namespace

2006-01-23 Thread Pan Menghan
Maybe you can use __name__ to determine which module the print statement is in:class out: def write(s,a): if __name__ =="myModule": mylog.write(a) else:
 sys.__stdout__.write(a)sys.stdout = out()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Some thougts on cartesian products

2006-01-23 Thread Erik Max Francis
Bryan Olson wrote:

> Christoph Zwerschke wrote:
> [...]
>> That may be the main problem to decide whether the cartesian product 
>> should return a generator or a list.
> 
> The Cartesion product is a set.

Sets are iterable, so that isn't an answer.  If it's a set, then it 
should either be a generator or a set.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Nothing is potent against love save impotence.
   -- Samuel Butler
-- 
http://mail.python.org/mailman/listinfo/python-list


Testing for the presence of input from stdin.

2006-01-23 Thread Will McDonald
Hi all.

I'm writing a little script that operates on either stdin or a file
specified on the command line when run. I'm trying to handle the
situation where the script's run without any input gracefully but
can't think how to test for stdin.

I can test for a file argument on the command line using getopt and
validate its existence with os.path.exists. If it doesn't I can print
the useage.

I can get the script to behave as expected when content's piped to it
using sys.stdin but I'd like to know that there's data coming from
stdin or fail and print the useage again. Is there a simple way to
achieve this?

Thanks,

Will.

Here's what I've got so far...

#!/usr/bin/python
#
# hail - heads and tails

import sys, os, getopt

def hail(file,headlines=10,taillines=10):
lines = file.readlines()
sys.stdout.writelines(lines[:headlines])
sys.stdout.writelines(lines[taillines:])

def useage():
print "Useage: hail [OPTION] [FILE]"
print "  -t, --top  # lines from top (default 10)"
print "  -b, --bottom   # lines from bottom (default 10)"
print "  -h, --help display this help and exit"

def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "t:b:h",
['top=','bottom=','help'])
except getopt.GetoptError:
useage()
sys.exit(2)
for o,a in opts:
if o in ("-t", "--top"):
toplines = a
if o in ("-b", "--bottom"):
bottomlines = a
if o in ("-h", "--help"):
useage()
sys.exit()
if len(args) == 1 and os.path.exists(str(args[0])):
file = (str(args[0]))
# else:
#   file = sys.stdin
hail(file,headlines=toplines,taillines=bottomlines)

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


Pyro problems...

2006-01-23 Thread adam

I'm using Pyro to develop a distribuited system

running my integration test suite I've found a strange
behaviour

it seems that whenever I have a failed resolve or unregister on
a name server, the name server acts normally during its life
span, but when I shut it down... something remains up...

if, afterwards, i lookup for a name server python freezes
and if i try to start a new name server, the port look occupied

is this a Pyro issue? or is that just me, that I've lost something
important?

i'll attach the code that causes the freeze

thanks!

Vieri


***


print('test_pyro_bug')
timeout = 10
#init pyro
Pyro.core.initServer(0)
Pyro.core.initClient(0)
#start name server
ns_host = 'localhost'
ns_port = 9090
name_server_starter = Pyro.naming.NameServerStarter()
name_server_thread = threading.Thread(
target = name_server_starter.start,
args = (ns_host, ns_port))
name_server_thread.setDaemon(True)
name_server_thread.start()
name_server_starter.waitUntilStarted(timeout)
#locate name server
locator = Pyro.naming.NameServerLocator()
name_server = locator.getNS(ns_host, ns_port)
name_server.createGroup( "my_group" )
#init daemon
daemon = Pyro.core.Daemon()
daemon.useNameServer(name_server)
daemon_thread = threading.Thread(
target = daemon.requestLoop,
args = ())
daemon_thread.setDaemon(True)
daemon_thread.start()
#try to unregisater a non existent object
dummy_name = "my_group" + ".dummy"
dummy = _DummyRemote()
daemon.connect(dummy, dummy_name)
try:
name_server.unregister(dummy_name + "not found")
except Pyro.core.NamingError:
pass
#shutdown daemon
daemon.shutdown()
daemon = None
daemon_thread.join(timeout)
daemon_thread = None
#shutdown name server
name_server._shutdown()
name_server_thread.join(timeout)
name_server_thread = None
#locate name server
locator = Pyro.naming.NameServerLocator()
##freezes here!
self.failUnlessRaises(
Pyro.core.ProtocolError,
locator.getNS, ns_host, ns_port)




Vieri del Bianco
CEFRIEL · Politecnico di Milano
Via Fucini, 2 · 20133 Milano (Italy)
t: +39 0223954355
e: [EMAIL PROTECTED]
w: http://www.cefriel.it


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


Re: How to generate graphics dynamically on the web using Python CGI script?

2006-01-23 Thread paron
Steve Holden wrote:
> Debashis Dey wrote:
> > Hello,
> >
> > I have a python CGI program. I would like to show a graph within a HTML
> > plage. I would like to dynamically generate the graph using the python
> > CGI script on the web server side and send it to the browser.
> >
> > My question is how can I do this in python? Is there a free tool to do
> > this? Can someone please send me some simple python code to draw simple
> > graphics within HTML (e.g. draw a line or a circle).
> >
> Unfortunately HTML does not include graphics facilities, simply the
> ability to refer to graphical resources.
>
> The typical way to include a created graphic would be:
>
>   1. Create a (.png, .jpg, .gif) file showing the
>  image you want
>
>   2. Store it in a temporary file whose name will be
>  unique to the current session
>
>   3. Generate an HTML response including an 
>  tag referring to the newly created graphic

SVG might be suitable; Firefox supports a reasonable subset of SVG out
of the box, and even IE supports it through an Adobe plugin.

If the OP is intending the page for a specific group of users, it could
be a very simple solution.

Ron

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


Re: Redirecting standard out in a single namespace

2006-01-23 Thread Fuzzyman

Bengt Richter wrote:

> On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <[EMAIL PROTECTED]> wrote:
>
> >Hello,
> >
> >I'm trying to redirect standard out in a single namespace.
> >
> >I can replace sys.stdout with a custom object - but that affects all
> >namespaces.
> >
> >There will be code running simultaneously that could import sys
> >afterwards - so I don't want to make the change in the sys module.
> >
> >I have an idea to redefine __import__ for the relevant namespace - so
> >that an attempt to import sys will return a different module with a
> >custom object for stdout. As sys is a builtin module this might not
> >work for the print statement, which is what I want to redirect.
[snip..]
> >Is there another way to shadow the sys module from a single namespace ?
> >
> It wouldn't be shadowing, but I suppose you could replace sys.stdout with
> a custom object whose methods check where they were called from.
> Then you could give the object initialization parameters as to which namespace
> you want to have the effect in, and/or methods to control the action or turn
> it on or off etc. BTW, how about stderr?
>

I've just tried checking __name__ in my custom stdout object.
Unfortunately __name__ is always the module in which the new stdout
object lives.

In theory I could go up (down?) the stack to the previous frame and
check __name__ there - but it sounds like a hack.

Any other ways of checking where sys.stdout is called from ?

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Regards,
> Bengt Richter

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


Re: Redirecting standard out in a single namespace

2006-01-23 Thread Fuzzyman

Bengt Richter wrote:

> On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <[EMAIL PROTECTED]> wrote:
>
> >Hello,
> >
> >I'm trying to redirect standard out in a single namespace.
> >
> >I can replace sys.stdout with a custom object - but that affects all
> >namespaces.
> >
> >There will be code running simultaneously that could import sys
> >afterwards - so I don't want to make the change in the sys module.
> >
> >I have an idea to redefine __import__ for the relevant namespace - so
> >that an attempt to import sys will return a different module with a
> >custom object for stdout. As sys is a builtin module this might not
> >work for the print statement, which is what I want to redirect.
> >[snip..]
> >Is there another way to shadow the sys module from a single namespace ?
> >
> It wouldn't be shadowing, but I suppose you could replace sys.stdout with
> a custom object whose methods check where they were called from.
> Then you could give the object initialization parameters as to which namespace
> you want to have the effect in, and/or methods to control the action or turn
> it on or off etc. BTW, how about stderr?
>

Redirecting stderr is identical in concept to redirecting stdout.

The following in the write method of the custom out object works :

sys._getframe(1).f_globals['__name__']

sys.stdout.write is *always* called from at least one frame deep in the
stack - so it works.

However the Python docs say of sys._getframe :

This function should be used for internal and specialized purposes
only.

Might this approach be brittle ?

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Regards,
> Bengt Richter

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


Re: Problem with running external process

2006-01-23 Thread ToMasz
This is the result of ulimit command on my machine:

core file size(blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) unlimited
max memory size   (kbytes, -m) unlimited
open files(-n) 1024
pipe size  (512 bytes, -p) 8
stack size(kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes(-u) 1014
virtual memory(kbytes, -v) unlimited

It looks like either pipe size or stack size may be too low. But my
main script must be running all the time to collect data so how much
should I increase these values to allow infinite executions of external
process?

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


Re: How to generate graphics dynamically on the web using Python CGI script?

2006-01-23 Thread Christophe
Steve Holden a écrit :
> Debashis Dey wrote:
> 
>> Hello,
>>  
>> I have a python CGI program. I would like to show a graph within a 
>> HTML plage. I would like to dynamically generate the graph using the 
>> python CGI script on the web server side and send it to the browser.
>>  
>> My question is how can I do this in python? Is there a free tool to do 
>> this? Can someone please send me some simple python code to draw 
>> simple graphics within HTML (e.g. draw a line or a circle).
>>  
> 
> Unfortunately HTML does not include graphics facilities, simply the 
> ability to refer to graphical resources.
> 
> The typical way to include a created graphic would be:
> 
>  1. Create a (.png, .jpg, .gif) file showing the
> image you want
> 
>  2. Store it in a temporary file whose name will be
> unique to the current session
> 
>  3. Generate an HTML response including an 
> tag referring to the newly created graphic
> 
> Step 1, which is what you seem to be asking about, can be handled by a 
> number of packages, perhaps the best-known of which is PIL, the Python 
> Imaging Library - see
> 
>   http://www.pythonware.com/products/pil/
> 
> This is open source, and available at no cost. There's a wealth of 
> information on how to use it on the web, and many regular readers of 
> this group are skilled with it!
> 
> regards
>  Steve

Actually, there's a way to store an image inline in the HTML  tag.

Here's an example usage : 
http://www.sencer.de/article/1135/how-to-inline-your-sparklinesimages-in-php-with-data-uris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: zipfile and file permissions

2006-01-23 Thread Pete Forman
Robert Kern <[EMAIL PROTECTED]> writes:

 > Pete Forman wrote:
>> I'm trying to move the building of a zip file from a shell script into
>> python.  It is mostly working but when I unzip the files the UNIX
>> permissions are not preserved.  The zip program I've been using is the
>> standard(?) one on Linux, from Info-Zip.  Presumably I need to do
>> something with external_attr in ZipInfo, any pointers?
>
 > C.f.: http://mail.python.org/pipermail/pythonmac-sig/2005-March/013491.html

Thanks.  I've put a work around in my code to set create_system.  I've
also made a patch for zipfile.py which I'm trying to submit to
sourceforge.  No luck so far, I'll try again later.  Recently I
submitted a patch to the python-mode project, so I think I'm following
the correct procedure.
-- 
Pete Forman-./\.-  Disclaimer: This post is originated
WesternGeco  -./\.-   by myself and does not represent
[EMAIL PROTECTED]-./\.-   opinion of Schlumberger, Baker
http://petef.port5.com   -./\.-   Hughes or their divisions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Testing for the presence of input from stdin.

2006-01-23 Thread Diez B. Roggisch
> I can get the script to behave as expected when content's piped to it
> using sys.stdin but I'd like to know that there's data coming from
> stdin or fail and print the useage again. Is there a simple way to
> achieve this?

There are more experienced UNIXers here, but from my POV I don't see how
that can happen. The reason is simply that

 - sys.stdin alwasy exists (unless you close it yourself)
 
 - in a pipe (which this essentially is) there is now way to know if there
is more date to come or not, except for the "broken pipe" error - but that
won't happen to you, as sys.stdin is not broken just because there is
currently no data arriving.


The only thing I can think of is to introduce a timeout. If no data has
arrived for a certain amount of time, you terminate. That could be achieved
using either threads, or non-blocking IO.

However, it's a heuristic. If your aunt sally starts the program and wants
to feed it manually, but is slow because she first has to fetch her glasses
from the kitchen, she'll think you're nasty because you terminated her
program...

Diez

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


Re: Testing for the presence of input from stdin.

2006-01-23 Thread Will McDonald
On 23/01/06, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> > I can get the script to behave as expected when content's piped to it
> > using sys.stdin but I'd like to know that there's data coming from
> > stdin or fail and print the useage again. Is there a simple way to
> > achieve this?
>
> There are more experienced UNIXers here, but from my POV I don't see how
> that can happen. The reason is simply that
>
>  - sys.stdin alwasy exists (unless you close it yourself)
>
>  - in a pipe (which this essentially is) there is now way to know if there
> is more date to come or not, except for the "broken pipe" error - but that
> won't happen to you, as sys.stdin is not broken just because there is
> currently no data arriving.

That's a good point. I did wonder if it'd just have to sit there
waiting for input much like cat would. I think that's preferable, and
simpler :), than implementing timeouts.

Thanks.

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


Re: Dominant color & PIL

2006-01-23 Thread Rinzwind
For example:

getdata

im.getdata() => sequence

Returns the contents of an image as a sequence object containing pixel
values. The sequence object is flattened, so that values for line one
follow directly after the values of line zero, and so on.

Note that the sequence object returned by this method is an internal
PIL data type, which only supports certain sequence operations. To
convert it to an ordinary sequence (e.g. for printing), use
list(im.getdata()).

So you could get them and count them in :)
Don't know if you should do that on a 1600x1200 wallpaper tho :D

Wim


Terry Hancock wrote:
> On Sun, 22 Jan 2006 21:07:45 +0100
> Sebastjan Trepca <[EMAIL PROTECTED]> wrote:
> > I was wondering is it possible to find out which colour is
> > dominant in an image using PIL?
> > It would be very easy to create interesting mozaic images
> > with that :)
>
> Shrink it to one pixel, and get that pixel's value. ;-)
>
> Seriously, that ought to do it.  Bear in mind that you need
> to use the right sampling mode (IIRC, you want ANTIALIAS).
>
> Cheers,
> Terry
>
> --
> Terry Hancock ([EMAIL PROTECTED])
> Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Dr. Dobb's Python-URL! - weekly Python news and links (Jan 23)

2006-01-23 Thread Magnus Lycka
QOTW:  "The IEEE-754 standard doesn't wholly define output conversions, and
explicitly allows that a conforming implementation may produce any digits
whatsoever at and after the 18th signficant digit, when converting a 754
double to string.  In practice, all implementations I know of that exploit
that produce zeroes at and after the 18th digit -- but they could produce 1s
instead, or 9s, or digits from pi, or repetitions of the gross national
product of Finland in 1967." - Tim Peters

"If you can't do a first version in six months with a team of six people it
is a sign that you don't really know what you want." - Jack Diederich


Besides the layout for the new Python web site, work on converting
the content from the current site has begun:

http://groups.google.se/group/comp.lang.python/browse_frm/thread/330af3b245145f7e/429bd0c83ff89b0c?rnum=3#429bd0c83ff89b0c

There has been interest in Sudoku solvers on comp.lang.python
lately:

http://groups.google.se/group/comp.lang.python/search?q=sudoku&start=0&scoring=d&;

Don't expect to use the ConfigParser for non-text data. Use ConfigObj
instead when that's what you need:

http://groups.google.se/group/comp.lang.python/browse_frm/thread/3b5f75051b1fb57c

How do you use Python without installing it on your computer?

http://groups.google.se/group/comp.lang.python/browse_frm/thread/8ed65089a7c01e3b

Should a web development framework be included in the standard
library?

http://groups.google.se/group/comp.lang.python/browse_frm/thread/d3e9bd6d002df4d4

Claudio Grondi tries to grok Python by asking questions that
seem to confuse those who try to answer:

http://groups.google.se/group/comp.lang.python/browse_frm/thread/b6515a4574dc9292

No, regular expressions aren't supposed to be gargantuan, but
there should really be a proper exception when they are:

http://groups.google.se/group/comp.lang.python/browse_frm/thread/64df1dd7202e247e

This is neither the first nor the last week, when someone asks
questions related to a mismatch between binary floats and decimal
numbers:

http://groups.google.se/group/comp.lang.python/browse_frm/thread/fe07673b9f77738e

How do we generate graphics dynamically with Python CGI scripts?

http://groups.google.se/group/comp.lang.python/browse_frm/thread/8179735820c85cb

A PHP programmer is making efforts to figure out Python, in
particular with regards to threads, databases and modularity.
(Welcome Robin!)

http://groups.google.se/group/comp.lang.python/browse_frm/thread/bf75a37e9242cce

http://groups.google.se/group/comp.lang.python/browse_frm/thread/2055bab118aeec50

Numarray, Numeric, NumPy... There should be one--and preferably
only one--obvious way to do it. So, which is it?

http://groups.google.se/group/comp.lang.python/browse_frm/thread/2a308411c39c042



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success S

Re: New Python.org website?

2006-01-23 Thread Sibylle Koczian
Tony Meyer schrieb:
>>> But sheesh, if I objected to every picture of the moon I
>>> see (or pictures that vaguely resemble a moon), I would be
>>> in a very sad state.
>>
>>
>> But you see Terry, the point is not that it is just a picture. And
>> let's not forget that as far as we know the moon has always been a
>> natural part of all human life on this earth before and after Islam,
>> and even for those who never heard of Islam. And so the moon is not a
>> Muslim monopoly.
> 
> 
> Perhaps you're not aware of this, but the 'plus' shape existed before  
> Christianity, too.
> 
> =Tony.Meyer

And the Python logo _is_ a plus sign and _not_ a christian cross. Try 
crucifying anybody on it.


-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


HOWTO Send a string???

2006-01-23 Thread Sbaush
Hi all.In my application I have to do implement a lot of networking in pythonMy application can create with a GUI a XML file in a string.(and now my application can do it wow!!)This string has to be sended to another host. i need a python application that send this string via UDP. 
The packet of this communication is |int|payload| where payload is the XML string.After the send my application has to wait for a response and has to receive response.For the heaven it should be implemented with separated thread. A thread send/receive while another indipendent thread do same.
Have you any ideas to do it more simply as possible?What is the best way to di it??What is the best way to thread programming in python?Thanks all for your help with me!-- Sbaush
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Who is www.python.org for? (was Re: New Python.org website ?)

2006-01-23 Thread Magnus Lycka
Roy Smith wrote:
> For the most part, I agree with Terry; I want a site that gives me the info 
> I need without any fluff getting in the way.  But, at the same time, I 
> realize that there is a need for marketing to suits.

I'll leave layout to others, but content-wise, I don't think this
is very difficult. A "Python is"-blurb with current buzzwords, (I
guess that could be autogenerated by some bot that extracts buzz-
words from the net ;) a few quotes (we have that) and links to
success stories. Both to http://www.pythonology.org/success and
to O'Reilly's both publications:
http://python.oreilly.com/news/python_success_stories.pdf
and http://python.oreilly.com/news/PythonSS.pdf
Adorn the O'Reilly links with images depicting the covers
of those booklets. (I'm sure it's fairly simple to extract
the covers from the PDF's to .png files.)

In general, I think it's a good idea to avoid producing content
that's already out there. Use the resources on the internet.
Sure, it means that we're not quite in control, but I'm sure it's
much less work to maintain some links than to create a lot of
content and keep that up-to-date. It also adds credibility to
show that we have such a wide support from third parties such as
the publishing houses and companies like Google etc.

I'm pretty sure that a lot of what's in the web site today could
be in the wiki, such as the topic guides and SIG pages.

For documentation, I'd put a prominent link to Amazon's page for
"Books > Subjects > Computers & Internet > Programming > Languages & 
Tools > Python" besides the standard documentation and a wiki page
were the community can maintain links to on-line tutorials etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with running external process

2006-01-23 Thread Dan Sommers
On 23 Jan 2006 04:33:17 -0800,
"ToMasz" <[EMAIL PROTECTED]> wrote:

> ...  how much should I increase these values to allow infinite
> executions of external process?

That sounds like a bad idea.  Long before you've run an infinite number
of processes, a real resource will be exhausted.

You are probably creating zombie processes (you can check with /bin/ps).
To get rid of them, execute os.waitpid(-1, os.WNOHANG) (or something
similar to that) periodically from within your python script.  Possibly
execute that statement repeatedly until it indicates that there are no
more zombies.  A good time/place to do this is right before you start
another process.

Regards,
Dan

-- 
Dan Sommers

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


Re: Who is www.python.org for? (was Re: New Python.org website ?)

2006-01-23 Thread A.M. Kuchling
On Sun, 22 Jan 2006 22:43:45 -0600, 
Terry Hancock <[EMAIL PROTECTED]> wrote:
> For me, the most important function of the python.org site
> is as a quick-reference to deeper documentation that I
> actually need in the process of writing Python code.

docs.python.org is probably the site most useful to you, then.

--amk

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


wxPython or wxWidgets

2006-01-23 Thread py
i need to design a GUI for my python app.  i heard of wxWidgets and was
going to look into that, but then I saw wxPython.  Why would I use
wxPython over wxWidgets?

thanks

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


Re: wxPython or wxWidgets

2006-01-23 Thread Lawrence Oluyede
"py" <[EMAIL PROTECTED]> writes:

> i need to design a GUI for my python app.  i heard of wxWidgets and was
> going to look into that, but then I saw wxPython.  Why would I use
> wxPython over wxWidgets?

wxPython is the Python porting of wxWidgets.

-- 
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython or wxWidgets

2006-01-23 Thread py
Lawrence Oluyede wrote:
> wxPython is the Python porting of wxWidgets.


got it, thanks.

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


Re: wxPython or wxWidgets

2006-01-23 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, py wrote:

> i need to design a GUI for my python app.  i heard of wxWidgets and was
> going to look into that, but then I saw wxPython.  Why would I use
> wxPython over wxWidgets?

wxPython are the Python bindings to wxWidgets which is a C++ library.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Launch file based on association

2006-01-23 Thread Chris Cioffi
Q:  If I have a file called "spreadsheet.xls" how can I launch it in what ever program it is associated with?  I don't care if that program is Excel or OpenOffice Calc.  I just want to launch the file.Since I want to just launch the new process, naturally I looked at 
os.execl().  However, I can't figure out how to make it work:>>> import os>>> os.execl("c:\\spreadsheet.xls")Traceback (most recent call last):  File "", line 1, in ?
  File "C:\Python24\lib\os.py", line 309, in execl    execv(file, args)OSError: [Errno 8] Exec format error>>> os.execl("c:\\spreadsheet.xls", "c:\\spreadsheet.xls")
Traceback (most recent call last):  File "", line 1, in ?  File "C:\Python24\lib\os.py", line 309, in execl    execv(file, args)OSError: [Errno 8] Exec format error
Is there some trick?  I _think_ I'm doing what the docs desribe...I've tried to Google around and I can't find anything of use.  Having said that, I'd really appreciate it if someone could give me the right 2 word Google search that pops up exactly what I'm looking for. ;->
Thanks!Chris-- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: HOWTO Send a string???

2006-01-23 Thread Martin Franklin
Sbaush wrote:
> Hi all.
> In my application I have to do implement a lot of networking in python
> My application can create with a GUI a XML file in a string.(and now my
> application can do it wow!!)
> This string has to be sended to another host. i need a python application
> that send this string via UDP.
> The packet of this communication is |int|payload| where payload is the XML
> string.
> After the send my application has to wait for a response and has to receive
> response.
> For the heaven it should be implemented with separated thread. A thread
> send/receive while another indipendent thread do same.
> 
> Have you any ideas to do it more simply as possible?
> What is the best way to di it??
> What is the best way to thread programming in python?
> 
> Thanks all for your help with me!
> --

for python & socket how to :

http://www.amk.ca/python/howto/sockets/


You may also want to look at:

http://pyro.sourceforge.net/

which gives you a pythonic solution

HTH,
Martin.








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


Re: Dominant color & PIL

2006-01-23 Thread Terry Hancock
On 23 Jan 2006 05:47:58 -0800
"Rinzwind" <[EMAIL PROTECTED]> wrote:
> For example:
> 
> getdata
> 
> im.getdata() => sequence
> 
> Returns the contents of an image as a sequence object
> containing pixel values. The sequence object is flattened,
> so that values for line one follow directly after the
> values of line zero, and so on.
> 
> Note that the sequence object returned by this method is
> an internal PIL data type, which only supports certain
> sequence operations. To convert it to an ordinary sequence
> (e.g. for printing), use list(im.getdata()).
> 
> So you could get them and count them in :)
> Don't know if you should do that on a 1600x1200 wallpaper
> tho :D

I think he's thinking of how to get the values for the
master image.

> Terry Hancock wrote:
> > On Sun, 22 Jan 2006 21:07:45 +0100
> > Sebastjan Trepca <[EMAIL PROTECTED]> wrote:
> > > I was wondering is it possible to find out which
> > > colour is dominant in an image using PIL?
> > > It would be very easy to create interesting mozaic
> > > images with that :)
> >
> > Shrink it to one pixel, and get that pixel's value. ;-)
> >
> > Seriously, that ought to do it.  Bear in mind that you
> > need to use the right sampling mode (IIRC, you want
> > ANTIALIAS).

This is answering the OP's question which is how to get
the average color for a whole image:

color = img.resize( (1,1), Image.ANTIALIAS).getpixel((0,0))

You just shrink the image down. The ANTIALIAS filter
averages every pixel in the image (this occurs in the PIL
library, so it's probably pretty fast), and then you fish
the single remaining pixel out into tuple format.

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Backreferences in python ?

2006-01-23 Thread Pankaj

I have something like below in perl and  i am searching for equivalent
in python:

::: Perl :::
***
while(  )
{

 line = $_;

 pattern = "printf\( \"$lineNo \" \),";

 line =~ s/"for(.*)\((*.)\;(.*)/for$1\($pattern$2\;$3/g;
}

This is used to

search for :for ( i = 0; i < 10; i++)
Replace with:  for( printf( "10" ), i =0; i < 10; i++)
Where 10 is the line no.


What i tried in python was::


f = open( "./1.c", "r")
fNew = open( "./1_new.c", "w")
for l in f:
print l
lineno = lineno + 1
strToFind = "for\((.*)\;(.*)"

##  For Converting int to string, i.e. line no. to string
lineNoClone = lineno

pattern = "printf(\"" + str( lineNoClone) + "\"),"

print pattern

strToReplace = "for\(" + pattern + "\1\;"

fNew.write( l.replace( strToFind, strToReplace) )

print l

fNew.close()

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


Re: Backreferences in python ?

2006-01-23 Thread Jean-Paul Calderone
On 23 Jan 2006 07:18:13 -0800, Pankaj <[EMAIL PROTECTED]> wrote:
>
> [snip]
>What i tried in python was::
>
>f = open( "./1.c", "r")
>fNew = open( "./1_new.c", "w")
>for l in f:
>print l
>lineno = lineno + 1
>strToFind = "for\((.*)\;(.*)"
>
>##  For Converting int to string, i.e. line no. to string
>lineNoClone = lineno
>
>pattern = "printf(\"" + str( lineNoClone) + "\"),"
>
>print pattern
>
>strToReplace = "for\(" + pattern + "\1\;"
>
>fNew.write( l.replace( strToFind, strToReplace) )
>
>print l
>
>fNew.close()
>

str.replace() does not support regular expressions.  Take a look at the re 
module.

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


Re: Cross-module imports?

2006-01-23 Thread Ant
You are always likely to have problems of one sort or another if you
are using circular references like this. It would be a much better
situation redesigning your modules so that they didn't depend on each
other.

The interpreter is complaining, since it is trying to compile A, hits
the line 'import B', goes straight off into B to compile that, where it
encounters the line 'print A.var1', of course there is no 'A.var1' yet,
since the compiler hasn't yet got that far. So the error message is
perfectly sane (the codes author on the other hand... ;-) )

I would imagine that you *could* get it to work if you first tried to
run the example with line 3 of module B commented out (the thing should
compile fine then) and then run it again with line 3 uncommented again.
This way A will be already compliled when B comes to import it.

If you have to trick the compiler like this though, I'd take a good
look at *why* you want to couple the modules so tightly in the first
place!

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


Re: Backreferences in python ?

2006-01-23 Thread Gerhard Häring
Pankaj wrote:
> [...]
> 
> What i tried in python was::
> 
> 
> f = open( "./1.c", "r")
> fNew = open( "./1_new.c", "w")
> for l in f:
> print l
> lineno = lineno + 1
> strToFind = "for\((.*)\;(.*)"
> [...]

Regular expressions are not handled automatically in Python the way you 
apparently think they are.

In Python, you will need to use the "re" module:

http://docs.python.org/lib/module-re.html

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


Re: ConfigParser: writes a list but reads a string?

2006-01-23 Thread Fuzzyman

Jeffrey Barish wrote:
> funkyj wrote:
>
> > making the config file XML and using xml.dom is another option,
> > although XML is a bit ugly to edit by hand.
> >   --jfc
> >
> I am seriously intrigued by ConfigObj.  I am currently using an crude
> improvisation involving tab-delimited fields to store metadata for
> recordings -- not configuration data -- in text files.  I had been planning
> to convert to XML, but now I am wondering whether ConfigObj would be
> easier.  I would like for the metadata files to be editable, but editing
> does not have to be easy as it needs to be done rarely.  I've never used
> XML, so I am wondering whether there are other tradeoffs between that
> approach and ConfigObj that I should be aware of.  I was thinking of XML
> mainly to have a more robust format.  For example, it would be nice if it
> were possible to add fields without obsoleting early versions of the
> reader.  Crossplatform compatibility is also desirable.

ConfigObj can be used for all sorts of data persistence type uses.
Because it is pure python there are likely to be no cross platform
issues.

You would have to 'name' entries, but entries can be single values or
lists - or even subsections (effectively dictionaries).

If you are happy with text, then it is *very* easy to use. If you
wanted to store other datatypes, then you may be interested in
ConfigPersist.py :


http://www.voidspace.org.uk/python/articles/configobj_for_data_persistence.shtml

It is easy to use a validating configspec, and then extend it - without
obsoleting earlier code or data files.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> -- 
> Jeffrey Barish

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


Re: HOWTO Send a string???

2006-01-23 Thread Sbaush
oh thanks i read the howto.Why i should use pyro? What is in poor words?2006/1/23, Martin Franklin <[EMAIL PROTECTED]
>:Sbaush wrote:> Hi all.> In my application I have to do implement a lot of networking in python
> My application can create with a GUI a XML file in a string.(and now my> application can do it wow!!)> This string has to be sended to another host. i need a python application> that send this string via UDP.
> The packet of this communication is |int|payload| where payload is the XML> string.> After the send my application has to wait for a response and has to receive> response.> For the heaven it should be implemented with separated thread. A thread
> send/receive while another indipendent thread do same.>> Have you any ideas to do it more simply as possible?> What is the best way to di it??> What is the best way to thread programming in python?
>> Thanks all for your help with me!> --for python & socket how to :http://www.amk.ca/python/howto/sockets/You may also want to look at:
http://pyro.sourceforge.net/which gives you a pythonic solutionHTH,Martin.--
http://mail.python.org/mailman/listinfo/python-list-- Sbaush
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Launch file based on association

2006-01-23 Thread Fredrik Lundh
Chris Cioffi wrote:

> Q:  If I have a file called "spreadsheet.xls" how can I launch it in what
> ever program it is associated with?  I don't care if that program is Excel
> or OpenOffice Calc.  I just want to launch the file.

>>> import os
>>> help(os.startfile)
Help on built-in function startfile in module nt:

startfile(...)
startfile(filepath) - Start a file with its associated application.

This acts like double-clicking the file in Explorer, or giving the file
name as an argument to the DOS "start" command:  the file is opened
with whatever application (if any) its extension is associated.

startfile returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way
to retrieve the application's exit status.

The filepath is relative to the current directory.  If you want to use
an absolute path, make sure the first character is not a slash ("/");
the underlying Win32 ShellExecute function doesn't work if it is.

 



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


RE: Strange python behavior with modules on an emt64 box

2006-01-23 Thread Joshua Luben
To clarify this issue,

I checked, DCOracle is compile such that sizeof(int) = 4, sizeof(long) =
8. I guess this is closer to what you are expecting.

If a 'Python' int is a C long, then why is it passing in a 4 byte size? 

Digging deaper, I've found that this size is not passed in by Python,
but by taking the sizeof() the long in a union for different types.
(Binding.u.l)

I guess this is now a GCC compiler bug, so I'll send this problem
elsewhere.

Thanks!

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Tim Peters
Sent: Friday, January 20, 2006 4:00 PM
To: [email protected]
Subject: Re: Strange python behavior with modules on an emt64 box

[Joshua Luben]
> I thought I would post this here first before seeking more experienced

> ears for this particular strangness.
>
> I have Python 2.4.2 installed from source on a dual processor dell
server.
> These are x86_64 processors (verified by /bin/arch) (aka emt64
extensions).
>
> uname -a gives
> Linux eps-linuxserv3 2.6.5-7.244-smp #1 SMP Mon Dec 12 18:32:25 UTC 
> 2005 x86_64 x86_64 x86_64 GNU/Linux
>
> The flavor of Linux is 64 bit SUSE SLES 9 with the latest updates.
>
>
> Now for the strangeness. I'm using DCOracle2 (can't use anything else,

> as this is the corporate standard) also compiled from source. When 
> calling
> executemany() when any parameter is of type int, I get a 
> OverflowError. I turned on debug traces in DCOracle2; this indicated 
> that PyArg_ParseTuple() was returning sizeof(int) = 4 bytes.

Sounds right to me.  I don't know of any platform other than old Cray
Research boxes where sizeof(int) > 4.

> DCOracle2 is compiled such that sizeof(int) = 8 bytes.

Sounds wrong to me.

> Python itself gives,
>
> python -c "import sys; print sys.maxint"
> 9223372036854775807
>
> Therefore, indicating that the size of int is 8 bytes.

No, it does not.  A Python `int` is a C `long`, and sizeof(long) = 8 on
most 64-bit boxes (Win64 is an exception).  The size of a platform C
long can be deduced from the value of Python's sys.maxint, but nothing
about the size of a platform C int.

> So I'll go out on a limb here and assume that this is a python 
> problem...but I don't know where to take it...

I'd start with this part, which sounds crazy:

DCOracle2 is compiled such that sizeof(int) = 8 bytes.
--
http://mail.python.org/mailman/listinfo/python-list
 
This email (including any attachments) may contain material that is 
confidential and privileged and is for the sole use of the intended recipient. 
Any review, reliance or distribution by others or forwarding without express 
permission is strictly prohibited. If you are not the intended recipient, 
please contact the sender and delete all copies.


Exelixis, Inc. reserves the right, to the extent and under circumstances 
permitted by applicable law, to retain, monitor and intercept e-mail messages 
to and from its systems.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: IT Industry Predicament

2006-01-23 Thread sszmidt
On Friday 20 January 2006 15:42, Keith Thompson wrote:
> "Xah Lee" <[EMAIL PROTECTED]> writes:
> [the usual]
>
>   ___
>   /|  /|  |  |
>
>   ||__||  |  Please do   |
>
>  /   O O\__ NOT  |
> /  \ feed the|
>/  \ \ trolls |

But it gave us something to laugh at... : ) The guy is outright FUNNY! Well, 
yes in a naive dumb sort of way, but still, a good laugh!

-- 

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


Re: Some thougts on cartesian products

2006-01-23 Thread Christoph Zwerschke
Bryan Olson schrieb:
> Christoph Zwerschke wrote:
> [...]
>> That may be the main problem to decide whether the cartesian product 
>> should return a generator or a list.
> 
> The Cartesion product is a set.

Of course it is a set. But if the factors of the product have a total 
order (as in the case of strings, tuples or lists), this carries over to 
the cartesian product (lexicographical order). The implementation should 
reflect that by giving you a list or a generator, not a set.

Only if I build the cartesian product of sets I would expect a set.

"ab"*"cd" should be "ac", "ad", "bc", "bd", in this order.

> Cartesian product is one of the essential operations of
> relational algebra; in that context it's widely useful.
> By itself, it's usually not what one wants.

Usually not. But sometimes you may want it. That's why SQL defines has 
the "cross join" clause. Usually it is not needed and should be avoided, 
but sometimes it may make sense.

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


Re: Cross-module imports?

2006-01-23 Thread Matthias Kaeppler
Ant wrote:
> If you have to trick the compiler like this though, I'd take a good
> look at *why* you want to couple the modules so tightly in the first
> place!

Yeah, you're right. I think loosening up the coupling by introducing a 
module which holds common shared data is probably a good idea anyway.

Thanks for clearing up,
Matthias
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Launch file based on association

2006-01-23 Thread Paul Boddie
Fredrik Lundh wrote:
> Chris Cioffi wrote:
>
> > Q:  If I have a file called "spreadsheet.xls" how can I launch it in what
> > ever program it is associated with?  I don't care if that program is Excel
> > or OpenOffice Calc.  I just want to launch the file.
>
> >>> import os
> >>> help(os.startfile)

[...]

And for a cross-platform experience, try the desktop module:

http://www.python.org/pypi/desktop

It uses os.startfile on Windows, but also provides access to file/URL
opening functionality in KDE, GNOME and Mac OS X. Given a comprehensive
enough selection of software (and a sane configuration), even Excel
files can be opened in Calc using desktop.open.

Paul

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


Re: wxPython or wxWidgets

2006-01-23 Thread Matthias Kaeppler
Marc 'BlackJack' Rintsch wrote:
> wxPython are the Python bindings to wxWidgets which is a C++ library.

Don't want to hijack the thread, but since it's answered already:
Has wxWidgets finally arrived at migrating to GTK2? ^^
If so, I might consider using wxPython instead of pygtk for that small 
application I am currently writing. This would help portability a lot 
(since IIRC, wxWidgets has been designed to work on Windows, too).

The last time I checked, wxWidgets was GTK1, although GTK2 has had been 
long around already. Because of this, and the nasty feeling that I was 
programming MFC when working with the wxWidgets somewhat drove me away 
from it with a big "Yuck!", but if it's based on GTK2 now I might risk 
another glimpse.

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


Re: Backreferences in python ?

2006-01-23 Thread Pankaj
My tries have with re have not yielded results::


{
  strToFind = 'for*;*'

## Converting int to string, i.e. line no. to string
lineNoClone = lineno

pattern = "printf(\"" + str( lineNoClone) + "\"),"

 regObj = re.compile( strToFind)

m =  regObj.search( l)


if ( m != None ) :
subStrPattern1_hasInitialization = "\1"
#m.group(1)

subStrPattern2_hasRestTillEnd = "\2"
#m.group(2)

strToReplace = "for(" + pattern +
subStrPattern1_hasInitialization + ";" + subStrPattern2_hasRestTillEnd
fNew.write( regObj.sub( strToFind, strToReplace ) )
else:
fNew.write( l)
}


Here problem is , i am not getting backreferences using \1 and \2

The string :   for( i =0; i < 10; i++)

is getting replace by: for *;* {

I don't believe this,  they have given that \1 and \2 store
backreferences, then where r they??

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


Re: wxPython or wxWidgets

2006-01-23 Thread Grant Edwards
On 2006-01-23, Matthias Kaeppler <[EMAIL PROTECTED]> wrote:

>> wxPython are the Python bindings to wxWidgets which is a C++ library.
>
> Don't want to hijack the thread, but since it's answered already:
> Has wxWidgets finally arrived at migrating to GTK2?

Yes.

-- 
Grant Edwards   grante Yow!  Hmmm... an arrogant
  at   bouquet with a subtle
   visi.comsuggestion of POLYVINYL
   CHLORIDE...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some thougts on cartesian products

2006-01-23 Thread Bryan Olson
Steven D'Aprano wrote:
> Bryan Olson wrote:
>>Christoph Zwerschke wrote:
>>[...]
>>
>>>That may be the main problem to decide whether the cartesian product 
>>>should return a generator or a list.
>>
>>The Cartesion product is a set.
> 
> And the generalization of mathematical sets in Python can be built-in
> sets, lists or tuples, depending on what you need.
> 
> Given that cartesian products tend to be *extremely* large, some sort of
> iterator is the only practical solution -- even if that's not
> mathematically pure.

Query languages have included Cartesian product for decades. Their
solution is to optimize expressions to avoid building, or even
iterating over, big Cartesian products.


>>[...]
>>
>>>That's the other problem. The uses cases (like the password cracker 
>>>example) are very limited and in these cases you can either write nested 
>>>loops or write your own cartesian product.
>>
>>Cartesian product is one of the essential operations of
>>relational algebra; in that context it's widely useful.
>>By itself, it's usually not what one wants.
> 
> Google on "Cartesian product python" and you will find thousands of hits.
> This is something that keeps coming up over and over again.

It keeps coming up in exercises and examples. How many of your
Google results note an application that actually calls for a
Cartesian product enumerator? I wrote one an old thread, and so
far I've written it one more time than I've used it.


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


Re: list comprehention

2006-01-23 Thread Mathijs
Op 19 jan 2006 vond "[EMAIL PROTECTED]" :

> another approach:
> 
> ref = [2,2,4,1,1]
> lis = [2,2,5,2,4]
> 
> len([ref.pop(ref.index(x)) for x in lis if x in ref])
> 

This is the type of solution I was hoping to see: one-liners, with no use 
of local variables. As Tim Chase already wrote, it has only one less 
elegant side: it alters the original ref list.

Thanks for your suggestion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Backreferences in python ?

2006-01-23 Thread Pankaj
I got my answer

if ( m != None ) :
 subStrPattern1_hasInitialization = m.group(1)


  subStrPattern2_hasRestTillEnd = m.group(2)

 str = subStrPattern1_hasInitialization  +
subStrPattern2_hasRestTillEnd
strToReplace = "for(" +  pattern + str


This gave me my solution

But to tell u, i have not got that, why i should concatenate and then
only place it . while i was trying the same thing by concatenation it
straight to replace string, it was not working

Any body has reasons ???

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


Re: list comprehention

2006-01-23 Thread Mathijs
Op 19 jan 2006 vond Peter Otten <[EMAIL PROTECTED]> :

> sum(min(list.count(n), ref.count(n)) for n in set(ref))
> 
> Is that it?

Seems like this is it! Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Backreferences in python ?

2006-01-23 Thread Duncan Booth
Pankaj wrote:

> Here problem is , i am not getting backreferences using \1 and \2
> 

You wrote:
>   subStrPattern1_hasInitialization = "\1"

"\1" is the way to create a string containing a control-A character. What 
you actually wanted was a string containing a backslash and a "1", so you 
need either:

"\\1"

or

r"\1"

Try using the print statement to see what all those strings you are 
creating actually contain.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehention

2006-01-23 Thread Mathijs
Op 19 jan 2006 vond "Paddy" <[EMAIL PROTECTED]>: 
 answer = [ val for val in set(ref) for x in
 range(min(lst.count(val), ref.count(val)))] answer
> [2, 2, 4]

I don't think it's correct. Your algoritm with the ref and lst below gives 
3 as answer. The answer should have been 2 (1,3).

ref=[3, 3, 1, 1, 3]
lst=[5, 1, 4, 5, 3]

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


Re: list comprehention

2006-01-23 Thread Mathijs
Op 20 jan 2006 vond Duncan Booth <[EMAIL PROTECTED]>: 
> Or in other words, define a function to return a dictionary containing
> a count of the number of occurrences of each element in the list (this
> assumes that the list elements are hashable). Then you just add up the
> values in the test list making sure each count is limited to no higher
> than the reference count.

Thanks. Though I don't know much about python (yet), this is more or less 
the way I'de do it the language I'm more comfortable with (object pascal), 
and I wouldn't label this as a pythonic solution. I could be wrong, 
though:)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some thougts on cartesian products

2006-01-23 Thread Bryan Olson
Steven D'Aprano wrote:
> Bryan Olson wrote:
> 
> 
[Christoph Zwerschke had written:]
>>>What I expect as the result is the "cartesian product" of the strings.
>>
>>There's no such thing; you'd have to define it first. Are duplicates
>>significant? Order?
> 
> 
> Google "cartesian product" and hit "I'm feeling lucky".
> 
> Or go here: http://mathworld.wolfram.com/CartesianProduct.html
> 
> Still think there is no such thing?

Uh, yes.

The Cartesian product of two sets A and B (also called the
product set, set direct product, or cross product) is defined to
be the set of [...]

All sets, no strings. What were you looking at?

(I'm also happy to see someone agrees with my capitalization of
"Cartesian".)


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


Re: Problem with running external process

2006-01-23 Thread ToMasz
Yes, each time the process is created, it remains.

os.waitpid(-1, os.WNOHANG) doesn't work before starting  the process
for the first time.

I tried this:

pid = os.fork()
if pid == 0:
  os.execl('ext_script.py','ext_script.py')
else:
  (pid,status) = os.waitpid(pid, 0)

It seems to work without leaving zombies.

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


Re: list comprehention

2006-01-23 Thread Duncan Booth
Mathijs wrote:

> Op 20 jan 2006 vond Duncan Booth <[EMAIL PROTECTED]>: 
>> Or in other words, define a function to return a dictionary
>> containing a count of the number of occurrences of each element in
>> the list (this assumes that the list elements are hashable). Then you
>> just add up the values in the test list making sure each count is
>> limited to no higher than the reference count.
> 
> Thanks. Though I don't know much about python (yet), this is more or
> less the way I'de do it the language I'm more comfortable with (object
> pascal), and I wouldn't label this as a pythonic solution. I could be
> wrong, though:)
> 
I'm curious what you think isn't pythonic about this solution?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Launch file based on association

2006-01-23 Thread Chris Cioffi
On 23/01/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
Chris Cioffi wrote:> Q:  If I have a file called "spreadsheet.xls" how can I launch it in what> ever program it is associated with?  I don't care if that program is Excel> or OpenOffice Calc.  I just want to launch the file.
>>> import os>>> help(os.startfile)Help on built-in function startfile in module nt:startfile(...)startfile(filepath) - Start a file with its associated application.
[snip]I knew that as soon as I asked this question someone would very simply show me why I'm a moron! ;)Thank you!  Chris-- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Dominant color & PIL

2006-01-23 Thread Sebastjan Trepca
Hehe, interesting. I'll try it out.Thanks, SebastjanOn 1/23/06, Terry Hancock <[EMAIL PROTECTED]
> wrote:On 23 Jan 2006 05:47:58 -0800"Rinzwind" <
[EMAIL PROTECTED]> wrote:> For example:>> getdata>> im.getdata() => sequence>> Returns the contents of an image as a sequence object> containing pixel values. The sequence object is flattened,
> so that values for line one follow directly after the> values of line zero, and so on.>> Note that the sequence object returned by this method is> an internal PIL data type, which only supports certain
> sequence operations. To convert it to an ordinary sequence> (e.g. for printing), use list(im.getdata()).>> So you could get them and count them in :)> Don't know if you should do that on a 1600x1200 wallpaper
> tho :DI think he's thinking of how to get the values for themaster image.> Terry Hancock wrote:> > On Sun, 22 Jan 2006 21:07:45 +0100> > Sebastjan Trepca <
[EMAIL PROTECTED]> wrote:> > > I was wondering is it possible to find out which> > > colour is dominant in an image using PIL?> > > It would be very easy to create interesting mozaic
> > > images with that :)> >> > Shrink it to one pixel, and get that pixel's value. ;-)> >> > Seriously, that ought to do it.  Bear in mind that you> > need to use the right sampling mode (IIRC, you want
> > ANTIALIAS).This is answering the OP's question which is how to getthe average color for a whole image:color = img.resize( (1,1), Image.ANTIALIAS).getpixel((0,0))You just shrink the image down. The ANTIALIAS filter
averages every pixel in the image (this occurs in the PILlibrary, so it's probably pretty fast), and then you fishthe single remaining pixel out into tuple format.--Terry Hancock (
[EMAIL PROTECTED])Anansi Spaceworks http://www.AnansiSpaceworks.com--http://mail.python.org/mailman/listinfo/python-list

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

Re: how to find not the next sibling but the 2nd sibling or findsibling "a" OR sinbling "b"

2006-01-23 Thread localpricemaps
well actually all i want it to do is find the first thing that shows up
whether its class:food or class: drink so that works for me.  only
thing is that after it finds class:food i think it runs through the
html again and finds the following class:drink and being that there is
not class tag after that class: drink tag it fails.

Fredrik Lundh wrote:
> [EMAIL PROTECTED] wrote:
>
> > ok i found something that works.  instead of using the def i did this:
> >
> > for incident in row('div', {'class': 'food' or 'drink' }):
> >
> > and it worked!
>
> 'food' or 'drink' doesn't do what you think it does:
>
> >>> 'food' or 'drink'
> 'food'
>
> >>> {'class': 'food' or 'drink'}
> {'class': 'food'}
> 
> 

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


Re: list comprehention

2006-01-23 Thread Peter Otten
Mathijs wrote:

> Op 20 jan 2006 vond Duncan Booth <[EMAIL PROTECTED]>:
>> Or in other words, define a function to return a dictionary containing
>> a count of the number of occurrences of each element in the list (this
>> assumes that the list elements are hashable). Then you just add up the
>> values in the test list making sure each count is limited to no higher
>> than the reference count.
> 
> Thanks. Though I don't know much about python (yet), this is more or less
> the way I'de do it the language I'm more comfortable with (object pascal),
> and I wouldn't label this as a pythonic solution. I could be wrong,
> though:)

You *are* wrong. Also, as the lists grow, Duncan's approach scales *much*
better than, e. g., mine. 

If picking a better algorithm were unpythonic there would not be much value
in striving for pythonic solutions.

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


Re: Numarray, numeric, NumPy, scpy_core ??!!

2006-01-23 Thread greg . landrum

Robert Kern wrote:
> Sébastien Boisgérault wrote:
>
> > By the way, I tried numpy 0.9.4 10 minutes ago and guess
> > what ? 'eigenvalue' is broken too ... (hangs forever)
>
> On what platform? Are you linking against an optimized BLAS? We can't fix
> anything without details. I'll be happy to work with you on this bug over on 
> the
> numpy-discussion list.

This is a guess, but the original poster is probably using one of the
newer (3.4.x or 4.0.x) versions of gcc. This is a known problem:
https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=138791
(that's one of the applicable bug reports).

A workaround to this problem is to add the option '-ffloat-store' to
your CFLAGS.



-greg

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


Re: Numarray, numeric, NumPy, scpy_core ??!!

2006-01-23 Thread Sébastien Boisgérault
Robert Kern wrote:
> Sébastien Boisgérault wrote:
>
> > By the way, I tried numpy 0.9.4 10 minutes ago and guess
> > what ? 'eigenvalue' is broken too ... (hangs forever)
>
> On what platform?
Linux, Mandriva 2006 (gcc 4.0.1, etc.)
> Are you linking against an optimized BLAS?
Nope -- I tried the basic install.

> We can't fix
> anything without details.
Obviously, sorry. I was not really expecting a fix,
just wanted to point out that Numpy (or Numeric)
may well not work "out of the box" today on some
platforms.

The (similar) problem has been reported  (2005-07-11)
is not assigned to anybody and is still open
See: http://sourceforge.net/tracker/?group_id=1369&atid=101369

> I'll be happy to work with you on this bug over on the
> numpy-discussion list.

Great Robert,  I will follow your advice then. Thanks
for the proposal.
> --
> Robert Kern
> [EMAIL PROTECTED]
>
> "In the fields of hell where the grass grows high
>  Are the graves of dreams allowed to die."
>   -- Richard Harter.

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


Problems with import of modules

2006-01-23 Thread Ilias Lazaridis
I am within a directory

\doc\template\

I launch script.py

within this script.py, I like to import a module from the doc directory.

this here does not work:

form ..\..\module_name import this_one

how do I go back in the directory hierarchy to import something?

If this is not possible:

How can I modify the python search-path from within the script, thus it 
contains the doc directory?

.

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


Redirecting stdin/stdout to self

2006-01-23 Thread Jan Danielsson
   Hello, I thought I'd write a program to collect information from pf
(packet filter) and insert it into a postgresql database for review on a
web page. First I checked if this has been done already, and found that
it has.. Using Perl and SQLite in a program called "hatchet".

Well, I want to do it in Python, and I want to use postgresql.

Anyway, upon looking in the hatchet Perl code I found this:

open(IN, "$tcpdump -neltttr $log 2>&1 |");

   That looks kind of funky... And if I'm reading it correctly, the Perl
script's process starts tcpdump, but redirects its output to its own
input, and reads it line by line.

I would normally have done it like this:

$ tcpdump -nelttt pflog0 | mypythonscript.py

   ...however, the Perl script solution looks interresting.. Is it
possible to do something like that in Python?

-- 
Kind Regards,
Jan Danielsson
Te audire non possum. Musa sapientum fixa est in aure.
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython layout problem

2006-01-23 Thread py
I have the following code:
[code]
class MainFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title,
style=wx.DEFAULT_FRAME_STYLE |wx.NO_FULL_REPAINT_ON_RESIZE)
# build top area
topSizer = self.buildTopPanel()
# build input area
inputSizer = self.buildInputPanel()

mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(topSizer, 1, wx.EXPAND | wx.ALL, 5)
mainSizer.Add(inputSizer, 1, wx.EXPAND | wx.ALL, 5)

p = wx.Panel(self, wx.ID_ANY)
p.SetSizer(mainSizer)

s = wx.BoxSizer(wx.VERTICAL)
s.Add(p, 1, wx.EXPAND)

self.SetAutoLayout(True)
self.SetSizer(s)
self.Layout()

def buildTopPanel(self):
p = wx.Panel(self, wx.ID_ANY)
self.text = wx.TextCtrl(p, wx.ID_ANY, style=wx.TE_MULTILINE |
wx.SUNKEN_BORDER)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.text, 1, wx.EXPAND)
return sizer

def buildInputPanel(self):
# the area to enter text
self.text2 = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_MULTILINE
| wx.SUNKEN_BORDER)

# panel to add button to
p = wx.Panel(self, wx.ID_ANY)
self.buttonClick = wx.Button(p, wx.ID_ANY, "Click")
hsizer = wx.BoxSizer(wx.HORIZONTAL)
hsizer.Add(self.buttonClick, 0, wx.ALIGN_CENTER)
p.SetSizer(hsizer)

# add the text control and button panel
box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(self.text2, 1, wx.EXPAND)
box.Add(p, 0, wx.EXPAND)
return box

if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MainFrame(None, wx.ID_ANY, "Test")
frame.Show()
app.MainLoop()
[/code]

there are two problems.
1) i want the sizer (that is returned from buildTopPanel()) to fill the
screen wide/tall.  now the text control in it is very small in the
upper-left corner.

2) the scroll bars and borders on the text controls dont appear until i
mouse over them, any ideas?

thanks

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


Loading a Python collection from an text-file

2006-01-23 Thread Ilias Lazaridis
within a python script, I like to create a collection which I fill with 
values from an external text-file (user editable).

How is this accomplished the easiest way (if possible without the need 
of libraries which are not part of the standard distribution)?

something like:

text-file:
{peter, 16},
{anton, 21}

-

within code:

users.load(text-file.txt)

for user in users
   user.name
   user.age

.

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


Re: Problems with import of modules

2006-01-23 Thread Farshid Lashkari
> How can I modify the python search-path from within the script, thus it 
> contains the doc directory?

Hi,

The sys.path variable is a list of strings that contains the current 
module search path. You can add your own path to this list:

import sys
sys.path.append('../')

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


Re: how to find not the next sibling but the 2nd sibling orfindsibling "a" OR sinbling "b"

2006-01-23 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> well actually all i want it to do is find the first thing that shows up
> whether its class:food or class: drink so that works for me.

what makes you think that looking "food" only will find either "food"
or "drink" ?





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


Re: Numarray, numeric, NumPy, scpy_core ??!!

2006-01-23 Thread Robert Kern
Sébastien Boisgérault wrote:
> Robert Kern wrote:
> 
>>Sébastien Boisgérault wrote:
>>
>>>By the way, I tried numpy 0.9.4 10 minutes ago and guess
>>>what ? 'eigenvalue' is broken too ... (hangs forever)
>>
>>On what platform?
> 
> Linux, Mandriva 2006 (gcc 4.0.1, etc.)

Okay, my answer then is, "Don't use gcc 4." gcc 4 broke enough other projects
that I don't feel too bad about saying that. In the meantime, can you try the
workaround that Greg Landrum suggested?

Also, we are using Trac now to manage numpy, so please submit tickets here:

  http://projects.scipy.org/scipy/numpy/

Thanks!

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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

Re: Backreferences in python ?

2006-01-23 Thread Paul McGuire
"Pankaj" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> I have something like below in perl and  i am searching for equivalent
> in python:
>
> ::: Perl :::
> ***
> while(  )
> {
>
>  line = $_;
>
>  pattern = "printf\( \"$lineNo \" \),";
>
>  line =~ s/"for(.*)\((*.)\;(.*)/for$1\($pattern$2\;$3/g;
> }
>
> This is used to
>
> search for :for ( i = 0; i < 10; i++)
> Replace with:  for( printf( "10" ), i =0; i < 10; i++)
> Where 10 is the line no.
>

Here is a solution using pyparsing instead of re's.  You're already used to
re's from using Perl, so you may be more comfortable using that tool in
Python as well.  But pyparsing has some builtin features for pattern
matching, calling out to callback routines during parsing, and a lineno
function to report the current line number, all wrapped up in a simple
transformString method call.

Download pyparsing at http://pyparsing.sourceforge.net.

-- Paul


from pyparsing import Keyword,SkipTo,lineno,cStyleComment

# define grammar for a for statement
for_ = Keyword("for")
forInitializer = SkipTo(';').setResultsName("initializer")
forStmt = for_ + "(" + forInitializer + ';'

# ignore silly comments
forStmt.ignore(cStyleComment)

# setup a parse action that will insert line numbers
# parse actions are all called with 3 args:
# - the original string being parsed
# - the current parse location where the match occurred
# - the matching tokens
# if a value is returned from this function, transformString will
# insert it in place of the original content
def insertPrintStatement(st,loc,toks):
lineNumber = lineno(loc,st)
if toks[0]:
return r'print("%d\n"), %s' % (lineNumber,toks[0])
else:
return r'print("%d\n")' % lineNumber
forInitializer.setParseAction(insertPrintStatement)

# transform some code
# this is how you would read in a whole file as a single string
#testdata = file(inputfilename).read()
# to read the entire file into a list of strings, do:
#testdata = file(inputfilename).readlines()
# for now, just fake some source code
testData = """
for(i = 0; i <= 100; ++i)
{
   /* some stuff */
}

for  (;;;)
{
/* do this forever */
}

/* this for has been commented out
for(a = -1; a < 0; a++)
*/

"""

# use the grammar and the associated parse action to
# transform the source code
print forStmt.transformString(testData)

--
Gives:
for(print("2\n"), i = 0; i <= 100; ++i)
{
   /* some stuff */
}

for(print("7\n");;;)
{
/* do this forever */
}

/* this for has been commented out
for(a = -1; a < 0; a++)
*/



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


Re: converting wiki markup to html (or xml)

2006-01-23 Thread Jarek Zgoda
Tim Parkin napisał(a):

> I'm trying to convert fragments of wiki markup into fragments of html
> (specifically using moinmoin markup). I've managed to do this with
> MoinMoin but I've had to create a data directory, config file and
> underlay. Does anybody know if there a sane way of doing this without
> the extra baggage?

If you consider docutils, markdown or textile (or whatever markup your
Wiki uses) an "extra baggage", then answer is "no".

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Oddities of Tkinter

2006-01-23 Thread Tuvas
I am building a tkinter program. A part of this program is to read data
from an incoming interface, and depending on the data, will display a
bit of text on the tk dialog, it decodes this data, so to speak. If one
command is sent, everything's just fine. When multiple are sent, the
program will stop responding, and will only continue to respond after
one types -c. The statement at fault is something like this.

e1=StringVar()
Label (master,textvariable=e1, width=32).grid(row=44, column=4)

def disp_mes1(text):
  e1.set(text)

It's the line 31.set(text) that takes so long when there's other
processes running. I've ran this program sucessfully many times on
another computer, however, when transfering to another with the same
OS, this problem was created. Any ideas as to what I might be able to
do to fix this problem? My main code is hopelessly complex to post the
entire thing, and I can't recreated the same structure with smaller
ammounts of code. Thanks for the help!

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


Re: Redirecting stdin/stdout to self

2006-01-23 Thread Grant Edwards
On 2006-01-23, Jan Danielsson <[EMAIL PROTECTED]> wrote:

> And if I'm reading it correctly, the Perl
> script's process starts tcpdump, but redirects its output to its own
> input, and reads it line by line.
[...]
>...however, the Perl script solution looks interresting.. Is it
> possible to do something like that in Python?

os.popen()

http://www.python.org/doc/current/lib/os-process.html


-- 
Grant Edwards   grante Yow!  Yow! I threw up on
  at   my window!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with import of modules

2006-01-23 Thread Carl J. Van Arsdall
Ilias Lazaridis wrote:
> I am within a directory
>
> \doc\template\
>
> I launch script.py
>
> within this script.py, I like to import a module from the doc directory.
>
> this here does not work:
>
> form ..\..\module_name import this_one
>   
Well, if you are in linux you can do this easily by changing your 
PYTHONPATH environment variable, either by changing it explicitely or by 
editing it in your .rc files to append the /doc directory.

Although I don't know specifically where this variable might be if you 
are using windows, in either case(windows or linux), you can alter this 
from python using sys.path

import sys
sys.path.append("/doc")

Hope that helps,

-carl

> how do I go back in the directory hierarchy to import something?
>
> If this is not possible:
>
> How can I modify the python search-path from within the script, thus it 
> contains the doc directory?
>
> .
>
>   


-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: Redirecting stdin/stdout to self

2006-01-23 Thread Grant Edwards
On 2006-01-23, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2006-01-23, Jan Danielsson <[EMAIL PROTECTED]> wrote:
>
>> And if I'm reading it correctly, the Perl
>> script's process starts tcpdump, but redirects its output to its own
>> input, and reads it line by line.
> [...]
>>...however, the Perl script solution looks interresting.. Is it
>> possible to do something like that in Python?
>
> os.popen()
>
> http://www.python.org/doc/current/lib/os-process.html

I should have also added that there's a module that allows you
to call libpcap directly (libpcap is the library that tcpdump
uses to capture packets). 

  http://sourceforge.net/projects/pylibpcap/

It's way, way more efficient than parsing tcpdump's output.  If
you're only grabbing a few packets it may not matter. For some
of the apps I've done, using pylibpcap has cut run-times by a
factor of 10 or more.
  
-- 
Grant Edwards   grante Yow!  Life is selling
  at   REVOLUTIONARY HAIR
   visi.comPRODUCTS!
-- 
http://mail.python.org/mailman/listinfo/python-list


XML + Elementree + (ZODB or Durus) experiments?

2006-01-23 Thread News Reader
A year or so ago, there was a posting - I believe on someone's blog - 
which told of a unique experiment.  The experimenter tried loading and 
searching a large XML document based on three strategies:

1. (I think) elementree directly
2. Store entire XML document in ZODB (or Durus, can't remember)
3. Subclass Elementree.Element, store each XML node separately in the 
ZODB/Durus.

The experimenter then did timings on opening up and using the XML 
documents in each of these three ways.

Does anybody remember that post?  Does any body have a link, code, 
cache, anything?

Please reply to the list, as the email address is invalid.

Thanks,

E. List


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


Re: Loading a Python collection from an text-file

2006-01-23 Thread James Stroud
Ilias Lazaridis wrote:
> within a python script, I like to create a collection which I fill with 
> values from an external text-file (user editable).
> 
> How is this accomplished the easiest way (if possible without the need 
> of libraries which are not part of the standard distribution)?
> 
> something like:
> 
> text-file:
> {peter, 16},
> {anton, 21}
> 
> -
> 
> within code:
> 
> users.load(text-file.txt)
> 
> for user in users
>   user.name
>   user.age
> 
> .
> 

This is specific for the text above. You will have to re-craft a regex 
if the actual file is different.

import re

def get_names(afile):
   regex = re.compile(r'{([^,]*),\s*([^}]*)}')
   names = []
   for aline in afile:
 m = regex.search(aline)
 names.append(m.groups())
   return names

def test():
   import cStringIO
   afile = cStringIO.StringIO("{peter, 16},\n{anton, 21}\n")
   print get_names(afile)

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


Re: Oddities of Tkinter

2006-01-23 Thread James Stroud
Tuvas wrote:
> I am building a tkinter program. A part of this program is to read data
> from an incoming interface, and depending on the data, will display a
> bit of text on the tk dialog, it decodes this data, so to speak. If one
> command is sent, everything's just fine. When multiple are sent, the
> program will stop responding, and will only continue to respond after
> one types -c. The statement at fault is something like this.
> 
> e1=StringVar()
> Label (master,textvariable=e1, width=32).grid(row=44, column=4)
> 
> def disp_mes1(text):
>   e1.set(text)
> 
> It's the line 31.set(text) that takes so long when there's other
> processes running. I've ran this program sucessfully many times on
> another computer, however, when transfering to another with the same
> OS, this problem was created. Any ideas as to what I might be able to
> do to fix this problem? My main code is hopelessly complex to post the
> entire thing, and I can't recreated the same structure with smaller
> ammounts of code. Thanks for the help!
> 

The code you posted looks okay (assuming "31.set(text)" is a typo). This 
is very standard usage of Tkinter, so your problem may be somewhere else 
in your code. What happens if you replace disp_mes1() with

def disp_mes1(text):
   print text

Does it still hang?

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


Re: Oddities of Tkinter

2006-01-23 Thread Tuvas
Nope, that's the oddest thing about it all... Perhaps the statement is
called twice or something along those lines, but there again, I can't
see how it would be...

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


Re: Oddities of Tkinter

2006-01-23 Thread James Stroud
Tuvas wrote:
> Nope, that's the oddest thing about it all... Perhaps the statement is
> called twice or something along those lines, but there again, I can't
> see how it would be...
> 

Very strange behavior can occur if the same python process instantiates 
  Tkinter.Tk more than once (either concurrently or at different times). 
This is my best guess without any other code to look at.

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


trying to use swig for the first time

2006-01-23 Thread Gary Wilson Jr
...I have some C code (foo.c and foo.h) that I would like to be able to access 
using python.

I've written my interface file (foo.i) like so:
%module foo
%{
#include "foo.h"
%}
%include "foo.h"

I then do the following on the command line:
$ swig -python foo.i
$ gcc -c foo.c foo_wrap.c -I /usr/include/python2.4
$ ld -shared foo.o foo_wrap.o -o _foo.so

Then when I try importing the module into python:
$ python -c "import foo"
Traceback (most recent call last):
   File "", line 1, in ?
   File "foo.py", line 5, in ?
 import _foo
ImportError: ./_foo.so: undefined symbol: EVP_DecodeBlock

Now, EVP_DecodeBlock can be found in /usr/include/openssl/evp.h:
int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n);

And evp.h in included in foo.h:
#include 

What am I doing wrong here?
Do I need to include more in the interface file?

I tried adding the EVP_DecodeBlock declaration to the interface file like so:
%module foo
%{
#include "foo.h"
extern int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n);
%}
%include "foo.h"
extern int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n);

But this led to the exact same error when trying to import the python module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Backreferences in python ?

2006-01-23 Thread Giovanni Bajo
Pankaj wrote:

 Perl :::
> ***
> while(  )
> {
>
>  line = $_;
>
>  pattern = "printf\( \"$lineNo \" \),";
>
>  line =~ s/"for(.*)\((*.)\;(.*)/for$1\($pattern$2\;$3/g;
> }
>
> This is used to
>
> search for :for ( i = 0; i < 10; i++)
> Replace with:  for( printf( "10" ), i =0; i < 10; i++)
> Where 10 is the line no.


import re
import fileinput

for L in fileinput.input(inplace=True):
pattern = 'printf("%d"),' % input.filelineno()
L = re.sub(r"for(.*)\((*.)\;(.*)", r"for\1\(%s\2;\3" % pattern, L)
print L,

or something
-- 
Giovanni Bajo


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


Re: ANN: Introduction to Event-Driven Programming

2006-01-23 Thread Carl Cerecke
Randall Parker wrote:
> Steve,
> 
> This is an aside: I'd love to see someone implement in Python a
> framework similar to the Quantum Leaps Quantum Framework for
> event-driven programming. I think Python has some features that lend
> themselves to a neater implementation than what can be done in C/C++.
> 
> More generally, I'd like to see an event driven framework which would
> be more declarative than the Quantum Framework. Rather than write code
> for most transitions it should be possible to declare in data what
> various events cause as transitions from states to states. Then
> optionally hang pointers to code for things to do before transitioning.
> Even let the code return a flag to test for whether to transition.
> 

There's a small discussion in this group currently regarding efficiently 
representing state machines in python (without resorting to bytecode 
hacks) under the thread "Python code written in 1998, how to 
improve/change it?". That would be a part of what you want.

Cheers,
Carl.

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


Re: Numarray, numeric, NumPy, scpy_core ??!!

2006-01-23 Thread Sébastien Boisgérault

[EMAIL PROTECTED] wrote:
> Robert Kern wrote:
> > Sébastien Boisgérault wrote:
> >
> > > By the way, I tried numpy 0.9.4 10 minutes ago and guess
> > > what ? 'eigenvalue' is broken too ... (hangs forever)
> >
> > On what platform? Are you linking against an optimized BLAS? We can't fix
> > anything without details. I'll be happy to work with you on this bug over 
> > on the
> > numpy-discussion list.
>
> This is a guess, but the original poster is probably using one of the
> newer (3.4.x or 4.0.x) versions of gcc. This is a known problem:
> https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=138791
> (that's one of the applicable bug reports).
>
> A workaround to this problem is to add the option '-ffloat-store' to
> your CFLAGS.

Great ! It works :)
Thank you greg !

SB

> 
> 
> -greg

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


Re: Numarray, numeric, NumPy, scpy_core ??!!

2006-01-23 Thread Sébastien Boisgérault

Robert Kern wrote:
> Sébastien Boisgérault wrote:
> > Robert Kern wrote:
> >
> >>Sébastien Boisgérault wrote:
> >>
> >>>By the way, I tried numpy 0.9.4 10 minutes ago and guess
> >>>what ? 'eigenvalue' is broken too ... (hangs forever)
> >>
> >>On what platform?
> >
> > Linux, Mandriva 2006 (gcc 4.0.1, etc.)
>
> Okay, my answer then is, "Don't use gcc 4." gcc 4 broke enough other projects
> that I don't feel too bad about saying that.

You certainly should not feel bad about that. Matlab does not support
anything
more recent than gcc 3.3 -- and specifically Simulink S-Functions do
not work
when compiled with gcc 3.4.x or 4.0.x.

> In the meantime, can you try the
> workaround that Greg Landrum suggested?

I tried it, it works :)

> Also, we are using Trac now to manage numpy, so please submit tickets here:

ok.

>   http://projects.scipy.org/scipy/numpy/
>
> Thanks!
>
> --
> Robert Kern
> [EMAIL PROTECTED]
>
> "In the fields of hell where the grass grows high
>  Are the graves of dreams allowed to die."
>   -- Richard Harter

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


Re: Some thougts on cartesian products

2006-01-23 Thread Kay Schluehr
Bryan Olson wrote:

> There's no such thing; you'd have to define it first. Are duplicates
> significant? Order?

That's all trivial isn't it? A string is a set of pairs (i,c) where i
is an integer number, the index, with 0<=ihttp://mail.python.org/mailman/listinfo/python-list


Re: Loading a Python collection from an text-file

2006-01-23 Thread Ken Starks
Ilias Lazaridis wrote:

> within a python script, I like to create a collection which I fill with
> values from an external text-file (user editable).
> 
> How is this accomplished the easiest way (if possible without the need
> of libraries which are not part of the standard distribution)?
> 
> something like:
> 
> text-file:
> {peter, 16},
> {anton, 21}
> 
> -
> 
> within code:
> 
> users.load(text-file.txt)
> 
> for user in users
>user.name
>user.age
> 
> .
> 
"""
What I do for this kind of work is to use a gnumeric spreadsheet
which saves the data in a simple xml format. xml is much less
error-prone than plain text.
Google for, and study 'The gnumeric file format' by David Gilbert.
You need to know how to unzip the file, and how to write a SAX parser.


If you want to use a plain text format, keep it simple. I would
separate the two fields with tab (thus permit a comma within a field)
and allow 'comment' lines that start with a hash.
You don't need the braces, or the end-of-line comma you included.

# snip 'text-file.txt'
# name and age on one line separated by tab
Jonny   8
Mary87
Moses   449


# end-snip 'text-file.txt'
Then:
"""

import string

class user:
def __init__(self,name,age):
self.name=name
self.age=int(age) # or a float, or a time-interval, or date-of-birth

def show(self):
print "%s is aged %s" % (self.name, self.age)

if __name__=="__main__":
users=[]
filename="text-file.txt"
fieldsep="\t"
F=open(filename,"r")
Lines=F.readlines()
for L0 in Lines:
L1=string.strip(L0)
if not L1.startswith("#"):
Record=string.split(L1,fieldsep)
# insert error handling/validation here
users.append(user(Record[0],Record[1]))

F.close()
for user in users:
   user.show()


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


Re: Concurrency, I guess

2006-01-23 Thread Stormcoder
Using candygram you can send the sync thread a message telling it to
reread the config file or you could send a message that changes the
setting directly. Candygram is much better than the standard threading
module which is designed after the Java threading library. Java
recently added another threading library because the old one was not
adequate.

The reason you can't simply share a global variable is that threads do
not share state. You have to go through a lot of trouble to share that
state. First you have to setup some form of interprocess communications
such as a memory mapped file, shared mem, pipe, socket etc. You then
have to implement locking and try to debug what you have done.
Debugging multi threaded programs is inherently difficult.
I would highly recommend using candygram or an asynchronous library,
since it sounds like you haven't done any multi-threaded programming
before. In candygram you can send threads messages which don't require
any synchronization or IPC setup.

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


  1   2   >