Re: Problem with MySQLdb and mod_python

2008-07-17 Thread Cyril Bazin
Thanks for your reply

The apache log contains lines like :

[Tue Jul 15 23:31:01 2008] [notice] mod_python (pid=11836,
interpreter='www.toto.fr'): Importing module
'/usr/local/apache2/htdocs/intranet/courrier/test.py'
[Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal
Segmentation fault (11)
[Tue Jul 15 23:31:19 2008] [notice] mod_python (pid=11764,
interpreter='www.toto.fr'): Importing module
'/usr/local/apache2/htdocs/intranet/courrier/test.py'
[Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal
Segmentation fault (11)

I think the problem comes from the MySQLdb module.
If I can't find another solution, I think I will downgrade the MySQLdb
version to 1.2.1

Cyril

On Thu, Jul 17, 2008 at 7:27 AM, Lawrence D'Oliveiro
[EMAIL PROTECTED] wrote:
 In message [EMAIL PROTECTED], Cyril Bazin
 wrote:

 But it seems, after many tests, that the script stops at the
 instruction : c.execute(requete)

 What's the error message? This should be in Apache's error_log file.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Problem with MySQLdb and mod_python

2008-07-15 Thread Cyril Bazin
Hi,

I installed an apache server with mod_python.
I have got a problem with the mysql connection of my python script.

In fact I tried this file :
-
import os
os.environ[PYTHON_EGG_CACHE] = /tmp
import MySQLdb
from mod_python import apache

def test(req):
db=MySQLdb.connect(user=xxx,passwd=xxx,host=xxx.xxx,db=xxx)
c = db.cursor()
requete = SELECT * FROM document
nbRows = c.execute(requete)
req.write(Result : %s%repr(nbRows))
return apache.OK

-

But it seems, after many tests, that the script stops at the
instruction : c.execute(requete)
The script works if I am logged on the server as root or www. I use :
-
Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
[GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2
Type help, copyright, credits or license for more information.
 import MySQLdb
 MySQLdb.__version__
'1.2.2'
 import mod_python
 mod_python.version
'3.3.1'
-

If someone has any information that can help me...

Thanks in advance,

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


Re: How to download a web page just like a web browser do ?

2006-08-23 Thread Cyril Bazin
look at the modules urllib and urllib2, they both are provided with python : http://docs.python.org/lib/module-urllib.html
http://docs.python.org/lib/module-urllib2.htmlAnd look at the examples :http://docs.python.org/lib/node483.html
http://docs.python.org/lib/urllib2-examples.htmlOn 23 Aug 2006 07:34:45 -0700, Bo Yang [EMAIL PROTECTED]
 wrote:Hi , It is about one month passed since I post to this list
last time . Yes , I use python , I used it in every day normalwork , whenever I need to do some scripts or other little-scaleworks , python is the first one I took consideration in . I mustsay it is a powerful tool for me , and what is more important
is there is a friendly and flourish community here . Oh , I must stop appriciation and go to my question now .Everyday , I receive a newsletter from NYTimes , but Ididn't want to read the news in evening the time the letter
came in . So , I am about to download the web pagecontains the news and read them next morning ! I decide touse python to write a tool , which should be feeded with aURL , and then download the page to my disk . This
function just like the Browser's save as... function . Iknow what shoud I do to accomplish that , I need to parsethe web page , and download all pages in the page , andmodify all the links to conrespond local disk links and ...
 So , is there any similar function any one have impelment?Does anyone can share some code with me ? I really don'twant to some confusing code to process such as text findingsand substitutions .
 Thanks in advance !Bo--http://mail.python.org/mailman/listinfo/python-list

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

Re: Python-like C++ library

2006-08-23 Thread Cyril Bazin
Look at boost and boost.python . In your case, bosst.python seems more interesting, but you take a look at boost it may help you at work... http://www.boost.org/
http://www.boost.org/libs/python/doc/CyrilOn 23 Aug 2006 07:19:42 -0700, Will McGugan [EMAIL PROTECTED]
 wrote:Hi folks,I'm forced to use C++ and STL at work, and consequently miss the ease
of use of Python. I was wondering if there was a C++ library thatimplemented the fundamental objects of Python as close as possible,perhaps using STL underneath the hood.Too clarify, Im not looking to interface C++ with Python in any way,
just to emulate the strings / containers / slicing etc. I did googlefor it but my search terms were too vague...Thanks in advance,Will McGugan--http://www.willmcgugan.com
--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: GIS

2006-04-03 Thread Cyril Bazin
Postgis is only an extension of Postgres which add new classes and new operations specialised for GIS.
All you should know, is how to build SQL requests for postgres...

If you want to be familiarised with the GIS, you should try to make your own little project. 
So you will be able to ask more precises questions.
Cyril
On 4/3/06, Albert Leibbrandt [EMAIL PROTECTED] wrote:
HiI need to get myself familiarised with GIS, specifically postgis forpostgres. Can anyone give some advice, or some docs that start at thebeginning. I've tried the postgis mailing list but it does not seem as
if that list is very active.Perhaps you guys know of gis packages for python?ThanksAlbert--http://mail.python.org/mailman/listinfo/python-list

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

Re: Try Python!

2006-03-30 Thread Cyril Bazin
Now, you can try laszlo in 10 minutes http://www.laszlosystems.com/lps/laszlo-in-ten-minutes/ .

Reference: http://www.openlaszlo.org/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: spliting on :

2006-03-06 Thread Cyril Bazin
On 3/6/06, Bryan Olson [EMAIL PROTECTED] wrote:
Peter Hansen wrote: The archives could tell you more, but basically on is usually interested in *identity* with a singleton object (None), not in whether the object on is examining happens to compare equal.A custom object could be
 designed to compare equal to None in certain cases, even though it *is not* None, leading to the == None approach being defective code.But if a custom class allows instances to compare as equal to None,
we might reasonably expect the programmers had a reason. There's notmuch anyone can do with None besides passing it around and comparingit by value or identity. Insisting on 'is' rather than '==' will break
whatever polymorphism such a custom object was trying to achieve.I agree. None is an object! If you want to compare an object to another objectwhy not using ==?Cyril

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

Re: spliting on :

2006-03-04 Thread Cyril Bazin
Your file looks like a list of IP adresses. You can use the urllib and urllib2 modules to parse IP adresses.import urllib2for line in open(fileName.txt): addr, port = urllib2.splitport(line)
 print (port != None) and '' or portCyril
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: spliting on :

2006-03-04 Thread Cyril Bazin
Ok, ok, there was a mistake in the code. (Of course, it was done on prupose in order to verify if everybody is aware ;-)I don't know why it is preferable to compare an object to the object None using is not.
== is, IMHO, more simple. Simple is better than complex. So I use ==. The correct program is:import urllib2for line in open(fileName.txt): addr, port = urllib2.splitport
(line)
 print (port == None) and '' or portor import urllib2
for line in open(fileName.txt):
 addr, port = urllib2.splitport(line)

 if port == None: print ''  else: print port
On 3/4/06, Peter Hansen [EMAIL PROTECTED] wrote:
Cyril Bazin wrote: Your file looks like a list of IP adresses. You can use the urllib and urllib2 modules to parse IP adresses. import urllib2 for line in open(fileName.txt):
 addr, port= urllib2.splitport(line) print (port != None) and '' or portIs this what you want to happen when port is None?  port = None  print (port != None) and '' or port
NoneI think you're getting caught by the classic and/or trap in Python,trying to avoid using a simple if statement.By the way, equality comparison with None is generally a bad idea aswell, so even if the above worked it should be (port is not None) rather
than (port != None).-Peter--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PEP 354: Enumerations in Python

2006-02-28 Thread Cyril Bazin
What about that?

SomeNumbers = enum('0', '1', '2', '3', '4', '5', '6', '7')

or

Rooms = enum('1bed', '2beds', 'moreThan2beds')

or even

Comments = enum('#', ';', '//')


CyrilOn 28 Feb 2006 03:14:25 -0800, Carl Banks [EMAIL PROTECTED] wrote:
Stefan Rank wrote: on 28.02.2006 07:50 Carl Banks said the following:  Ben Finney wrote:  This PEP specifies an enumeration data type for Python.  [snip] 
  Here's why I think it's not too useful to begin with: the benefits of  the enum you describe here are pretty weak. I need to disagree heavily here :)the benefits of the enum you describe here [beyond my example which I
claimed enum was only a minor improvement over] are pretty weak.  It's a pretty weak case to have a dedicated builtin to prevent  duplicates in something that changes maybe once a month, as enums tend
  to change rather slowly.(At least, that's the way enums in other  languages are used, and the design you present here seems to suggest  you intend to use them that way as well.)And frankly, a unit test or
  assertion could check this. [snip] I don't understand what you mean by 'change rather slowly'?Construct data structure on-the-fly from an XML file edited by multiplepeople every day= changes rather quickly
Construct data structure from a Python file that was last edited a yearand a half ago = changes rather slowlyTypically, enums fall into the latter category.You set the enumvalues, and then pretty much leave them alone, adding new values only
occasionally.(Come on, how often do the days of the week change?)All I was saying is, changes to the enum values are infrequent enoughthat having a special type just to make sure there are no duplicates is
a waste.The only justification for a built-in enum is the other stuffyou mentioned. One thing that is probably missing to allow this, is a enum-set-creation with the | operator::Weekdays = enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
daysihate = Weekdays.mon | Weekdays.thu (and this discussion needs to move to python-dev ?)What's wrong with set((Weekdays.mon,Weekdays.thu))?Explicit is betterthan implicit.
 As for the metaclass versions: For myself, the above version feels more natural and straightforward (in the same way as the PEP author describes it), though I understand the subclassing ideas.
 But are there use cases for subclassing, that aren't better served with a new enum or something homegrown? Can C++/Pascal/Java enums be subclassed?In C++, enum is a type but not a class.Same thing with Ada.Java
didn't have enums last time I checked.Don't know about Pascal.Ididn't care too much about subclassing; I just thought different enumconstant that couldn't (or, rather, oughtn't) be compared probablyshould be instances of a separate class.It doesn't matter much,
though.Should something like this work:day = Weekdays.monisinstance(day,Weekdays)?Carl Banks--http://mail.python.org/mailman/listinfo/python-list

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

Re: Vectorization and Numeric (Newbie)

2006-02-28 Thread Cyril Bazin
Are you looking for the map function?

 def f(x): return x+4
 map(f, [1,2,3,3,70])
[5, 6, 7, 7, 74]

CyrilOn 2/28/06, Ronny Mandal [EMAIL PROTECTED] wrote:
Assume you have a mathematical function, e.g. f(x) = x + 4To calculate all the values from 1 to n, a loop is one alternative.But to make this function work with vectors instead i.ef(x_vector) = result_vector,
how should the function then be implemented?ThanksRM--Support bacteria - it's the only culture some people have!--http://mail.python.org/mailman/listinfo/python-list

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

www.mywebsite.py

2006-01-24 Thread Cyril Bazin
Does someone ever tried (and succeed) to make an address like www.website.py.I found that the .py extension is given to the paraguay.I found this link (
http://www.nic.py/) but I don't speak spanish... If someone has more informations...Cyril
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: flatten a level one list

2006-01-13 Thread Cyril Bazin
I added my own function to the benchmark of Robin Becker:from itertools import chaindef flatten9(x, y): return list(chain(*izip(x, y)))Results: 
no psyco Name 10 20100200500 1000
 flatten1104.499199.699854.301 1673.102 4084.301 8078.504
 flatten2111.103204.706944.901 1778.793 4554.701 8773.494 flatten3174.594310.302
 1526.308 2880.001 7332.49212373.209 flatten4115.204156.093467.2058
53.705 1920.795 2755.713 flatten5 79.894117.803406.504762.892 1764.297 2663.898
 flatten6136.399246.596 1142.406 2243.400 5494.809 8625.221
flatten6a163.889279.689 1320.195 2691.817 6481.910 9879.899
flatten6b175.881275.111 1220.393 2440.596 5955.291 8979.106
flatten6c160.813272.989 1138.186 2472.591 5726.314 8415.699
flatten6d126.004215.292988.603 1932.383 4734.492 7447.696
 flatten7 37.217 43.297 89.407134.897233.006343.013
 flatten8 93.198190.306 1739.597 4987.90727208.01878883.505flat
ten8a112.915220.299 1875.997 5491.59028395.31981628.394 flatten9 98.896159.812
651.288 1153.994 2980.685 3927.398Unfortunatly I can't test with psyco for the moment...Cyril
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: flatten a level one list

2006-01-12 Thread Cyril Bazin
Another try:

def flatten6(x, y):
return list(chain(*izip(x, y)))

(any case, this is shorter ;-)

Cyril

On 1/12/06, Michael Spencer [EMAIL PROTECTED] wrote:
 Tim Hochberg wrote:
  Michael Spencer wrote:
Robin Becker schrieb:
Is there some smart/fast way to flatten a level one list using the
latest iterator/generator idioms.
  ...
 
  David Murmann wrote:
Some functions and timings
  ...
 
  Here's one more that's quite fast using Psyco, but only average without it.
 
 
  def flatten6():
   n = min(len(xdata), len(ydata))
   result = [None] * (2*n)
   for i in xrange(n):
   result[2*i] = xdata[i]
   result[2*i+1] = ydata[i]
 
  -tim
 
 Indeed:

 I added yours to the list (after adding the appropriate return)

testthem()
timethem()
   flatten1(...)  702 iterations, 0.71msec per call
   flatten2(...)  641 iterations, 0.78msec per call
   flatten3(...)  346 iterations, 1.45msec per call
   flatten4(...)  1447 iterations, 345.66usec per call
   flatten5(...)  1218 iterations, 410.55usec per call
   flatten6(...)  531 iterations, 0.94msec per call
   

 (See earlier post for flatten1-5)

 Michael

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

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


Re: initialising a list of lists

2005-11-16 Thread Cyril Bazin
Hello,

 b = [[] for _ in xrange(6)] # - note the xrange!
 b[3].append('X')
 b
[[], [], [], ['X'], [], []]
This syntax might be less hairy but could be better when you use large table.

You can hide this syntax by making a function:

def buildMatrix(nbRows):
 return [[] for _ in xrange(nbRows)]

Then you call:

 b = buildMatrix(6)

Or:

 b = buildMatrix(nbRows=6)

Is it better for you? 

Cyril

On 11/16/05, Peter Kleiweg [EMAIL PROTECTED] wrote:
Fredrik Lundh schreef op de 16e dag van de slachtmaand van het jaar 2005: Peter Kleiweg wrote:  This does not what I want it to do:   a = [[]] * 6
  a[3].append('X')  a [['X'], ['X'], ['X'], ['X'], ['X'], ['X']]   This does what I want:   b = [[] for _ in range(6)]
  b[3].append('X')  b [[], [], [], ['X'], [], []]   The first is clear and wrong. The second is hairy and right.  Is there a way to do it clear and right?
 http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-listIn other words: no there isn't.
--Peter KleiwegL:NL,af,da,de,en,ia,nds,no,sv,(fr,it)S:NL,de,en,(da,ia)info: http://www.let.rug.nl/~kleiweg/ls.html--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can Anyone Help me on this

2005-11-03 Thread Cyril Bazin
Here is an example of copying then reversing a list:

 l1 = [1,2,C]
 l2 = l1[:]
 l2.reverse()
 l2
['C', 2, 1]
-- 
http://mail.python.org/mailman/listinfo/python-list


meschach + Python

2005-10-31 Thread Cyril Bazin
Hello,

I need to compute eigenvalues and eigenvectors on sparse matrix.
I found a C library meschach which seems to do the work. 
Unfortunatly, this libray doesn't seem to be interfaced in Python.

Has anyone ever used this library and interfaced it in Python or has a solution
to compute eigenvalues and eigenvalues on sparse matrix efficiently in Python?

Thanks in advance,

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

Re: A rather unpythonic way of doing things

2005-09-29 Thread Cyril Bazin
Crypthonic could be the exact word...On 29 Sep 2005 15:19:11 +0100, Peter Corbett [EMAIL PROTECTED]
 wrote:Richie Hindle [EMAIL PROTECTED]
 writes: [Peter]  http://www.pick.ucam.org/~ptc24/yvfc.html [Jeff]  Yuma Valley Agricultural Center?
  Yaak Valley Forest Council? I went through the same process.My guess is Yes, Very F'ing Clever. Peter?You're all thinking about it the wrong way (he says, being cryptic).
Peter--A frightful hobgoblin is stalking throughout Europe. - The Communist Manifesto, 1st English Edition--http://mail.python.org/mailman/listinfo/python-list

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

Re: [newbie]search string in tuples

2005-08-20 Thread Cyril Bazin
Try the code below. 

#-
list=[airplane,car,boat]
select = None
while select not in list:
  select=raw_input(Which vehicle?)#-

Cyril
On 8/20/05, Viper Jack [EMAIL PROTECTED] wrote:
Hi all,i'm new to python programming so excuseme if the question is very stupid.here the problem.this code worklist=[airplane]select=varswhile select != list[0]: select=raw_input(Wich vehicle?)
but i want check on several object inside the tuple so i'm trying this:list=[airplane,car,boat]select=varswhile select != list[0] or list[1] or list[2]: select=raw_input(Wich vehicle?)
but loops and doesn't want work.I have tried with other methods (for) but nothings.I haven't find nothing on this topic, so i asked here.Thanks in advance.--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A PIL Question

2005-08-14 Thread Cyril Bazin
Try Image.new in place of Image.Image if you want to build a new image.

At which level are you?

CyrilOn 14 Aug 2005 10:34:38 -0700, Ray [EMAIL PROTECTED] wrote:
Hello,I'm using latest PIL version with Python 2.4.1. (for solving a level inPython Challenge actually...). Anyway, I'm trying to draw a picture. Myquestion is, why is it that putdata() won't work? Even this won't run:
import Imageim = Image.open(something.jpg)seq = im.getdata()image = Image.Image()image.putdata(seq)image.show()I always get:Traceback (most recent call last):
File Script1.py, line 31, in ?image.putdata(seq)File D:\Development\Python24\Lib\site-packages\PIL\Image.py, line1120, in putdataself.im.putdata(data, scale, offset)
AttributeError: 'NoneType' object has no attribute 'putdata'Anybody has any idea why this is the case?Thanks,Ray--http://mail.python.org/mailman/listinfo/python-list

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

Re: Help sorting a list by file extension

2005-08-12 Thread Cyril Bazin
Maybe simpler but not very much simpler: one line for each solution. 

And in your solution the lambda is evaluated at each comparaison of the sort algorithm isn't it? 

So your code seems less productive than the bengt's code which apply
the same code as the lambda only one time by entry in the list.
Cyril
On 8/12/05, George Yoshida [EMAIL PROTECTED] wrote:
Bengt Richter wrote:[name for dec,name in sorted((int(nm.split('.')[1]),nm) for nm in namelist)] ['test.1', 'test.2', 'test.3', 'test.4', 'test.10', 'test.15', 'test.20']Giving a key argument to sorted will make it simpler::
 sorted(namelist, key=lambda x:int(x.rsplit('.')[-1]))-- george--http://mail.python.org/mailman/listinfo/python-list

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

Re: need help with python syntax

2005-08-11 Thread Cyril Bazin
I think bs = BeautifulSoup.BeautifulSoup( oFile) but I don't understand what you are doing...
(I never used BeautifulSoup...)

Maybe It is somthing like:

import itertools
for incident in itertools.chain(bs('tr',{'bgcolor' : '#ee'}), bs('tr',{'bgcolor' : 'white'})):
 do_something()
Look at some examples on the web or ask a precise question (what is your problem exactly?):
http://www.petersblog.org/taxonomy/term/2
http://crummy.com/software/BeautifulSoup/documentation.html
... 

Cyril
On 11 Aug 2005 11:56:49 -0700, yaffa [EMAIL PROTECTED] wrote:
dear python gurus,quick question on syntax.i have a line of code like thisfor incident in bs('tr',{'bgcolor' : '#ee'}):what i want it to do is look for 'bgcolor' : '#ee' or 'bgcolor' :
'white' and then do a whole bunch of stuff.i've tried this:for incident in bs('tr',{'bgcolor' : '#ee'} or {'bgcolor' :'white'} ): but it only seems to pick up the stuff from the{'bgcolor' : '#ee'}
any ideas folks?thanksyaffa--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Splitting a string into groups of three characters

2005-08-08 Thread Cyril Bazin
Another solution derived from an old discussion about the same problem?

def takeBy(s, n):
 import itertools
 list(''.join(x) for x in itertools.izip(*[iter(s)]*n))

(Hoping len(s) % n = 0)

CyrilOn 8 Aug 2005 11:04:31 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED]
 wrote:Yes i know i made a mistake,['Hell','o W','orl','d']but you know what I mean lol,
I'll probly useJohn Machin's def nsplit(s, n):return [s[k:k+n] for k in xrange(0, len(s), n)]It seems fast, and does not require any imports.But anyways, thank you for all your help, you rock! :)
--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Parallel arithmetic?

2005-08-04 Thread Cyril Bazin
Hello,

I propose 3 solutions. If someone have time to waste, he can make a
benchmark to know which is the fastest and give us the results on the
list. 

Solution 1:

import itertools
c = [a_i-b_i for a_i, b_i in itertools.izip(a, b)]
Solution 2:

c = map(operator.sub, a, b)
#map will be removed from the next versions of python. So, it's not a good solution.

Solution 3:

import itertools
c = list(itertools.imap(operator.sub, a, b))


These solutions give you a list. Depending on your usage, an iterator can be better.

Cyril

On 04 Aug 2005 15:41:28 -0700, Paul Rubin http://phr.cx@nospam.invalid wrote:
Terrance N. Phillip [EMAIL PROTECTED]
 writes: Given a and b, two equal length lists of integers, I want c to be [a1-b1, a2-b2, ... , an-bn].c = [a[i] - b[i] for i in xrange(len(a))]--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Simple Problem

2005-07-24 Thread Cyril Bazin
By any chance are you speaking about the function repr ?
Cyril
On 24 Jul 2005 18:14:13 -0700, ncf [EMAIL PROTECTED] wrote:
I know I've seen this somewhere before, but does anyone know what thefunction to escape a string is? (i.e., encoding newline to \n and achr(254) to \xfe) (and visa-versa)Thanks for helping my ignorance :P
-Wes--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Hash functions

2005-07-21 Thread Cyril Bazin
Maybe in certain case you could use hash to compare objects (hashable
of course) quicker by comparing there hash values, if the hash values
are the same you test the equality between the objects. 

But the sets and dicts cover the greatest part of the use of hash.
(Personally, I never used that explicitly in my programs)

Cyril

On 7/21/05, Michael Hudson [EMAIL PROTECTED] wrote:
Steven D'Aprano [EMAIL PROTECTED] writes: Do people often use hash() on built-in types?Only implicitly. What do you find it useful for?
Dictionaries :) How about on custom classes?Same here. Can anyone give me some good tips or hints for writing and using hash functions in Python?Well, the usual tip for writing them is, don't, unless you need to.
If implement __eq__, then you need to, so it's fairly common to justhash a tuple containing the things that are considered by the __eq__method.Something like:class C(object):def __init__(self, a, b, c):
self.a = aself.b = bself.c = cdef __eq__(self, other):return self.a == other.a and self.b == other.bdef __hash__(self):return hash((self.a, self.b
))Cheers,mwh--I'm a keen cyclist and I stop at red lights.Those who don't needhitting with a great big slapping machine.
-- Colin Davidson, cam.misc--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python certification

2005-07-20 Thread Cyril Bazin
Fine, 

Go to http://www.pythonchallenge.com and try the challenge, if you
are able to get to the level 17-18, you can say you start to have good
skills in Python. You will prove:
you are not stupid, 
you know regex, basic sound/image treatment, the basics of zip/bz2, you
understood how to use urllib/urllib2 and xmlrpc and many other things.

When you get to the level 17-18, go to the IRC and ask to theSamet a
certification. If he is in a good mood, maybe he will give you an
ascii-art diplom like Rocco! ;-)

Cyril
On 20 Jul 2005 05:41:39 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED]
 wrote:hii bassically need it cuz i am appyling to colleges this year and
i know this kind of stuff really helps.besides since i am learning python i thought i might get some creditfor it as well.its bassically for a mention in my resume/bio-data/appliccationi am willing to spend about $50-100 but any more is out of my bugdet.
even $50 is hard on me.i did find this great site that wouldlet me give a perl exam in $9.99but they don't have python.--http://mail.python.org/mailman/listinfo/python-list

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

Re: How to store 3D data? (data structure question)

2005-07-20 Thread Cyril Bazin
The question of the type of the data sutructure depends of your use of the data. 
You could avoid some confusion without naming your columns lines...

Anyway, here is a piece of code that read the file and count the star on the fly:
(The result is a dict of dict of int.)

-
import itertools
import csv

f = open(toto.data) #change your file name
lineReader = csv.reader(f)
 
#Set the lines titles (RHA280, etc)
l = lineReader.next() 
linesTitles = l[2:]

#We construct the data structure and count the stars on the fly
datas = {}
for l in lineReader:
 name, allele = l[:2]
 if not allele: #empty line
 continue
 if name: #new block defining a TD*
 currentName = name
 d = dict.fromkeys(linesTitles, 0)
 datas[currentName] = d
 lines = l[2:]
 #add 1 to the lines not empty (= with a star)
 for title, value in itertools.izip(linesTitles,lines): 
 if value:
 d[title] += 1
 
#little tests
print datas
print datas[TDF1][RHA280]
print datas[TDF3][RHA280]
-
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Dictionary, keys and alias

2005-07-19 Thread Cyril Bazin
Glauco, 

Be careful if you decide to use hash. 
There is possibility of bugs due to that approach, (if hash(x) == hash(y) and x != y).
Even if the probability of bug is near 0, your computer will certainly recall you what is the murphy law.
If I were you, I would prefer another approach. 

Cyril
On 7/19/05, Glauco [EMAIL PROTECTED] wrote:
Steven D'Aprano wrote: On Mon, 18 Jul 2005 12:17:37 +0200, Glauco wrote:I want to insert a concept of alias in a dict_based class.The ideais to have a facoltative name in the same dict that correspond
at the same value. With this alias i can change original value.example:mydict['a'] = 1I must define an aliasexample: myFunctAlias( mydict, 'a', 'b')
print mydict{'a':1, 'b':1}mydict['b'] = 2print mydict{'a':2, 'b':2}The only idea i have is to implement two dictionary one for convert
name, alias in two keys with the same value (eg.numeric) in the firstdict. The second for store only one time the k, v . You need some sort of redirection, something like this (untested):
 class Doubledict: def __init__(self, **kargs): self.data = ""> self.aliases = {} for key in kargs: # Point the key to a hash.
 self.aliases[key] = hash(key) # And point the hash at the value. self.data[hash(key)] = kargs[key] def setalias(self, key, alias): # Point the alias to the same hash as the real key.
 self.aliases[alias] = hash(key) def __getitem__(self, key): return self.data[self.aliases[key]] def __setitem__(self, key, value): self.data
[self.aliases[key]] = value The only niggly worry I have is I'm not sure when hash can be used, when it is unique, or even if is it guaranteed to be unique.Thank Steve, the idea was the same...
but yours using hash is much elegant.Thank youGlauco--\\\|///\\-
-//
(@ @)+-oOOo-( )-oOOo--+||| I have a dream that one day this nation will rise up and || live out the true meaning of its creed: We hold these |
| truths to be self-evident:that all men are created equal.|| I have a dream that one day on the red hills of Georgia|| the sons of former slaves and the sons of former || slaveowners will be able to sit down together at a table |
|
of
brotherhood.|| I have a dream that one day even the state of Mississippi, || a desert state, sweltering with the heat of injustice|| and oppression, will be transformed into an oasis of |
|
freedom and
justice.
|| I have a dream that my four children will one day live in|| a nation where they will not be judged by the color of || their skin but by the content of their character.||
I have a dream
today.Martin
Luther King, Jr28 Ago 1963 |++|glauco(at)uriland.it||www.uriland.it.oooOICQ:
115323690 |+- ( )-- Oooo.-+
\ (( )\_))
/(_/--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: What is your favorite Python web framework?

2005-07-18 Thread Cyril Bazin
Hello,

I never used a web framework using Python modules, but I think cheetah,
Karrigel and CherryPy are not good since they allow user to play with
the HTML code. IMO, it's not pythonic but phpythonic.

Isn't there a python framework inspirated by the Smalltalk framework Seaside? 
I think it's the way to build a web site like an application and not like an HTML page. 

CyrilOn 18 Jul 2005 00:52:40 -0700, laurent [EMAIL PROTECTED] wrote:
hello,I follow somes projects that have a pythonic way to make web site.there's thats projects : http://www.cherrypy.org/and 
http://subway.python-hosting.com/subway aim to be like ruby on rails frameworks , simple and fastdeveloppment. It uses cherrypy and other project like : * http://www.cheetahtemplate.org/
 * http://www.formencode.org/ * http://www.sqlobject.org/--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Dictionary, keys and alias

2005-07-18 Thread Cyril Bazin
I think hash doesn't guarantee the unicity of the result. But, it should avoid the collisions...

 foo = foo
 hash(foo)
-740391237
 hash(-740391237)
-740391237

I think it's like some kind md5sum...

I propose this solution:

---
from UserDict import UserDict

class DoubleDict(UserDict):
 def __init__(self, *args):
 UserDict.__init__(self, *args)
 self.values = {}
 #self.aliases = {}

 def setAlias(self, key, alias):
 # Point the alias to the same hash as the real key.
 if key in self:
 self.data[alias] = self.data[key]
 else:
 self[alias] = key

 def __getitem__(self, key):
 return self.values[self.data[key]]

 def __setitem__(self, key, value):
 self.data.setdefault(key, key)
 self.values[self.data[key]] = value
  
print Result:
d = DoubleDict()
d[a] = 1
d[c] = 4
d.setAlias(a, b)
print d[a], d[b], d[c]
d[a] = 2
print d[a], d[b], d[c]
d[b] = 3
d.setAlias(b, c)
print d[a], d[b], d[c]
del d[c]
d[c] = 5
print d[a], d[b], d[c]
del d[a]
d[a] = 6
print d[a], d[b], d[c]

---
Result: 
1 1 4
2 2 4
3 3 3
3 3 5
6 6 5

As you can see the last test (del a and reassign a) fail because it reassign b. 
But, if your application doesn't need to midify the aliases, it's ok (I think). Else you can redefine the method __delitem__.
Cyril
On 7/18/05, Steven D'Aprano [EMAIL PROTECTED] wrote:
On Mon, 18 Jul 2005 12:17:37 +0200, Glauco wrote: I want to insert a concept of alias in a dict_based class. The ideais to have a facoltative name in the same dict that correspond at the same value. With this alias i can change original value.
 example: mydict['a'] = 1 I must define an aliasexample: myFunctAlias( mydict, 'a', 'b') print mydict {'a':1, 'b':1} mydict['b'] = 2 print mydict
 {'a':2, 'b':2} The only idea i have is to implement two dictionary one for convert name, alias in two keys with the same value (eg.numeric) in the first dict. The second for store only one time the k, v .
You need some sort of redirection, something like this (untested):class Doubledict:def __init__(self, **kargs):self.data = "">self.aliases = {}for key in kargs:
# Point the key to a hash.self.aliases[key] = hash(key)# And point the hash at the value.self.data[hash(key)] = kargs[key]def setalias(self, key, alias):
# Point the alias to the same hash as the real key.self.aliases[alias] = hash(key)def __getitem__(self, key):return self.data[self.aliases[key]]def __setitem__(self, key, value):
self.data[self.aliases[key]] = valueThe only niggly worry I have is I'm not sure when hash can be used, whenit is unique, or even if is it guaranteed to be unique.--Steven.--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Efficiently Split A List of Tuples

2005-07-13 Thread Cyril Bazin
if t is your data, you can use:

l1, l2 = zip(*t)
Cyril

On 7/14/05, Richard [EMAIL PROTECTED] wrote:
I have a large list of two element tuples.I want two separatelists: One list with the first element of every tuple, and thesecond list with the second element of every tuple.Each tuple contains a datetime object followed by an integer.
Here is a small sample of the original list: ((datetime.datetime(2005, 7, 13, 16, 0, 54), 315), (datetime.datetime(2005, 7, 13, 16, 6, 12), 313), (datetime.datetime(2005, 7, 13, 16, 16, 45), 312),
 (datetime.datetime(2005, 7, 13, 16, 22), 315), (datetime.datetime(2005, 7, 13, 16, 27, 18), 312), (datetime.datetime(2005, 7, 13, 16, 32, 35), 307), (datetime.datetime(2005, 7, 13, 16, 37, 51), 304), (datetime.datetime
(2005, 7, 13, 16, 43, 8), 307))I know I can use a 'for' loop and create two new listsusing 'newList1.append(x)', etc.Is there an efficient wayto create these two new lists without using a slow for loop?
r--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'

2005-07-12 Thread Cyril Bazin
If that can help you...

def replaceLastComma(s):
 i = s.rindex(,)
 return ' and'.join([s[:i], s[i+1:]])
 
I don't know of ot's better to do a:
' and'.join([s[:i], s[i+1:]])
Or:
''.join([s[:i], ' and', s[i+1:]])
Or:
s[:i] + ' and' + s[i+1]
Maybe the better solution is not in the list...

Cyril
On 7/12/05, Ric Da Force [EMAIL PROTECTED] wrote:
Hi,I have a string such as 'C1, C2, C3'. Without assuming that each bit oftext is of fixed size, what is the easiest way to change this list so thatit reads:'C1, C2 and C3' regardless of the length of the string.
Regards and sorry for the newbie question,Ric--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Trying to come to grips with static methods

2005-07-12 Thread Cyril Bazin
Im my opinion, class method are used to store some functions related to a class in the scope of the class.

For example, I often use static methods like that:
class Foo:
 
On 7/12/05, Steven D'Aprano [EMAIL PROTECTED] wrote:
I've been doing a lot of reading about static methods in Python, and I'mnot exactly sure what they are useful for or why they were introduced.Here is a typical description of them, this one from Guido:
The new descriptor API makes it possible to add static methods and classmethods. Static methods are easy to describe: they behave pretty much likestatic methods in C++ or Java.
http://www.python.org/2.2.3/descrintro.htmlGreat. So I have learn an entire new language to understand staticmethods. Perhaps not -- hence this cry for help.As near as I can see it, static methods are object methods that act just
like functions. Er. I always thought that object methods *were* functions,except they had some runtime magic that passed the object itself as thefirst argument.From Guido's example: class C:
... def foo(x, y):... print staticmethod, x, y... foo = staticmethod(foo)... C.foo(1, 2)staticmethod 1 2 c = C() c.foo(1, 2)
staticmethod 1 2So I compare with an ordinary class function, er, method: class D:... def foo(self, x, y):... print method, x, y... D.foo
(1, 2)Traceback (most recent call last):File stdin, line 1, in ?TypeError: unbound method foo() must be called with D instance as firstargument (got int instance instead)Okay, that is to be expected. Actually, I expected an exception that I
hadn't passed enough arguments (2 arguments when foo expects 3), but inhindsight it is obvious enough.First point of confusion. In the above exception, foo is called an unboundmethod. But type(D.foo) returns type 'instancemethod' even though foo is
being access through the class, not an instance. And type(D().foo) returnsthe same.Can I assume that in Python unbound method is just another way of sayinga method of a class that expects to be called via an instance?
I next tried this: D.foo(D(), 1, 2)method 1 2 D().foo(1, 2)method 1 2Clear as mud. An ordinary method called from an instance is the same as astatic method called from anywhere, provided you don't -- or rather, can't
-- try to access self from the static method.When would you use a static method instead of an ordinary method? It hasbeen suggested that you might use it for functions that don't need toaccess self. But that doesn't seem very convincing to me, because there is
already a perfectly good idiom for that: class E:... def foo():# returns calculated value... return 1... foo = staticmethod(foo)... def bar(self):... return 1# just ignore the value of self
... E.foo()1 e = E() e.bar()1What are some usage cases for using Class.StaticMethod() instead ofinstance.method()? Everything I've read seems to just assume that the
benefits of static methods are so obvious that they don't need explaining.Unfortunately, I haven't come from a background in OO and I'm easilyconfused, hence this post.--Steven.--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Trying to come to grips with static methods

2005-07-12 Thread Cyril Bazin
(sorry, my fingers send the mail by there own ;-)

Im my opinion, class method are used to store some functionalities (function) related to a class in the scope of the class.
For example, I often use static methods like that:

class Point:
 def __init__(self, x, y):
 self.x, self.y = x, y

 def fromXML(xmlText):
 x, y = functionToParseXMLUsingMinidomForExample(xmlText)
 return Point(x, y)
 fromXML = staticmethod(fromXML)

Here, it is used to define some kind of second constructor... 

Note that class decorator can simplify the notation, but break the compatility with older Python...

Cyril

On 7/12/05, Steven D'Aprano [EMAIL PROTECTED]
 wrote:
I've been doing a lot of reading about static methods in Python, and I'mnot exactly sure what they are useful for or why they were introduced.Here is a typical description of them, this one from Guido:

The new descriptor API makes it possible to add static methods and classmethods. Static methods are easy to describe: they behave pretty much likestatic methods in C++ or Java.

http://www.python.org/2.2.3/descrintro.htmlGreat. So I have learn an entire new language to understand staticmethods. Perhaps not -- hence this cry for help.As near as I can see it, static methods are object methods that act just
like functions. Er. I always thought that object methods *were* functions,except they had some runtime magic that passed the object itself as thefirst argument.From Guido's example: class C:
... def foo(x, y):... print staticmethod, x, y... foo = staticmethod(foo)... C.foo(1, 2)staticmethod 1 2 c = C() c.foo(1, 2)
staticmethod 1 2So I compare with an ordinary class function, er, method: class D:... def foo(self, x, y):... print method, x, y... 
D.foo
(1, 2)Traceback (most recent call last):File stdin, line 1, in ?TypeError: unbound method foo() must be called with D instance as firstargument (got int instance instead)Okay, that is to be expected. Actually, I expected an exception that I
hadn't passed enough arguments (2 arguments when foo expects 3), but inhindsight it is obvious enough.First point of confusion. In the above exception, foo is called an unboundmethod. But type(D.foo) returns type 'instancemethod' even though foo is
being access through the class, not an instance. And type(D().foo) returnsthe same.Can I assume that in Python unbound method is just another way of sayinga method of a class that expects to be called via an instance?
I next tried this: D.foo(D(), 1, 2)method 1 2 D().foo(1, 2)method 1 2Clear as mud. An ordinary method called from an instance is the same as astatic method called from anywhere, provided you don't -- or rather, can't
-- try to access self from the static method.When would you use a static method instead of an ordinary method? It hasbeen suggested that you might use it for functions that don't need toaccess self. But that doesn't seem very convincing to me, because there is
already a perfectly good idiom for that: class E:... def foo():# returns calculated value... return 1... foo = staticmethod(foo)... def bar(self):... return 1# just ignore the value of self
... E.foo()1 e = E() e.bar()1What are some usage cases for using Class.StaticMethod() instead ofinstance.method()? Everything I've read seems to just assume that the
benefits of static methods are so obvious that they don't need explaining.Unfortunately, I haven't come from a background in OO and I'm easilyconfused, hence this post.--Steven.--

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



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

Re: Trying to come to grips with static methods

2005-07-12 Thread Cyril Bazin
Ok, sorry, you are right Robert. 

What about this one: 

class Parser(object):
 def toParser(p):
 if type(p) == str:
 if len(p) == 1:
 return lit(p)
 return txt(p)
 return p
 toParser = staticmethod(toParser)

This is meant to translate p to a parser if it's not one.
'lit' is a function that take a string of length 1 and return a parser of char.
'txt' is a function that take a string of any length and return a parser.
I hope it is a better example!
That one of the rare case I used static method in Python...

Cyril
On 7/12/05, Robert Kern [EMAIL PROTECTED] wrote:
Cyril Bazin wrote: (sorry, my fingers send the mail by there own ;-) Im my opinion, class method are used to store some functionalities (function) related to a class in the scope of the class.
 For example, I often use static methods like that: class Point: def __init__(self, x, y): self.x, self.y = x, y def fromXML(xmlText): x, y = functionToParseXMLUsingMinidomForExample(xmlText)
 return Point(x, y) fromXML = staticmethod(fromXML) Here, it is used to define some kind of second constructor... Note that class decorator can simplify the notation, but break the
 compatility with older Python...Huh? classmethod was introduced with staticmethod, and in fact, this usecase is exactly what classmethods are for, not staticmethods.In [2]: class Point(object):# -- note inheritance from object
...: def __init__(self, x, y):...: self.x, self.y = x, y...: def fromXML(cls, xmlText):...: x, y = parseXML(xmlText)...: return cls(x, y)...: fromXML = classmethod(fromXML)
...:In [3]: class NewPoint(Point):...: pass...:In [4]: def parseXML(xmlText):...: return 1, 4...:In [5]: p = NewPoint.fromXML('point x=1 y=4/point')
In [6]: isinstance(p, NewPoint)Out[6]: True--Robert Kern[EMAIL PROTECTED]In the fields of hell where the grass grows highAre the graves of dreams allowed to die.
 -- Richard Harter--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Tricky Dictionary Question from newbie

2005-07-11 Thread Cyril Bazin
Hello, 

Try that, it may not be the better solution, but it seems to work:

#def invertDict(d):
# d2 = {}
# for k, v in d.iteritems():
# d2.setdefault(v, []).append(k)
# return d2
Cyril
On 7/11/05, Ric Da Force [EMAIL PROTECTED] wrote:
Hi all,I have a dictionary containing about 300 items, some of the values beingrepeated.Both keys and values are strings.How can I turn this thing onits head so that we create a key based on each unique value and build the
values based on the keys corresponding to the repeated values?It is hard to explain but this is what I mean:Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This isnot'}I want this to return a new dict with string keys and lists containing the
previous keys for repeated values.NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']}I am still learning Python and have struggled with this for hours beforedeciding to go for help.Unfortunately, I didn't really know how to search
for this in google and decided to post it here.I apologise if this is toobasic for this newsgroup...Ric--http://mail.python.org/mailman/listinfo/python-list

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

Re: Tricky Dictionary Question from newbie

2005-07-11 Thread Cyril Bazin
Hum... I think an iteritems is better, this way, python don't need to create in memory 
a complete list of couple key, value.On 7/11/05, Markus Weihs [EMAIL PROTECTED] wrote:
Hi! Dict = {'rt': 'repeated', 'sr':'repeated', 'gf':'not repeated'} NewDic = {} for k,v in Dict.items(): NewDic.setdefault(v, []).append(k)Regards, mawe--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: FORTRAN like formatting

2005-07-09 Thread Cyril Bazin
Ok, dennis, your solution may be better, but is quite dangerous:
Python can't handle if there is exactly 3 arguments passed to the
function. The created code is correct but the error will appear when
your run Fortran.

Cyril

On 7/9/05, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 On Fri, 8 Jul 2005 20:31:06 +0200, Cyril BAZIN [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:
 
 
 
  def toTable(n1, n2, n3):
  return %20s%20s%20s%tuple([%.12f%x for x in [n1, n2, n3]])
 
 Ugh...
 
 def toTable(*ns):
 return (%20.12f * len(ns)) % ns
 
 toTable(3.14, 10.0, 3, 4, 5.99)
 '  3.1400 10.  3.'
 toTable(3.14, 10.0, 3, 4, 5.99)
 '  3.1400 10.  3.
 4.  5.9900'
 toTable(1)
 '  1.'
 
 The second one IS one line, it just wraps in the news message.
 Using the *ns argument definition lets the language collect all
 arguments into a tuple, using * len(ns) creates enough copies of a
 single item format to handle all the arguments.
 
 Oh, a top-poster... No wonder I didn't recall seeing any
 Fortran.
 
  On 7/8/05, Einstein, Daniel R [EMAIL PROTECTED] wrote:
  
  
   Hi,
  
   Sorry for this, but I need to write ASCII from my Python to be read by
   FORTRAN and the formatting is very important. Is there any way of doing
   anything like:
  
   write(*,'(3( ,1pe20.12))') (variable)
  
 
 Which Fortran compiler? I know VMS Fortran was very friendly,
 when specifying blanks not significant or something like that... To
 read three floating numbers (regardless of format) merely required
 something like:
 
 read(*, '(bn,3f)') a, b, c
 
 (or 'bs' for blanks significant -- I forget which one enabled free
 format input processing)
 
 You aren't going to get prescaling; Python follows C format
 codes (if one doesn't use the generic %s string code and rely on Python
 to convert numerics correctly).
 
 def toTable(*ns):
 return (%20.12e * len(ns)) % ns
 
 toTable(3.14, 10.0, 3)
 ' 3.1400e+000 1.e+001 3.e+000'
 
 --
   == 
 [EMAIL PROTECTED]  | Wulfraed  Dennis Lee Bieber  KD6MOG 
[EMAIL PROTECTED] |   Bestiaria Support Staff   
   == 
 Home Page: http://www.dm.net/~wulfraed/
  Overflow Page: http://wlfraed.home.netcom.com/
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: FORTRAN like formatting

2005-07-08 Thread Cyril BAZIN
Hello,

I don't anderstand very well Fortran syntax, but want you say
something like that:

def toTable(n1, n2, n3):
return %20s%20s%20s%tuple([%.12f%x for x in [n1, n2, n3]])


Example:
 import math
 toTable(math.pi, 10, 8.2323)
'  3.141592653590 10.  8.2323'

If it is not that, please could you give an example of input and
output of your code?

Cyril

On 7/8/05, Einstein, Daniel R [EMAIL PROTECTED] wrote:
  
 
 Hi, 
 
 Sorry for this, but I need to write ASCII from my Python to be read by
 FORTRAN and the formatting is very important. Is there any way of doing
 anything like: 
 
 write(*,'(3( ,1pe20.12))') (variable) 
 
 In other words, I want three columns 20 spaces long, with 12 digits after
 the decimal and so on and so forth. 
 
 What I am really looking for is some general indication of how to do such
 formatting in Python. 
 
 Any help? 
 
 Dan 
  
 
 Daniel R Einstein, PhD
  Biological Monitoring and Modeling
  Pacific Northwest National Laboratory
  P.O. Box 999; MSIN P7-59
  Richland, WA 99352
  Tel: 509/ 376-2924
  Fax: 509/376-9064
  [EMAIL PROTECTED] 
  
 --
 http://mail.python.org/mailman/listinfo/python-list
 

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


Re: f*cking re module

2005-07-04 Thread Cyril BAZIN
If you are looking for HTML tags or something like that. Have a look
at the HTMLParser (docs.python.org).

On 4 Jul 2005 03:37:02 -0700, jwaixs [EMAIL PROTECTED] wrote:
 Thank you for your replies, it's much obvious now. I know more what I
 can and can't do with the re module. But is it possible to search for
 more than one string in the same line?
 
 bv. I want to replace the python with  
 /python with \n and every thing that's not between the two python
 tags must begin with \nprint \\\ and end with n? Or do I
 need more than one call?
 
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Boss wants me to program

2005-06-28 Thread Cyril BAZIN
Hello,

If you have enough money to buy a licence, Visual Basic seem a very good option.
(But you should learn how to use design patterns.)
Without knowing this language I was able to perform a graphical user interface to 
interact with an automat, a mySQL database and many analogical sensors in less 
than 1 month. 

Cyril


On 27 Jun 2005 11:51:21 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
I'm a manager where I work(one of the cogs in a food service company).The boss needed one of us to become the tech guy, and part of that is
writing small windows programs for the office. He wants the developmentwork done in house, and he knows I am in school for a CS minor. I knowbasic C++(Part 2 of that is in the fall), and I will be taking Java 1
in the fall also. What is the easiest way for me to make windowsprograms that will do basic things like(Inventory, Menu Management,etc...)? I have heard visual basic is where it's at. I want to keep anopen mind though, so I am wondering if python could be an option. The
programs haveno speed requirement.But they must be pretty, and not confuse myboss. Plus he wants well documented help for each function. I asked thewindows programming group, but I thought I would ask here also. Thanks.
Xeys--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Geometry library

2005-06-14 Thread Cyril BAZIN
Hello,

I am looking for a geometry library for Python. 
I want to make some computations like: 
-distance between vertex and polygon, vertex and polyline, vertex and segment, etc
-if a point is inside a polygon, if a polyline intersect a polygon, etc

Thanks for your help,

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

Re: Is there a better way of doing this?

2005-05-29 Thread Cyril BAZIN
Hi,

I don't know very well what you want to do, but if you want to parse
c++, take a look at GCC-XML python (http://www.gccxml.org) and the
python binding (http://pygccxml.sourceforge.net/). These tools
translate c++ code to XML. Then, you can parse xml with your favorite
tools and find the namespaces for example...

Your code don't seem very pythonic, and it seems there is a bug...
For example what's append if a comment contains a '}' inside a
namesapce? (or a string contains a '{' ? 

I think you should better use most appropriate tools to do this kind of jobs...

Cyril
On 5/28/05, Michael [EMAIL PROTECTED] wrote:
Hi,I'm fairly new at Python, and have the following code that works but isn'tvery concise, is there a better way of writing it?? It seems much morelengthy than python code i have read. :-)(takes a C++ block and extracts the namespaces from it)
def ExtractNamespaces(data): print(Extracting Namespaces) p = re.compile( 'namespace (?Pname[\w]*)[\n\t ]*{') subNamespaces = [] newNS = p.search(data) while( newNS ):
print \t + newNS.group(name)OPCount = 1Offset = newNS.end()while(OPCount  0): if( data[Offset] == } ):OPCount = OPCount -1; elif( data[Offset] == { ):
OPCount = OPCount + 1; Offset = Offset+1;#Extract Data:newNSData = data[newNS.end():Offset-1]data = "" + data[Offset:]newNamespace = [newNS.group(name), newNSData];
subNamespaces.append(newNamespace)#Perform NewSearchnewNS = p.search(data) return [subNamespaces,data]--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: searching substrings with interpositions

2005-05-24 Thread Cyril BAZIN
Just another solution, pretty and effective:

def fct(a, b):
 idx = -1
 for c in a:
 idx = b.find(c, idx+1)
 if idx == -1:
 return False
 return True
On 24 May 2005 06:06:03 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED]
 wrote:thanx everyone, is what i need.As Claudio argues, it's a standard problem of dna sequences
comparation.the next step of my job is to make limits of lenght of interposedsequences (if someone can help me in this way i'll apreciate a lot)thanx everyone.giorgio--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: executea string

2005-02-22 Thread Cyril BAZIN
   c=2
   e=3
   s=12
   code.append('funtion (c, e,s)')
   print \n.join(code) + '\n'
 

Hello, 

You could try this: 

---
from string import Template
code = 
c=2
e=3
s=12
code.append(Template('function ($c, $e, $s)').substitute(vars()))
print \n.join(code) + '\n'


For more informations about templates, see:
http://docs.python.org/lib/node105.html
Note that is new in version 2.4...


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


Re: [perl-python] exercise: partition a list by equivalence

2005-02-18 Thread Cyril BAZIN
Hello John, 

Try your python code on this example:
merge([[1,2], [3,4], [1,2], [5,3]])

The result given by your function is:
[[3, 4, 5]]

Sorry... 

To Xah: next time you propose an exercise, write some UNIT TESTS!!!
Then people will be able to test if there answers are correct or not.

Cyril



On Fri, 18 Feb 2005 13:20:51 -0300, John Lenton [EMAIL PROTECTED] wrote:
 On Thu, Feb 17, 2005 at 03:46:20PM -0800, Xah Lee wrote:
  here's another interesting algorithmic exercise, again from part of a
  larger program in the previous series.
 
  Here's the original Perl documentation:
 
  =pod
 
  merge($pairings) takes a list of pairs, each pair indicates the
  sameness
  of the two indexes. Returns a partitioned list of same indexes.
 
  For example, if the input is
  merge( [ [1,2], [2,4], [5,6] ] );
 
  that means 1 and 2 are the same. 2 and 4 are the same. Therefore
  1==2==4. The result returned is
 
  [[4,2,1],[6,5]];
 
  (ordering of the returned list and sublists are not specified.)
 
  =cut
 
 in Python:
 
 def merge(pairings):
 rev = {}
 res = []
 for pairing in pairings:
 first, second = pairing
 has_first = first in rev
 has_second = second in rev
 if has_first and has_second:
 rev[first].extend(rev[second])
 rev[second][:] = []
 rev[second] = rev[first]
 elif has_first:
 rev[first].append(second)
 rev[second] = rev[first]
 elif has_second:
 rev[second].append(first)
 rev[first] = rev[second]
 else:
 copy = [first, second]
 res.append(copy)
 rev[first] = rev[second] = copy
 return filter(None, res)
 
 and in Perl:
 
 sub merge($)
 {
 my %rev = ();
 my @res = ();
 my ($pairing, $first, $second, $has_first, $has_second);
 foreach $pairing (@{$_[0]})
 {
 ($first, $second) = @$pairing;
 $has_first = exists $rev{$first};
 $has_second = exists $rev{$second};
 if ($has_first and $has_second)
 {
 push @{$rev{$first}}, @{$rev{$second}};
 @{$rev{$second}} = ();
 $rev{$second} = $rev{$first};
 }
 elsif (exists $rev{$first})
 {
 push @{$rev{$first}}, $second;
 $rev{$second} = $rev{$first};
 }
 elsif (exists $rev{$second})
 {
 push @{$rev{$second}}, $first;
 $rev{$first} = $rev{$second};
 }
 else
 {
 my @copy = ($first, $second);
 push @res, [EMAIL PROTECTED];
 $rev{$first} = $rev{$second} = [EMAIL PROTECTED];
 }
 }
 return [grep @$_, @res];
 }
 
 although in Perl you wouldn't define it to take a reference to a list
 (as you did), but rather a list, and you wouldn't define it to return
 a reference to a list, but rather a list in list context (and possibly
 a reference in scalar context).
 
 Both versions are (IMHO) pretty clear (when the docstring/pod is
 included), and O(n) because dict/hash lookup and list
 appending/pushing is O(1) in both languages. Both versions can
 probably be tweaked for speed quite a bit, but I don't *think* there's
 a better-than-O(n) algorithm for this.
 
 Note that the Python version assumes that the pairs' elements are
 hashable; your example used numbers, so I thought it was pretty safe
 assumption. The Perl version has no such restriction.
 
 --
 John Lenton ([EMAIL PROTECTED]) -- Random fortune:
 Noble cosa es, aún para un anciano, el aprender.
 -- Sófocles. (497-406 a.C.) Filósofo griego.
 
 
 --
 http://mail.python.org/mailman/listinfo/python-list
 
 

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


listerator clonage

2005-02-12 Thread Cyril BAZIN
Hello, 

I want to build a function which return values which appear two or
more times in a list:

So, I decided to write a little example which doesn't work:
#l = [1, 7, 3, 4, 3, 2, 1]
#i = iter(l)
#for x in i:
#j = iter(i)
#for y in j:
#if x == y:
#print x

In thinked that the instruction 'j= iter(i)' create a new iterator 'j'
based on 'i' (some kind of clone). I wrote this little test which show
that 'j = iter(i)' is the same as 'j = i' (that makes me sad):

#l = [1, 7, 3, 4, 2]
#i = iter(l)
#j = iter(i)
#k = i
#i, j, k
(listiterator object at 0x02167B50, listiterator object at
0x02167B50, listiterator object at 0x02167B50)

Just in order to test, I wrote these little test:
#l = [1, 7, 3, 4, 2]
#i = iter(l)
#import pickle
#j = pickle.loads(pickle.dumps(i))
Traceback (most recent call last):
  File input, line 1, in ?
  File C:\Python24\lib\pickle.py, line 1386, in dumps
Pickler(file, protocol, bin).dump(obj)
  File C:\Python24\lib\pickle.py, line 231, in dump
self.save(obj)
  File C:\Python24\lib\pickle.py, line 313, in save
rv = reduce(self.proto)
  File C:\Python24\lib\copy_reg.py, line 69, in _reduce_ex
raise TypeError, can't pickle %s objects % base.__name__
TypeError: can't pickle listiterator objects

#import copy
#j = copy.copy(i)
Traceback (most recent call last):
  File input, line 1, in ?
  File C:\Python24\lib\copy.py, line 95, in copy
return _reconstruct(x, rv, 0)
  File C:\Python24\lib\copy.py, line 320, in _reconstruct
y = callable(*args)
  File C:\Python24\lib\copy_reg.py, line 92, in __newobj__
return cls.__new__(cls, *args)
TypeError: object.__new__(listiterator) is not safe, use listiterator.__new__()

So, I would like to know if there is a way to 'clone' a 'listiterator'
object. I know that is possible in Java for example...

If it is impossible, have you better ideas to find duplicate entries
in a list...

Thanks,

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